diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1d04af1d59..8800d60e27 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -175,7 +175,7 @@ add_subdirectory(${TORCHNPU_ROOT}/core)
add_subdirectory(${TORCHNPU_ROOT}/distributed)
add_subdirectory(${TORCHNPU_ROOT}/framework)
add_subdirectory(${TORCHNPU_ROOT}/npu)
-add_subdirectory(${TORCHNPU_ROOT}/profiler)
+# add_subdirectory(${TORCHNPU_ROOT}/profiler)
add_subdirectory(${TORCHNPU_ROOT}/utils)
# Compile code with pybind11
diff --git a/README.en.md b/README.en.md
index f95d4efabd..6c9d9ee4f1 100644
--- a/README.en.md
+++ b/README.en.md
@@ -1,85 +1,105 @@
# AscendPyTorch
-## Overview
-This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors. When setting up the environments for PyTorch model development and operating, developers can manually compile related modules on servers.
-## Prerequisites
+# Project Introduction
-- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
-- Python 3.7.5, 3.8, and 3.9 are supported.
+This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors.
+
+# Compilation/Execution Constraints
+
+GCC version: 7.3.0 (required only in compilation scenarios)
+
+CMake version: 3.12.0 or later (required only in compilation scenarios)
+
+Python version: 3.7.5, 3.8.x, or 3.9.x (PyTorch1.5 does not support Python 3.9.x.)
# System Dependencies
## CentOS & EulerOS
-yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
-
-yum install -y gcc==7.3.0 cmake==3.12.0
+yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas
## Ubuntu
-apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
+apt-get install -y gcc g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 cmake dos2unix libopenblas-dev
-apt-get install -y gcc==7.3.0 cmake==3.12.0
-> **NOTE:**
->If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
# Ascend Auxiliary Software
-| AscendPyTorch Version| CANN Version| Supported PyTorch Version| Gitee Branch|
-| :------------ | :----------- | :----------- | ------------- |
-| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
-| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
-| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
-| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
-| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
-| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
-| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
-# Installation Methods
+| AscendPyTorch Version | CANN Version | Supported PyTorch Version | Gitee Branch |
+| :-------------------- | :----------- | :------------------------ | -------------- |
+| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
+| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.2.tr5 |
+| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.2.tr5 |
+| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
+| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
-## Install the PyTorch environment dependencies.
-
-If you install dependencies as a non-root user, add **--user** at the end of each command in this step, for example, **pip3 install pyyaml --user**.
-
-```sh
-pip3 install pyyaml
-pip3 install wheel
-```
+# Installation Method
## Compile and install the PyTorch and Ascend plugin.
-Install the official torch package, and then compile and install the plugin.
+Download the plugin code.
```sh
-#x86_64
-pip3 install torch==1.8.1+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
-
-#AArch64
-#The community does not provide the CPU installation package of the ARM architecture. For details, see the first FAQ to compile and install PyTorch using the source code.
+git clone -b v1.8.1-3.0.rc1 https://gitee.com/ascend/pytorch.git
```
-Compile and generate the binary installation package of the PyTorch plugin.
-Download code of the corresponding branch and go to the root directory of the plugin.
-```
-#
-git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
-cd pytorch
-# Specify the Python version packaging mode:
-bash ci/build.sh --python=3.7
-# or
-bash ci/build.sh --python=3.8
-# or
-bash ci/build.sh --python=3.9
+Code in the current repository is PyTorch 1.8.1. Obtain the native Pytorch source code from the root directory **/pytorch** of the current repository and rename it to **pytorch_v1.8.1**.
+
+```sh
+// Version 1.8.1
+
+cd pytorch # Root directory of the plugin
+
+git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git pytorch_v1.8.1
```
-Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
+Run the following commands to go to the native PyTorch source code directory **pytorch_v1.8.1** and obtain the PyTorch passive dependency code:
```
-pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
+cd pytorch_v1.8.1
+git submodule sync
+git submodule update --init --recursive
```
-Download TorchVision.
+
+After the preceding operations are complete and no error is reported, the PyTorch and the third-party code on which the PyTorch depends are generated. Then, the patch is added to the PyTorch source code and compiled.
+
+```sh
+cd ../patch
+bash apply_patch.sh ../pytorch_v1.8.1
+cd ../pytorch_v1.8.1
+Specify the Python version packaging mode:
+bash build.sh --python=3.7
+or
+bash build.sh --python=3.8
+or
+bash build.sh --python=3.9
```
-pip3 install torchvision==0.9.1
+
+Install the torch package generated in the **pytorch/pytorch_v1.8.1/dist** directory, and then compile and install the plugin.
+
+```
+cd dist
+pip3 install --upgrade torch-1.8.1+ascend.rc1-cp37-cp37m-linux_{arch}.whl
+```
+
+Build and generate the binary installation package of the PyTorch plugin.
+
+```
+cd ../../ci # Access the root directory of the plugin.
+Specify the Python version packaging mode:
+bash build.sh --python=3.7
+or
+bash build.sh --python=3.8
+or
+bash build.sh --python=3.9
+```
+
+Install the torch_npu package generated in the **pytorch/dist** directory.
+
+```
+cd ../dist
+pip3 install --upgrade torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
```
@@ -90,70 +110,39 @@ pip3 install torchvision==0.9.1
Run the script for setting environment variables in the root directory of the current repository.
```
+cd ../
source env.sh
```
## Customize environment variables.
+The following environment variables are function classes used in NPU scenarios or environment variables that can improve performance:
+
+```
+export TASK_QUEUE_ENABLE=1 # Delivered by an asynchronous task to asynchronously call the ACL interface. You are advised to enable this environment variable and set its value to **1**.
+```
+
The following are optional environment variables that may affect running models:
```
-export COMBINED_ENABLE=1 # (Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency.
-export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
+export DYNAMIC_COMPILE_ENABLE=1 # Dynamic shape feature. This environment variable is optional for shape change scenarios. To enable it, set its value to **1**.
+export COMBINED_ENABLE=1 # (Optional) Optimizes the scenario where two inconsecutive operators are combined. To enable this function, set the value to **1**.
+export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to **1**.
+export DYNAMIC_OP="ADD#MUL" # Operator implementation. The ADD and MUL operators have different performance in different scenarios. Optional
```
-**Table 1** Description of environment variables
-
-
-
Environment Variable
- |
-Description
-
- |
-COMBINED_ENABLE
- |
-(Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency. However, the host delivery performance may deteriorate.
- |
-
-ACL_DUMP_DATA
- |
-(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
- |
-
-
-
-
-
## Run the unit test script.
-Verify the running. The output is **OK**.
+Verify the execution. The output result is OK.
```shell
cd test/test_network_ops/
python3 test_div.py
```
-# (Optional) Installing the Mixed Precision Module
-
-AscendPyTorch 1.8.1 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
-
-- AMP
- - Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
- - Tensor fusion is not supported.
-
-- Apex
-
- - O1 configuration mode: Conv and Matmul use the float16 precision for computing, and Softmax and BN use float32.
- - O2 configuration mode: BN uses the float32 precision for computing, and others use float16.
- - Static loss scale: Parameters are statically set to ensure the convergence of training with mixed precision.
- - Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
-
-
-
-
-# Documents
+# Documentation
For more details about the installation guide, model porting and training/inference tutorials, and API list, see [User Documents](https://gitee.com/ascend/pytorch/tree/master/docs/en).
@@ -165,64 +154,32 @@ We sincerely welcome you to join discussions in the community and contribute you
The version branches of AscendPyTorch have the following maintenance phases:
-| **Status** | **Duration** | **Description** |
-|-------------|---------------|--------------------------------------------------|
-| Planning | 1-3 months | Plan features. |
-| Development | 3 months | Develop features. |
-| Maintained | 6-12 months | Allow the incorporation of all resolved issues and release the version.|
-| Unmaintained| 0-3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
-| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
+| **Status** | **Duration** | **Description** |
+| ----------------- | ------------- | ------------------------------------------------------------ |
+| Planning | 1 - 3 months | Plan features. |
+| Development | 3 months | Develop features. |
+| Maintained | 6 - 12 months | Allow the incorporation of all resolved issues and release the version. |
+| Unmaintained | 0 - 3 months | Allow the incorporation of all resolved issues. No dedicated maintenance personnel are available. No version will be released. |
+| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
# Maintenance Status of Existing Branches
-| **Branch Name**| **Status** | **Launch Date** | **Subsequent Status** | **EOL Date**|
-|------------|--------------|----------------------|----------------------------------------|------------|
-| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained
2022-07-29 estimated | |
-| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained
2022-10-15 estimated | |
-| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained
2023-01-15 estimated | |
-| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained
2023-04-10 estimated | |
-| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained
2023-07-15 estimated |
-# FAQs
+| **Branch Name** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
+| --------------- | ---------- | --------------- | -------------------------------------- | ------------ |
+| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained
2022-07-29 estimated | |
+| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained
2022-10-15 estimated | |
+| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained
2023-01-15 estimated | |
+| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained
2023-04-10 estimated | |
-## When the CPU architecture is ARM, PyTorch 1.8.1 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.8.1.
-Download the PyTorch 1.8.1 source package.
-
-```
-git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
-```
-
-Access the source package to obtain the passive dependency code.
-
-```
-cd pytorch_v1.8.1
-git submodule sync
-git submodule update --init --recursive
-```
-
-Compile and install PyTorch 1.8.1.
-
-```
-python3 setup.py install
-```
-
-## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
-
-When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
-
-```
-pip3 install -r requirments.txt
-```
+# FAQ
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
-```
pip3 install pyyaml
-
pip3 install typing_extensions
-```
After the installation is successful, run **make clean** and then **bash build.sh** to perform compilation. Otherwise, an unknown compilation error may occur due to the cache.
@@ -230,183 +187,40 @@ After the installation is successful, run **make clean** and then **bash build.s
Development state:
-```
-cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 # {arch} is the architecture name.
-
-pip3 install --upgrade topi-0.4.0-py3-none-any.whl
-
-pip3 install --upgrade te-0.4.0-py3-none-any.whl
-```
+cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64
User state:
-```
-cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
+cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
-```
-
-## During CMake installation through the CLI, an error is reported indicating that the package cannot be found. During CMake compilation, another error is reported indicating that the version is too early. In this cause, you can use the installation script or source code to compile and install CMake.
-
-Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
-
- x86_64 environment: cmake-3.12.0-Linux-x86_64.sh
- AArch64 environment: cmake-3.12.0-Linux-aarch64.sh
-1. Run the following command:
-
- ```
- ./cmake-3.12.0-Linux-{arch}.sh # {arch} indicates the architecture name.
- ```
-
-2. Set the soft link.
-
- ```
- ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
- ```
-
-3. Run the following command to check whether CMake has been installed:
-
- ```
- cmake --version
- ```
-
- If the message "cmake version 3.12.0" is displayed, the installation is successful.
-
-Method 2: Use the source code to compile and install.
-
-1. Obtain the CMake software package.
-
- ```
- wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
- ```
-
-2. Decompress the package and go to the software package directory.
-
- ```
- tar -xf cmake-3.12.0.tar.gz
- cd cmake-3.12.0/
- ```
-
-3. Run the configuration, compilation, and installation commands.
-
- ```
- ./configure --prefix=/usr/local/cmake
- make && make install
- ```
-
-4. Set the soft link.
-
- ```
- ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
- ```
-
-5. Run the following command to check whether CMake has been installed:
-
- ```
- cmake --version
- ```
-
- If the message "cmake version 3.12.0" is displayed, the installation is successful.
-
-## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
-
-When downloading GCC from some sources, you may be prompted by an error message indicating that the package cannot be found. In this case, use the source code to compile and install GCC.
-
-Perform the following steps as the **root** user.
-
-1. Download **gcc-7.3.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz).
-
-2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
-
- ```
- sudo rm -rf /tmp/*
- ```
-
-3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
-
- - For CentOS, run the following command:
-
- ```
- yum install bzip2
- ```
-
- - For Ubuntu, run the following command:
-
- ```
- apt-get install bzip2
- ```
-
-4. Compile and install GCC.
-
- 1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
-
- ```
- tar -zxvf gcc-7.3.0.tar.gz
- ```
-
- 2. Go to the extracted directory and download the GCC dependency packages:
-
- ```
- cd gcc-7.3.0
- ./contrib/download_prerequisites
- ```
-
- If an error is reported during the command execution, run the following commands in the **gcc-7.3.0/** directory to download the dependency packages:
-
- ```
- wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
- wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
- wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
- wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
- ```
-
- After the preceding dependencies are downloaded, run the following command again:
-
- ```
- ./contrib/download_prerequisites
- ```
-
- If the verification fails, check whether there are duplicate dependency packages in the folder. If yes, delete duplicate ones.
-
- 3. Run the configuration, compilation, and installation commands.
-
- ```
- ./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
- make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15. You can set the parameters as required.
- make install
- ```
-
- > **NOTICE:**
- >The **--prefix** option is used to specify the **linux\_gcc7.3.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.3.0**.
- 4. Change the soft links.
-
- ```
- ln -s ${install_path}/bin/gcc /usr/bin/gcc
- ln -s ${install_path}/bin/g++ /usr/bin/g++
- ln -s ${install_path}/bin/c++ /usr/bin/c++
- ```
-5. Configure the environment variable.
+
+## An error message is reported during CMake compilation, indicating that the version is too early.
+
+Download the Linux version from the CMake official website and install it. (The current version is 3.18.0.)
+
+1. Run the **yum install -y cmake==3.18.0** command to install it.
+
+2. Download the **cmake sh** script and install it. (For details, see the CMake official website.)
+
+ Recommended script in the x86_64 environment: **cmake-3.18.2-Linux-x86_64.sh**
- Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
- ```
- export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
- ```
+## GCC version switch errors occur.
- **${install_path}** indicates the GCC 7.3.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/gcc7.3.0/**.
+When the test environment is switched from GCC 4.8.5 to GCC 7.3.0, errors may occur and the PyTorch compilation fails. The following lists the libraries that require soft connections:
- > **NOTE:**
- >Skip this step if you do not need to use the compilation environment with GCC upgraded.
-
-If the PyTorch compilation fails, check whether the soft link library is correct.
+gcc, g++, c++ (The version must be 7.3.0.)
libstdc++->libstdc++.so.6.0.24(7.3.0)
+
+
## libblas.so cannot be found.
The OpenBLAS library is missing in the environment. You need to install it.
@@ -423,71 +237,6 @@ Ubuntu
apt install libopenblas-dev
```
-## No device is mounted to the container.
+# Release Notes
-An NPU-related error is reported when a script is run in the container. The **device** parameter is not set before container instance startup. As a result, the instance cannot be started.
-
-
-
-Run the following command to restart the container:
-
-```sh
-docker run -it --ipc=host \
---device=/dev/davinciX \
---device=/dev/davinci_manager \
---device=/dev/devmm_svm \
---device=/dev/hisi_hdc \
--v /usr/local/Ascend/driver \
--v /usr/local/dcmi \
--v /usr/local/bin/npu-smi \
-${image name}:{tag} \
-/bin/bash
-```
-
-Parameter description:
-
-**/dev/davinci*X***: NPU device. *X* is the physical ID of the chip, for example, **davinci0**.
-
-**/dev/davinci_manager**: management device
-
-**/dev/devmm_svm**: management device
-
-**/dev/hisi_hdc**: management device
-
-**/usr/local/Ascend/driver**: driver directory
-
-**/usr/local/dcmi**: DCMI directory
-
-**/usr/local/bin/npu-smi**: npu-smi tool
-
-**$*{image name}:{tag}***: image name and version
-
-## An error is reported during installation of -torch--whl-, indicating that -torch-1-5-0xxxx- and -torchvision- versions do not match.
-
-During installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
-
-
-When the PyTorch is installed, the version check is automatically triggered. The version of the torchvision installed in the environment is 0.6.0. During the check, it is found that the version of the **torch-\*.whl** is inconsistent with the required version 1.5.0. As a result, an error message is displayed, but the installation is successful.
-
-This problem does not affect the actual result, and no action is required.
-
-
-## When you run **import torch_npu**, if "_has_compatible_shallow_copy_type" is output, a warning about a repeated registration error is displayed.
-
-The warning is triggered by the shallow copy operation of **Tensor.set_data**, as shown in the following figure. The main cause is that after the PyTorch plugin is decoupled, `_has_compatible_shallow_copy_type` cannot detect shallow copy of NPU tensors. You need to register `_has_compatible_shallow_copy_type` again.
-
-This error can be ignored because it does not affect the model accuracy and performance.
-
-It will be resolved after the NPU's device ID is incorporated into the community or the `_has_compatible_shallow_copy_type` registration mode is changed in a later PyTorch version.
-
-
-
-## An error is reported when torch_npu is referenced with Python commands in the compilation directory.
-
-To verify the torch_npu reference, switch to another directory. If you perform the verification in the compilation directory, the following error message is displayed:
-
-
-
-# Version Description
-
-For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
+For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
\ No newline at end of file
diff --git a/README.zh.md b/README.zh.md
index c06e2874f1..7c86d860dc 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -1,35 +1,30 @@
# AscendPyTorch
-简介
-本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。用户在准备相关环境进行基于PyTorch框架模型的开发、运行时,可以选择在服务器中手动编译相关模块。
-前提条件
+# 项目简介
+本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
-- 需完成CANN开发或运行环境的安装,具体操作请参考《CANN 软件安装指南》。
-- Python支持版本为3.7.5、3.8、3.9。
+# 编译/执行约束
+
+gcc版本: 7.3.0(只在编译场景要求)
+
+cmake版本:3.12.0以上版本(只在编译场景要求)
+
+python版本:3.7.5、3.8.x、3.9.x(PyTorch1.5不支持python3.9.x)
# 系统依赖库
## CentOS & EulerOS
-yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
-
-yum install -y gcc==7.3.0 cmake==3.12.0
+yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas
## Ubuntu
-apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
-
-apt-get install -y gcc==7.3.0 cmake==3.12.0
-
-
-
-> **说明:**
->若安装gcc与cmake依赖命令报错,请参考FAQ使用源码安装。
-
+apt-get install -y gcc g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 cmake dos2unix libopenblas-dev
# Ascend配套软件
+
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 | Gitee分支名称 |
| :------------ | :----------- | :----------- | ------------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
@@ -37,38 +32,20 @@ apt-get install -y gcc==7.3.0 cmake==3.12.0
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
-| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
-| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
# 安装方式
-## 安装Pytorch依赖环境
-
-如果使用非root用户安装,用户需要在本步骤的每句命令后加**--user**,示例如:pip3 install pyyaml --user。
-
-```sh
-pip3 install pyyaml
-pip3 install wheel
-```
-
## 编译安装PyTorch和昇腾插件
-首先安装官方torch包,然后编译安装插件。
-
+首先安装官方torch包,然后编译安装插件
```sh
-#x86_64
-pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
-
-#aarch64
-#社区未提供arm架构cpu安装包,请参见FAQ第一条,使用源码编译安装pytorch
+pip3 install torch==1.8.1+cpu
```
编译生成pytorch插件的二进制安装包。
```
-# 下载master分支代码,进入插件根目录
-git clone -b master https://gitee.com/ascend/pytorch.git
-cd pytorch
+git clone https://gitee.com/ascend/pytorch.git & cd pytorch # 下载代码,进入插件根目录
# 指定python版本编包方式:
bash ci/build.sh --python=3.7
# 或
@@ -77,16 +54,12 @@ bash ci/build.sh --python=3.8
bash ci/build.sh --python=3.9
```
-然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
+然后安装pytorch/dist下生成的插件torch_npu包
```
-pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
+pip3 install --upgrade dist/torch_npu-1.8.1rc1-cp37-cp37m-linux_{arch}.whl
```
-下载torchvision。
-```
-pip3 install torchvision==0.9.1
-```
# 运行
@@ -95,40 +68,28 @@ pip3 install torchvision==0.9.1
在当前仓库根目录中执行设置环境变量脚本
```
+cd ../
source env.sh
```
## 自定义环境变量
+以下环境变量为NPU场景下使用的功能类或可以提升性能的环境变量:
+
+```
+export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
+```
+
可选的环境变量可能会对运行的模型产生影响:
```
-export COMBINED_ENABLE=1 # 非连续转连续二级推导优化,可选,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。
+export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1
+export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
+export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
-**表 1** 环境变量说明
-
-
-配置项
- |
-说明
- |
|---|
COMBINED_ENABLE
- |
-(可选)非连续转连续二级推导优化,开启设置为1。当模型中有大量AsStrided高耗时算子被调用时,可以尝试开启此优化以获得潜在的device执行效率的提升。但是Host下发性能存在下降风险。
- |
-
-ACL_DUMP_DATA
- |
-(可选)算子数据dump功能,调试时使用,开启设置为1。
- |
-
-
-
-
-
-
## 执行单元测试脚本
@@ -139,24 +100,6 @@ cd test/test_network_ops/
python3 test_div.py
```
-# 安装混合精度模块(可选)
-
-AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
-
-- AMP
- - 动态loss scale:动态计算loss scale的值并判断是否溢出。
- - 不支持tensor融合功能。
-
-- APEX
-
- - O1配置模式:Conv,Matmul等使用float16精度计算,其他如softmax、BN使用float32精度。
- - O2配置模式:除BN使用float32精度外,其他部分使用float16精度。
- - 静态loss scale:静态设置参数确保混合精度训练收敛。
- - 动态loss scale:动态计算loss scale的值并判断是否溢出。
-
-
-
-
# 文档
有关安装指南、模型迁移和训练/推理教程和API列表等更多详细信息,请参考[用户文档](docs/zh)。
@@ -185,49 +128,16 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained
2022-10-15 estimated | |
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained
2023-01-15 estimated | |
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained
2023-04-10 estimated | |
-| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained
2023-07-15 estimated | |
+
# FAQ
-## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.8.1,需要使用源码编译安装。
-
-下载PyTorch v1.8.1源码包。
-
-```
-git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
-```
-
-进入源码包获取被动依赖代码。
-
-```
-cd pytorch_v1.8.1
-git submodule sync
-git submodule update --init --recursive
-```
-
-执行编译安装。
-
-```
-python3 setup.py install
-```
-
-## 在PIP设置为华为源时,安装requirments.txt中的typing依赖后,会导致python环境错误。
-
-在PIP设置为华为源时,需打开requirments.txt文件,删除typing依赖,再执行命令。
-
-```
-pip3 install -r requirments.txt
-```
-
## 编译过程执行bash build.sh报错no module named yaml/typing_extensions.
pytorch编译依赖 yaml库和typing_extensions库,需要手动安装。
-```
pip3 install pyyaml
-
pip3 install typing_extensions
-```
安装成功后,注意需要执行make clean在执行bash build.sh进行编译,否则可能因缓存出现未知编译错误。
@@ -235,186 +145,40 @@ pip3 install typing_extensions
开发态:
-```
-cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 #{arch}为架构名称
-
-pip3 install --upgrade topi-0.4.0-py3-none-any.whl
-
-pip3 install --upgrade te-0.4.0-py3-none-any.whl
-```
+cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64
用户态:
-```
-cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 #{arch}为架构名称
+cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
-```
-
-## 命令行安装cmake依赖时提示找不到包、编译cmake报错版本过低,可使用安装脚本或源码编译安装。
-
-方法一:下载安装脚本安装cmake。(参考cmake官网)
-
- X86_64环境脚本安装:cmake-3.12.0-Linux-x86_64.sh
-
- aarch64环境脚本安装:cmake-3.12.0-Linux-aarch64.sh
-
-1. 执行命令。
-
- ```
- ./cmake-3.12.0-Linux-{arch}.sh #{arch}为架构名称
- ```
-
-2. 设置软连接。
-
- ```
- ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
- ```
-
-3. 执行如下命令验证是否安装成功。
-
- ```
- cmake --version
- ```
-
- 如显示“cmake version 3.12.0”则表示安装成功。
-方法二:使用源码编译安装。
-1. 获取cmake软件包。
+## 编译cmake报错版本过低
- ```
- wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
- ```
+cmake官网下载linux版本安装(当前3.18.0)
-2. 解压并进入软件包目录。
+1. 使用yum命令安装: yum install -y cmake==3.18.0
- ```
- tar -xf cmake-3.12.0.tar.gz
- cd cmake-3.12.0/
- ```
+2. 下载cmake sh脚本安装:(参考cmake官网)
-3. 执行配置、编译和安装命令。
+ X86_64环境推荐脚本安装: cmake-3.18.2-Linux-x86_64.sh
- ```
- ./configure --prefix=/usr/local/cmake
- make && make install
- ```
+
-4. 设置软连接。
+## GCC版本问题切换问题
- ```
- ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
- ```
-
-5. 执行如下命令验证是否安装成功。
-
- ```
- cmake --version
- ```
-
- 如显示“cmake version 3.12.0”则表示安装成功。
-
-## 命令行安装gcc依赖时提示找不到包、编译时gcc报错问题
-
-部分源下载gcc时会提示无法找到包,需要使用源码编译安装。
-
-以下步骤请在root用户下执行。
-
-1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
-
-2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
-
- ```
- sudo rm -rf /tmp/*
- ```
-
-3. 安装依赖(以CentOS和Ubuntu系统为例)。
-
- - CentOS执行如下命令安装。
-
- ```
- yum install bzip2
- ```
-
- - Ubuntu执行如下命令安装。
-
- ```
- apt-get install bzip2
- ```
-
-4. 编译安装gcc。
-
- 1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
-
- ```
- tar -zxvf gcc-7.3.0.tar.gz
- ```
-
- 2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
-
- ```
- cd gcc-7.3.0
- ./contrib/download_prerequisites
- ```
-
- 如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
-
- ```
- wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
- wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
- wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
- wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
- ```
-
- 下载好上述依赖包后,重新执行以下命令:
-
- ```
- ./contrib/download_prerequisites
- ```
-
- 如果命令校验失败,需要确认上述依赖包在文件夹中的唯一性,无重复下载,若存在重复的依赖包,需删除。
-
- 3. 执行配置、编译和安装命令:
-
- ```
- ./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
- make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
- make install
- ```
-
- > **须知:**
- >其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
-
- 4. 修改软连接。
-
- ```
- ln -s ${install_path}/gcc-7.3.0/bin/gcc /usr/bin/gcc
- ln -s ${install_path}/gcc-7.3.0/bin/g++ /usr/bin/g++
- ln -s ${install_path}/gcc-7.3.0/bin/c++ /usr/bin/c++
- ```
-
- 5.配置环境变量。
-
- 当用户执行训练时,需要用到gcc升级后的编译环境,因此要在训练脚本中配置环境变量,通过如下命令配置。
-
- ```
- export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
- ```
-
- 其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/gcc7.3.0/“。
-
- > **说明:**
- >本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
-
-若存在pytorch编译不过,请检查软连接的库是否正确。
+目前存在测试环境从GCC4.8.5 切换到 GCC7.3.0。这个过程容易出现错误导致pytorch编译不过,以下是需要软连接的库
+gcc, g++,c++(--version 必须是7.3.0)
libstdc++->libstdc++.so.6.0.24(7.3.0)
+
+
## 找不到libblas.so问题
环境缺少openblas库,需要安装openblas库
@@ -431,71 +195,6 @@ Ubuntu环境
apt install libopenblas-dev
```
-## 容器中未挂载device问题
-
-在容器中运行脚本出现NPU相关ERROR。由于启动容器实例时,未挂载device参数,导致无法正常启动实例。
-
-
-
-请用户参考以下命令,重启容器。
-
-```sh
-docker run -it --ipc=host \
---device=/dev/davinciX \
---device=/dev/davinci_manager \
---device=/dev/devmm_svm \
---device=/dev/hisi_hdc \
--v /usr/local/Ascend/driver \
--v /usr/local/dcmi \
--v /usr/local/bin/npu-smi \
-${镜像名称}:{tag} \
-/bin/bash
-```
-
-参数说明:
-
-/dev/davinciX:NPU设配,X是芯片物理ID号例如davinci0。
-
-/dev/davinci_manager:管理设备。
-
-/dev/devmm_svm:管理设备。
-
-/dev/hisi_hdc:管理设备。
-
-/usr/local/Ascend/driver:驱动目录。
-
-/usr/local/dcmi:DCMI目录。
-
-/usr/local/bin/npu-smi:npu-smi工具。
-
-${镜像名称}:{tag}:镜像名称与版本号。
-
-## 安装-torch--whl-提示-torch-1-5-0xxxx-与-torchvision-所依赖的版本不匹配
-
-安装“torch-\*.whl”时,提示"ERROR:torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible"。
-
-
-安装torch时,会自动触发torchvision进行依赖版本检查,环境中安装的torchvision版本为0.6.0,检查时发现我们安装的torch-\*.whl的版本号与要求的1.5.0不一致,所以提示报错,但实际安装成功 。
-
-对实际结果无影响,无需处理。
-
-## import torch_npu 显示_has_compatible_shallow_copy_type重复注册warning问题
-
-warning如下图所示,由Tensor.set_data浅拷贝操作触发。主要原因是PyTorch插件化解耦后,`_has_compatible_shallow_copy_type`缺乏对NPU Tensor的浅拷贝判断支持,因此需要重新注册`_has_compatible_shallow_copy_type`。
-
-该warning不影响模型的精度和性能,可以忽略。
-
-待NPU 设备号合入社区或者后续Pytorch版本`_has_compatible_shallow_copy_type`注册方式发生变动,该warning会被解决。
-
-
-
-## 在编译torch_npu的目录进入python引用torch_npu报错问题
-
-验证torch_npu的引入,请切换至其他目录进行,在编译目录执行会提示如下错误。
-
-
-
-
# 版本说明
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
\ No newline at end of file
diff --git a/Third_Party_Open_Source_Software_Notice b/Third_Party_Open_Source_Software_Notice
deleted file mode 100644
index be761a51ff..0000000000
--- a/Third_Party_Open_Source_Software_Notice
+++ /dev/null
@@ -1,550 +0,0 @@
-OPEN SOURCE SOFTWARE NOTICE
-
-Please note we provide an open source software notice along with this product and/or this product firmware (in the following just “this product”). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
-
-Warranty Disclaimer
-THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
-
-Copyright Notice and License Texts
-
-Software: pytorch 1.8.1
-Copyright notice:
-Copyright 2005, Google Inc.
-Copyright (c) 2011-2013 NYU
-Copyright (c) 2008 - 2012 The Khronos Group Inc.
-Copyright (c) 2007-2017 Free Software Foundation, Inc.
-Copyright (c) 2011-2019 Stephan Brumme
-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation
-Copyright (c) Facebook, Inc. and its affiliates
-Copyright (c) 2014 Indiana University
-Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
-Copyright 2015 The Gemmlowp Authors
-Copyright (c) 2017-2020 Advanced Micro Devices, Inc.
-Copyright (c) 2008-2012 The Khronos Group Inc.
-Copyright (c) 2014-2017 The Regents of the University of California (Regents)
-Copyright (c) 2010 ActiveState Software Inc.
-Copyright 2019 Kakao Brain
-Copyright (c) 2017-2018 Facebook Inc.
-Copyright (c) 2017 Microsoft
-Copyright (c) 2006 The Android Open Source Project
-Copyright (c) 2016-present, Facebook Inc.
-Copyright (c) 2015 Google Inc.
-Copyright (c) 2017 The Android Open Source Project
-Copyright (c) 2018 Marat Dukhan
-Copyright (c) 2017-present, Facebook, Inc.
-Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
-Copyright (c) 2014-2015 The Khronos Group Inc.
-Copyright (c) 2008-2015 The Khronos Group Inc.
-Copyright (c) 2015, 2016 the respective contributors
-Copyright 2006, Google Inc.
-Copyright (c) Facebook Inc. and Microsoft Corporation
-Copyright (c) 2017 Georgia Institute of Technology
-Copyright (c) 2016 Facebook Inc.
-Copyright (c) PyTorch contributors
-copyright 2019, Torch
-Copyright (c) 2013 Eddy Petrisor
-Copyright (c) 2006, Laurent Montel,
-Copyright Python Software Foundation
-Copyright (c) 2015 Yangqing Jia
-Copyright (c) 2016-present, Facebook, Inc.
-Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers
-Copyright (c) 2003-2017 Josef Weidendorfer
-Copyright (c) 2014-2017, the respective contributors
-Copyright (c) 2000-2017 Julian Seward
-Copyright (c) 2014, The Regents of the University of California (Regents)
-Copyright (c) 1994 Hewlett-Packard Company
-Copyright 2013-2014 RAD Game
-copyright 2019 The TensorFlow Authors
-Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
-Copyright (c) Edward Z. Yang
-Copyright (c) 2016-2017, ARM Limited and Contributors
-Copyright (c) 2011-2014 Idiap Research Institute
-Copyright (c) 2008-2013 The Khronos Group Inc.
-Copyright (c) 2001-2014 Python Software Foundation
-Copyright (c) 2005-2010 ActiveState Software Inc.
-Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
-Copyright (c) 2018, Steven Moshier
-Copyright (c) 2018-present, Facebook, Inc.
-Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
-Copyright (c) 2012-2014 Deepmind Technologies
-Copyright 2015 Google Inc.
-Copyright 2016 Facebook
-Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
-Copyright (c) 2014, 2015, the respective contributors
-Copyright (c) 2005-2017, NumPy Developers
-Copyright (c) 2016 Microsoft
-Copyright (c) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura
-Copyright (c) 2016, NVIDIA CORPORATION
-Copyright Michael Park, 2015-2017
-Copyright 2005 Robert Kern (robert.kern@gmail.com)
-Copyright (c) 2013, 2014, 2015, the respective contributors
-Copyright (c) 2014, the respective contributors
-Copyright 2019-2020 Kakao Brain
-Copyright 2004-present Facebook
-Copyright (c) 1996-1998 Silicon Graphics Computer Systems, Inc.
-Copyright (c) 2015-2017 The Khronos Group Inc.
-Copyright (c) 2016- Facebook, Inc
-Copyright 2016 Martin Raiber
-Copyright (c) 2006 Idiap Research Institute
-Copyright (c) 2011 - 2012 Andrzej Krzemienski
-Copyright (c) 2014- Facebook, Inc
-Copyright Malte Skarupke 2017
-Copyright 2013 Conrad Steenberg
-Copyright (c) 2015-2016 Advanced Micro Devices, Inc.
-Copyright (c) 2001-2019 Free Software Foundation, Inc.
-Copyright (c) 2008 - 2009 NVIDIA Corporation
-Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
-Copyright (c) 2012 Giovanni Garberoglio Interdisciplinary Laboratory for Computational Science (LISC) Fondazione Bruno Kessler and University of Trento
-Copyright (c) 2010-2017 Benjamin Peterson
-
-
-License: BSD 3-Clause License
-Copyright (c) ,
-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.
-
-
-License: Apache License V2.0
-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.
-
-
-License: zlib/libpng License
-Copyright (c)
-This software is provided 'as-is', without any express or implied
-warranty. In no event will the authors be held liable for any damages
-arising from the use of this software.
-Permission is granted to anyone to use this software for any purpose,
-including commercial applications, and to alter it and redistribute it
-freely, subject to the following restrictions:
-1. 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.
-2. Altered source versions must be plainly marked as such, and must not be
-misrepresented as being the original software.
-3. This notice may not be removed or altered from any source
-distribution.
-
-
-License: GPL V3.0
-GNU GENERAL PUBLIC LICENSE
-Version 3, 29 June 2007
-Copyright © 2007 Free Software Foundation, Inc.
-Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
-Preamble
-The GNU General Public License is a free, copyleft license for software and other kinds of works.
-The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
-When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
-To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
-For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
-Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
-For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
-Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
-Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
-The precise terms and conditions for copying, distribution and modification follow.
-TERMS AND CONDITIONS
-0. Definitions.
-“This License” refers to version 3 of the GNU General Public License.
-“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
-“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
-To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
-A “covered work” means either the unmodified Program or a work based on the Program.
-To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
-To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
-An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
-1. Source Code.
-The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
-A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
-The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
-The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
-The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
-The Corresponding Source for a work in source code form is that same work.
-2. Basic Permissions.
-All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
-You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
-Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
-3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
-When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
-4. Conveying Verbatim Copies.
-You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
-You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
-5. Conveying Modified Source Versions.
-You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
-•a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
-•b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
-•c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
-•d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
-A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
-6. Conveying Non-Source Forms.
-You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
-•a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
-•b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
-•c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
-•d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
-•e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
-A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
-A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
-“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
-If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
-The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
-Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
-7. Additional Terms.
-“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
-When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
-Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
-•a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
-•b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
-•c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
-•d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
-•e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
-•f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
-All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
-If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
-Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
-8. Termination.
-You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
-However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
-Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
-Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
-9. Acceptance Not Required for Having Copies.
-You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
-10. Automatic Licensing of Downstream Recipients.
-Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
-An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
-You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
-11. Patents.
-A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
-A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
-Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
-In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
-If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
-If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
-A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
-Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
-12. No Surrender of Others' Freedom.
-If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
-13. Use with the GNU Affero General Public License.
-Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
-14. Revised Versions of this License.
-The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
-If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
-Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
-15. Disclaimer of Warranty.
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-16. Limitation of Liability.
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-17. Interpretation of Sections 15 and 16.
-If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
-END OF TERMS AND CONDITIONS
-
-
-License: Boost Software License V1.0
- Boost Software License - Version 1.0August 17th, 2003Permission is hereby granted, free of charge, to any person or organizationobtaining a copy of the software and accompanying documentation covered bythis license (the _;Software_;) to use, reproduce, display, distribute,execute, and transmit the Software, and to prepare derivative works of theSoftware, and to permit third-parties to whom the Software is furnished todo so, all subject to the following:The copyright notices in the Software and this entire statement, includingthe above license grant, this restriction and the following disclaimer,must be included in all copies of the Software, in whole or in part, andall derivative works of the Software, unless such copies or derivativeworks are solely in the form of machine-executable object code generated bya source language processor.THE SOFTWARE IS PROVIDED _;AS IS_;, WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENTSHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLEFOR 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 OTHERDEALINGS IN THE SOFTWARE.
-
-
-License: BSD 2-Clause License
-BSD Two Clause LicenseRedistribution 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 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.
-
-
-License: MIT License
-The MIT License
-Copyright (c)
-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.
-
-
-License: LGPL V2.0
-GNU Library General Public LicenseVersion 2, June 1991Copyright (C) 1991 Free Software Foundation, Inc.59 Temple Place, Suite 330, Boston, MA 02111-1307 USAEveryone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.[This is the first released version of the Library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.]PreambleThe licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to other libraries whose authors who decide to use it. You can use it for your libraries too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license, which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor_039;s protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors_039; reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone_039;s free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don_039;t assume that anything in it is the same as in the ordinary license.The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better.However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries.The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a _;work based on the library_; and a _;work that uses the library_;. The former contains code derived from the library, while the latter only works together with the library.Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one.TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called _;this License_;). Each licensee is addressed as _;you_;.A _;library_; means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The _;Library_;, below, refers to any such software library or work which has been distributed under these terms. A _;work based on the Library_; means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term _;modification_;.) _;Source code_; for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library_039;s complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a _;work that uses the Library_;. Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a _;work that uses the Library_; with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a _;work that uses the library_;. The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a _;work that uses the Library_; uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a _;work that uses the Library_; with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer_039;s own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable _;work that uses the Library_;, as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.For an executable, the required form of the _;work that uses the Library_; must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients_039; exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and _;any later version_;, you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY _;AS IS_; WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONSHow to Apply These Terms to Your New LibrariesIf you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the _;copyright_; line and a pointer to where the full notice is found. one line to give the library_039;s name and an idea of what it does.Copyright (C) year name of author This library is free software; you can redistribute it and/ormodify it under the terms of the GNU Library General PublicLicense as published by the Free Software Foundation; eitherversion 2 of the License, or (at your option) any later version.This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNULibrary General Public License for more details.You should have received a copy of the GNU Library General PublicLicense along with this library; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin St, Fifth Floor,Boston, MA 02110-1301, USAAlso add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a _;copyright disclaimer_; for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest inthe library `Frob_039; (a library for tweaking knobs) writtenby James Random Hacker.signature of Ty Coon, 1 April 1990Ty Coon, President of ViceThat_039;s all there is to it!
-
-
-License: LGPL V2.1
-GNU Lesser General Public License
-Version 2.1, February 1999
-Copyright (C) 1991, 1999 Free Software Foundation, Inc.
-59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-Everyone is permitted to copy and distribute verbatim copies
-of this license document, but changing it is not allowed.
-[This is the first released version of the Lesser GPL. It also counts
-as the successor of the GNU Library Public License, version 2, hence
-the version number 2.1.]
-Preamble
-The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.
-This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.
-When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.
-To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.
-For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.
-We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.
-To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.
-Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.
-Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.
-When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.
-We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.
-For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.
-In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.
-Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.
-The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.
-TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".
-A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.
-The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)
-"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.
-Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.
-1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.
-You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
-2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
-a) The modified work must itself be a software library.
-b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
-c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
-d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.
-(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)
-These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
-Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.
-In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
-3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.
-Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.
-This option is useful when you wish to copy part of the code of the Library into a program that is not a library.
-4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.
-If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.
-5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.
-However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.
-When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.
-If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)
-Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.
-6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.
-You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:
-a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
-b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
-c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
-d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
-e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.
-For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
-It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.
-7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:
-a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
-b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
-8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
-9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.
-10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.
-11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.
-If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.
-It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
-This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
-12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
-13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.
-14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
-NO WARRANTY
-15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-END OF TERMS AND CONDITIONS
-How to Apply These Terms to Your New Libraries
-If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).
-To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
-one line to give the library's name and an idea of what it does.
-Copyright (C) year name of author
-This library is free software; you can redistribute it and/or
-modify it under the terms of the GNU Lesser General Public
-License as published by the Free Software Foundation; either
-version 2.1 of the License, or (at your option) any later version.
-This library is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-Lesser General Public License for more details.
-You should have received a copy of the GNU Lesser General Public
-License along with this library; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-Also add information on how to contact you by electronic and paper mail.
-You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:
-Yoyodyne, Inc., hereby disclaims all copyright interest in
-the library `Frob' (a library for tweaking knobs) written
-by James Random Hacker.
-signature of Ty Coon, 1 April 1990
-Ty Coon, President of Vice
-That's all there is to it!
\ No newline at end of file
diff --git a/ci/build.sh b/ci/build.sh
index 88c3dacb46..f0bbc1c5a1 100644
--- a/ci/build.sh
+++ b/ci/build.sh
@@ -54,11 +54,11 @@ function parse_script_args() {
args_num=$((args_num-1))
shift
;;
- --tocpu=*)
- export 'NPU_TOCPU'=${1:8}
- args_num=$((args_num-1))
- shift
- ;;
+ # --tocpu=*)
+ # export 'NPU_TOCPU'=${1:8}
+ # args_num=$((args_num-1))
+ # shift
+ # ;;
-*)
echo "ERROR Unsupported parameters: ${1}"
return 1
diff --git a/figures/.keep b/figures/.keep
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/figures/210926103326800.png b/figures/210926103326800.png
deleted file mode 100644
index c80fd7d78d..0000000000
Binary files a/figures/210926103326800.png and /dev/null differ
diff --git a/figures/FAQ torch_npu.png b/figures/FAQ torch_npu.png
deleted file mode 100644
index 8c840c5fda..0000000000
Binary files a/figures/FAQ torch_npu.png and /dev/null differ
diff --git a/figures/FAQ.png b/figures/FAQ.png
deleted file mode 100644
index a7accdf1b3..0000000000
Binary files a/figures/FAQ.png and /dev/null differ
diff --git a/figures/icon-caution.gif b/figures/icon-caution.gif
deleted file mode 100644
index 6e90d7cfc2..0000000000
Binary files a/figures/icon-caution.gif and /dev/null differ
diff --git a/figures/icon-danger.gif b/figures/icon-danger.gif
deleted file mode 100644
index 6e90d7cfc2..0000000000
Binary files a/figures/icon-danger.gif and /dev/null differ
diff --git a/figures/icon-note.gif b/figures/icon-note.gif
deleted file mode 100644
index 6314297e45..0000000000
Binary files a/figures/icon-note.gif and /dev/null differ
diff --git a/figures/icon-notice.gif b/figures/icon-notice.gif
deleted file mode 100644
index 86024f61b6..0000000000
Binary files a/figures/icon-notice.gif and /dev/null differ
diff --git a/figures/icon-tip.gif b/figures/icon-tip.gif
deleted file mode 100644
index 93aa72053b..0000000000
Binary files a/figures/icon-tip.gif and /dev/null differ
diff --git a/figures/icon-warning.gif b/figures/icon-warning.gif
deleted file mode 100644
index 6e90d7cfc2..0000000000
Binary files a/figures/icon-warning.gif and /dev/null differ
diff --git a/figures/zh-cn_image_0000001190081735.png b/figures/zh-cn_image_0000001190081735.png
deleted file mode 100644
index ede83f4bc1..0000000000
Binary files a/figures/zh-cn_image_0000001190081735.png and /dev/null differ
diff --git a/patch/apply_patch.sh b/patch/apply_patch.sh
index 1ab5151158..ebe6137160 100644
--- a/patch/apply_patch.sh
+++ b/patch/apply_patch.sh
@@ -22,7 +22,7 @@ PYTORCH_DIR=$1
function main()
{
cd $PYTORCH_DIR
- patch -N -p1 < $ROOT_DIR/patch/npu.patch
+ patch -p1 < $ROOT_DIR/patch/npu.patch
cp -r $ROOT_DIR/third_party/* $PYTORCH_DIR/third_party/
}
diff --git a/patch/include/c10/core/StorageImpl.h b/patch/include/c10/core/StorageImpl.h
index 7a20b96f9a..f87a069423 100644
--- a/patch/include/c10/core/StorageImpl.h
+++ b/patch/include/c10/core/StorageImpl.h
@@ -45,7 +45,7 @@ struct C10_API StorageImpl : public c10::intrusive_ptr_target {
StorageImpl() = delete;
StorageImpl(StorageImpl&& other) = default;
StorageImpl(const StorageImpl&) = delete;
- ~StorageImpl() = default;
+ ~StorageImpl() override = default;
void reset() {
data_ptr_.clear();
@@ -86,12 +86,18 @@ struct C10_API StorageImpl : public c10::intrusive_ptr_target {
return data_ptr_;
};
- // Returns the previous data_ptr
+ // Returns the previous data_ptr
at::DataPtr set_data_ptr(at::DataPtr&& data_ptr) {
- std::swap(data_ptr_, data_ptr);
- return std::move(data_ptr);
+ at::DataPtr old_data_ptr(std::move(data_ptr_));
+ data_ptr_ = std::move(data_ptr);
+ return old_data_ptr;
};
+ void set_data_ptr_noswap(at::DataPtr&& data_ptr) {
+ data_ptr_ = std::move(data_ptr);
+ }
+
+ // TODO: Return const ptr eventually if possible
void* data() {
return data_ptr_.get();
}
diff --git a/patch/include/c10d/comm.hpp b/patch/include/c10d/comm.hpp
index 3a39baccc9..43ffdb07d7 100644
--- a/patch/include/c10d/comm.hpp
+++ b/patch/include/c10d/comm.hpp
@@ -3,123 +3,138 @@
#include
#include
#include
+#include
namespace c10d {
// Broadcast many tensors to all processes in the process group.
-void broadcast_coalesced(
+TORCH_API void broadcast_coalesced(
c10::intrusive_ptr process_group,
at::TensorList tensors,
size_t buffer_size,
int rank = 0);
-// This class passes bucket contents tensor (for multiple replicas) to
-// DDP communication hook.
-// Optionally in the future this can be enhanced with parameter to bucket
-// mappings as well.
-class GradBucket {
+// This class passes bucket contents tensor to DDP communication hook.
+class TORCH_API GradBucket {
public:
explicit GradBucket(
size_t index,
- const std::vector& tensors,
- const std::vector& offsets = {},
- const std::vector& lengths = {},
- const std::vector& sizes_vec = {})
+ size_t bucket_count,
+ const at::Tensor& tensor,
+ const std::vector& offsets,
+ const std::vector& lengths,
+ const std::vector& sizes_vec,
+ const std::vector& parameters)
: index_(index),
- tensors_(tensors),
+ bucket_count_(bucket_count),
+ buffer_(tensor),
offsets_(offsets),
lengths_(lengths),
- sizes_vec_(sizes_vec) {}
+ sizes_vec_(sizes_vec),
+ parameters_(parameters) {}
// Returns the index of the bucket, which is unique across all the buckets.
size_t getIndex() const {
return index_;
}
- // Each tensor in the list that getTensors returns refers to the replica on
- // each device. There will be multiple replicas only in the case of single
- // process multiple device mode. In the single process single device mode,
- // this list would consist of only a single tensor.
- const std::vector& getTensors() const {
- return tensors_;
+ const at::Tensor& getBuffer() const {
+ return buffer_;
}
- // Returns a mutable tensor vector compared with the above method.
- std::vector& getTensorsRef() {
- return tensors_;
+ // Returns a mutable buffer compared with the above method.
+ at::Tensor& getBufferRef() {
+ return buffer_;
}
- // Returns the start index of each variable in tensors_[0].
- const std::vector& getOffsets() const {
- return offsets_;
+ // Overwrites the buffer at a specific index.
+ void setBuffer(at::Tensor& buffer) {
+ buffer_ = buffer;
}
- // Returns the total (i.e., flattened) length of each variable in
- // tensors_[0].
- const std::vector& getLengths() const {
- return lengths_;
+ // Each tensor in the list that getGradients corresponds to a
+ // parameter.
+ std::vector getGradients() const;
+
+ // Returns model parameters belonging to this bucket. They are returned in the
+ // same order as gradient tensors via getGradients(). For example,
+ // getParameters[i] will have its gradient stored in
+ // getGradients[i]
+ const std::vector getParameters() const {
+ return parameters_;
}
- // Returns the multi-dimensional sizes/shape of each variable in tensors_[0].
- const std::vector& getSizesVec() const {
- return sizes_vec_;
+ // Returns whther this bucket is the last bucket to allreduce in an iteration.
+ bool isLast() const {
+ return index_ == bucket_count_ - 1;
}
private:
size_t index_;
- std::vector tensors_;
+ size_t bucket_count_;
+ at::Tensor buffer_;
- // Per-variable info in tensors_[0].
+ // Per-variable info in buffer_.
std::vector offsets_;
std::vector lengths_;
std::vector sizes_vec_;
+ // Model parameters for this bucket.
+ const std::vector parameters_;
};
// Base class of both `PythonCommHook` and `CppCommHook`.
// Requires implementing 1) `runHook` method that communicates gradients
// asynchronously, and 2) `parseHookResult` method that converts the hook
-// result into a tensor vector.
-class TORCH_PYTHON_API CommHookInterface {
+// result into a tensor.
+class TORCH_API CommHookInterface {
public:
- virtual ~CommHookInterface() {}
+ virtual ~CommHookInterface() = default;
// Passes the input grad bucket to the registered communication hook.
- // Once the tensors in the bucket are ready, kicks off the hook asynchronously
+ // Once the tensor in the bucket are ready, kicks off the hook asynchronously
// and returns a future that holds the communication results.
virtual c10::intrusive_ptr runHook(
GradBucket& bucket) = 0;
- // Returns the resulting tensors once the communication hook result is
- // ready. The resulting tensors will then be copied to the grads of
+ // Returns the resulting tensor once the communication hook result is
+ // ready. The resulting tensor will then be copied to the grads of
// individual parameters.
- virtual std::vector parseHookResult(
+ virtual at::Tensor parseHookResult(
const c10::IValue& result) = 0;
};
+namespace detail {
+// This helper function is called both by CppCommHookInterface below and inside
+// reducer.
+inline at::Tensor parseCppCommHookResult(
+ const c10::IValue& result) {
+ TORCH_INTERNAL_ASSERT(
+ result.isTensor() || result.isTensorList(),
+ "expected the hook result is either a Tensor or a TensorList");
+
+ if (result.isTensor()) {
+ return result.toTensor();
+ }
+
+ return result.toTensorVector()[0];
+}
+} // namespace detail
+
// This CppCommHook interface only requires implementing runHook method that
// potentially uses a state.
-// Still need TORCH_PYTHON_API instead of TORCH_API to support Windows platform.
template
-class TORCH_PYTHON_API CppCommHookInterface : public CommHookInterface {
+class CppCommHookInterface : public CommHookInterface {
public:
explicit CppCommHookInterface(T& state) : state_(state) {}
- virtual ~CppCommHookInterface() {}
+ ~CppCommHookInterface() override = default;
- std::vector parseHookResult(const c10::IValue& result) override {
- TORCH_INTERNAL_ASSERT(
- result.isTensor() || result.isTensorList(),
- "expected the hook result is either a Tensor or a TensorList");
-
- if (result.isTensor()) {
- return {result.toTensor()};
- }
-
- return result.toTensorVector();
+ at::Tensor parseHookResult(const c10::IValue& result) override {
+ return detail::parseCppCommHookResult(result);
}
protected:
- T state_; // Not owned.
+ T state_;
};
} // namespace c10d
diff --git a/patch/include/c10d/debug.h b/patch/include/c10d/debug.h
new file mode 100644
index 0000000000..ecfb494482
--- /dev/null
+++ b/patch/include/c10d/debug.h
@@ -0,0 +1,27 @@
+// Copyright (c) Meta Platforms, Inc. and its affiliates.
+// All rights reserved.
+//
+// This source code is licensed under the BSD-style license found in the
+// LICENSE file in the root directory of this source tree.
+
+#pragma once
+
+#include
+
+namespace c10d {
+
+enum class DebugLevel {
+ Off,
+ Info,
+ Detail
+};
+
+TORCH_API void setDebugLevel(DebugLevel level);
+
+// Sets the debug level based on the value of the `TORCH_DISTRIBUTED_DEBUG`
+// environment variable.
+TORCH_API void setDebugLevelFromEnvironment();
+
+TORCH_API DebugLevel debug_level() noexcept;
+
+} // namespace c10d
diff --git a/patch/include/c10d/default_comm_hooks.hpp b/patch/include/c10d/default_comm_hooks.hpp
index 077d29bd97..37b64a4bad 100644
--- a/patch/include/c10d/default_comm_hooks.hpp
+++ b/patch/include/c10d/default_comm_hooks.hpp
@@ -1,7 +1,7 @@
#pragma once
-#include
#include
+#include
namespace c10d {
@@ -15,7 +15,7 @@ class AllReduceCommHook : public CppCommHookInterface {
explicit AllReduceCommHook(ProcessGroup* state)
: CppCommHookInterface(state) {}
- ~AllReduceCommHook() override {}
+ ~AllReduceCommHook() override = default;
c10::intrusive_ptr runHook(GradBucket& bucket) override;
};
@@ -25,7 +25,22 @@ class FP16CompressCommHook : public CppCommHookInterface {
explicit FP16CompressCommHook(ProcessGroup* state)
: CppCommHookInterface(state) {}
- ~FP16CompressCommHook() override {}
+ ~FP16CompressCommHook() override = default;
+
+ c10::intrusive_ptr runHook(GradBucket& bucket) override;
+};
+
+// Almost same as AllReduceCommHook, but without division inside the hook.
+// This enables the optimization of fusing copy and division and saves one scan
+// over all the input parameters, when no communication hook is provided by the user.
+// Only used internally and not released as a public built-in communication hook.
+class _AllReduceBySumCommHook
+ : public CppCommHookInterface {
+ public:
+ explicit _AllReduceBySumCommHook(ProcessGroup* state)
+ : CppCommHookInterface(state) {}
+
+ ~_AllReduceBySumCommHook() override = default;
c10::intrusive_ptr runHook(GradBucket& bucket) override;
};
diff --git a/patch/include/c10d/frontend.hpp b/patch/include/c10d/frontend.hpp
deleted file mode 100644
index d91ac3cb67..0000000000
--- a/patch/include/c10d/frontend.hpp
+++ /dev/null
@@ -1,261 +0,0 @@
-#pragma once
-
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-
-namespace c10d {
-
-#ifdef USE_C10D_GLOO
-constexpr char* GLOO_SOCKET_IFNAME_ENV = "GLOO_SOCKET_IFNAME";
-#endif
-
-inline std::vector split(
- char separator,
- const std::string& string) {
- std::vector pieces;
- std::stringstream ss(string);
- std::string item;
- while (std::getline(ss, item, separator)) {
- pieces.push_back(std::move(item));
- }
- return pieces;
-}
-
-class Backend {
- public:
- // Maps to Backend.__new__ in Python.
- static std::string get(const std::string&);
-
- // TODO: How to support registering third_party backend?
- static void registerBackend();
-
- private:
- // TODO: Should this be an enum list instead since this set doesn't
- // change at all.
- std::unordered_set registered_backends_;
-};
-
-class TORCH_PYTHON_API DistributedC10d : public torch::CustomClassHolder {
- public:
- static c10::intrusive_ptr get();
-
- DistributedC10d() = default;
-
- void initProcessGroup(
- const std::string& backend,
- const std::string& init_method,
- const std::chrono::milliseconds& timeout,
- int64_t world_size,
- int64_t rank,
- c10::intrusive_ptr store,
- const std::string& group_name);
-
- void destroyProcessGroup(c10::intrusive_ptr group);
- int64_t getRank(const c10::intrusive_ptr& group) const;
- int64_t getWorldSize(const c10::intrusive_ptr& group) const;
-
- c10::intrusive_ptr isend(
- at::Tensor tensor,
- int64_t dst,
- const c10::intrusive_ptr& group,
- c10::optional& tag);
-
- c10::intrusive_ptr irecv(
- at::Tensor tensor,
- int64_t src,
- const c10::intrusive_ptr& group,
- c10::optional& tag);
-
- void send(
- at::Tensor tensor,
- int64_t dst,
- const c10::intrusive_ptr& group,
- c10::optional& tag);
-
- int64_t recv(
- at::Tensor tensor,
- const c10::optional& src,
- const c10::intrusive_ptr& group,
- c10::optional& tag);
-
- c10::intrusive_ptr broadcastMultiGPU(
- std::vector& tensor_list,
- int64_t src,
- const c10::intrusive_ptr& group,
- bool async_op = false,
- int64_t src_tensor = 0);
-
- c10::intrusive_ptr broadcast(
- at::Tensor tensor,
- int64_t src,
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr allReduceMultiGPU(
- std::vector& tensor_list,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false);
-
- c10::intrusive_ptr allReduce(
- at::Tensor tensor,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false);
-
- c10::intrusive_ptr allReduceCoalesced(
- std::vector& tensors,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false);
-
- c10::intrusive_ptr reduceMultiGPU(
- std::vector& tensor_list,
- int64_t dst,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false,
- int64_t dst_tensor = 0);
-
- c10::intrusive_ptr reduce(
- at::Tensor tensor,
- int64_t dst,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false);
-
- c10::intrusive_ptr allGatherMultiGPU(
- std::vector>& output_tensor_lists,
- std::vector& input_tensor_list,
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr allGather(
- std::vector& tensor_list,
- at::Tensor tensor,
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr allGatherCoalesced(
- std::vector>& output_tensor_lists,
- std::vector& input_tensor_list,
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr gather(
- at::Tensor tensor,
- const c10::optional>& gather_list,
- const c10::intrusive_ptr& group,
- int64_t dst = 0,
- bool async_op = false);
-
- c10::intrusive_ptr scatter(
- at::Tensor tensor,
- std::vector& scatter_list,
- const c10::intrusive_ptr& group,
- int64_t src = 0,
- bool async_op = false);
-
- c10::intrusive_ptr reduceScatterMultiGPU(
- std::vector& output_tensor_list,
- std::vector>& input_tensor_lists,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false);
-
- c10::intrusive_ptr reduceScatter(
- at::Tensor output,
- std::vector& input_tensor_list,
- const c10::intrusive_ptr& group,
- ReduceOp op = ReduceOp::SUM,
- bool async_op = false);
-
- c10::intrusive_ptr allToAllSingle(
- at::Tensor output,
- at::Tensor input,
- std::vector& output_split_sizes,
- std::vector& input_split_sizes,
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr allToAll(
- std::vector& output_tensor_list,
- std::vector& input_tensor_list,
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr barrier(
- const c10::intrusive_ptr& group,
- bool async_op = false);
-
- c10::intrusive_ptr newGroup(
- std::vector ranks,
- std::chrono::milliseconds timeout,
- Backend backend);
-
- c10::intrusive_ptr worldProcessGroup();
-
- c10::intrusive_ptr newProcessGroupHelper(
- const int64_t world_size,
- const int64_t rank,
- const std::vector& group_ranks,
- const std::string& backend_str,
- const c10::intrusive_ptr& store,
- c10::optional group_name,
- int64_t timeout_milisesonds);
-
- c10::intrusive_ptr getProcessGroupByName(
- const std::string& name) const;
-
- std::string getNameOfProcessGroup(
- const c10::intrusive_ptr& pg) const;
-
- void registerProcessGroupName(const c10::intrusive_ptr& process_group, const std::string& name);
-
- private:
-
- bool rankNotInGroup(const c10::intrusive_ptr& group) const;
- int64_t getGroupRank(
- const c10::intrusive_ptr& group,
- const int64_t rank) const;
- int64_t getGlobalRank(
- const c10::intrusive_ptr& group,
- const int64_t group_rank) const;
- void checkDefaultPg() const;
- int64_t getGroupSize(const c10::intrusive_ptr& group) const;
- std::string getBackend(const c10::intrusive_ptr& group);
-
- std::string backend_;
- // TODO: Ask Alex what kind of equality we need. It determine whether we
- // need to use ProcessGroup or ProcesGroup* as key.
- std::unordered_map<
- c10::intrusive_ptr,
- std::pair>>
- pg_map_;
-
- // Note, this is different mapping relationship than original Python
- // implementation.
- std::unordered_map, std::string> pg_names_;
-
- // Process group's global rank to local rank mapping
- std::unordered_map<
- c10::intrusive_ptr,
- std::unordered_map>
- pg_group_ranks_;
-
- c10::intrusive_ptr default_pg_;
-
- // Default value should be "env://"
- std::string default_pg_init_method_;
-
- int64_t group_count_;
-};
-
-} // namespace c10d
diff --git a/patch/include/c10d/logger.hpp b/patch/include/c10d/logger.hpp
new file mode 100644
index 0000000000..d471578056
--- /dev/null
+++ b/patch/include/c10d/logger.hpp
@@ -0,0 +1,110 @@
+#include
+#include
+
+#include
+
+namespace c10d {
+
+class TORCH_API Logger {
+ public:
+ explicit Logger(std::shared_ptr reducer);
+ // Set logging data that can be got during DistributedDataParallel
+ // construction time.
+ void set_construction_data_and_log(
+ const std::string& module_name,
+ const std::vector& device_ids,
+ int output_device,
+ bool broadcast_buffers,
+ bool has_sync_bn);
+
+ void set_static_graph();
+
+ // An interface for users to get DDPLoggingData and log them
+ // in the applications. Explanation of logging fields are in
+ // "struct DDPLoggingData" of "torch/c10/util/Logging.h".
+ at::DDPLoggingData get_ddp_logging_data();
+
+ // Stream insertion operator for logging data to stream under
+ // TORCH_DISTRIBUTED_DEBUG.
+ friend std::ostream& operator<<(std::ostream& output, const Logger& logger);
+
+ ~Logger() noexcept(false) {
+ // Log if DDP graph is static in Logger dtor instead of Reducer dtor since
+ // Logger is deleted before Reducer.
+ log_if_graph_static(reducer_->ddp_graph_static());
+ }
+
+ // Set environment variables.
+ void set_env_variables();
+ // Set parameters stats.
+ void set_parameter_stats();
+ // Get size of each bucket (Bytes).
+ std::vector get_bucket_sizes();
+ // Get bucket size limits specified during DDP construction.
+ std::vector get_bucket_size_limits();
+ // Get variable indices for each bucket.
+ std::vector> get_per_bucket_variable_indices();
+ // Set comm. hook, if used
+ void set_comm_hook(const std::string& hook);
+ // Set running with uneven input detection (model.join() context manager)
+ void set_uneven_input_join();
+
+ // Reset performance stats at current iteration
+ void reset_performance_stats();
+
+ // Calculate avg stats using cpu timer and gpu timer
+ // that has been recorded in reducer.
+ void calculate_avg_time(
+ int64_t& avg_time,
+ int64_t& time_duration,
+ Timer& timer,
+ Timer::Event start_event,
+ Timer::Event end_event);
+
+ // Set the absolute time of the event that has been recorded in reducer.
+ void set_event_time(
+ int64_t& event_time,
+ Timer& timer,
+ Timer::Event event
+ );
+ // Set stats that can be collected only during
+ // training loop. It is called at the beginning of forward call
+ // to record the run time stats of sampled iterations that previouly ran.
+ // GPU performance stats are collected only for single process
+ // single device program and single device module right now.
+ // TODO to support single process multiple devices and multi device modules,
+ // events need to be created and recorded on multiple devices.
+ void set_runtime_stats_and_log();
+
+ // Called when DDP/reducer is failing with an error. The
+ // logging data structure will have two fields filled: "has_error" indicating
+ // that this iteration encountered an error and other fields are not valid,
+ // and "error", a string which contains the error message that DDP failed
+ // with.
+ template
+ void set_error_and_log(const std::string& ddp_error, const Args&... args) {
+ ddp_logging_data_->ints_map["has_error"] = 1;
+ auto err = c10::str(ddp_error, args...);
+ ddp_logging_data_->strs_map["error"] = err;
+ // Report the iteration we are erroring at so user knows how many examples
+ // successfully processed before this error was hit.
+ ddp_logging_data_->ints_map["iteration"] = reducer_->num_iterations_;
+ at::LogPyTorchDDPUsage(*ddp_logging_data_);
+ }
+
+ // When running without static graph, called when reducer is destroyed to log
+ // if graph was actually static and is a candidate for static graph
+ // optimization.
+ void log_if_graph_static(bool is_static);
+
+
+ private:
+ // ddp_logging_data_ is used to hold all the ddp related logging
+ // data fields.
+ std::unique_ptr ddp_logging_data_;
+ std::shared_ptr reducer_;
+ // track the number of iterations when runtime stats are collected so far.
+ long num_iterations_stats_recorded_ = 0;
+};
+
+} // namespace c10d
diff --git a/patch/include/torch/csrc/autograd/profiler_utils.cpp b/patch/include/torch/csrc/autograd/profiler_utils.cpp
new file mode 100644
index 0000000000..b41f59f932
--- /dev/null
+++ b/patch/include/torch/csrc/autograd/profiler_utils.cpp
@@ -0,0 +1,247 @@
+#include
+
+namespace torch { namespace autograd { namespace profiler {
+
+static constexpr auto kConv2dStride = 3;
+static constexpr auto kConv2dPadding = 4;
+static constexpr auto kConv2dDilation = 5;
+static constexpr auto kConv2dGroups = 6;
+
+// List of supported operators
+static constexpr auto kConv2dOp = "aten::conv2d";
+static constexpr auto kGemmOp = "aten::mm";
+static constexpr auto kMulOp = "aten::mul";
+static constexpr auto kAddOp = "aten::add";
+
+static constexpr auto kInputSize = "input_size";
+static constexpr auto kWeightSize = "weight_size";
+static constexpr auto kGroups = "groups";
+static constexpr auto kPadding = "padding";
+static constexpr auto kStride = "stride";
+static constexpr auto kDilation = "dilation";
+static constexpr auto kMatSize = "mat_size";
+static constexpr auto kMat1Size = "mat1_size";
+static constexpr auto kMat2Size = "mat2_size";
+
+static bool validateInput(const std::string &op_name, size_t min_size,
+ const std::vector& inputs,
+ const std::vector& should_be_tensor) {
+ std::stringstream ss;
+ if (inputs.size() < min_size) {
+ ss << "Failed to save extra arguments for flops compuation of op "
+ << op_name
+ << ", min size: " << min_size
+ << ", actual size: " << inputs.size();
+ TORCH_WARN(ss.str());
+ return false;
+ }
+ for (auto index : should_be_tensor) {
+ if (!inputs[index].isTensor()) {
+ ss << "Failed to save extra arguments for flops compuation of op "
+ << op_name
+ << ", input[" << index
+ << "] must be a tensor.";
+ TORCH_WARN(ss.str());
+ return false;
+ }
+ }
+ return true;
+}
+
+std::unordered_map saveExtraArgs(const at::RecordFunction& fn) {
+ // for specific types of fn, return the saved extra args for computing flops
+ std::unordered_map map;
+ std::vector inputs = fn.inputs();
+ std::string fname(fn.name().str());
+
+ if (inputs.empty()) {
+ // Input shape is unavailable, return empty map
+ return map;
+ }
+
+ if (fname == kConv2dOp) {
+ std::vector tensors{0, 1};
+ bool check = validateInput(fname, kConv2dGroups + 1, inputs, tensors);
+ if (!check) {
+ return map;
+ }
+
+ at::Tensor input = inputs[0].toTensor();
+ at::Tensor weight = inputs[1].toTensor();
+ if (weight.sizes().size() != 4) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because it requires a 4D kernel tensor.");
+ return map;
+ }
+ map[kInputSize] = at::IValue(input.sizes());
+ map[kWeightSize] = at::IValue(weight.sizes());
+ map[kStride] = inputs[kConv2dStride];
+ map[kPadding] = inputs[kConv2dPadding];
+ map[kDilation] = inputs[kConv2dDilation];
+ map[kGroups] = inputs[kConv2dGroups];
+ } else if (fname == kGemmOp) {
+ std::vector tensors{0, 1};
+ bool check = validateInput(fname, 2, inputs, tensors);
+ if (!check) {
+ return map;
+ }
+
+ at::Tensor left = inputs[0].toTensor();
+ at::Tensor right = inputs[1].toTensor();
+ map[kMat1Size] = at::IValue(left.sizes());
+ map[kMat2Size] = at::IValue(right.sizes());
+ } else if (fname == kMulOp) {
+ std::vector tensors{0};
+ bool check = validateInput(fname, 1, inputs, tensors);
+ if (!check) {
+ return map;
+ }
+
+ at::Tensor mat = inputs[0].toTensor();
+ map[kMatSize] = at::IValue(mat.sizes());
+ } else if (fname == kAddOp) {
+ std::vector tensors{0};
+ bool check = validateInput(fname, 1, inputs, tensors);
+ if (!check) {
+ return map;
+ }
+
+ at::Tensor mat = inputs[0].toTensor();
+ map[kMatSize] = at::IValue(mat.sizes());
+ }
+
+ return map;
+}
+
+uint64_t computeFlops(const std::string &op_name, const std::unordered_map &extra_args) {
+ if (op_name == kConv2dOp) {
+ if (extra_args.find(kInputSize) == extra_args.end()
+ || extra_args.find(kWeightSize) == extra_args.end()
+ || extra_args.find(kGroups) == extra_args.end()
+ || extra_args.find(kPadding) == extra_args.end()
+ || extra_args.find(kStride) == extra_args.end()
+ || extra_args.find(kDilation) == extra_args.end()) {
+ TORCH_WARN("Calculating flops for aten::conv2d requires groups, padding, stride, dilation, input_size, and weight_size in saved arguments.");
+ return 0;
+ }
+ auto input_sizes_ref = extra_args.at(kInputSize);
+ auto kernel_sizes_ref = extra_args.at(kWeightSize);
+ auto groups_ref = extra_args.at(kGroups);
+ auto padding_ref = extra_args.at(kPadding);
+ auto stride_ref = extra_args.at(kStride);
+ auto dilation_ref = extra_args.at(kDilation);
+ if (!input_sizes_ref.isIntList() || !kernel_sizes_ref.isIntList()) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because it requires input and weight tensor sizes.");
+ return 0;
+ }
+ if (!padding_ref.isIntList() || !stride_ref.isIntList() || !dilation_ref.isIntList()) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because it requires padding, stride, and dilation values.");
+ return 0;
+ }
+
+ const std::vector input_sizes = input_sizes_ref.toIntVector();
+ const std::vector kernel_sizes = kernel_sizes_ref.toIntVector();
+ const uint64_t groups = groups_ref.toInt();
+ const std::vector padding = padding_ref.toIntVector();
+ const std::vector stride = stride_ref.toIntVector();
+ const std::vector dilation = dilation_ref.toIntVector();
+ if (input_sizes.size() != 4 || kernel_sizes.size() != 4) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because both input and weight must be size 4.");
+ return 0;
+ }
+ if (!groups) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because group size must not be 0.");
+ return 0;
+ }
+ if (padding.size() != 2 || dilation.size() != 2) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because both padding and dilation must be size 2.");
+ return 0;
+ }
+ if (stride.size() != 2 || (stride[0] * stride[1] == 0)) {
+ TORCH_WARN("Failed to compute flops for op aten::conv2d because stride must be size 2 and cannot be 0.");
+ return 0;
+ }
+ // format of the input is defined in torch.nn.quantized.functional.conv2d()
+ uint64_t minibatch = 0, in_channels = 0, input_h = 0, input_w = 0;
+ uint64_t out_channels = 0, kernel_h = 0, kernel_w = 0;
+ const uint64_t conv2d_multiply_factor = 2;
+ std::tie(minibatch, in_channels, input_h, input_w) = std::make_tuple(input_sizes[0], input_sizes[1],
+ input_sizes[2], input_sizes[3]);
+ std::tie(out_channels, std::ignore, kernel_h, kernel_w) = std::make_tuple(kernel_sizes[0], kernel_sizes[1],
+ kernel_sizes[2], kernel_sizes[3]);
+ uint64_t output_h = (input_h + 2 * padding[0] - dilation[0] * (kernel_h - 1) - 1) / stride[0] + 1;
+ uint64_t output_w = (input_w + 2 * padding[1] - dilation[1] * (kernel_w - 1) - 1) / stride[1] + 1;
+
+ return conv2d_multiply_factor * minibatch * output_h * output_w *
+ kernel_h * kernel_w * in_channels * out_channels / groups;
+ } else if (op_name == kGemmOp) {
+ if (extra_args.find(kMat1Size) == extra_args.end()
+ || extra_args.find(kMat2Size) == extra_args.end()) {
+ TORCH_WARN("Calculating flops for aten::mm requires mat1_size and mat2_size in saved arguments.");
+ return 0;
+ }
+ auto mat1_sizes_ref = extra_args.at(kMat1Size);
+ auto mat2_sizes_ref = extra_args.at(kMat2Size);
+ if (!mat1_sizes_ref.isIntList() || !mat2_sizes_ref.isIntList()) {
+ TORCH_WARN("Failed to compute flops for op aten::mm because it requires mat1_size and mat2_size to be IntList.");
+ return 0;
+ }
+
+ std::vector mat1_size = mat1_sizes_ref.toIntVector();
+ std::vector mat2_size = mat2_sizes_ref.toIntVector();
+ if (mat1_size.size() == 0) {
+ return 0;
+ } else {
+ int64_t overlap_dim = mat1_size.back();
+ const uint64_t gemm_multiply_factor = 2;
+ uint64_t flops = 1;
+ for(int64_t dim : mat1_size) {
+ flops *= dim;
+ }
+ flops /= overlap_dim;
+ for(int64_t dim : mat2_size) {
+ flops *= dim;
+ }
+ flops *= gemm_multiply_factor;
+ return flops;
+ }
+ } else if (op_name == kMulOp) {
+ if (extra_args.find(kMatSize) == extra_args.end()) {
+ TORCH_WARN("Calculating flops for aten::mul.Tensor requires mat_size in saved arguments.");
+ return 0;
+ }
+ auto mat_sizes = extra_args.at(kMatSize);
+ if (!mat_sizes.isIntList()) {
+ TORCH_WARN("Failed to compute flops for op aten::mul because it requires mat_size to be IntList.");
+ return 0;
+ }
+
+ std::vector mat_size = mat_sizes.toIntVector();
+ uint64_t flops = 1;
+ for(int64_t dim : mat_size) {
+ flops *= dim;
+ }
+ return flops;
+ } else if (op_name == kAddOp) {
+ if (extra_args.find(kMatSize) == extra_args.end()) {
+ TORCH_WARN("Calculating flops for aten::add.Tensor requires mat_size in saved arguments.");
+ return 0;
+ }
+ auto mat_sizes = extra_args.at(kMatSize);
+ if (!mat_sizes.isIntList()) {
+ TORCH_WARN("Failed to compute flops for op aten::add because it requires mat_size to be IntList.");
+ return 0;
+ }
+
+ std::vector mat_size = mat_sizes.toIntVector();
+ uint64_t flops = 1;
+ for(int64_t dim : mat_size) {
+ flops *= dim;
+ }
+ return flops;
+ }
+ return 0;
+}
+
+} // namespace profiler
+} // namespace autograd
+} // namespace torch
diff --git a/patch/include/torch/csrc/autograd/profiler_utils.h b/patch/include/torch/csrc/autograd/profiler_utils.h
new file mode 100644
index 0000000000..959821983e
--- /dev/null
+++ b/patch/include/torch/csrc/autograd/profiler_utils.h
@@ -0,0 +1,16 @@
+#pragma once
+
+#include
+#include
+#include
+#include
+
+namespace torch { namespace autograd {
+namespace profiler {
+
+std::unordered_map TORCH_API saveExtraArgs(const at::RecordFunction& fn);
+
+uint64_t TORCH_API computeFlops(const std::string &op_name,
+ const std::unordered_map &extra_args);
+
+}}}
diff --git a/patch/include/torch/csrc/code_template.h b/patch/include/torch/csrc/code_template.h
new file mode 100644
index 0000000000..52082b7e9a
--- /dev/null
+++ b/patch/include/torch/csrc/code_template.h
@@ -0,0 +1,246 @@
+#pragma once
+
+#include
+
+#include
+#include
+#include
+#include
+
+namespace at { namespace jit {
+
+// A template environment is a mapping from template variable names, e.g.,
+// identifier (corresponding to $identifier) to their expansions.
+//
+// This template environment supports storing strings, numbers and lists
+// of strings, and can be chained together (so that lookup proceeds in
+// in the top level environment, and then recurses into a parent
+// environment if the key is not found.)
+struct TemplateEnv {
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
+ TemplateEnv() : parent(nullptr) {}
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init)
+ TemplateEnv(TemplateEnv& parent) : parent(&parent) {}
+
+ using string_list = std::vector;
+
+ // Add a string 'v' to the map at key 'k'.
+ void s(const std::string& k, const std::string& v) {
+ strings_[k] = v;
+ lists_.erase(k);
+ }
+
+ // Add a number 'v' to the map at key 'k'
+ template
+ void d(const std::string& k, const T& v) {
+ strings_[k] = c10::to_string(v);
+ lists_.erase(k);
+ }
+
+ // Retrieve the string representation of the value stored at 'k' from the map.
+ // Raises an exception if the key is not found.
+ const std::string& s(const std::string& k) const {
+ if (strings_.count(k) == 0) {
+ if (parent) {
+ return parent->s(k);
+ }
+ notFound(k);
+ }
+ return strings_.at(k);
+ }
+
+ // Store a list of strings 'v' in the map at 'k'.
+ void v(const std::string& k, const string_list& v) {
+ lists_[k] = v;
+ strings_.erase(k);
+ }
+
+ // Retrieve a list of strings stored at 'k' from the map.
+ // Raises an exception if the key is not found.
+ const string_list& v(const std::string& k) const {
+ if (lists_.count(k) == 0) {
+ if (parent) {
+ return parent->v(k);
+ }
+ notFound(k);
+ }
+ return lists_.at(k);
+ }
+
+ // Test if a string 'k' is a string (as opposed to a list.)
+ bool keyIsString(const std::string& k) const {
+ if (strings_.count(k) > 0)
+ return true;
+ if (lists_.count(k) > 0)
+ return false;
+ if (parent)
+ return parent->keyIsString(k);
+ notFound(k);
+ }
+
+ private:
+ [[noreturn]] void notFound(const std::string& k) const {
+ std::stringstream ss;
+ ss << "key not found: " << k;
+ throw std::logic_error(ss.str());
+ }
+
+ std::unordered_map strings_;
+ std::unordered_map lists_;
+ TemplateEnv* parent;
+};
+
+/*
+# Match $identifier or ${identifier} and replace with the 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 all lines of all elements.
+# 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.
+*/
+struct CodeTemplate {
+ /* implicit */ CodeTemplate(std::string t) : template_text(std::move(t)) {}
+
+ std::string format(const TemplateEnv& env) const {
+ std::stringstream out;
+ size_t pos = 0;
+ size_t indent = 0;
+ bool all_whitespace = true;
+ while (pos < template_text.size()) {
+ char c = template_text[pos];
+ if (c == '$') {
+ std::stringstream kss;
+ // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+ bool comma_before;
+ // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
+ bool comma_after;
+ size_t new_pos = parseKey(pos, kss, comma_before, comma_after);
+ std::string k = kss.str();
+ bool is_string = env.keyIsString(k);
+ if (all_whitespace) {
+ if (is_string)
+ emitStringWithIndents(out, indent, env.s(k));
+ else
+ emitLinesIndented(out, indent, env.v(k));
+ } else {
+ if (is_string)
+ out << env.s(k);
+ else
+ emitCommaSeparatedList(out, env.v(k), comma_before, comma_after);
+ }
+ all_whitespace = false;
+ pos = new_pos;
+ } else {
+ out << c;
+ if (!isspace(c))
+ all_whitespace = false;
+ indent++;
+ if (c == '\n') {
+ indent = 0;
+ all_whitespace = true;
+ }
+ pos++;
+ }
+ }
+ return out.str();
+ }
+
+ private:
+ using string_list = std::vector;
+ char charAt(size_t p) const {
+ if (p >= template_text.size())
+ throw std::logic_error("EOS found in key");
+ return template_text[p];
+ }
+ size_t parseKey(
+ size_t pos,
+ std::ostream& k,
+ bool& comma_before,
+ bool& comma_after) const {
+ comma_before = false;
+ comma_after = false;
+ pos++;
+ if (charAt(pos) == '{') {
+ pos++;
+ if (charAt(pos) == ',') {
+ comma_before = true;
+ pos++;
+ }
+ pos = parseIdent(pos, k);
+ if (charAt(pos) == ',') {
+ comma_after = true;
+ pos++;
+ }
+ if (charAt(pos) != '}')
+ throw std::logic_error("missing terminating '}'");
+ pos++;
+ return pos;
+ } else {
+ return parseIdent(pos, k);
+ }
+ }
+ size_t parseIdent(size_t pos, std::ostream& k) const {
+ while (pos < template_text.size() &&
+ (isalnum(template_text[pos]) || template_text[pos] == '_')) {
+ k << template_text[pos];
+ pos++;
+ }
+ return pos;
+ }
+ void emitCommaSeparatedList(
+ std::ostream& out,
+ const string_list& strings,
+ bool comma_before,
+ bool comma_after) const {
+ if (comma_before && strings.size() > 0)
+ out << ", ";
+ for (const auto i : c10::irange(strings.size())) {
+ if (i > 0)
+ out << ", ";
+ out << strings[i];
+ }
+ if (comma_after && strings.size() > 0)
+ out << ", ";
+ }
+ // These indentation functions follow the convention that they never emit
+ // leading or trailing newlines when the input string does not have leading
+ // or trailing newlines. It's the responsibility of the calling function
+ // to indent correctly in the context.
+ void emitIndent(std::ostream& out, size_t indent) const {
+ for (const auto i : c10::irange(indent)) {
+ (void)i; // Suppress unused variable warning
+ out << " ";
+ }
+ }
+ void emitStringWithIndents(
+ std::ostream& out,
+ size_t indent,
+ const std::string& str) const {
+ for (auto c : str) {
+ out << c;
+ if (c == '\n') {
+ emitIndent(out, indent);
+ }
+ }
+ }
+ void emitLinesIndented(
+ std::stringstream& out,
+ size_t indent,
+ const string_list& strings) const {
+ for (const auto i : c10::irange(strings.size())) {
+ if (i > 0)
+ emitIndent(out, indent);
+ emitStringWithIndents(out, indent, strings[i]);
+ if (i + 1 != strings.size())
+ out << "\n";
+ }
+ }
+ std::string template_text;
+};
+
+static inline std::string format(const std::string& fmt, TemplateEnv& env) {
+ return CodeTemplate(fmt).format(env);
+}
+
+}} // at::jit
diff --git a/patch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h b/patch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h
index 41067cac9a..5f1c312885 100644
--- a/patch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h
+++ b/patch/include/torch/csrc/distributed/autograd/rpc_messages/autograd_metadata.h
@@ -1,6 +1,6 @@
#pragma once
-#include
+// #include
#include
namespace torch {
diff --git a/patch/include/torch/csrc/distributed/c10d/python_comm_hook.h b/patch/include/torch/csrc/distributed/c10d/python_comm_hook.h
index 64879d78b2..ddfeb86984 100644
--- a/patch/include/torch/csrc/distributed/c10d/python_comm_hook.h
+++ b/patch/include/torch/csrc/distributed/c10d/python_comm_hook.h
@@ -23,7 +23,7 @@ class TORCH_PYTHON_API PythonCommHook : public CommHookInterface {
c10::intrusive_ptr runHook(GradBucket& bucket) override;
- std::vector parseHookResult(const c10::IValue& result) override;
+at::Tensor parseHookResult(const c10::IValue& result) override;
private:
// Only needed for stateful communication.
diff --git a/patch/include/torch/csrc/distributed/rpc/message.h b/patch/include/torch/csrc/distributed/rpc/message.h
index 3d2d623e82..95fe315db6 100644
--- a/patch/include/torch/csrc/distributed/rpc/message.h
+++ b/patch/include/torch/csrc/distributed/rpc/message.h
@@ -1,6 +1,6 @@
#pragma once
-#include
+// #include
#include
#include
diff --git a/patch/include/torch/csrc/generic/Storage.h b/patch/include/torch/csrc/generic/Storage.h
index 07389af482..a206359320 100644
--- a/patch/include/torch/csrc/generic/Storage.h
+++ b/patch/include/torch/csrc/generic/Storage.h
@@ -4,7 +4,7 @@
#include
-THP_API PyObject * THPStorage_(New)(THWStorage *ptr);
+TORCH_PYTHON_API PyObject * THPStorage_(New)(c10::intrusive_ptr ptr);
extern PyObject *THPStorageClass;
#include
diff --git a/patch/include/torch/csrc/generic/serialization.h b/patch/include/torch/csrc/generic/serialization.h
index 5f7d6406c5..326a8064f4 100644
--- a/patch/include/torch/csrc/generic/serialization.h
+++ b/patch/include/torch/csrc/generic/serialization.h
@@ -3,9 +3,10 @@
#else
template
-void THPStorage_(writeFileRaw)(THWStorage *self, io fd, bool save_size);
+void THPStorage_(writeFileRaw)(c10::StorageImpl *self, io fd, bool save_size, uint64_t element_size);
template
-THWStorage * THPStorage_(readFileRaw)(io fd, THWStorage *storage);
+c10::intrusive_ptr THPStorage_(readFileRaw)(
+ io fd, c10::intrusive_ptr storage, uint64_t element_size);
#endif
diff --git a/patch/include/torch/csrc/generic/utils.h b/patch/include/torch/csrc/generic/utils.h
index fcc5b09d0b..7ec4d68601 100644
--- a/patch/include/torch/csrc/generic/utils.h
+++ b/patch/include/torch/csrc/generic/utils.h
@@ -11,8 +11,6 @@
struct THPStorage;
struct THSPTensor;
-typedef class THPPointer THWStoragePtr;
-typedef class THPPointer THWTensorPtr;
typedef class THPPointer THPStoragePtr;
#if (!defined(THC_GENERIC_FILE)) && \
diff --git a/scripts/codegen/api/cpp.py b/scripts/codegen/api/cpp.py
index 764c0ca948..9ac627037e 100644
--- a/scripts/codegen/api/cpp.py
+++ b/scripts/codegen/api/cpp.py
@@ -58,12 +58,10 @@ def name(func: FunctionSchema, *, faithful_name_for_out_overloads: bool = False)
# types. Returns None if the type in question is not a value type.
def valuetype_type(t: Type, *, binds: ArgName) -> Optional[NamedCType]:
if isinstance(t, BaseType):
- if t.name == BaseTy.Tensor:
+ if t.name == BaseTy.Tensor or t.name == BaseTy.Scalar:
return None
- elif t.name in BaseTypeToCppMapping:
- return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
- else:
- raise AssertionError(f"unsupported type {repr(t)}")
+ # 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)
if elem is None:
diff --git a/scripts/codegen/api/native.py b/scripts/codegen/api/native.py
index 726f56cf99..09a2acad24 100644
--- a/scripts/codegen/api/native.py
+++ b/scripts/codegen/api/native.py
@@ -17,8 +17,7 @@
from typing import Union, Sequence, List, Optional
from codegen.model import (Argument, FunctionSchema, Return,
- SelfArgument, TensorOptionsArguments, Type, UseC10Dispatcher,
- assert_never)
+ SelfArgument, TensorOptionsArguments, Type)
from codegen.api.types import (ArgName, BaseCType, Binding,
ConstRefCType, NamedCType, CType, MutRefCType, ListCType,
@@ -26,6 +25,7 @@ from codegen.api.types import (ArgName, BaseCType, Binding,
deviceT, boolT, scalarTypeT)
from codegen.api import cpp
from codegen import local
+from codegen.utils import assert_never
# 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
@@ -36,13 +36,13 @@ from codegen import local
# (no translation is needed from dispatcher API to native API).
def name(func: FunctionSchema) -> str:
- func_name = str(func.name.name)
+ name = str(func.name.name)
# TODO: delete this!
if func.is_out_fn():
- func_name += '_out'
+ name += '_out'
if func.name.overload_name:
- func_name += f'_{func.name.overload_name}'
- return func_name
+ name += f'_{func.name.overload_name}'
+ return name
def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
if str(t) == 'Tensor?':
@@ -53,6 +53,10 @@ def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
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)
def returns_type(rs: Sequence[Return]) -> CType:
@@ -120,15 +124,4 @@ def arguments(func: FunctionSchema) -> List[Binding]:
args: List[Union[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, is_out=func.is_out_fn())]
-
-def native_arguments(func: FunctionSchema, dispatch: UseC10Dispatcher) -> List[Binding]:
- args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
- if dispatch is UseC10Dispatcher.full:
- args.extend(func.arguments.non_out)
- args.extend(func.arguments.out)
- else:
- args.extend(func.arguments.out)
- args.extend(func.arguments.non_out)
-
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
\ No newline at end of file
diff --git a/scripts/codegen/api/python.py b/scripts/codegen/api/python.py
index 6bbdae2411..bc20c917d6 100644
--- a/scripts/codegen/api/python.py
+++ b/scripts/codegen/api/python.py
@@ -981,16 +981,16 @@ def dispatch_lambda_return_str(f: NativeFunction) -> str:
raise RuntimeError(f'{f.func.name} returns unsupported type {return_str}')
return return_str
-def cpp_record_func(f: NativeFunction, custom=False) -> str:
- name = cpp.name(f.func)
+# def cpp_record_func(f: NativeFunction, custom=False) -> str:
+# name = cpp.name(f.func)
- if Variant.function in f.variants:
- if custom:
- record_func = f'RECORD_FUNCTION("{name}", std::vector({{}}));'
- else:
- record_func = f'// RECORD_FUNCTION("{name}")'
- return record_func
- raise RuntimeError(f'could not dispatch, neither function nor method: {f.func}')
+# if Variant.function in f.variants:
+# if custom:
+# record_func = f'RECORD_FUNCTION("{name}", std::vector({{}}));'
+# else:
+# record_func = f'// RECORD_FUNCTION("{name}")'
+# return record_func
+# raise RuntimeError(f'could not dispatch, neither function nor method: {f.func}')
def cpp_dispatch_target(f: NativeFunction, custom=False) -> str:
name = cpp.name(f.func)
@@ -998,7 +998,7 @@ def cpp_dispatch_target(f: NativeFunction, custom=False) -> str:
return f'self.{name}'
if Variant.function in f.variants:
if custom:
- namespace = 'at_npu::native::NPUNativeFunctions'
+ namespace = 'at_npu::native::XLANativeFunctions'
elif has_tensor_options(f) or f.func.name.name.base.endswith('_like'):
namespace = 'torch'
else:
diff --git a/scripts/codegen/api/types.py b/scripts/codegen/api/types.py
index 23df546ef7..d90fdbef8a 100644
--- a/scripts/codegen/api/types.py
+++ b/scripts/codegen/api/types.py
@@ -15,10 +15,10 @@
# limitations under the License.
from dataclasses import dataclass
-from typing import Optional, Union, TypeVar, List, Dict
+from typing import Optional, Union, Sequence, TypeVar, List, Set, Dict
from enum import Enum
-from codegen.model import Argument, SelfArgument, TensorOptionsArguments, BaseTy
+from codegen.model import Argument, SelfArgument, TensorOptionsArguments, BaseTy, FunctionSchema, NativeFunction
_T = TypeVar('_T')
@@ -314,3 +314,276 @@ class Binding:
class Expr:
expr: str
type: NamedCType
+
+# 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.
+@dataclass(frozen=True)
+class CppSignature:
+ # 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
+
+ # 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 implementors 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,
+ method=self.method, cpp_no_default_args=self.cpp_no_default_args)
+
+ def name(self) -> str:
+ n = cpp.name(self.func, faithful_name_for_out_overloads=self.faithful)
+ if self.fallback_binding:
+ n = f"__dispatch_{n}"
+ return n
+
+ # Render the C++ declaration for this signature
+ def decl(self, *, name: Optional[str] = None, prefix: str = "", is_redispatching_fn: bool = False) -> str:
+ returns_type = cpp.returns_type(self.func.returns).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()
+ 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: Optional[str] = None, prefix: str = "", is_redispatching_fn: bool = False) -> str:
+ returns_type = cpp.returns_type(self.func.returns).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).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).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: Optional[CppSignature]
+
+ def most_faithful_signature(self) -> CppSignature:
+ if self.faithful_signature:
+ return self.faithful_signature
+ else:
+ return self.signature
+
+ @staticmethod
+ def from_native_function(f: NativeFunction, *, method: bool, fallback_binding: bool = False) -> 'CppSignatureGroup':
+ func = f.func
+ faithful_signature: Optional[CppSignature]
+ if func.arguments.tensor_options is not None or len(func.arguments.out) > 0:
+ faithful_signature = CppSignature(
+ func=func,
+ faithful=True,
+ method=method,
+ fallback_binding=fallback_binding,
+ cpp_no_default_args=f.cpp_no_default_args
+ )
+ else:
+ faithful_signature = None
+ signature = CppSignature(
+ func=func,
+ faithful=False,
+ method=method,
+ fallback_binding=fallback_binding,
+ cpp_no_default_args=f.cpp_no_default_args
+ )
+ return CppSignatureGroup(
+ func=func,
+ signature=signature,
+ faithful_signature=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 = ""
+
+ def arguments(self) -> List[Binding]:
+ return dispatcher.arguments(self.func)
+
+ def name(self) -> str:
+ return self.prefix + dispatcher.name(self.func)
+
+ def decl(self, name: Optional[str] = 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: Optional[str] = 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)
+
+ 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 = '') -> 'DispatcherSignature':
+ return DispatcherSignature(func, prefix)
+
+@dataclass(frozen=True)
+class NativeSignature:
+ # The schema this signature is derived from
+ func: FunctionSchema
+
+ prefix: str = ""
+
+ def name(self) -> str:
+ return self.prefix + native.name(self.func)
+
+ def decl(self, name: Optional[str] = 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).cpp_type()} {name}({args_str})"
+
+ def defn(self, name: Optional[str] = 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).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).cpp_type()} (*)({args_str})'
+
+ def arguments(self) -> List[Binding]:
+ return native.arguments(self.func)
+
+ def returns_type(self) -> CType:
+ return native.returns_type(self.func.returns)
+
+ def dispatcher_exprs(self) -> List[Expr]:
+ return translate.translate(self.arguments(), dispatcher.arguments(self.func), method=False)
+
+@dataclass(frozen=True)
+class ViewInverseSignature:
+ # The NativeFunction this signature is derived from
+ f: NativeFunction
+
+ def name(self) -> str:
+ return functionalization.name(self.f, functional_op=self.f, is_reverse=True, include_namespace=False)
+
+ def decl(self) -> str:
+ return_type = functionalization.returns_type(self.f.func)
+ decls = [a.decl() for a in functionalization.inner_arguments(self.f.func, is_reverse=True)]
+ return f"static {return_type.cpp_type()} {self.name()}({', '.join(decls)});"
+
+ @staticmethod
+ def from_func(f: NativeFunction) -> 'ViewInverseSignature':
+ # Some assertions: lambdas are only used for view ops
+ assert f.is_view_op
+ assert not f.func.name.name.inplace # only functional view ops need an inverse (e.g. not transpose_())
+ return ViewInverseSignature(f)
+
+@dataclass(frozen=True)
+class FunctionalizationLambda:
+ # The NativeFunction this signature is derived from
+ f: NativeFunction
+
+ # The corresponding out-of-place variant of the above NativeFunction
+ # This only really matters for inplace-view ops.
+ # e.g. transpose_() -> transpose().
+ functional_op: NativeFunction
+
+ # are we generating the forward lambda or the reverse lambda?
+ is_reverse: bool
+
+ def captures(self) -> List[Expr]:
+ # The lambda lives inside of a kernel following the dispatcher API, so its outer context is the dispatcher arguments
+ outer_ctx = dispatcher.arguments(self.f.func)
+ capture_bindings = functionalization.capture_arguments(self.f.func, is_reverse=self.is_reverse)
+ # allow_expensive_conversions is set because we want to convert
+ # some reference types (IntArrayRef) to value types (vector).
+ capture_exprs = translate.translate(outer_ctx, capture_bindings, method=False, allow_expensive_conversions=True)
+ return capture_exprs
+
+ def decl(self) -> str:
+ return_type = functionalization.returns_type(self.f.func)
+ capture_str = ', '.join(f'{val.type.name} = {val.expr}' for val in self.captures())
+ decls = [a.decl() for a in functionalization.outer_arguments(is_reverse=self.is_reverse)]
+ return f"[{capture_str}]({', '.join(decls)}) -> {return_type.cpp_type()}"
+
+ def inner_call(self) -> str:
+ inner_call_name = functionalization.name(
+ self.f, functional_op=self.functional_op, is_reverse=self.is_reverse, include_namespace=True)
+
+ arg_ctx = functionalization.outer_arguments(is_reverse=self.is_reverse)
+ capture_ctx = functionalization.capture_arguments(self.f.func, is_reverse=self.is_reverse)
+ full_ctx = arg_ctx + capture_ctx
+
+ call_bindings = functionalization.inner_arguments(self.f.func, is_reverse=self.is_reverse)
+ maybe_index = functionalization.inner_call_index(self.f.func)
+ call_exprs = [e.expr for e in translate.translate(full_ctx, call_bindings, method=False)]
+ if not self.is_reverse and maybe_index is not None:
+ return f'{inner_call_name}({", ".join(call_exprs)})[{maybe_index.name}];'
+ else:
+ return f'{inner_call_name}({", ".join(call_exprs)});'
+
+ @staticmethod
+ def from_func(f: NativeFunction, *, functional_op: NativeFunction, is_reverse: bool) -> 'FunctionalizationLambda':
+ # Some assertions: lambdas are only used for view ops
+ assert f.is_view_op
+ assert functional_op.is_view_op
+ # functional_op corresponds to the functional-variant of f, and is only actually used if f itself is an inplace_view op.
+ assert f.func.signature() == functional_op.func.signature()
+ return FunctionalizationLambda(f, functional_op, is_reverse)
diff --git a/scripts/codegen/dest/__init__.py b/scripts/codegen/dest/__init__.py
index 408a414c54..db6c70cbec 100644
--- a/scripts/codegen/dest/__init__.py
+++ b/scripts/codegen/dest/__init__.py
@@ -14,7 +14,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-from .register_dispatch_key import RegisterDispatchKey as RegisterDispatchKey
-from .register_dispatch_key import gen_registration_helpers as gen_registration_helpers
+from .register_dispatch_key import (
+ RegisterDispatchKey as RegisterDispatchKey,
+ gen_registration_helpers as gen_registration_helpers,
+ gen_registration_headers as gen_registration_headers,
+)
from .native_functions import compute_native_function_declaration as compute_native_function_declaration
-from .register_dispatch_key_cpu import RegisterDispatchKeyCPU as RegisterDispatchKeyCPU
diff --git a/scripts/codegen/dest/register_dispatch_key.py b/scripts/codegen/dest/register_dispatch_key.py
index f81e8676df..21a5954666 100644
--- a/scripts/codegen/dest/register_dispatch_key.py
+++ b/scripts/codegen/dest/register_dispatch_key.py
@@ -40,6 +40,28 @@ from codegen.api.translate import translate
from codegen.selective_build.selector import SelectiveBuilder
+def gen_registration_headers(
+ backend_index: BackendIndex,
+ per_operator_headers: 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:
+ headers.append("#include ")
+ elif per_operator_headers:
+ headers += [
+ "#include ",
+ "#include "]
+ else:
+ headers.append("#include ")
+
+ return headers
+
def gen_create_out_helper(backend_index: BackendIndex) -> List[str]:
if backend_index.dispatch_key == DispatchKey.Meta:
# TODO: dedupe this with below
@@ -366,7 +388,7 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
device_check = RegisterDispatchKey.gen_device_check(f.device_check, list(device_check_args), name)
device_guard = "// DeviceGuard omitted" # default
- record_func_def = "torch_npu::profiler::NPURecordFunction guard;"
+ # record_func_def = "torch_npu::profiler::NPURecordFunction guard;"
if f.device_guard and is_cuda_dispatch_key(self.backend_index.dispatch_key):
has_tensor_options = any(isinstance(a.argument, TensorOptionsArguments) for a in args)
if has_tensor_options:
@@ -397,7 +419,6 @@ namespace {{
{device_check}
{device_guard}
- {record_func_def}
return {impl_name}({args_exprs_str});
}}
diff --git a/scripts/codegen/dest/register_dispatch_key_cpu.py b/scripts/codegen/dest/register_dispatch_key_cpu.py
deleted file mode 100644
index d409164e6f..0000000000
--- a/scripts/codegen/dest/register_dispatch_key_cpu.py
+++ /dev/null
@@ -1,669 +0,0 @@
-# Copyright (c) 2020 Huawei Technologies Co., Ltd
-# Copyright (c) 2019, Facebook CORPORATION.
-# All rights reserved.
-#
-# Licensed under the BSD 3-Clause License (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://opensource.org/licenses/BSD-3-Clause
-#
-# 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.
-
-import itertools
-import textwrap
-
-from dataclasses import dataclass
-from typing import List, Optional, Union, Tuple
-from typing_extensions import Literal
-
-from codegen.context import method_with_native_function, native_function_manager
-from codegen.utils import Target, map_maybe
-from codegen.model import (DispatchKey, NativeFunction,
- NativeFunctionsGroup, SchemaKind,
- TensorOptionsArguments,FunctionSchema,
- Argument, SelfArgument, TensorOptionsArguments, UseC10Dispatcher,
- DeviceCheckType, Argument, assert_never,
- is_cuda_dispatch_key, BackendIndex)
-from codegen.api.types import (BaseCType, Binding, ConstRefCType,
- Expr, MutRefCType, tensorT, NamedCType)
-from codegen.api.signature import (CppSignature, CppSignatureGroup, kernel_signature,
- NativeSignature, DispatcherSignature)
-import codegen.api.meta as meta
-import codegen.api.cpp as cpp
-import codegen.api.structured as structured
-import codegen.api.native as native_arguments
-from codegen.api.translate import translate
-from codegen.selective_build.selector import SelectiveBuilder
-from codegen.api.types import (BaseCType, TupleCType, BaseCppType)
-from .utils import transfer_args_of_wrapper_func_to_cpu, transfer_ret_of_wrapper_func_to_xla
-
-# 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 RegisterDispatchKeyCPU:
- backend_index: BackendIndex
-
- target: Union[
- Literal[Target.ANONYMOUS_DEFINITION],
- Literal[Target.NAMESPACED_DEFINITION],
- Literal[Target.NAMESPACED_DECLARATION],
- Literal[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
-
- # The namespace that the kernels are written in. This is just `at::native` for in-tree kernels.
- cpp_namespace: str
-
- # 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: Optional[str]
-
- @staticmethod
- def gen_device_check(check_type: DeviceCheckType, args: List[Argument], method_name: str) -> str:
- if check_type == DeviceCheckType.NoCheck:
- return ' // No device check\n'
-
- device_check = 'c10::optional common_device = 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: Union[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 []
- else:
- return list(map_maybe(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)
- return []
-
- def wrapper_kernel_sig(self, f: NativeFunction) -> Union[NativeSignature, DispatcherSignature]:
- # The prefix is just to ensure uniqueness. The Dispatcher API doesn't guarantee unique kernel names.
- return kernel_signature(f, self.backend_index, prefix=f'wrapper_{f.func.name.overload_name}_')
-
- def gen_out_inplace_wrapper(self, f: NativeFunction, g: Optional[NativeFunctionsGroup]) -> Optional[str]:
- 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)})'
- else:
- ret_name = return_names[0]
- updates = f'{copy_op}({func_res}, {ret_name});'
- returns = ret_name
-
- functional_sig = self.wrapper_kernel_sig(g.functional)
- wrapper_name = sig.name()
-
- return f"""\
-{sig.defn(name=wrapper_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:
- assert not self.backend_index.has_kernel(g.out), \
- "Do not explicitly specify Meta dispatch key on structured " \
- "functions, they will be automatically generated for you"
- elif self.backend_index.dispatch_key == DispatchKey.CompositeExplicitAutograd:
- assert not self.backend_index.has_kernel(g.out), \
- "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(map_maybe(lambda f: self.gen_unstructured(f, g), g.functions()))
-
- structured_gen = StructuredRegisterDispatchKey(
- self.backend_index,
- self.target,
- self.selector,
- self.rocm,
- self.cpp_namespace,
- self.class_method_name,
- g
- )
- return list(map_maybe(structured_gen.gen_one, g.functions()))
-
- def gen_unstructured(self, f: NativeFunction, g: Optional[NativeFunctionsGroup] = None) -> Optional[str]:
- with native_function_manager(f):
- inplace_meta = False
- gets_out_inplace_wrapper = False
-
- current_backend_index = None;
-
- if self.backend_index.has_kernel(f):
- current_backend_index = self.backend_index
- else:
- return None
-
- '''
- 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()
-
- if True not in ['Tensor' in str(arg.type) for arg in args]:
- return None
- if 'quant' in current_backend_index.get_kernel(f).kernel:
- return None
- if '_th_' in current_backend_index.get_kernel(f).kernel:
- return None
-
- 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)
-
- if self.target is Target.NAMESPACED_DECLARATION:
- result = f"TORCH_API {cpp_sig_group.signature.decl()};\n"
- if cpp_sig_group.faithful_signature is not None:
- result += f"TORCH_API {cpp_sig_group.faithful_signature.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 = generate_defn(cpp_sig_group.signature)
- if cpp_sig_group.faithful_signature is not None:
- result += generate_defn(cpp_sig_group.faithful_signature)
- return result
- elif self.target is Target.ANONYMOUS_DEFINITION:
- # short circuit for inplace_meta
- if inplace_meta:
- assert f.func.arguments.self_arg is not None
- 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 = current_backend_index.get_kernel(f)
- if metadata is None:
- return None
- if self.class_method_name is None:
- impl_name = f"at::{metadata.kernel}"
- else:
- impl_name = f"at::native::{metadata.kernel}"
-
- trans_to_cpu_code, args_name = transfer_args_of_wrapper_func_to_cpu(sig, f)
- args_exprs_str = ', '.join(_ for _ in args_name)
- func_call_code = f"{impl_name}({args_exprs_str})"
- return_part = transfer_ret_of_wrapper_func_to_xla(sig, func_call_code)
-
- device_check = ' // No device check\n'
-
- device_guard = "// DeviceGuard omitted" # default
- if f.device_guard and is_cuda_dispatch_key(current_backend_index.dispatch_key):
- has_tensor_options = any(isinstance(a.argument, TensorOptionsArguments) for a in args)
- if has_tensor_options:
- # kernel is creating a tensor
- device_guard = """globalContext().lazyInitCUDA();
- const DeviceGuard device_guard(device_or_default(device));"""
- 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}
- {trans_to_cpu_code}
- {return_part}
-}}
-
-}} // anonymous namespace
-"""
-
- elif self.target is Target.REGISTRATION:
- if f.manual_kernel_registration:
- return None
- else:
- payload = f"TORCH_FN({name})"
- return f'm.impl("{f.func.name}",\n{payload});\n'
- else:
- assert_never(self.target)
- return ""
-
-
-# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
-#
-# STRUCTURED
-#
-# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
-
-@dataclass(frozen=True)
-class StructuredRegisterDispatchKey(RegisterDispatchKeyCPU):
- g: NativeFunctionsGroup
-
- def gen_class_set_output(self, k: SchemaKind, parent_class: str, generate_super: bool) -> str:
- if generate_super:
- set_output_super = f"{parent_class}::set_output(output_idx, sizes, strides, options, names);"
- else:
- set_output_super = ""
- maybe_star = "*" if k is SchemaKind.functional else ""
- return f"""
-void set_output(int64_t output_idx, IntArrayRef sizes, IntArrayRef strides,
- TensorOptions options, DimnameList names) override {{
-{textwrap.indent(self.gen_class_set_output_body(k), " ")}
- if (!names.empty()) {{
- namedinference::propagate_names({maybe_star}outputs_[output_idx], names);
- }}
- // super must happen after, so that downstream can use maybe_get_output
- // to retrieve the output
-{textwrap.indent(set_output_super, " ")}
-}}
-"""
-
- def gen_class_set_output_body(self, k: SchemaKind) -> str:
- if self.backend_index.dispatch_key in [DispatchKey.CUDA, DispatchKey.CompositeExplicitAutograd]:
- 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 k is SchemaKind.functional:
- assert self.backend_index.dispatch_key in (
- DispatchKey.Meta, DispatchKey.CPU, DispatchKey.CUDA,
- DispatchKey.CompositeExplicitAutograd)
- 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);"""
- elif k is SchemaKind.out:
- return f"""{maybe_set_guard_line}
-const auto& out = outputs_[output_idx].get();
-resize_out(out, sizes, strides, options);"""
- else:
- assert_never(k)
- return ""
-
- # 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} }} {{}}"
- else:
- assert_never(k)
- return ""
-
- def gen_class(
- self, f: NativeFunction, k: SchemaKind, *, class_name: str, parent_class: str, generate_super: bool
- ) -> str:
- maybe_star = ''
- if k is SchemaKind.functional:
- output_type = "c10::ExclusivelyOwned"
- maybe_star = '*'
- elif k is SchemaKind.inplace:
- output_type = "std::reference_wrapper"
- elif k is SchemaKind.out:
- output_type = "std::reference_wrapper"
-
- if self.backend_index.dispatch_key == DispatchKey.CUDA:
- if self.rocm:
- guard_field = 'c10::hip::OptionalHIPGuardMasqueradingAsCUDA guard_;'
- else:
- guard_field = 'c10::cuda::OptionalCUDAGuard guard_;'
- elif self.backend_index.dispatch_key == DispatchKey.CompositeExplicitAutograd:
- 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(k, parent_class, generate_super), indent)}",
- " const Tensor& maybe_get_output(int64_t output_idx) override {",
- f" return {maybe_star}outputs_[output_idx];",
- " }",
- f" std::array<{output_type}, {len(f.func.returns)}> outputs_;",
- 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) -> Optional[str]:
- assert not f.manual_kernel_registration
-
- 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 CompositeExplicitAutograd 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 implementor. 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.CompositeExplicitAutograd and f.func.kind() is SchemaKind.out:
- # Never generate a default implementation for out, that's what you
- # have to define as a backend implementor
- 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
- sig = NativeSignature(f.func, prefix="wrapper_")
-
- if self.target is Target.NAMESPACED_DECLARATION:
- result = f"TORCH_API {cpp_sig_group.signature.decl()};\n"
- if cpp_sig_group.faithful_signature is not None:
- result += f"TORCH_API {cpp_sig_group.faithful_signature.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 = generate_defn(cpp_sig_group.signature)
- if cpp_sig_group.faithful_signature is not None:
- result += generate_defn(cpp_sig_group.faithful_signature)
- 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[Union[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.CompositeExplicitAutograd:
- # 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)
- assert metadata is not None
- class_name = f"structured_{metadata.kernel}_{k.name}"
- parent_class = f"{self.cpp_namespace}::structured_{metadata.kernel}"
-
- if is_cuda_dispatch_key(self.backend_index.dispatch_key):
- device_check_args = itertools.chain(
- f.func.arguments.out,
- f.func.arguments.flat_positional
- )
- sig_body.append(
- RegisterDispatchKeyCPU.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.
- for precomputed_elems in self.g.out.precomputed.replace.values():
- for arg in precomputed_elems:
- context.append(Expr(
- expr=f"precompute.{arg.name}",
- type=structured.argument_type(arg, binds=arg.name),
- ))
-
- # 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)
- maybe_star = '*' if k is SchemaKind.functional else ''
- for i, out_arg in enumerate(out_args):
- assert ConstRefCType(BaseCType(tensorT)) == out_arg.nctype.type
- context.append(Expr(
- expr=f"{maybe_star}op.outputs_[{i}]",
- # 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.CompositeExplicitAutograd:
- # 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});")
-
- # 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]).take()" # small optimization
- else:
- moved = ', '.join(f"std::move(op.outputs_[{i}]).take()" 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};")
-
- 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/scripts/codegen/dest/utils.py b/scripts/codegen/dest/utils.py
deleted file mode 100644
index c98abb49da..0000000000
--- a/scripts/codegen/dest/utils.py
+++ /dev/null
@@ -1,129 +0,0 @@
-# Copyright (c) 2020 Huawei Technologies Co., Ltd
-# All rights reserved.
-#
-# Licensed under the BSD 3-Clause License (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# https://opensource.org/licenses/BSD-3-Clause
-#
-# 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.
-
-from typing import Tuple, List
-
-from codegen.api.types import (BaseCType, TupleCType, OptionalCType, BaseCppType)
-
-from codegen.api.signature import DispatcherSignature, NativeSignature
-from codegen.model import SchemaKind, NativeFunction
-from codegen.api.native import native_arguments
-
-backend = None
-
-def transfer_args_of_wrapper_func_to_cpu(sig: DispatcherSignature, func: NativeFunction) -> Tuple[str, List[str]]:
- convert: str = f"// Convert args to cpu in order to use at::native kernel \n " \
- f"std::cout << \"Cur kernel: {sig.func.name} is running on cpu.\" << std::endl; \n "
- args_names: List[str] = []
- args = native_arguments(sig.func, func.use_c10_dispatcher)
- for arg in args:
- arg_type = str(arg.type)
- if 'Tensor' not in arg_type:
- args_names.append(f"{arg.nctype.name}")
- continue
- cpu_arg_name = f"{arg.nctype.name}_cpu"
- args_names.append(cpu_arg_name)
- if arg_type == 'at::Tensor &':
- convert += f"auto {cpu_arg_name} = {arg.nctype.name}.cpu();\n "
- elif arg_type == 'const at::Tensor &':
- convert += f"const auto {cpu_arg_name} = {arg.nctype.name}.cpu();\n "
- elif arg_type == 'const c10::optional &':
- convert += f"auto {cpu_arg_name} = (*{arg.nctype.name}).cpu();\n "
- elif arg_type == 'at::TensorList':
- convert += f"""\
-::std::vector {cpu_arg_name}({arg.nctype.name}.size());
- ::std::transform({arg.nctype.name}.begin(), {arg.nctype.name}.end(), {cpu_arg_name}.rbegin(),
- [](const Tensor & temp) {{ return temp.cpu(); }});
-"""
- else:
- assert False, f'Do not support cur type {arg.type}'
-
- return convert, args_names
-
-
-def transfer_ret_of_wrapper_func_to_xla(sig: DispatcherSignature, func_call: str) -> str:
- ret_code = ''
- if sig.func.kind() == SchemaKind.functional:
- if sig.returns_type().cpp_type() == 'at::Tensor':
- ret_code = f"return {func_call}.toBackend(Backend::{backend});"
- elif sig.returns_type().cpp_type() == '::std::vector':
- ret_code += f"""\
-auto cpu_ret = {func_call};
- ::std::vector ret_xla(cpu_ret.size());
- ::std::transform(cpu_ret.begin(), cpu_ret.end(), ret_xla.rbegin(),
- [](const Tensor & temp) {{return temp.toBackend(Backend::{backend}); }});
- return ret_xla;
- """
- elif type(sig.returns_type()) == BaseCType:
- ret_code = f"return {func_call};"
- elif type(sig.returns_type()) == TupleCType:
- ret_code += f"auto cpu_ret = {func_call}; \n "
- tuple_ele_names: List[str] = []
- for i, e in enumerate(sig.returns_type().elems):
- assert e.cpp_type() == 'at::Tensor' or type(e) == BaseCppType, f'do not support cur type {e.cpp_type()}'
- if str(e.type) == 'at::Tensor':
- ret_code += f"auto xla_tuple_ele_{i} = ::std::get<{i}>(cpu_ret).toBackend(Backend::{backend}); \n "
- tuple_ele_names.append(f"xla_tuple_ele_{i}")
- else:
- ret_code += f"const auto & tuple_ele_{i} = ::std::get<{i}>(cpu_ret); \n "
- tuple_ele_names.append(f"tuple_ele_{i}")
- tuple_ele_names_str = ','.join(_ for _ in tuple_ele_names)
- ret_code += f"return ::std::make_tuple({tuple_ele_names_str});"
- else:
- assert False, f'Do not support cur type {sig.returns_type()}'
-
- elif sig.func.kind() == SchemaKind.out:
- out_names = [_.name for _ in sig.func.arguments.out]
- ret_code = f"{func_call};\n "
- for out_name in out_names:
- ret_code += f"{out_name}.copy_({out_name}_cpu);\n "
- if sig.returns_type().cpp_type() == 'at::Tensor &':
- ret_code += f"return {out_names[0]};"
- elif type(sig.returns_type()) == TupleCType:
- return_types: List[str] = []
- for i, e in enumerate(sig.returns_type().elems):
- assert e.cpp_type() == 'at::Tensor &', f'Do not support cur type {e.cpp_type()}'
- return_types.append(e.cpp_type())
- tuple_args_str = ','.join(_ for _ in out_names)
- return_type_str = ','.join(_ for _ in return_types)
- ret_code += f"::std::tuple<{return_type_str}> ret_xla({tuple_args_str});\n " \
- f"return ret_xla;"
- else:
- assert False, f'Do not support cur type {sig.returns_type()}'
-
- elif sig.func.kind() == SchemaKind.inplace:
- ret_code = f"{func_call};\n "
- self_arg_name = sig.func.arguments.self_arg.argument.name
-
- if sig.returns_type().cpp_type() == 'at::Tensor &':
- ret_code += f"{self_arg_name}.copy_({self_arg_name}_cpu);\n "
- ret_code += f"return {self_arg_name};"
- elif sig.returns_type().cpp_type() == 'void':
- if str(sig.func.arguments.self_arg.argument.type) == 'Tensor[]':
- ret_code += f"""\n \
- for (int i = 0; i < {self_arg_name}.size(); i++) {{
- {self_arg_name}[i].copy_({self_arg_name}_cpu[i]);
- }}\n
-"""
- ret_code += f" return;"
- else:
- ret_code += f"{self_arg_name}.copy_({self_arg_name}_cpu);\n "
- ret_code += f"return;"
- else:
- assert False, f'Do not support cur type {sig.returns_type()}'
- else:
- assert False, f'Do not support cur func type {sig.func.kind()}'
-
- return ret_code
\ No newline at end of file
diff --git a/scripts/codegen/gen.py b/scripts/codegen/gen.py
index b0277cea52..dd8a9e2450 100644
--- a/scripts/codegen/gen.py
+++ b/scripts/codegen/gen.py
@@ -15,18 +15,47 @@
# limitations under the License.
import os
-import stat
-import functools
-import hashlib
-from typing import List, Dict, Optional, Set, Callable, Any, Union, Sequence, TypeVar, Iterable
-from collections import defaultdict
+from typing import List, Dict, Optional, Tuple, Set, Any, Union, Sequence, TypeVar
+from typing_extensions import Literal
+import yaml
+from collections import OrderedDict, defaultdict, namedtuple
+import argparse
+import pathlib
+import json
+from dataclasses import dataclass
-from codegen.code_template import CodeTemplate
-from codegen.model import (FunctionSchema, NativeFunction,
- NativeFunctionsGroup, OperatorName,
- SchemaKind, assert_never)
-
-from codegen.utils import concat_map
+from codegen.model import (Argument, DispatchKey, FunctionSchema,
+ Location, NativeFunction,
+ NativeFunctionsGroup, OperatorName,
+ BackendIndex, BackendMetadata,
+ OptionalType, SchemaKind, SelfArgument,
+ TensorOptionsArguments, Type, Variant,
+ is_cuda_dispatch_key,
+ is_generic_dispatch_key,
+ Tag, BaseOperatorName)
+from codegen.api.types import (Binding, CppSignature, CppSignatureGroup,
+ DispatcherSignature, NativeSignature)
+from codegen.api import cpp
+import codegen.api.dispatcher as dispatcher
+import codegen.api.native as native
+import codegen.api.meta as meta
+import codegen.api.structured as structured
+from codegen.api.translate import translate
+from codegen.selective_build.selector import SelectiveBuilder
+from codegen.utils import (
+ Target, concat_map, context, mapMaybe, YamlDumper, YamlLoader, FileManager, assert_never
+)
+from codegen.context import (method_with_native_function,
+ native_function_manager,
+ with_native_function_and_indices,
+ with_native_function)
+import codegen.dest as dest
+from codegen.gen_functionalization_type import (
+ needs_functionalization,
+ gen_functionalization_definition,
+ gen_functionalization_registration,
+ gen_functionalization_view_inverse_declaration
+)
T = TypeVar('T')
@@ -58,13 +87,64 @@ T = TypeVar('T')
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
+# 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
+
+_GLOBAL_PARSE_NATIVE_YAML_CACHE = {}
+
+# Parse native_functions.yaml into a sequence of NativeFunctions and Backend Indices.
+ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])
+def parse_native_yaml(path: str) -> ParsedYaml:
+ global _GLOBAL_PARSE_NATIVE_YAML_CACHE
+ if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
+ with open(path, 'r') as f:
+ es = yaml.load(f, Loader=LineLoader)
+ assert isinstance(es, list)
+ rs: List[NativeFunction] = []
+ bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
+ for e in es:
+ assert isinstance(e.get('__line__'), int), e
+ loc = Location(path, e['__line__'])
+ funcs = e.get('func')
+ with context(lambda: f'in {loc}:\n {funcs}'):
+ func, m = NativeFunction.from_yaml(e, loc)
+ 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,
+ index={}))
+ 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),
+ index=v)
+ _GLOBAL_PARSE_NATIVE_YAML_CACHE[path] = ParsedYaml(rs, indices)
+
+ 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[f.structured_delegate]
@@ -72,6 +152,17 @@ def error_check_native_functions(funcs: Sequence[NativeFunction]) -> None:
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"
+ if f.tag is not None and f.tag is Tag.inplace_view:
+ base_name = f.func.name.name
+ overload_name = f.func.name.overload_name
+ assert base_name.inplace, \
+ 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)
+ assert len(base_func_map[out_of_place_base_name]) > 0, \
+ 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 """
@@ -85,148 +176,815 @@ def cpp_string(s: str) -> str:
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, concat_map
+# and similar functional combinators.
+
+def static_dispatch_keys(backend: Optional[BackendIndex]) -> List[DispatchKey]:
+ if backend is None:
+ return []
+ else:
+ return [
+ backend.dispatch_key,
+ DispatchKey.CompositeImplicitAutograd,
+ DispatchKey.CompositeExplicitAutograd
+ ]
+
+def get_static_dispatch_backend(f: NativeFunction, backend_index: BackendIndex) -> Optional[DispatchKey]:
+ 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_implicit_autograd_kernel:
+ return DispatchKey.CompositeImplicitAutograd
+ return None
+
+
+def static_dispatch_ops_header(
+ f: NativeFunction,
+ backend_index: Optional[BackendIndex]) -> Optional[str]:
+ if backend_index is None or f.manual_kernel_registration:
+ return None
+
+ dispatch_key = get_static_dispatch_backend(f, backend_index)
+ return (f'#include '
+ if dispatch_key is not None else None)
+
+
+def static_dispatch_extra_headers(backend: Optional[BackendIndex], skip_tensor_include: bool = False) -> List[str]:
+ if skip_tensor_include:
+ # See Note [Avoiding Include Cycles In Static Dispatch]
+ maybe_inl = '_inl'
+ else:
+ maybe_inl = ''
+ return [f'#include '
+ for dispatch_key in static_dispatch_keys(backend)]
+
+
+def static_dispatch(
+ f: NativeFunction, cpp_sig: CppSignature,
+ *, method: bool, backend_index: Optional[BackendIndex]
+) -> Optional[str]:
+ if backend_index is None or f.manual_kernel_registration:
+ return None
+ target_sig = CppSignatureGroup.from_native_function(f, method=False, fallback_binding=False).signature
+ name = target_sig.name()
+ exprs = translate(cpp_sig.arguments(), target_sig.arguments(), method=method)
+ exprs_str = ', '.join(a.expr for a in exprs)
+
+ dispatch_key = get_static_dispatch_backend(f, backend_index)
+ if dispatch_key is not None:
+ return f'return at::{dispatch_key.lower()}::{name}({exprs_str});'
+
+ return f'TORCH_CHECK(false, "Static dispatch does not support {name} for {backend_index.dispatch_key}.");'
+
+# 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
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> Optional[str]:
+ if not self.selector.is_native_function_selected(f):
+ return None
+ return f'm.def({cpp_string(str(f.func))});\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: Union[
+ Literal[Target.DECLARATION],
+ Literal[Target.DEFINITION]
+ ]
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> str:
+ sig = DispatcherSignature.from_schema(f.func)
+ name = f.func.name.unambiguous_name()
+ call_method_name = 'call'
+ redispatch_method_name = 'redispatch'
+
+ 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_STR_INL_EXCEPT_WIN_CUDA(name, "aten::{f.func.name.name}")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "{f.func.name.overload_name}")
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, {cpp_string(str(f.func))})
+ static {sig.defn(name=call_method_name, is_redispatching_fn=False)};
+ static {sig.defn(name=redispatch_method_name, is_redispatching_fn=True)};
+}};"""
+ elif self.target is Target.DEFINITION:
+ defns = f"""
+STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA({name}, name, "aten::{f.func.name.name}")
+STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA({name}, overload_name, "{f.func.name.overload_name}")
+STATIC_CONST_STR_OUT_OF_LINE_FOR_WIN_CUDA({name}, schema_str, {cpp_string(str(f.func))})
+
+// 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()])
+ dispatcher_call = 'redispatch'
+ method_name = f'{name}::{redispatch_method_name}'
+ else:
+ dispatcher_exprs_str = ', '.join([a.name for a in sig.arguments()])
+ dispatcher_call = 'call'
+ method_name = f'{name}::{call_method_name}'
+
+ defns += f"""
+// aten::{f.func}
+{sig.defn(name=method_name, is_redispatching_fn=is_redispatching_fn)} {{
+ static auto op = create_{name}_typed_handle();
+ return op.{dispatcher_call}({dispatcher_exprs_str});
+}}
+"""
+ return defns
+ else:
+ assert_never(self.target)
+
+
+# Generates Function.h, which provides the functional public C++ API,
+# and the scaffolding to call into the dispatcher from these functions.
+@dataclass(frozen=True)
+class ComputeFunction:
+ static_dispatch_backend_index: Optional[BackendIndex]
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> Optional[str]:
+ if Variant.function not in f.variants:
+ return None
+
+ sig_group = CppSignatureGroup.from_native_function(f, method=False, fallback_binding=f.manual_cpp_binding)
+
+ def generate_defn(faithful: bool) -> str:
+ if faithful:
+ sig = sig_group.faithful_signature
+ assert sig is not None
+ else:
+ sig = sig_group.signature
+
+ # 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])
+
+ static_dispatch_block = static_dispatch(f, sig, method=False, backend_index=self.static_dispatch_backend_index)
+ if static_dispatch_block is None:
+ return f"""
+// aten::{f.func}
+TORCH_API inline {sig.decl()} {{
+ return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
+}}
+"""
+ else:
+ return f"""
+// aten::{f.func}
+TORCH_API inline {sig.decl()} {{
+ {static_dispatch_block}
+}}
+"""
+ result = generate_defn(False)
+ if sig_group.faithful_signature is not None:
+ result += generate_defn(True)
+
+ 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: Union[
+ Literal[Target.DECLARATION],
+ Literal[Target.DEFINITION]
+ ]
+ static_dispatch_backend_index: Optional[BackendIndex]
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> Optional[str]:
+ if Variant.method not in f.variants:
+ return None
+
+ assert not f.func.is_out_fn()
+ assert f.func.arguments.self_arg is not None
+
+ sig_group = CppSignatureGroup.from_native_function(f, method=True, fallback_binding=f.manual_cpp_binding)
+
+ if self.target is Target.DECLARATION:
+ result = f"{sig_group.signature.decl()} const;\n"
+ if sig_group.faithful_signature is not None:
+ result += f"{sig_group.faithful_signature.decl()} const;\n"
+ return result
+
+ if self.target is not Target.DEFINITION:
+ assert_never(self.target)
+
+ def generate_defn(faithful: bool) -> str:
+ if faithful:
+ sig = sig_group.faithful_signature
+ assert sig is not None
+ else:
+ sig = sig_group.signature
+
+ 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])
+
+ static_dispatch_block = static_dispatch(f, sig, method=True, backend_index=self.static_dispatch_backend_index)
+ if static_dispatch_block is None:
+ return f"""
+// aten::{f.func}
+inline {sig.defn(prefix="Tensor::")} const {{
+ return at::_ops::{f.func.name.unambiguous_name()}::call({exprs_str});
+}}
+"""
+ else:
+ return f"""
+// aten::{f.func}
+inline {sig.defn(prefix="Tensor::")} const {{
+ {static_dispatch_block}
+}}
+"""
+
+ result = generate_defn(faithful=False)
+ if sig_group.faithful_signature is not None:
+ result += generate_defn(faithful=True)
+
+ 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) -> Optional[str]:
+ # 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)
+
+ def generate_defn(faithful: bool) -> str:
+ if faithful:
+ sig = sig_group.faithful_signature
+ assert sig is not None
+ else:
+ sig = sig_group.signature
+
+ target_sig = DispatcherSignature.from_schema(f.func)
+ exprs = translate(sig.arguments(), target_sig.arguments())
+ exprs_str = ', '.join(['dispatchKeySet'] + [a.expr for a in exprs])
+
+ return f"""
+// aten::{f.func}
+TORCH_API inline {sig.decl(is_redispatching_fn=True)} {{
+ return at::_ops::{f.func.name.unambiguous_name()}::redispatch({exprs_str});
+}}
+"""
+ result = generate_defn(False)
+ if sig_group.faithful_signature is not None:
+ result += generate_defn(True)
+
+ 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) -> Optional[str]:
+ 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_elements = [elem for replace_list in precomputed.replace.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"\"{precomputed_elements[i].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: Union[
+ Literal[Target.DEFINITION],
+ Literal[Target.REGISTRATION]
+ ]
+
+ # Selector object to determine which operators to generate
+ # registration code for.
+ selector: SelectiveBuilder
+
+ @method_with_native_function
+ def __call__(self, f: NativeFunction) -> Optional[str]:
+ if not needs_backend_select(f, self.selector):
+ return None
+
+ name = native.name(f.func)
+ native_sig = NativeSignature(f.func)
+
+ 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: Union[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:
+ 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:
+ 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]
+
+# 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'
+ return cpp.argumenttype_type(t, mutable=False, binds='__placeholder__').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,
+ 'type': cpp.return_type(r).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,
+ 'type': cpp.argument_type(a, binds="__placeholder__").cpp_type(),
+ }
+ if a.default is not None:
+ arg['default'] = pythonify_default(cpp.default_expr(a.default, a.type))
+ 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 = set(a.name for a in f.func.arguments.flat_kwarg_only)
+ out_arg_set = 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, has_tensor_options=False)
+ ]
+
+ cpp_returns = cpp.returns_type(f.func.returns).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_registration_declarations()
+ args = dispatcher.arguments(f.func)
+ args_str = ', '.join(a.no_default().decl_registration_declarations() 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}),
+ '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
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
-@functools.lru_cache(maxsize=None)
-def _read_template(template_fn: str) -> CodeTemplate:
- return CodeTemplate.from_file(template_fn)
+def get_custom_build_selector(
+ provided_op_registration_allowlist: Optional[List[str]],
+ op_selection_yaml_path: Optional[str]) -> SelectiveBuilder:
+ assert not (
+ provided_op_registration_allowlist is not None and
+ op_selection_yaml_path is not None), (
+ "Both provided_op_registration_allowlist and " +
+ "op_selection_yaml_path can NOT be provided at the " +
+ "same time.")
+ op_registration_allowlist: Optional[Set[str]] = None
+ if provided_op_registration_allowlist is not None:
+ op_registration_allowlist = set(provided_op_registration_allowlist)
-# String hash that's stable across different executions, unlike builtin hash
-def string_stable_hash(s: str) -> int:
- sha1 = hashlib.sha1(s.encode('latin1')).digest()
- return int.from_bytes(sha1, byteorder='little')
+ 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()
-# 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:
- install_dir: str
- template_dir: str
- dry_run: bool
- filenames: Set[str]
+ return selector
- def __init__(self, install_dir: str, template_dir: str, dry_run: bool) -> None:
- self.install_dir = install_dir
- self.template_dir = template_dir
- self.filenames = set()
- self.dry_run = dry_run
-
- @staticmethod
- def _write_if_changed(filename: str, contents: str) -> None:
- old_contents: Optional[str]
- try:
- with open(filename, 'r') as f:
- old_contents = f.read()
- except IOError:
- old_contents = None
- if contents != old_contents:
- with os.fdopen(os.open(filename, os.O_RDWR|os.O_CREAT, stat.S_IWUSR|stat.S_IRUSR), "w") as f:
- f.write(contents)
-
- def write_with_template(self, filename: str, template_fn: str,
- env_callable: Callable[[], Union[str, Dict[str, Any]]]) -> None:
- filename = '{}/{}'.format(self.install_dir, filename)
- assert filename not in self.filenames, "duplicate file write {filename}"
- self.filenames.add(filename)
- if not self.dry_run:
- env = env_callable()
- if isinstance(env, dict):
- # TODO: Update the comment reference to the correct location
- if 'generated_comment' not in env:
- comment = "@" + "generated by tools/codegen/gen.py"
- comment += " from {}".format(os.path.basename(template_fn))
- env['generated_comment'] = comment
- env['legacy_th_headers'] = []
- template = _read_template(os.path.join(self.template_dir, template_fn))
- self._write_if_changed(filename, template.substitute(env))
- elif isinstance(env, str):
- self._write_if_changed(filename, env)
- else:
- assert_never(env)
-
-
- def write(self, filename: str, env_callable: Callable[[], Union[str, Union[str, Dict[str, Any]]]]) -> None:
- self.write_with_template(filename, filename, env_callable)
-
- def write_sharded(
- self,
- filename: str,
- items: Iterable[T],
- *,
- key_fn: Callable[[T], str],
- env_callable: Callable[[T], Dict[str, List[str]]],
- num_shards: int,
- base_env: Optional[Dict[str, Any]] = None,
- sharded_keys: Set[str]
- ) -> None:
-
- 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:
- assert isinstance(shard[key], list), "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():
- assert k in sharded_keys, f"undeclared sharded key {k}"
- into[k] += v
-
- 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)
-
- dot_pos = filename.rfind('.')
- if dot_pos == -1:
- dot_pos = len(filename)
- base_filename = filename[:dot_pos]
- extension = filename[dot_pos:]
-
- for shard in all_shards:
- shard_id = shard['shard_id']
- self.write_with_template(f"{base_filename}{shard_id}{extension}",
- filename,
- lambda: shard)
-
- # filenames is used to track compiled files, but FooEverything.cpp isn't meant to be compiled
- self.filenames.discard(
- f"{self.install_dir}/{base_filename}Everything{extension}")
-
- def write_outputs(self, filename: str) -> None:
- """Write a file containing the list of all outputs which are
- generated by this script.
- """
- self._write_if_changed(
- filename,
- ''.join(name + ";" for name in sorted(self.filenames)))
-
-def get_grouped_native_functions(
- native_functions: Sequence[NativeFunction]) -> Sequence[Union[NativeFunction, NativeFunctionsGroup]]:
+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()]
assert f.func.kind() not in d
d[f.func.kind()] = f
+ return pre_grouped_native_functions
+def get_grouped_native_functions(
+ native_functions: Sequence[NativeFunction]) -> Sequence[Union[NativeFunction, NativeFunctionsGroup]]:
def flatten_pre_group(d: Dict[SchemaKind, NativeFunction]) -> Sequence[Union[NativeFunction, NativeFunctionsGroup]]:
r = NativeFunctionsGroup.from_dict(d)
if r is None:
@@ -234,4 +992,728 @@ def get_grouped_native_functions(
else:
return [r]
+ # TODO: how come ValuesView isn't a Sequence lol
+ pre_grouped_native_functions = pre_group_native_functions(native_functions)
return list(concat_map(flatten_pre_group, list(pre_grouped_native_functions.values())))
+
+def gen_aggregated_headers(
+ *,
+ native_functions: Sequence[NativeFunction],
+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
+ static_dispatch_idx: Optional[BackendIndex],
+ selector: SelectiveBuilder,
+ backend_indices: Dict[DispatchKey, BackendIndex],
+ cpu_fm: FileManager,
+ cuda_fm: 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
+ structured_native_functions = [g for g in grouped_native_functions
+ if isinstance(g, NativeFunctionsGroup)]
+ 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), method_native_functions)),
+ })
+ cpu_fm.write('Operators.h', lambda: {
+ 'Operators_includes': ['#include '],
+ 'Operators_declarations': list(mapMaybe(ComputeOperators(
+ Target.DECLARATION), 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(
+ static_dispatch_backend_index=static_dispatch_idx), native_functions)),
+ })
+ cpu_fm.write('NativeFunctions.h', lambda: {
+ 'NativeFunctions_includes': ['#include '],
+ 'NativeFunctions_declarations': list(concat_map(
+ # Convert to a set first to remove duplicate kernel names.
+ # Backends are allowed to repeat kernel names; only generate the declaration once!
+ lambda f: list(OrderedDict.fromkeys(concat_map(
+ lambda backend_idx:
+ dest.compute_native_function_declaration(f, backend_idx),
+ backend_indices.values()))),
+ grouped_native_functions)),
+ })
+
+ for dispatch_key in dispatch_keys:
+ fm = cuda_fm if is_cuda_dispatch_key(dispatch_key) else cpu_fm
+ if dispatch_key in functions_keys:
+ if dispatch_key in static_dispatch_keys(static_dispatch_idx):
+ # See Note [Avoiding Include Cycles In Static Dispatch]
+ inl_headers = ''
+ else:
+ inl_headers = f'#include '
+
+ fm.write_with_template(f'{dispatch_key}Functions.h', 'DispatchKeyFunctions.h', lambda: {
+ 'dispatch_key': str(dispatch_key),
+ 'inline_headers_for_nonstatic_build': 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': list(concat_map(
+ dest.RegisterDispatchKey(
+ backend_indices[dispatch_key],
+ Target.NAMESPACED_DECLARATION,
+ selector,
+ rocm=rocm,
+ cpp_namespace='at::native',
+ class_method_name=None),
+ grouped_native_functions
+ )),
+ })
+
+ del fm
+
+def gen_per_operator_headers(
+ *,
+ native_functions: Sequence[NativeFunction],
+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
+ static_dispatch_idx: Optional[BackendIndex],
+ selector: SelectiveBuilder,
+ backend_indices: Dict[DispatchKey, BackendIndex],
+ cpu_fm: FileManager,
+ cuda_fm: 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(lambda: [])
+ for fn in native_functions:
+ functions_by_root_name[fn.root_name].append(fn)
+
+ grouped_functions_by_root_name: Dict[str, List[Union[NativeFunction, NativeFunctionsGroup]]] = defaultdict(lambda: [])
+ 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), 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(
+ static_dispatch_backend_index=static_dispatch_idx), 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)),
+ })
+
+
+ ops_fm.write_with_template(
+ f'{name}_native.h', 'NativeFunction.h', lambda: {
+ 'extra_includes': (f'#include '
+ if is_structured else []),
+ 'native_function_declarations': list(concat_map(
+ # Convert to a set first to remove duplicate kernel names.
+ # Backends are allowed to repeat kernel names; only generate the declaration once!
+ lambda f: list(OrderedDict.fromkeys(concat_map(
+ lambda backend_idx:
+ dest.compute_native_function_declaration(f, backend_idx),
+ backend_indices.values()))),
+ grouped_functions)),
+ })
+
+ for category, suffix in [
+ ('Functions', ''),
+ ('Operators', '_ops'),
+ ('NativeMetaFunctions', '_meta'),
+ ('NativeFunctions', '_native'),
+ ]:
+ cpu_fm.write(f'{category}.h', lambda: {
+ 'static_dispatch_extra_headers': [],
+ 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(concat_map(
+ dest.RegisterDispatchKey(
+ backend_indices[dispatch_key],
+ Target.NAMESPACED_DECLARATION,
+ selector,
+ rocm=rocm,
+ cpp_namespace='at::native',
+ class_method_name=None),
+ 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 = cuda_fm if is_cuda_dispatch_key(dispatch_key) else cpu_fm
+ if dispatch_key in static_dispatch_keys(static_dispatch_idx):
+ # See Note [Avoiding Include Cycles In Static Dispatch]
+ inl_headers = ''
+ else:
+ inl_headers = f'#include '
+
+ fm.write_with_template(f'{dispatch_key}Functions.h', 'DispatchKeyFunctions.h', lambda: {
+ 'dispatch_key': str(dispatch_key),
+ 'inline_headers_for_nonstatic_build': 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],
+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
+ static_dispatch_idx: Optional[BackendIndex],
+ selector: SelectiveBuilder,
+ backend_indices: Dict[DispatchKey, BackendIndex],
+ core_fm: FileManager,
+ cpu_fm: FileManager,
+ cuda_fm: 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,
+ cuda_fm=cuda_fm,
+ 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,
+ static_dispatch_idx=static_dispatch_idx,
+ selector=selector,
+ backend_indices=backend_indices,
+ cpu_fm=cpu_fm,
+ cuda_fm=cuda_fm,
+ dispatch_keys=dispatch_keys,
+ functions_keys=functions_keys,
+ rocm=rocm,
+ )
+
+ def static_dispatch_method_headers() -> List[str]:
+ return list(mapMaybe(
+ lambda fn: static_dispatch_ops_header(fn, backend_index=static_dispatch_idx),
+ [fn for fn in native_functions if Variant.method in fn.variants]))
+
+
+ core_fm.write('TensorBody.h', lambda: {
+ 'static_dispatch_ops_headers': (
+ static_dispatch_method_headers() if per_operator_headers
+ else static_dispatch_extra_headers(static_dispatch_idx, skip_tensor_include=True)),
+ 'tensor_method_declarations': list(mapMaybe(ComputeTensorMethod(
+ target=Target.DECLARATION, static_dispatch_backend_index=static_dispatch_idx), native_functions)),
+ 'tensor_method_definitions': list(mapMaybe(ComputeTensorMethod(
+ target=Target.DEFINITION, static_dispatch_backend_index=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('FunctionalInverses.h', lambda: {
+ 'view_inverse_declarations': list(mapMaybe(gen_functionalization_view_inverse_declaration, native_functions))
+ })
+
+
+ def gen_aten_interned_strings() -> Dict[str, str]:
+ attrs = 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)
+
+ for arg in func.func.schema_order_arguments():
+ attrs.add(arg.name)
+
+ # These are keywords in C++, so aren't valid symbol names
+ # https://en.cppreference.com/w/cpp/language/operator_alternative
+ names -= set(['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_source_files(
+ *,
+ native_functions: Sequence[NativeFunction],
+ grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
+ static_dispatch_idx: Optional[BackendIndex],
+ selector: SelectiveBuilder,
+ backend_indices: Dict[DispatchKey, BackendIndex],
+ core_fm: FileManager,
+ cpu_fm: FileManager,
+ cuda_fm: FileManager,
+ dispatch_keys: Sequence[DispatchKey],
+ functions_keys: Set[DispatchKey],
+ rocm: bool,
+ force_schema_registration: bool,
+ per_operator_headers: bool,
+) -> None:
+ extra_cuda_headers = '''\
+#include
+#include
+#include
+#include '''
+ if rocm:
+ extra_cuda_headers = '''\
+#include
+#include