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 ->![](figures/icon-note.gif) **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 - ``` - - >![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/docs/en/PyTorch%20Network%20Model%20Porting%20and%20Training%20Guide/public_sys-resources/icon-notice.gif) **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: - >![](figures/icon-note.gif) **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. - -![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/FAQ.png) - -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. -![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/zh-cn_image_0000001190081735.png) - -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. - -![Input Image Description](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png) - -## 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 - - - ->![](figures/icon-note.gif) **说明:** ->若安装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 - ``` - - >![](figures/icon-notice.gif) **须知:** - >其中“--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/“。 - - >![](figures/icon-note.gif) **说明:** - >本步骤为用户在需要用到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参数,导致无法正常启动实例。 - -![](figures/FAQ.png) - -请用户参考以下命令,重启容器。 - -```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"。 -![](figures/zh-cn_image_0000001190081735.png) - -安装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会被解决。 - -![输入图片说明](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png) - -## 在编译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 +#include +#include ''' + + for dispatch_key in dispatch_keys: + fm = cuda_fm if is_cuda_dispatch_key(dispatch_key) else cpu_fm + + if per_operator_headers: + def operator_headers() -> List[str]: + headers = [] + for fn in native_functions: + is_registered = backend_index.has_kernel(fn) or ( + fn.structured and dispatch_key in + (DispatchKey.Meta, DispatchKey.CompositeExplicitAutograd)) + if not is_registered: + continue + + headers.append(f"#include ") + if dispatch_key == DispatchKey.CompositeExplicitAutograd: + headers.append(f"#include ") + if dispatch_key in functions_keys: + headers.append( + f"#include ") + + return sorted(set(headers)) + else: + def operator_headers() -> List[str]: + headers = ["#include "] + if dispatch_key == DispatchKey.CompositeExplicitAutograd: + headers.append("#include ") + if dispatch_key in functions_keys: + headers.append(f"#include ") + return headers + + backend_index = backend_indices[dispatch_key] + dispatch_namespace = str(dispatch_key).lower() + fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: { + 'extra_cuda_headers': extra_cuda_headers if is_cuda_dispatch_key(dispatch_key) else '', + 'external_backend_headers': '', + 'dispatch_headers': dest.gen_registration_headers(backend_index, per_operator_headers), + 'ops_headers': operator_headers(), + 'DispatchKey': dispatch_key, + 'dispatch_namespace': dispatch_key.lower(), + 'dispatch_helpers': dest.gen_registration_helpers(backend_index), + 'dispatch_namespaced_definitions': list(concat_map( + dest.RegisterDispatchKey( + backend_index, + Target.NAMESPACED_DEFINITION, + selector, + rocm=rocm, + cpp_namespace='at::native', + class_method_name=None), + grouped_native_functions + )), + 'dispatch_anonymous_definitions': list(concat_map( + dest.RegisterDispatchKey( + backend_index, + Target.ANONYMOUS_DEFINITION, + selector, + rocm=rocm, + cpp_namespace='at::native', + class_method_name=None), + grouped_native_functions + )), + 'dispatch_registrations': list(concat_map( + dest.RegisterDispatchKey( + backend_index, + Target.REGISTRATION, + selector, + rocm=rocm, + cpp_namespace='at::native', + class_method_name=None), + grouped_native_functions + )), + }) + + # BackendSelect is generated specially + def gen_backend_select() -> Dict[str, List[str]]: + relevant_fns = [fn for fn in native_functions if needs_backend_select(fn, selector)] + return { + 'ops_headers': [f'#include ' for fn in relevant_fns], + 'backend_select_method_definitions': + list(mapMaybe(ComputeBackendSelect(Target.DEFINITION, selector), relevant_fns)), + 'backend_select_function_registrations': + list(mapMaybe(ComputeBackendSelect(Target.REGISTRATION, selector), relevant_fns)), + } + cpu_fm.write('RegisterBackendSelect.cpp', gen_backend_select) + + schema_selector = selector + if force_schema_registration: + schema_selector = SelectiveBuilder.get_nop_selector() + cpu_fm.write('RegisterSchema.cpp', lambda: { + 'schema_registrations': list(mapMaybe(RegisterSchema(schema_selector), native_functions)), + }) + + def key_func(fn: Union[NativeFunction, NativeFunctionsGroup]) -> str: + return fn.root_name + + cpu_fm.write_sharded( + 'Operators.cpp', + native_functions, + key_fn=key_func, + env_callable=lambda fn: { + 'operator_headers': [f'#include '], + 'definitions': [ComputeOperators(Target.DEFINITION)(fn)]}, + num_shards=5, + sharded_keys={'operator_headers', 'definitions'} + ) + + cpu_fm.write('Functions.cpp', lambda: {}) + + core_fm.write('TensorMethods.cpp', lambda: {}) + + core_fm.write('ATenOpList.cpp', lambda: { + 'aten_ops': list(mapMaybe(compute_aten_op, native_functions)), + }) + + # We need to easily map from [inplace_op_name] -> [functional_op] for the functionalization pass, + # so here I generate a mapping from every operator name to its corresponding functional NativeFunction (if it exist). + pre_grouped_d: Dict[FunctionSchema, Dict[SchemaKind, NativeFunction]] = pre_group_native_functions(native_functions) + to_functional_op: Dict[OperatorName, Optional[NativeFunction]] = { + k: v for d in [ + {f.func.name: pre_grouped_d[func][SchemaKind.functional] + if SchemaKind.functional in pre_grouped_d[func].keys() else None + for f in pre_grouped_d[func].values()} + for func in pre_grouped_d.keys()] + for k, v in d.items() + } + + + def functionalization_env_callable( + g: Union[NativeFunction, NativeFunctionsGroup] + ) -> Dict[str, List[str]]: + functions = [g] if isinstance(g, NativeFunction) else list(g.functions()) + functions_needing_functionalization = [ + fn for fn in functions if needs_functionalization(selector, fn)] + return { + 'ops_headers': ([ + f"#include ", + f"#include ", + ] if functions_needing_functionalization else []), + 'func_definitions': list(mapMaybe( + lambda f: gen_functionalization_definition(selector, f, to_functional_op[f.func.name]), + functions_needing_functionalization)), + 'func_registrations': list(mapMaybe( + lambda f: gen_functionalization_registration( + selector, f, backend_indices[DispatchKey.CompositeImplicitAutograd]), + functions_needing_functionalization)), + } + + + cpu_fm.write_sharded( + 'RegisterFunctionalization.cpp', + grouped_native_functions, + key_fn=key_func, + env_callable=functionalization_env_callable, + num_shards=4, + sharded_keys={'ops_headers', 'func_definitions', 'func_registrations'} + ) + + +def gen_declarations_yaml( + cpu_fm: FileManager, + native_functions: Sequence[NativeFunction]) -> None: + cpu_fm.write('Declarations.yaml', lambda: + format_yaml([compute_declaration_yaml(f) for f in native_functions])) + +def main() -> None: + parser = argparse.ArgumentParser(description='Generate ATen source files') + parser.add_argument( + '-s', + '--source-path', + help='path to source directory for ATen', + default='aten/src/ATen') + parser.add_argument( + '-o', + '--output-dependencies', + help='output a list of dependencies into the given file and exit') + parser.add_argument( + '--dry-run', action='store_true', + help='run without writing any files (still updates outputs)') + parser.add_argument( + '--per-operator-headers', action='store_true', + help='generate separate headers per operator in ATen/ops') + parser.add_argument( + '-d', '--install_dir', help='output directory', + default='build/aten/src/ATen') + parser.add_argument( + '--rocm', + action='store_true', + help='reinterpret CUDA as ROCm/HIP and adjust filepaths accordingly') + # TODO: --op_registration_whitelist will be removed when all call-sites + # for gen.py are moved over to using the operator YAML file for mobile + # custom build. + parser.add_argument( + '--op_registration_whitelist', + nargs='*', + help='filter op registrations by the whitelist (if set); ' + 'each item is `namespace`::`operator name` without overload name; ' + 'e.g.: aten::empty aten::conv2d ...') + parser.add_argument( + '--op_selection_yaml_path', + help='Provide a path to the operator selection (for custom build) YAML ' + 'that contains the information about the set of selected operators ' + 'and their categories (training, ...). Each operator is either a ' + 'full operator name with overload or just a bare operator name. ' + 'The operator names also contain the namespace prefix (e.g. aten::)') + parser.add_argument( + '--backend_whitelist', + nargs='*', + help='filter dispatch backend by the whitelist (if set), ' + 'e.g.: CPU CUDA QuantizedCPU ...') + parser.add_argument( + '--static_dispatch_backend', + help='generate static dispatch code for the specific backend (if set)') + parser.add_argument( + '--force_schema_registration', + action='store_true', + help='force it to generate schema-only registrations for all ops, including' + 'those that are not listed on --op_registration_whitelist') + parser.add_argument( + '--generate', + type=str, + nargs='*', + choices=['headers', 'sources', 'declarations_yaml'], + default=['headers', 'sources', 'declarations_yaml'], + help='Generate only a subset of files') + options = parser.parse_args() + + selector = get_custom_build_selector( + options.op_registration_whitelist, + options.op_selection_yaml_path, + ) + + native_yaml_path = os.path.join(options.source_path, 'native/native_functions.yaml') + parsed_yaml = parse_native_yaml(native_yaml_path) + native_functions, backend_indices = parsed_yaml.native_functions, parsed_yaml.backend_indices + grouped_native_functions = get_grouped_native_functions(native_functions) + + template_dir = os.path.join(options.source_path, "templates") + + # NB: It is mandatory to NOT use os.path.join here, as the install directory + # will eventually be ingested by cmake, which does not respect Windows style + # path slashes. If you switch this to use os.path.join, you'll get an error + # like: + # + # Syntax error in cmake code when parsing string + # + # C:/Jenkins/workspace/pytorch-builds/pytorch-win-ws2016-cuda9-cudnn7-py3-build/build/aten/src/ATen\core/TensorMethods.h + # + # Invalid character escape '\c'. + core_install_dir = f'{options.install_dir}/core' + pathlib.Path(core_install_dir).mkdir(parents=True, exist_ok=True) + ops_install_dir = f'{options.install_dir}/ops' + pathlib.Path(ops_install_dir).mkdir(parents=True, exist_ok=True) + + def make_file_manager(install_dir: str) -> FileManager: + return FileManager(install_dir=install_dir, template_dir=template_dir, dry_run=options.dry_run) + + core_fm = make_file_manager(core_install_dir) + cpu_fm = make_file_manager(options.install_dir) + cuda_fm = make_file_manager(options.install_dir) + ops_fm = make_file_manager(ops_install_dir) + + extra_cuda_headers = '''\ +#include +#include +#include +#include ''' + if options.rocm: + extra_cuda_headers = '''\ +#include +#include +#include +#include ''' + + dispatch_keys = [ + DispatchKey.CPU, + DispatchKey.SparseCPU, + DispatchKey.SparseCsrCPU, + DispatchKey.MkldnnCPU, + DispatchKey.CUDA, + DispatchKey.SparseCUDA, + DispatchKey.SparseCsrCUDA, + DispatchKey.QuantizedCPU, + DispatchKey.QuantizedCUDA, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeExplicitAutograd, + # Meta is a magic key: it is automatically generated for structured + # kernels + DispatchKey.Meta, + DispatchKey.ZeroTensor, + ] + # Only a limited set of dispatch keys get CPUFunctions.h headers generated + # for them; this is the set + functions_keys = { + DispatchKey.CPU, + DispatchKey.CUDA, + DispatchKey.CompositeImplicitAutograd, + DispatchKey.CompositeExplicitAutograd, + DispatchKey.Meta, + } + if options.backend_whitelist: + dispatch_keys = [k for k in dispatch_keys if is_generic_dispatch_key(k) or str(k) in options.backend_whitelist] + + static_dispatch_idx: Optional[BackendIndex] = None + if options.static_dispatch_backend: + static_dispatch_idx = backend_indices[DispatchKey.parse(options.static_dispatch_backend)] + + if 'sources' in options.generate: + gen_source_files( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + core_fm=core_fm, + cpu_fm=cpu_fm, + cuda_fm=cuda_fm, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=options.rocm, + force_schema_registration=options.force_schema_registration, + per_operator_headers=options.per_operator_headers, + ) + + if 'headers' in options.generate: + gen_headers( + native_functions=native_functions, + grouped_native_functions=grouped_native_functions, + static_dispatch_idx=static_dispatch_idx, + selector=selector, + backend_indices=backend_indices, + core_fm=core_fm, + cpu_fm=cpu_fm, + cuda_fm=cuda_fm, + ops_fm=ops_fm, + dispatch_keys=dispatch_keys, + functions_keys=functions_keys, + rocm=options.rocm, + per_operator_headers=options.per_operator_headers, + ) + + if 'declarations_yaml' in options.generate: + gen_declarations_yaml( + native_functions=native_functions, + cpu_fm=cpu_fm) + + if options.output_dependencies: + depfile_path = pathlib.Path(options.output_dependencies).resolve() + depfile_name = depfile_path.name + depfile_stem = depfile_path.stem + + for fm, prefix in [ + (cpu_fm, ""), + (core_fm, "core_"), + (cuda_fm, "cuda_"), + (ops_fm, "ops_"), + ]: + varname = prefix + depfile_stem + path = depfile_path.parent / (prefix + depfile_name) + fm.write_outputs(varname, str(path)) + + +if __name__ == '__main__': + main() diff --git a/scripts/codegen/gen_backend_stubs.py b/scripts/codegen/gen_backend_stubs.py index e75d95c5e7..f1c3260680 100644 --- a/scripts/codegen/gen_backend_stubs.py +++ b/scripts/codegen/gen_backend_stubs.py @@ -22,34 +22,41 @@ from collections import namedtuple, Counter, defaultdict from typing import List, Dict, Union, Sequence, Optional import yaml -from codegen.gen import FileManager, get_grouped_native_functions, error_check_native_functions -from codegen.model import (BackendIndex, BackendMetadata, DispatchKey, +from codegen.gen import FileManager, get_grouped_native_functions, error_check_native_functions, LineLoader, parse_native_yaml +from codegen.model import (BackendIndex, BackendMetadata, DispatchKey, Location, is_cuda_dispatch_key, NativeFunction, NativeFunctionsGroup, OperatorName) from codegen.selective_build.selector import SelectiveBuilder -from codegen.utils import Target, concat_map, context +from codegen.utils import Target, concat_map, context, YamlLoader from codegen.context import native_function_manager import codegen.dest as dest -import codegen.dest.utils as utils import codegen.api.dispatcher as dispatcher from codegen.api.signature import DispatcherSignature +# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key. +# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping) # Create backend_indices map for func retrieval with the key of each func we supported. -def create_backend_index(backend_ops: List[str], - dispatch_key: DispatchKey, - native_funcs_map: Dict[OperatorName, NativeFunction]) -> BackendIndex: +def create_backend_index( + backend_ops: List[str], + dispatch_key: DispatchKey, + native_functions_map: Dict[OperatorName, NativeFunction], + *, + use_out_as_primary: bool, + use_device_guard: bool + ) -> BackendIndex: metadata: Dict[OperatorName, BackendMetadata] = {} for op in backend_ops: op_name = OperatorName.parse(op) - assert op_name in native_funcs_map, f"Found an invalid operator name: {op_name}" + assert op_name in native_functions_map, f"Found an invalid operator name: {op_name}" # See Note [External Backends Follow Dispatcher API] - kernel_name = dispatcher.name(native_funcs_map[op_name].func) + kernel_name = dispatcher.name(native_functions_map[op_name].func) # TODO: allow structured external backends later. m = BackendMetadata(kernel=kernel_name, structured=False) metadata[op_name] = m return BackendIndex( dispatch_key=dispatch_key, - use_out_as_primary=False, + use_out_as_primary=use_out_as_primary, external=True, + device_guard=use_device_guard, index=metadata) # Check whether the function is placed at the wrong place. @@ -88,14 +95,16 @@ def parse_native_and_custom_yaml(path: str, custom_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.safe_load(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 {path}:\n {funcs}'): - func, m = NativeFunction.from_yaml(e) + with context(lambda: f'in {loc}:\n {funcs}'): + func, m = NativeFunction.from_yaml(e, loc) rs.append(func) BackendIndex.grow_index(bs, m) @@ -112,29 +121,41 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml: f_str.write(line) f_str.seek(0) - custom_es = yaml.safe_load(f_str) + custom_es = yaml.load(f_str, Loader=LineLoader) for e in custom_es: + assert isinstance(e.get('__line__'), int), e + loc = Location(custom_path, e['__line__']) funcs = e.get('func') - with context(lambda: f'in {custom_path}:\n {funcs}'): - func, m = NativeFunction.from_yaml(e) + 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, index={})) + 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, index=v) + 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] # Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key. -# Returns a Tuple of (true_backend, backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping) +# Returns a Tuple of (backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping) ParsedExternalYaml = namedtuple('ParsedExternalYaml', [ - 'true_backend', 'backend_key', 'autograd_key', 'cpp_namespace', 'backend_indices']) + 'backend_key', 'autograd_key', 'cpp_namespace', 'backend_indices']) def parse_backend_yaml( backend_yaml_path: str, grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]], @@ -143,31 +164,42 @@ def parse_backend_yaml( native_functions_map: Dict[OperatorName, NativeFunction] = { f.func.name: f - for f in concat_map(lambda f: [f] if isinstance(f, NativeFunction) - else list(f.functions()), grouped_native_functions) + for f in concat_map(lambda f: [f] if isinstance(f, NativeFunction) else list(f.functions()), grouped_native_functions) } with open(backend_yaml_path, 'r') as f: - yaml_values = yaml.safe_load(f) + yaml_values = yaml.load(f, Loader=YamlLoader) assert isinstance(yaml_values, dict) - valid_keys = ['backend', 'cpp_namespace', 'extra_headers', 'supported', 'autograd', 'custom', 'custom_autograd'] + valid_keys = ['backend', 'cpp_namespace', 'extra_headers', 'supported', 'autograd', 'full_codegen', 'custom', 'custom_autograd'] - true_backend = yaml_values.pop('backend', None) - assert true_backend is not None, 'You must provide a value for "backend"' - backend = "NPU" + backend = yaml_values.pop('backend', None) + assert backend is not None, 'You must provide a value for "backend"' cpp_namespace = yaml_values.pop('cpp_namespace', None) assert cpp_namespace is not None, 'You must provide a value for "cpp_namespace"' + # Mostly just defaulting to false to stick with LazyTensor convention. + use_out_as_primary = yaml_values.pop('use_out_as_primary', False) + assert isinstance(use_out_as_primary, bool), \ + f'You must provide either True or False for use_out_as_primary. Provided: {use_out_as_primary}' + + use_device_guard = yaml_values.pop('device_guard', False) + assert isinstance(use_device_guard, bool), \ + f'You must provide either True or False for device_guard. Provided: {use_device_guard}' + supported = yaml_values.pop('supported', []) if supported is None: supported = [] # Allow an empty list of supported ops - assert isinstance(supported, list), f'expected "supported" to be a list, but got type {type(supported)}' + assert isinstance(supported, list), f'expected "supported" to be a list, but got: {supported} (of type {type(supported)})' supported_autograd = yaml_values.pop('autograd', []) - assert isinstance(supported_autograd, list), f'expected "autograd" to be a list, but got: {supported_autograd}' + assert isinstance(supported, list), f'expected "autograd" to be a list, but got: {supported_autograd}' + # full_codegen is ignored by parse_backend_yaml, and re-parsed in gen_lazy_tensor.py + full_codegen = yaml_values.pop('full_codegen', []) + supported.extend(full_codegen) + custom = yaml_values.pop('custom', []) assert isinstance(custom, list), f'expected "autograd" to be a list, but got: {custom}' for item in custom: @@ -190,7 +222,8 @@ Only the following keys are supported: {", ".join(valid_keys)}' with context(lambda: f'The provided value for "backend" must be a valid DispatchKey, but got {backend}.'): backend_key = DispatchKey.parse(backend) - backend_idx = create_backend_index(supported, backend_key, native_functions_map) + backend_idx = create_backend_index( + supported, backend_key, native_functions_map, use_out_as_primary=use_out_as_primary, use_device_guard=use_device_guard) assert backend_key not in backend_indices backend_indices[backend_key] = backend_idx @@ -200,12 +233,13 @@ Only the following keys are supported: {", ".join(valid_keys)}' the behavior of autograd for some operators on your backend. However "Autograd{backend}" is not a valid DispatchKey.'): autograd_key = DispatchKey.parse(f'Autograd{backend}') - autograd_idx = create_backend_index(supported_autograd, autograd_key, native_functions_map) + autograd_idx = create_backend_index( + supported_autograd, autograd_key, native_functions_map, use_out_as_primary=use_out_as_primary, use_device_guard=use_device_guard) assert autograd_key not in backend_indices backend_indices[autograd_key] = autograd_idx check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions) - return ParsedExternalYaml(true_backend, backend_key, autograd_key, cpp_namespace, backend_indices) + return ParsedExternalYaml(backend_key, autograd_key, cpp_namespace, backend_indices) # Double-check the functions we supported to see whether there exists something mismatch. def error_on_missing_kernels( @@ -235,8 +269,7 @@ def error_on_missing_kernels( expected_backend_op_names: List[OperatorName] = \ list(backend_indices[backend_key].index.keys()) + list(backend_indices[autograd_key].index.keys()) - expected_backend_native_funcs: List[NativeFunction] = \ - [f for f in native_functions if f.func.name in expected_backend_op_names] + expected_backend_native_funcs: List[NativeFunction] = [f for f in native_functions if f.func.name in expected_backend_op_names] expected_backend_kernel_name_counts: Dict[str, List[NativeFunction]] = defaultdict(list) for native_f in expected_backend_native_funcs: expected_backend_kernel_name_counts[dispatcher.name(native_f.func)].append(native_f) @@ -265,28 +298,88 @@ but expected {expected_overload_count} kernel(s). The expected function schemas if unsupported_ops_list != "": print(f"Unsupported Ops List:\n{unsupported_ops_list}") -def error_on_cpu_kernels( - cur_backend_key: DispatchKey, - native_functions: Sequence[NativeFunction], +def gen_dispatchkey_nativefunc_headers( + fm: FileManager, + class_name: str, + cpp_namespace: str, backend_indices: Dict[DispatchKey, BackendIndex], -) -> None: + grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]], + backend_dispatch_key: DispatchKey, + autograd_dispatch_key: Optional[DispatchKey]) -> None: + assert class_name is not None + generated_comment = 'Autogenerated file by gen_backend_stubs.py. Do not edit directly!' - expected_backend_op_names: List[OperatorName] = \ - list(backend_indices[cur_backend_key].index.keys()) - expected_backend_native_funcs: List[NativeFunction] = \ - [f for f in native_functions if f.func.name in expected_backend_op_names] - expected_backend_kernel_name_counts: Dict[str, List[NativeFunction]] = defaultdict(list) - for native_f in expected_backend_native_funcs: - expected_backend_kernel_name_counts[dispatcher.name(native_f.func)].append(native_f) + # Convert to a set first to remove duplicate kernel names. + # Backends are allowed to repeat kernel names; only generate the declaration once! + # Sort for deterministic output. + backend_declarations = list(sorted(set(concat_map( + lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]), + grouped_native_functions)))) + autograd_declarations = list(sorted(set(concat_map( + lambda f: [] if autograd_dispatch_key is None else + dest.compute_native_function_declaration(f, backend_indices[autograd_dispatch_key]), + grouped_native_functions)))) - for expected_name, funcs in expected_backend_kernel_name_counts.items(): - for func in funcs: - backend_indices[DispatchKey.CPU].index.pop(func.func.name, None) + fm.write_with_template(f'{backend_dispatch_key}NativeFunctions.h', 'DispatchKeyNativeFunctions.h', lambda: { + 'generated_comment': generated_comment, + 'cpp_namespace': cpp_namespace, + 'class_name': class_name, + 'dispatch_declarations': backend_declarations + autograd_declarations, + }) +def gen_dispatcher_registrations( + fm: FileManager, + output_dir: str, + cpp_namespace: str, + backend_indices: Dict[DispatchKey, BackendIndex], + grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]], + backend_dispatch_key: DispatchKey, + dispatch_key: DispatchKey, + selector: 'SelectiveBuilder') -> None: + backend_index = backend_indices[dispatch_key] + fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: { + 'extra_cuda_headers': '', + 'external_backend_headers': f'#include "{output_dir}/{backend_dispatch_key}NativeFunctions.h"', + 'ops_headers': '#include ', + 'namespaced_headers': '', + 'DispatchKey': dispatch_key, + 'dispatch_namespace': dispatch_key.lower(), + 'dispatch_headers': dest.gen_registration_headers(backend_index, per_operator_headers=False), + 'dispatch_helpers': dest.gen_registration_helpers(backend_index), + 'dispatch_namespaced_definitions': list(concat_map( + dest.RegisterDispatchKey( + backend_index, + Target.NAMESPACED_DEFINITION, + selector, + rocm=False, + cpp_namespace=cpp_namespace, + class_method_name=f'{backend_dispatch_key}NativeFunctions'), + grouped_native_functions + )), + 'dispatch_anonymous_definitions': list(concat_map( + dest.RegisterDispatchKey( + backend_index, + Target.ANONYMOUS_DEFINITION, + selector, + rocm=False, + cpp_namespace=cpp_namespace, + class_method_name=f'{backend_dispatch_key}NativeFunctions'), + grouped_native_functions + )), + 'dispatch_registrations': list(concat_map( + dest.RegisterDispatchKey( + backend_index, + Target.REGISTRATION, + selector, + rocm=False, + cpp_namespace=cpp_namespace, + class_method_name=f'{dispatch_key}NativeFunctions'), + grouped_native_functions + )), + }) + def main() -> None: parser = argparse.ArgumentParser(description='Generate backend stub files') - parser.add_argument( - '--to_cpu', type=str, default="TRUE", help='move op which npu does not support to cpu') parser.add_argument( '-s', '--source_yaml', @@ -299,9 +392,9 @@ def main() -> None: '--impl_path', type=str, default=None, help='path to the source C++ file containing kernel definitions') options = parser.parse_args() - run(options.to_cpu, options.source_yaml, options.output_dir, options.dry_run, options.impl_path) + run(options.source_yaml, options.output_dir, options.dry_run, options.impl_path) -def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path: Optional[str]) -> None: +def run(source_yaml: str, output_dir: str, dry_run: bool, impl_path: Optional[str]) -> None: template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates") @@ -315,131 +408,30 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path native_functions, backend_indices = parsed_yaml.native_functions, parsed_yaml.backend_indices grouped_native_functions = get_grouped_native_functions(native_functions) parsed_backend_yaml = parse_backend_yaml(source_yaml, grouped_native_functions, backend_indices) - true_backend = parsed_backend_yaml.true_backend - utils.backend = true_backend backend_key = parsed_backend_yaml.backend_key autograd_key = parsed_backend_yaml.autograd_key cpp_namespace = parsed_backend_yaml.cpp_namespace backend_indices = parsed_backend_yaml.backend_indices selector = SelectiveBuilder.get_nop_selector() - if backend_key is not None: - backend_dispatch_key: DispatchKey = backend_key - autograd_dispatch_key: DispatchKey = autograd_key - class_name = backend_indices[backend_dispatch_key].native_function_class_name() - if impl_path is not None: - error_on_missing_kernels(native_functions, backend_indices, backend_key, autograd_key, impl_path) - assert class_name is not None - generated_comment = 'Autogenerated file by gen_backend_stubs.py. Do not edit directly!' - fm.write_with_template(f'{backend_dispatch_key}NativeFunctions.h', 'DispatchKeyNativeFunctions.h', lambda: { - 'generated_comment': generated_comment, - 'cpp_namespace': cpp_namespace, - 'class_name': class_name, - # Convert to a set first to remove duplicate kernel names. - # Backends are allowed to repeat kernel names; only generate the declaration once! - 'dispatch_declarations': list(set(concat_map( - lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]), - grouped_native_functions - ))) + list(set(concat_map( - lambda f: dest.compute_native_function_declaration(f, backend_indices[autograd_dispatch_key]), - grouped_native_functions - ))) if autograd_dispatch_key else list(set(concat_map( - lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]), - grouped_native_functions - ))), - }) + if backend_key is None: + # This could be useful if a backend wants to quickly set up a noop yaml file but doesn't have any kernels ready yet. + return - for dispatch_key in [backend_dispatch_key, autograd_dispatch_key]: - if not dispatch_key: - continue + class_name = backend_indices[backend_key].native_function_class_name() - native_func_header = f'#include "torch_npu/csrc/aten/NPUNativeFunctions.h"' - fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: { - 'external_backend_headers': native_func_header, - 'namespaced_headers': '', - 'DispatchKey': dispatch_key.name.replace("NPU", true_backend), - 'dispatch_namespace': dispatch_key.lower(), - 'dispatch_helpers': dest.gen_registration_helpers(backend_indices[dispatch_key]), - 'dispatch_namespaced_definitions': list(concat_map( - dest.RegisterDispatchKey( - backend_indices[dispatch_key], - Target.NAMESPACED_DEFINITION, - selector, - rocm=False, - cpp_namespace=cpp_namespace, - class_method_name=f'{backend_dispatch_key}NativeFunctions'), - grouped_native_functions - )), - 'dispatch_anonymous_definitions': list(concat_map( - dest.RegisterDispatchKey( - backend_indices[dispatch_key], - Target.ANONYMOUS_DEFINITION, - selector, - rocm=False, - cpp_namespace=cpp_namespace, - class_method_name=f'{backend_dispatch_key}NativeFunctions'), - grouped_native_functions - )), - 'dispatch_registrations': list(concat_map( - dest.RegisterDispatchKey( - backend_indices[dispatch_key], - Target.REGISTRATION, - selector, - rocm=False, - cpp_namespace=cpp_namespace, - class_method_name=f'{backend_dispatch_key}NativeFunctions'), - grouped_native_functions - )), - }) + if impl_path is not None: + error_on_missing_kernels(native_functions, backend_indices, backend_key, autograd_key, impl_path) - if to_cpu.upper() in ['OFF', '0', 'NO', 'FALSE', 'F', 'N']: - return - backend_list = [backend_key, autograd_key, DispatchKey.Math, DispatchKey.CompositeExplicitAutograd] - for key in backend_list: - error_on_cpu_kernels(key, native_functions, backend_indices) + gen_dispatchkey_nativefunc_headers(fm, class_name, cpp_namespace, backend_indices, + grouped_native_functions, backend_key, autograd_key) - dispatch_key = true_backend - native_func_header = f'#include "torch_npu/csrc/aten/NPUNativeFunctions.h"\n' - fm.write_with_template(f'RegisterCPU.cpp', 'RegisterDispatchKey.cpp', lambda: { - 'external_backend_headers': native_func_header, - 'namespaced_headers': '', - 'DispatchKey': dispatch_key, - 'dispatch_namespace': dispatch_key.lower(), - 'dispatch_helpers': dest.gen_registration_helpers(backend_indices[DispatchKey.CPU]), - 'dispatch_namespaced_definitions': list(concat_map( - dest.RegisterDispatchKeyCPU( - backend_indices[DispatchKey.CPU], - Target.NAMESPACED_DEFINITION, - selector, - rocm=False, - cpp_namespace=cpp_namespace, - class_method_name=f'NPUNativeFunctions'), - grouped_native_functions - )), - 'dispatch_anonymous_definitions': list(concat_map( - dest.RegisterDispatchKeyCPU( - backend_indices[DispatchKey.CPU], - Target.ANONYMOUS_DEFINITION, - selector, - rocm=False, - cpp_namespace=cpp_namespace, - class_method_name=f'NPUNativeFunctions'), - grouped_native_functions - )), - 'dispatch_registrations': list(concat_map( - dest.RegisterDispatchKeyCPU( - backend_indices[DispatchKey.CPU], - Target.REGISTRATION, - selector, - rocm=False, - cpp_namespace=cpp_namespace, - class_method_name=f'NPUNativeFunctions'), - grouped_native_functions - )), - }) + for dispatch_key in [backend_key] if autograd_key is None else [backend_key, autograd_key]: + gen_dispatcher_registrations(fm, output_dir, cpp_namespace, backend_indices, grouped_native_functions, + backend_key, dispatch_key, selector) if __name__ == '__main__': main() diff --git a/scripts/codegen/gen_functionalization_type.py b/scripts/codegen/gen_functionalization_type.py new file mode 100644 index 0000000000..893563bcce --- /dev/null +++ b/scripts/codegen/gen_functionalization_type.py @@ -0,0 +1,365 @@ +from codegen.api import cpp +from codegen.api.types import ( + DispatcherSignature, Binding, FunctionalizationLambda, ViewInverseSignature +) +from codegen.api.translate import translate +from codegen.context import with_native_function +from codegen.model import ( + Argument, NativeFunction, SchemaKind, BackendIndex, + Tag, FunctionSchema, SelfArgument, TensorOptionsArguments, BaseType, BaseTy +) +from codegen.selective_build.selector import SelectiveBuilder +from typing import List, Optional, Union, Tuple +from codegen.utils import mapMaybe + +def modifies_arguments(f: NativeFunction) -> bool: + return f.func.kind() in [SchemaKind.inplace, SchemaKind.out] + +# This function constructs the return statement for the kernels that contain mutations +# It mostly just needs to special case multi-output returns to wrap the result in a tuple +def return_str(f: NativeFunction) -> str: + if len(f.func.arguments.out) != 0: + if len(f.func.arguments.out) > 1: + return_names = ', '.join(a.name for a in f.func.arguments.out) + return f'return {DispatcherSignature.from_schema(f.func).returns_type().cpp_type()}({return_names});' + else: + return f'return {f.func.arguments.out[0].name}' + if f.func.arguments.self_arg is not None: + return f'return {f.func.arguments.self_arg.argument.name}' + return '' + +def wrapper_name(func: FunctionSchema) -> str: + if func.name.overload_name: + return f'{cpp.name(func)}_{func.name.overload_name}' + else: + return cpp.name(func) + +def is_tensor_like(a: Union[Argument, TensorOptionsArguments, SelfArgument]) -> bool: + return isinstance(a, SelfArgument) or (isinstance(a, Argument) and a.type.is_tensor_like()) + +# unwraps all tensor-like arguments, returning: +# (1) a string containing all of the logic that does the unwrapping +# (2) a context, to be used by translate(), with all of the relevant bindings. +def unwrap_tensor_args(sig: DispatcherSignature) -> Tuple[str, List[Binding]]: + context: List[Binding] = [] + unwrapped_tensor_args: List[str] = [] + for arg in sig.arguments(): + if is_tensor_like(arg.argument): + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + unwrapped_name = f'{arg.name}_' + unwrapped_tensor_args.append( + f'auto {unwrapped_name} = at::functionalization::impl::from_functional_tensor({arg.name});') + context.append(arg.with_name(unwrapped_name)) + else: + # for non-tensor inputs, we want to pass them directly into the redispatch calls. + context.append(arg) + unwrap_tensor_args_str = '\n '.join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + +# converts all tensor-like arguments to meta tensors, which are used to compute stride info. Returns: +# (1) a string containing all of the logic that does the conversions. +# (2) a context, to be used by translate(), with all of the relevant bindings. +def convert_to_meta_tensors(sig: DispatcherSignature) -> Tuple[str, List[Binding]]: + context: List[Binding] = [] + unwrapped_tensor_args: List[str] = [] + for arg in sig.arguments(): + if is_tensor_like(arg.argument): + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + # for tensor inputs, we want to unwrap them before passing them into the redispatch calls. + a_ = arg.name + unwrapped_name = f'{arg.name}_meta' + unwrapped_tensor_args.append( + f"auto {unwrapped_name} = at::native::empty_strided_meta({a_}.sizes(), {a_}.strides(), \ +/*dtype=*/c10::make_optional({a_}.scalar_type()), /*layout=*/c10::make_optional({a_}.layout()), \ +/*device=*/c10::make_optional(c10::Device(kMeta)), /*pin_memory=*/c10::nullopt);" + ) + context.append(arg.with_name(unwrapped_name)) + else: + # for non-tensor inputs, we want to pass them directly into the redispatch calls. + context.append(arg) + unwrap_tensor_args_str = '\n '.join(unwrapped_tensor_args) + return unwrap_tensor_args_str, context + +# The functionalization codegen currently expects view op schemas to have this form: +# foo(Tensor(a), ...) -> Tensor(a) (e.g. transpose) +# foo(Tensor(a!), ...) -> Tensor(a!) (e.g. transpose_) +def assert_view_op_properties(func: FunctionSchema) -> None: + def is_alias(a: Argument) -> bool: + return a.annotation is not None + + args = func.arguments.flat_non_out + # The first argument is a tensor with an alias semantics (annotations) + assert len(args) > 0 and args[0].type == BaseType(BaseTy.Tensor), \ + f"""In the functionalization codegen, we expect the first argument of every view operator to be a tensor, +but found an argument of type {str(args[0].type)} for operator: {str(func.name)}.""" + # No other arguments have aliasing semantics + assert is_alias(args[0]) and not any(is_alias(a) for a in args[1:]), \ + """In the functionalization codegen, we expect the first argument of every view operator to alias the output. +View operators with multiple aliasing inputs aren't supported yet. Found an operator that doesn't satisfy this constraint""" + +# Generates the Functionalization kernel for: +# - ops that create aliases (e.g. transpose()) +# - ops that are views AND mutations (e.g. transpose_()) +def emit_view_functionalization_body( + f: NativeFunction, + functional_op: NativeFunction +) -> str: + # view op case + assert f.is_view_op + + if f.tag is Tag.inplace_view: + # This op is both an inplace op AND a view op. + # See Note [Functionalization Pass - Inplace View Ops] for details. + # I currently have the view meta call into the out-of-place variant of the view, to avoid + # having to define an extra ~20 inplace {view}_inverse_ functions. + # Most view ops don't have NativeFunctionGroup's both, because we don't define out= variants for view ops. + # I'm assuming that every inplace-view op has a corresponding out-of-place view op, + # with the same name but the trailing underscore removed. + # This is currently asserted at parse time in gen.py (see error_check_native_functions). + assert f.func.kind() is SchemaKind.inplace + # Requirement: Every inplace_view op needs to have a corresponding functional view op, which we paired together beforehand. + assert functional_op is not None + api_name = functional_op.func.name.unambiguous_name() + call_sig = DispatcherSignature.from_schema(functional_op.func) + else: + api_name = f.func.name.unambiguous_name() + call_sig = DispatcherSignature.from_schema(f.func) + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + assert_view_op_properties(f.func) + view_tensor_name = dispatcher_sig.arguments()[0].name + + keyset = 'dispatchKeySet & c10::after_func_keyset' + return_type = dispatcher_sig.returns_type().remove_const_ref().cpp_type() + + unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args(dispatcher_sig) + view_redispatch_args = [keyset] + [e.expr for e in translate(unwrapped_args_ctx, call_sig.arguments(), method=False)] + + forward_lambda = FunctionalizationLambda.from_func(f, functional_op=functional_op, is_reverse=False) + reverse_lambda = FunctionalizationLambda.from_func(f, functional_op=functional_op, is_reverse=True) + + # The meta API call should use the same arguments, but convert all tensors to meta tensors first. + meta_conversion_str, meta_call_ctx = convert_to_meta_tensors(dispatcher_sig) + meta_call_args = [e.expr for e in translate(meta_call_ctx, call_sig.arguments(), method=False)] + + if f.tag is Tag.inplace_view: + # See Note [Functionalization Pass - Inplace View Ops] for more details + return f""" + at::functionalization::ViewMeta view_meta = at::functionalization::ViewMeta( + {forward_lambda.decl()} {{ + return {forward_lambda.inner_call()} + }}, + {reverse_lambda.decl()} {{ + return {reverse_lambda.inner_call()} + }} + ); + at::functionalization::impl::mutate_view_meta({view_tensor_name}, view_meta); + {unwrap_tensor_args_str} + {return_type} reference_tensor_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + {meta_conversion_str} + reference_tensor_output = at::_ops::{api_name}::call({', '.join(meta_call_args)}); + }} + // See Note [Propagating strides in the functionalization pass] + at::functionalization::impl::set_sizes_strides_offset({view_tensor_name}, reference_tensor_output); + return {view_tensor_name}; +""" + + else: + return f""" + {unwrap_tensor_args_str} + {return_type} tmp_output; + {return_type} reference_tensor_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + {meta_conversion_str} + reference_tensor_output = at::_ops::{api_name}::call({', '.join(meta_call_args)}); + tmp_output = at::_ops::{api_name}::redispatch({', '.join(view_redispatch_args)}); + // I'm fusing the [alias removal], [mutation removal], [add views back] passes together. + // Later, we'll want to turn them into separate passes (since e.g. vulkan only cares about alias removal). + }} + at::functionalization::ViewMeta view_meta = at::functionalization::ViewMeta( + {forward_lambda.decl()} {{ + return {forward_lambda.inner_call()} + }}, + {reverse_lambda.decl()} {{ + return {reverse_lambda.inner_call()} + }} + ); + auto out = at::functionalization::impl::create_functional_tensor_with_view_meta(tmp_output, {view_tensor_name}, view_meta); + // See Note [Propagating strides in the functionalization pass] + at::functionalization::impl::set_sizes_strides_offset(out, reference_tensor_output); + return out; +""" + +# Generates the Functionalization kernel for inplace ops +def emit_inplace_functionalization_body( + f: NativeFunction, + functional_op: Optional[NativeFunction] +) -> str: + # mutation case + assert(modifies_arguments(f)) + + dispatcher_sig = DispatcherSignature.from_schema(f.func) + + keyset = 'dispatchKeySet & c10::after_func_keyset' + return_type = dispatcher_sig.returns_type().remove_const_ref().cpp_type() + + unwrap_tensor_args_str, unwrapped_args_ctx = unwrap_tensor_args(dispatcher_sig) + + maybe_return = '' if len(f.func.returns) == 0 else 'return ' + sync_tensor_args = '\n '.join(mapMaybe( + lambda arg: f'at::functionalization::impl::sync({arg.name});' + if arg.type.is_tensor_like() else None, + f.func.arguments.flat_all)) + + # Note [functionalizating copy_() and not preserving strides] + # copy_() can't be functionalized, since there doesn't exist an out-of-place variant. + # We could add one, but that would be sub-optimal for functorch: copy() would need to allocate a fresh tensor. + # This may seem like a large hack for one optimization, but copy_() is one of the most common inplace operators. + # Instead, we can replace `self.copy_(src)` with `src.to(self).expand_as(self)`. + # This maintains the exact same semantics, EXCEPT that we don't preserve the strides from `self`. + # This seems like a reasonable tradeoff, for a few reasons: + # - mutation removal is only used by functorch, and not by Vulkan or XLA. Functorch already doesn't preserve strides. + # - There are actually a few other places where the functionalization pass currently doesn't support strides: + # calls to slice/diagonal_scatter don't currently preserve the strides of their inputs (but maybe we should fix this). + if str(f.func.name) == 'copy_': + exprs = [keyset] + [a.name for a in unwrapped_args_ctx] + functional_call_str = f"""\ + auto tmp_intermediate = at::_ops::to_other::redispatch({keyset}, src_, self_, non_blocking, false, c10::nullopt); + tmp_output = at::_ops::expand_as::redispatch({keyset}, tmp_intermediate, self_);""" + elif functional_op is None: + # We can't functionalize this inplace op, since we don't know what the corresponding functional op is. + inplace_exprs = [keyset] + [e.expr for e in translate(unwrapped_args_ctx, dispatcher_sig.arguments(), method=False)] + warn_str = "Note: the functionalization pass encountered an operator ({}) that it could not functionalize, \ +because it couldn't find an out-of-place equivalent of the operator to call. \ +Instead, it's calling the inplace/view operator directly. \ +If this causes problems in your program, consider upstreaming the out-of-place op to PyTorch.".format(str(f.func.name)) + + return f""" + if (c10::impl::tls_local_dispatch_key_set().included_.has(c10::DispatchKey::Functionalize)) {{ + TORCH_WARN("{warn_str}"); + }} + {sync_tensor_args} + {unwrap_tensor_args_str} + at::AutoDispatchSkipFunctionalize guard; + // Redispatch as normally otherwise, since XLA has its own lowerings for special inplace ops. + {maybe_return}at::_ops::{f.func.name.unambiguous_name()}::redispatch({', '.join(inplace_exprs)}); +""" + else: + # call the out-of-place variant of the op + functional_sig = DispatcherSignature.from_schema(functional_op.func) + functional_exprs = [keyset] + [e.expr for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False)] + functional_call_str = \ + f"tmp_output = at::_ops::{functional_op.func.name.unambiguous_name()}::redispatch({', '.join(functional_exprs)});" + + mutable_input_post_processing = '\n'.join([ + f""" + auto {a.name}_functional = at::functionalization::impl::unsafeGetFunctionalWrapper({a.name}); + {a.name}_functional->replace_(tmp_output); + {a.name}_functional->commit_update();""" + for a in f.func.arguments.flat_non_out + if a.annotation and a.annotation.is_write and a.type.is_tensor_like()]) + + return f""" + {sync_tensor_args} + {unwrap_tensor_args_str} + {return_type} tmp_output; + {{ + at::AutoDispatchSkipFunctionalize guard; + // The functionalization pass explicitly doesn't pass out= parameters to the redispatch + {functional_call_str} + }} + {mutable_input_post_processing} + {return_str(f)};""" + + +def emit_declaration_for_noncomposite_views(f: NativeFunction) -> str: + # For every view op, we need a corresponding "inverse view" function. + # This generates the declarations so we get a good compiler error when someone adds a new view. + view_inverse_sig = ViewInverseSignature(f) + return view_inverse_sig.decl() + + +# The below functions generate RegisterFunctionalization.cpp +# These files provide the kernels that run the functionalization pass, which can be opted into +# per backend (e.g. XLA or Vulkan), or as a composable transform (functionalize() in functorch). + +def needs_functionalization( + selector: SelectiveBuilder, + f: NativeFunction, +) -> bool: + return (selector.include_all_operators and + (f.is_view_op or modifies_arguments(f))) + + +def gen_functionalization_registration( + selector: SelectiveBuilder, + f: NativeFunction, + composite_implicit_autograd_index: BackendIndex +) -> Optional[str]: + @with_native_function + def emit_registration_helper(f: NativeFunction) -> Optional[str]: + # Note: for now, this logic is meant to avoid registering functionalization kernels for mobile. + # At some point, Vulkan we'll want to use functionalization and we'll need to change this. + if not needs_functionalization(selector, f): + return None + if f.is_view_op and f.has_composite_implicit_autograd_kernel: + metadata = composite_implicit_autograd_index.get_kernel(f) + assert metadata is not None + native_api_name = metadata.kernel + sig = DispatcherSignature.from_schema(f.func) + # Note [Composite view ops in the functionalization pass] + # We don't need to worry about implemententing functionalization kernels for views with + # CompositeImplicitAutograd kernels, because we can just decompose them into their base operators. + # We can't just opt the entire Functionalization dispatch key into the composite keyset though, + # because we don't want to decompose non-view ops that are composite, like `at::ones`. + registration_str = f'static_cast<{sig.ptr_type()}>(at::native::{native_api_name})' + else: + registration_str = f'TORCH_FN(functionalization::{wrapper_name(f.func)})' + + return f'm.impl("{f.func.name}", {registration_str});' + + return emit_registration_helper(f) + +def gen_functionalization_definition( + selector: SelectiveBuilder, + f: NativeFunction, + functional_op: Optional[NativeFunction] +) -> Optional[str]: + @with_native_function + def emit_definition_helper(f: NativeFunction) -> Optional[str]: + if not needs_functionalization(selector, f): + return None + if f.is_view_op and f.has_composite_implicit_autograd_kernel: + # See Note [Composite view ops in the functionalization pass] + return None + # order is important here, ops that are both views and mutations should hit the view path. + if f.is_view_op: + # Every view op is expected to have a functional counterpart (e.g. transpose_() -> transpose()) + assert functional_op is not None + body_str = emit_view_functionalization_body(f, functional_op) + else: + # inplace op + assert modifies_arguments(f) + body_str = emit_inplace_functionalization_body(f, functional_op) + sig = DispatcherSignature.from_schema(f.func) + return f""" + {sig.defn(name=wrapper_name(f.func), is_redispatching_fn=True)} {{ + {body_str} + }} + """ + + return emit_definition_helper(f) + +# See Note [Functionalization Pass: View Inverses]. +@with_native_function +def gen_functionalization_view_inverse_declaration(f: NativeFunction) -> Optional[str]: + # We only need to generate view_inverse declarations for view ops that: + # - aren't composite (since they'll decompose and we'll get them for free). + # - aren't inplace (since they should have a corresponding functional version, which we call instead). + if f.is_view_op and not f.has_composite_implicit_autograd_kernel and not modifies_arguments(f): + output = emit_declaration_for_noncomposite_views(f) + return output + return None diff --git a/scripts/codegen/gen_python_functions.py b/scripts/codegen/gen_python_functions.py index 40cd3e8e29..76a7bc0a91 100644 --- a/scripts/codegen/gen_python_functions.py +++ b/scripts/codegen/gen_python_functions.py @@ -33,17 +33,16 @@ from codegen.api.python import (PythonSignature, PythonSignatureNativeFunctionPair, arg_parser_output_exprs, cpp_dispatch_exprs, - cpp_record_func, cpp_dispatch_target, dispatch_lambda_args, dispatch_lambda_exprs, dispatch_lambda_return_str, has_tensor_options, namedtuple_fieldnames, signature) -from codegen.gen import cpp_string, FileManager, error_check_native_functions +from codegen.gen import cpp_string, FileManager, LineLoader, error_check_native_functions from codegen.context import with_native_function from codegen.model import (BaseOperatorName, NativeFunction, - Type, Variant, BackendIndex, + Type, Variant, BackendIndex, Location, BackendMetadata, DispatchKey, OperatorName) from codegen.utils import context @@ -54,7 +53,7 @@ _SKIP_PYTHON_BINDINGS = [ '.*_backward', '.*_backward_(out|input|weight|bias)', '.*_forward', '.*_forward_out', '_unsafe_view', 'tensor', '_?sparse_coo_tensor.*', '_?sparse_csr_tensor.*', - '_arange.*', '_range.*', '_linspace.*', '_logspace.*', + '_arange.*', '_range.*', 'linspace.*', 'logspace.*', '_sparse_add_out', '_sparse_div.*', '_sparse_mul.*', '_sparse_sub.*', '_sparse_dense_add_out', 'index', 'unique_dim_consecutive', '_cumsum.*', '_cumprod.*', '_sum.*', '_prod.*', @@ -74,7 +73,6 @@ _SKIP_PYTHON_BINDINGS = [ '_fw_primal', 'fake_quantize_per_tensor_affine_cachemask', 'fake_quantize_per_channel_affine_cachemask', '_reshape_alias', - '_cudnn.*', '.*_quantized', 'fft_.*', ] SKIP_PYTHON_BINDINGS = list(map(lambda pattern: re.compile(rf'^{pattern}$'), _SKIP_PYTHON_BINDINGS)) @@ -117,11 +115,13 @@ def parse_custom_yaml(custom_path: str) -> ParsedYaml: f_str.write(line) f_str.seek(0) - custom_es = yaml.safe_load(f_str) - for e_with_vars in custom_es: - funcs = e_with_vars.get('func') - with context(lambda: f'in {custom_path}:\n {funcs}'): - func, m = NativeFunction.from_yaml(e_with_vars) + custom_es = yaml.load(f_str, Loader=LineLoader) + for e in custom_es: + assert isinstance(e.get('__line__'), int), e + loc = Location(custom_path, e['__line__']) + funcs = e.get('func') + with context(lambda: f'in {loc}:\n {funcs}'): + func, m = NativeFunction.from_yaml(e, loc) func.variants.discard(Variant.method) rs.append(func) BackendIndex.grow_index(bs, m) @@ -129,10 +129,10 @@ def parse_custom_yaml(custom_path: str) -> ParsedYaml: 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, index={})) + 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, index=v) + indices[k] = BackendIndex(dispatch_key=k, use_out_as_primary=True, external=False, device_guard=False, index=v) return ParsedYaml(rs, indices) @@ -166,7 +166,6 @@ def group_filter_overloads( def create_python_bindings( fm: FileManager, pairs: Sequence[PythonSignatureNativeFunctionPair], - pairs_device: Sequence[PythonSignatureNativeFunctionPair], pred: Callable[[NativeFunction], bool], module: Optional[str], filename: str, @@ -177,12 +176,8 @@ def create_python_bindings( py_methods: List[str] = [] py_method_defs: List[str] = [] py_forwards: List[str] = [] - py_device_methods: List[str] = [] - py_device_forwards: List[str] = [] - py_device_method_defs: List[str] = [] grouped = group_filter_overloads(pairs, pred) - grouped_device = group_filter_overloads(pairs_device, pred) for name in sorted(grouped.keys(), key=lambda x: str(x)): overloads = grouped[name] @@ -190,80 +185,14 @@ def create_python_bindings( py_method_defs.append(method_def(name, module, overloads, method=method)) py_forwards.extend(forward_decls(name, overloads, method=method)) - for name in sorted(grouped_device.keys(), key=lambda x: str(x)): - overloads = grouped_device[name] - py_device_methods.append(method_impl(name, module, overloads, method=method, custom=False)) - py_device_method_defs.append(method_def(name, module, overloads, method=method)) - py_device_forwards.extend(forward_decls(name, overloads, method=method)) - fm.write_with_template(filename, filename, lambda: { 'generated_comment': '@' + f'generated from {fm.template_dir}/{filename}', 'py_forwards': py_forwards, 'py_methods': py_methods, - 'py_device_methods': py_device_methods, 'py_method_defs': py_method_defs, - 'py_device_forwards': py_device_forwards, - 'py_device_method_defs': py_device_method_defs, }) -def create_python_device_bindings( - fm: FileManager, - pairs: Sequence[PythonSignatureNativeFunctionPair], - pred: Callable[[NativeFunction], bool], - module: Optional[str], - filename: str, - *, - method: bool, -) -> None: - """Generates Python bindings to ATen functions""" - py_device_method_defs: List[str] = [] - device_methods_def_py_dispatch: List[str] = [] - - grouped = group_filter_overloads(pairs, pred) - - PY_DEVICE_METHOD_DEF = CodeTemplate("""\ - torch.${name} = _${name} -""") - - PY_DEVICE_METHOD_DEF_DISPATCH = CodeTemplate("""\ - -@torch_device_guard -def _${name}(*args, **kwargs): - return torch_npu.${name}(*args, **kwargs) - -""") - - def method_device_def(name): - return PY_DEVICE_METHOD_DEF.substitute(name=name) - - def method_device_def_dispatch(name): - return PY_DEVICE_METHOD_DEF_DISPATCH.substitute(name=name) - - for name in sorted(grouped.keys(), key=lambda x: str(x)): - py_device_method_defs.append(method_device_def(name)) - device_methods_def_py_dispatch.append(method_device_def_dispatch(name)) - - - fm.write_with_template(filename, filename, lambda: { - 'device_methods_def_py': py_device_method_defs, - 'device_methods_def_py_dispatch': device_methods_def_py_dispatch - }) - - def query_methods(filepath): - with open(filepath, 'r', encoding='UTF-8') as f: - read_lines = f.readlines() - def_methods = [] - for read_line in read_lines: - if read_line.startswith("def"): - def_methods.append((read_line[4:read_line.index("(")]).strip()) - return def_methods - - device_methods = query_methods(fm.install_dir + filename) - if len(device_methods) != len(set(device_methods)): - raise RuntimeError("In device methods file " + - str(fm.install_dir + filename) + " has multi-definition function.") - def load_signatures( native_functions: List[NativeFunction], *, @@ -392,8 +321,7 @@ def method_impl( module: Optional[str], overloads: Sequence[PythonSignatureNativeFunctionPair], *, - method: bool, - custom: bool = True + method: bool ) -> str: """ Generate a python binding for all overloads of an op. @@ -418,7 +346,7 @@ def method_impl( for overload_index, overload in enumerate(grouped_overloads): overload_signature = overload.signature.signature_str() signatures.append(f'{cpp_string(str(overload_signature))},') - dispatch_body = emit_dispatch_case(overload, namedtuple_typenames, custom) + dispatch_body = emit_dispatch_case(overload, namedtuple_typenames) dispatch.append( PY_VARIABLE_CASE.substitute(overload_index=overload_index, body=dispatch_body) if not is_singleton else dispatch_body) @@ -454,7 +382,6 @@ if (_r.isNone(${out_idx})) { def emit_dispatch_case( overload: PythonSignatureGroup, namedtuple_typenames: Dict[str, str], - custom: bool = True ) -> str: """ Emit dispatching code for a single parsed signature. This corresponds to either @@ -467,14 +394,14 @@ def emit_dispatch_case( return PY_VARIABLE_OUT.substitute( out_idx=overload.signature.output_idx(), call_dispatch=emit_single_dispatch( - overload.signature, overload.base, namedtuple_typenames, custom), + overload.signature, overload.base, namedtuple_typenames), call_dispatch_out=emit_single_dispatch( - overload.signature, overload.outplace, namedtuple_typenames, custom), + overload.signature, overload.outplace, namedtuple_typenames), ) else: # no-output version only return emit_single_dispatch( - overload.signature, overload.base, namedtuple_typenames, custom) + overload.signature, overload.base, namedtuple_typenames) def forward_decls( @@ -545,20 +472,18 @@ def group_overloads( bases[sig] = overload for sig, out in outplaces.items(): - if sig in bases: - continue - - candidates: List[str] = [] - for overload in overloads: - if str(overload.function.func.name.name) == str(out.function.func.name.name) \ - and not overload.function.func.is_out_fn(): - candidates.append(overload.signature.signature_str(skip_outputs=True)) - out_sig = out.signature.signature_str() - raise RuntimeError( - f'While identifying overloads, we found an out schema {out_sig} without a corresponding non-out ' - f'variant. We expected the non-out variant to have schema: \n- {sig}\nPlease check that you ' - f'spelled the schema correctly in native_functions.yaml. We discovered the following candidate(s): \n' - + '\n'.join(f'- {candidate}' for candidate in candidates)) + if sig not in bases: + candidates: List[str] = [] + for overload in overloads: + if str(overload.function.func.name.name) == str(out.function.func.name.name) \ + and not overload.function.func.is_out_fn(): + candidates.append(overload.signature.signature_str(skip_outputs=True)) + out_sig = out.signature.signature_str() + raise RuntimeError( + f'While identifying overloads, we found an out schema {out_sig} without a corresponding non-out variant. ' + f'We expected the non-out variant to have schema: \n- {sig}\nPlease check that you spelled the schema ' + 'correctly in native_functions.yaml. We discovered the following candidate(s): \n' + + '\n'.join(f'- {candidate}' for candidate in candidates)) grouped: List[PythonSignatureGroup] = [] for sig, base in bases.items(): @@ -629,9 +554,50 @@ def sort_overloads( return list(map(lambda x: grouped_overloads[x], sorted_ids)) +def create_python_device_bindings( + fm: FileManager, + pairs: Sequence[PythonSignatureNativeFunctionPair], + pred: Callable[[NativeFunction], bool], + module: Optional[str], + filename: str, + *, + method: bool, +) -> None: + """Generates Python bindings to ATen functions""" + py_device_method_defs: List[str] = [] + + grouped = group_filter_overloads(pairs, pred) + + PY_DEVICE_METHOD_DEF = CodeTemplate("""\ + torch.${name} = torch_npu.${name} +""") + + def method_device_def(name): + return PY_DEVICE_METHOD_DEF.substitute(name=name) + + for name in sorted(grouped.keys(), key=lambda x: str(x)): + py_device_method_defs.append(method_device_def(name)) + + fm.write_with_template(filename, filename, lambda: { + 'device_methods_def_py': py_device_method_defs, + }) + + def query_methods(filepath): + with open(filepath, 'r', encoding='UTF-8') as f: + read_lines = f.readlines() + def_methods = [] + for read_line in read_lines: + if read_line.startswith("def"): + def_methods.append((read_line[4:read_line.index("(")]).strip()) + return def_methods + + device_methods = query_methods(fm.install_dir + filename) + if len(device_methods) != len(set(device_methods)): + raise RuntimeError("In device methods file " + + str(fm.install_dir + filename) + " has multi-definition function.") def emit_single_dispatch( - ps: PythonSignature, f: NativeFunction, namedtuple_typenames: Dict[str, str], custom = True + ps: PythonSignature, f: NativeFunction, namedtuple_typenames: Dict[str, str] ) -> str: """ Emit dispatch code for a single native function. @@ -644,23 +610,16 @@ def emit_single_dispatch( # dispatch lambda signature name = cpp.name(f.func) lambda_formals = ', '.join(map(lambda a: f"{a.type_str} {a.name}", - dispatch_lambda_args(ps, f, custom))) + dispatch_lambda_args(ps, f, True))) lambda_return = dispatch_lambda_return_str(f) - # device init - if custom and ("Device" in str(f.func)): - init_npu_device = f"torch_npu::utils::maybe_initialize_npu(device);" - else: - init_npu_device = f"//" - # dispatch lambda body - record_func_define = cpp_record_func(f, custom=custom) - dispatch_callee = cpp_dispatch_target(f, custom=custom) - dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=custom)) + dispatch_callee = cpp_dispatch_target(f, custom=True) + dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=True)) # from arg parser outputs to dispatch lambda arguments parser_outputs = arg_parser_output_exprs(ps, f) - lambda_arg_exprs = dispatch_lambda_exprs(ps, f, custom) + lambda_arg_exprs = dispatch_lambda_exprs(ps, f, True) inits = '\n'.join(lambda_arg_exprs.inits) lambda_args = ', '.join(lambda_arg_exprs.exprs) @@ -674,9 +633,7 @@ def emit_single_dispatch( {schema_comment} {inits} auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{ - {init_npu_device} pybind11::gil_scoped_release no_gil; - {record_func_define} {dispatch_callee}({dispatch_args}); }}; dispatch_{name}({lambda_args}){set_requires_grad}; @@ -689,9 +646,7 @@ Py_RETURN_NONE; {schema_comment} {inits} auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{ - {init_npu_device} pybind11::gil_scoped_release no_gil; - {record_func_define} return {dispatch_callee}({dispatch_args}); }}; return wrap({namedtuple_typeref}dispatch_{name}({lambda_args}){set_requires_grad}); @@ -713,9 +668,11 @@ def parse_native_yaml(path: str) -> List[NativeFunction]: with_device_base_operator = set() 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 {path}:\n {funcs}'): - func, m = NativeFunction.from_yaml(e) + func, m = NativeFunction.from_yaml(e, loc) if "Device" in funcs: with_device_base_operator.add(func.func.name.name.base) @@ -750,13 +707,5 @@ if __name__ == "__main__": valid_native_functions = list(filter(should_generate_py_binding, parsed_native_functions)) functions = load_signatures(valid_native_functions, method=False) - torch_native_functions = list(filter(should_generate_py_binding, parse_native_yaml(options.native_yaml))) - device_native_functions = load_signatures(torch_native_functions, method=False) - - create_python_bindings(file_manager, functions, device_native_functions, lambda f: Variant.function in f.variants, - 'torch_npu', 'python_custom_functions.cpp', method=False) - - file_device_manager=FileManager(install_dir=options.output_dir +"../../utils/", - template_dir=options.template_path, dry_run=False) - create_python_device_bindings(file_device_manager, device_native_functions, - lambda f: Variant.function in f.variants, 'torch_npu', 'torch_funcs.py', method=False) + create_python_bindings(file_manager, functions, lambda f: Variant.function in f.variants, + 'torch_npu', 'python_custom_functions.cpp', method=False) \ No newline at end of file diff --git a/scripts/codegen/model.py b/scripts/codegen/model.py index 7b2b889d04..ce91058f01 100644 --- a/scripts/codegen/model.py +++ b/scripts/codegen/model.py @@ -52,6 +52,15 @@ def assert_never(x: NoReturn) -> NoReturn: # and you're expected to populate information once during # construction. +# Represent a source location; used for better error reporting +@dataclass(frozen=True) +class Location: + file: str + line: int + + def __str__(self) -> str: + return "{}:{}".format(self.file, self.line) + # Valid values of the 'variants' field in native_functions.yaml Variant = Enum('Variant', ('function', 'method')) @@ -95,6 +104,7 @@ class DispatchKey(Enum): PrivateUse3 = auto() EndOfBackendKeys = PrivateUse3 + ZeroTensor = auto() Meta = auto() BackendSelect = auto() Named = auto() @@ -172,6 +182,19 @@ class DeviceCheckType(Enum): NoCheck = 0 ExactSame = 1 +class Tag(Enum): + inplace_view = 0 + + def __str__(self) -> str: + return self.name + + @staticmethod + def parse(value: str) -> 'Tag': + for k, v in Tag.__members__.items(): + if k == value: + return v + raise AssertionError(f'unknown tag {value}') + # The basic input to the code generation is native_functions.yaml. # The name "native", BTW, comes from the distinction between native # functions and legacy TH functions. The legacy TH functions are gone, @@ -193,10 +216,6 @@ class NativeFunction: # classes for expository clarity.) func: 'FunctionSchema' - # Corresponds to the 'use_c10_dispatcher' field. The default - # is 'full' - use_c10_dispatcher: UseC10Dispatcher - # Whether or not to generate mutable tensor arguments like regular # ones use_const_ref_for_mutable_tensors: bool @@ -228,6 +247,10 @@ class NativeFunction: # so you can make use of the normal binding if you need it. manual_cpp_binding: bool + # The location in the YAML file were this native function entry was + # defined. This is for conveniently reporting error messages! + loc: 'Location' + # Whether or not this out functions is a "structured kernel". Structured # kernels are defined a little differently from normal kernels; in # particular, their shape checking logic is defined separately from @@ -273,6 +296,11 @@ class NativeFunction: has_composite_implicit_autograd_kernel: bool has_composite_explicit_autograd_kernel: bool + # Tags are used to describe semantic information about (groups of) operators, + # That aren't easily inferrable directly from the operator's schema. + # For now operators have at most one tag. + tag: Optional['Tag'] + # NB: The benefit of defining a dataclass is that we automatically get # a constructor defined for all the fields we specify. No need # to explicitly write it out. @@ -280,83 +308,64 @@ class NativeFunction: # We parse both the NativeFunction + backend-specific information about it, which it stored # in a corresponding BackendIndex. @staticmethod - def from_yaml(ei: Dict[str, object]) -> Tuple['NativeFunction', - Dict[DispatchKey, Dict['OperatorName', 'BackendMetadata']]]: + def from_yaml( + ei: Dict[str, object], + loc: 'Location' + ) -> Tuple['NativeFunction', Dict[DispatchKey, Dict['OperatorName', 'BackendMetadata']]]: + """ + Parse a NativeFunction from a dictionary as directly parsed + from native_functions.yaml + """ e = ei.copy() - def parse_func(e): - funcs = e.pop('func') - assert isinstance(funcs, str), f'not a str: {funcs}' - func = FunctionSchema.parse(funcs) - return func + + funcs = e.pop('func') + assert isinstance(funcs, str), f'not a str: {funcs}' + func = FunctionSchema.parse(funcs) - def parse_cpp_no_default_args(e): - cpp_no_default_args_list = e.pop('cpp_no_default_args', []) - assert isinstance(cpp_no_default_args_list, list) - cpp_no_default_args = set(cpp_no_default_args_list) - return cpp_no_default_args - - def parse_use_dispatcher(e): - use_c10_dispatcher_s = e.pop('use_c10_dispatcher', None) - assert use_c10_dispatcher_s != 'full', \ - "No need to specify 'use_c10_dispatcher: full' anymore. This is the default now. Just remove the line." - if use_c10_dispatcher_s is None: - use_c10_dispatcher = UseC10Dispatcher.full - elif use_c10_dispatcher_s == 'hacky_wrapper_for_legacy_signatures': - use_c10_dispatcher = UseC10Dispatcher.hacky_wrapper_for_legacy_signatures - else: - raise AssertionError(f'use_c10_dispatcher must be full or hacky_wrapper_for_legacy_signatures,' - f' got {use_c10_dispatcher_s}') - return use_c10_dispatcher - - def parse_variants(e): - variants_s = e.pop('variants', 'function') - assert isinstance(variants_s, str) - variants: Set[Variant] = set() - for v in variants_s.split(', '): - if v == 'function': - variants.add(Variant.function) - elif v == 'method': - variants.add(Variant.method) - else: - raise AssertionError(f'illegal variant {v}') - return variants - - func = parse_func(e) - cpp_no_default_args = parse_cpp_no_default_args(e) - use_c10_dispatcher = parse_use_dispatcher(e) - variants = parse_variants(e) + cpp_no_default_args_list = e.pop('cpp_no_default_args', []) + assert isinstance(cpp_no_default_args_list, list) + cpp_no_default_args = set(cpp_no_default_args_list) use_const_ref_for_mutable_tensors = e.pop('use_const_ref_for_mutable_tensors', False) - manual_kernel_registration = e.pop('manual_kernel_registration', False) - manual_cpp_binding = e.pop('manual_cpp_binding', False) - device_guard = e.pop('device_guard', True) - assert isinstance(use_const_ref_for_mutable_tensors, bool) and isinstance(manual_kernel_registration, bool) \ - and isinstance(manual_cpp_binding, bool) and isinstance(device_guard, bool), f'exists non-bool value.' + assert isinstance(use_const_ref_for_mutable_tensors, bool) - def parse_device_check(e): - device_check_s = e.pop('device_check', None) - assert device_check_s is None or isinstance(device_check_s, str), f'not a str: {device_check_s}' - device_check: DeviceCheckType - if device_check_s is None: - device_check = DeviceCheckType.ExactSame + variants_s = e.pop('variants', 'function') + assert isinstance(variants_s, str) + variants: Set[Variant] = set() + for v in variants_s.split(', '): + if v == 'function': + variants.add(Variant.function) + elif v == 'method': + variants.add(Variant.method) else: - device_check = DeviceCheckType[device_check_s] - return device_check + raise AssertionError(f'illegal variant {v}') + + manual_kernel_registration = e.pop('manual_kernel_registration', False) + assert isinstance(manual_kernel_registration, bool), f'not a bool: {manual_kernel_registration}' + + manual_cpp_binding = e.pop('manual_cpp_binding', False) + assert isinstance(manual_cpp_binding, bool), f'not a bool: {manual_cpp_binding}' + + device_guard = e.pop('device_guard', True) + assert isinstance(device_guard, bool), f'not a bool: {device_guard}' + + device_check_s = e.pop('device_check', None) + assert device_check_s is None or isinstance(device_check_s, str), f'not a str: {device_check_s}' + device_check: DeviceCheckType + if device_check_s is None: + device_check = DeviceCheckType.ExactSame + else: + device_check = DeviceCheckType[device_check_s] - device_check = parse_device_check(e) structured = e.pop('structured', False) assert isinstance(structured, bool), f'not a bool: {structured}' - def parse_structured_delegate(e): - structured_delegate_s = e.pop('structured_delegate', None) - assert structured_delegate_s is None or isinstance(structured_delegate_s, str), \ - f'not a str: {structured_delegate_s}' - structured_delegate: Optional[OperatorName] = None - if structured_delegate_s is not None: - structured_delegate = OperatorName.parse(structured_delegate_s) - return structured_delegate + structured_delegate_s = e.pop('structured_delegate', None) + assert structured_delegate_s is None or isinstance(structured_delegate_s, str), f'not a str: {structured_delegate}' + structured_delegate: Optional[OperatorName] = None + if structured_delegate_s is not None: + structured_delegate = OperatorName.parse(structured_delegate_s) - structured_delegate = parse_structured_delegate(e) structured_inherits = e.pop('structured_inherits', None) assert structured_inherits is None or isinstance(structured_inherits, str), f'not a str: {structured_inherits}' @@ -366,83 +375,97 @@ class NativeFunction: category_override = e.pop('category_override', None) assert category_override is None or isinstance(category_override, str), f'not a str: {category_override}' - def parse_precomputed(e, structured): - precomputed_dict = e.pop('precomputed', None) - assert precomputed_dict is None or structured is True - precomputed = Precompute.parse(precomputed_dict) if precomputed_dict else None - return precomputed + precomputed_dict = e.pop('precomputed', None) + assert precomputed_dict is None or structured is True + precomputed = Precompute.parse(precomputed_dict) if precomputed_dict else None - precomputed = parse_precomputed(e, structured) + tag_str = e.pop('tags', None) + assert tag_str is None or isinstance(tag_str, str), f'not a str: {tag_str}' + tag = Tag.parse(tag_str) if tag_str else None from codegen.api import cpp - def parse_dispatch(e, func, manual_kernel_registration, structured_delegate, structured): - raw_dispatch = e.pop('dispatch', None) - assert raw_dispatch is None or isinstance(raw_dispatch, dict), e - dispatch: Dict[DispatchKey, str] = {} - if raw_dispatch is not None: - assert not manual_kernel_registration, \ - "cannot specify both manual_kernel_registration and dispatch; with " \ - "manual registration, dispatch has no effect!" - for ks, v in raw_dispatch.items(): - if ks == '__line__': - continue # not worth tracking line numbers for dispatch entries - assert isinstance(ks, str), e - assert isinstance(v, str), e - for k in ks.split(","): - dispatch_key = DispatchKey.parse(k.strip()) - dispatch[dispatch_key] = v - assert dispatch != {DispatchKey.CompositeImplicitAutograd: cpp.name(func)}, \ - "unnecessary dispatch table for this function; just delete the dispatch " \ - "key entirely" - # if a function is a structured delegate, deleting the dispatch - # table is NOT semantics preserving - assert structured_delegate or dispatch.keys() != {DispatchKey.CompositeImplicitAutograd}, \ - f"unexpected name for singleton CompositeImplicitAutograd dispatch entry:" \ - f" expected {cpp.name(func)} but got {dispatch[DispatchKey.CompositeImplicitAutograd]}." \ - f" Rename your implementation to the expected name, then delete the dispatch table" - elif not structured and structured_delegate is None: - dispatch[DispatchKey.CompositeImplicitAutograd] = cpp.name(func) + raw_dispatch = e.pop('dispatch', None) + assert raw_dispatch is None or isinstance(raw_dispatch, dict), e + dispatch: Dict[DispatchKey, str] = {} + if raw_dispatch is not None: + assert not manual_kernel_registration, \ + "cannot specify both manual_kernel_registration and dispatch; with " \ + "manual registration, dispatch has no effect!" + for ks, v in raw_dispatch.items(): + if ks == '__line__': + continue # not worth tracking line numbers for dispatch entries + assert isinstance(ks, str), e + assert isinstance(v, str), e + for k in ks.split(","): + dispatch_key = DispatchKey.parse(k.strip()) + dispatch[dispatch_key] = v + assert dispatch != {DispatchKey.CompositeImplicitAutograd: cpp.name(func)}, \ + "unnecessary dispatch table for this function; just delete the dispatch " \ + "key entirely" + # if a function is a structured delegate, deleting the dispatch + # table is NOT semantics preserving + assert structured_delegate or dispatch.keys() != {DispatchKey.CompositeImplicitAutograd}, \ + f"unexpected name for singleton CompositeImplicitAutograd dispatch entry: expected {cpp.name(func)} " \ + f"but got {dispatch[DispatchKey.CompositeImplicitAutograd]}. Rename your implementation to the expected " \ + "name, then delete the dispatch table" + elif not structured and structured_delegate is None: + dispatch[DispatchKey.CompositeImplicitAutograd] = cpp.name(func) - assert not (DispatchKey.CompositeExplicitAutograd in dispatch and - DispatchKey.CompositeImplicitAutograd in dispatch), \ - "cannot specify both CompositeExplicitAutograd and CompositeImplicitAutograd on a single kernel;" \ - " each strictly subsumes the other. If you wanted to provide an explicit autograd " \ - "implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd only" - return dispatch + assert not (DispatchKey.CompositeExplicitAutograd in dispatch and DispatchKey.CompositeImplicitAutograd in dispatch), \ + "cannot specify both CompositeExplicitAutograd and CompositeImplicitAutograd on a single kernel; each " \ + "strictly subsumes the other. If you wanted to provide an explicit autograd " \ + "implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd only" - dispatch = parse_dispatch(e, func, manual_kernel_registration, structured_delegate, structured) - is_abstract = True if structured_delegate else dispatch.keys() != {DispatchKey.CompositeImplicitAutograd} + if structured_delegate: + # Structured functions MUST have a dispatch table + is_abstract = True + else: + is_abstract = dispatch.keys() != {DispatchKey.CompositeImplicitAutograd} has_composite_implicit_autograd_kernel = DispatchKey.CompositeImplicitAutograd in dispatch.keys() has_composite_explicit_autograd_kernel = DispatchKey.CompositeExplicitAutograd in dispatch.keys() + # BackendMetadata is used to store any information about a NativeFunction that is backend dependent. + # The most obvious information is the kernel name, which usually contains the name of the backend in it for cpu/cuda. + # Why is 'structured' included? External backends (e.g. XLA) opt into which ops are structured + # independently of which in-tree ops are structured backend_metadata = {k: {func.name: BackendMetadata( kernel=v, structured=structured and is_structured_dispatch_key(k))} for k, v in dispatch.items()} - def assert_last(e, structured_delegate, dispatch): - # don't care if it exists or not; make it easier to use this function - # with other yaml parsers that aren't setting __line__ in the dict - e.pop('__line__', None) - assert not e, f"leftover entries: {e}" + # don't care if it exists or not; make it easier to use this function + # with other yaml parsers that aren't setting __line__ in the dict + e.pop('__line__', None) + assert not e, f"leftover entries: {e}" - # Asserts that we can't do in post_init, because they rely on backend-specific info - if structured_delegate is not None: - for key in STRUCTURED_DISPATCH_KEYS: - assert key not in dispatch, \ - f"if structured_delegate, then must not have {key} in dispatch dictionary " \ - "(it is delegated!)" - assert_last(e, structured_delegate, dispatch) - return NativeFunction(func=func, use_c10_dispatcher=use_c10_dispatcher, + # Asserts that we can't do in post_init, because they rely on backend-specific info + if structured_delegate is not None: + for key in STRUCTURED_DISPATCH_KEYS: + assert key not in dispatch, \ + f"if structured_delegate, then must not have {key} in dispatch dictionary " \ + "(it is delegated!)" + + return NativeFunction( + func=func, use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors, - variants=variants, structured=structured, structured_delegate=structured_delegate, - structured_inherits=structured_inherits, precomputed=precomputed, - manual_kernel_registration=manual_kernel_registration, manual_cpp_binding=manual_cpp_binding, - python_module=python_module, category_override=category_override, device_guard=device_guard, - device_check=device_check, cpp_no_default_args=cpp_no_default_args, is_abstract=is_abstract, + variants=variants, + structured=structured, + structured_delegate=structured_delegate, + structured_inherits=structured_inherits, + precomputed=precomputed, + manual_kernel_registration=manual_kernel_registration, + manual_cpp_binding=manual_cpp_binding, + python_module=python_module, + category_override=category_override, + device_guard=device_guard, + device_check=device_check, + loc=loc, + cpp_no_default_args=cpp_no_default_args, + is_abstract=is_abstract, has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel, - has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel), backend_metadata - + has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel, + tag=tag, + ), backend_metadata def validate_unstructured(self) -> None: # TODO: probably better to accumulate these errors and report them all @@ -481,9 +504,6 @@ class NativeFunction: if a.default is not None} invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments) assert len(invalid_args) == 0, f'Invalid cpp_no_default_args: {invalid_args}' - if self.structured or self.structured_delegate: - assert self.use_c10_dispatcher is UseC10Dispatcher.full, \ - "Structured kernels MUST be use_c10_dispatcher: full; port your argument order" if self.structured_inherits is not None: assert self.structured, "structured_inherits must also imply structured: True" if str(self.func.name).startswith('_foreach'): @@ -650,6 +670,10 @@ class BackendIndex: # is used to implement the others. # All in-tree ops use out kernels, while XLA uses functional kernels. use_out_as_primary: bool + # Whether the backend requires a device guard, and device checks. + # For in-tree backends, this is currently just CUDA/HIP + # For out-of-tree backends, this is currently just Intel XPU + device_guard: bool # Whether the backend is in-tree (CPU/CUDA) or out-of-tree (XLA) external: bool # Other backend-specific information that is on a per-operator basis @@ -771,7 +795,9 @@ class FunctionSchema: def parse(func: str) -> 'FunctionSchema': # We should probably get a proper parser here assert ' -> ' in func, "function schema missing return type (spaces are mandatory)" - func_decl, return_decl = [x.strip() for x in func.split(' -> ')] + last_index = func.rfind(" -> ") + func_decl = func[:last_index] + return_decl = func[last_index + len(" -> "):] ops, args = func_decl.split('(', 1) assert args[-1] == ")", "Expecting closing )" args = args[:-1] @@ -912,19 +938,30 @@ class Annotation: # we can conveniently assume it is canonically ordered alias_set: Tuple[str, ...] is_write: bool + alias_set_after: str @staticmethod def parse(ann: str) -> 'Annotation': - m = re.match(r'^([a-z])(!?)(!?)$', ann) + # Only handling afterSet == Wildcard for now + becomes_wildcard_index = ann.find(" -> *") + if becomes_wildcard_index != -1: + after_set = "*" + # TODO: im not good enough with regexes to ignore -> * + m = re.match(r'^([a-z])(!?)(!?)$', ann[:becomes_wildcard_index] + ann[becomes_wildcard_index + len(" -> *"):]) + else: + after_set = "" + m = re.match(r'^([a-z])(!?)(!?)$', ann) assert m is not None, f'unrecognized alias annotation {ann}' alias_set = (m.group(1),) is_write = m.group(2) == '!' - r = Annotation(alias_set=alias_set, is_write=is_write) + r = Annotation(alias_set=alias_set, is_write=is_write, alias_set_after=after_set) assert str(r) == ann, f'{r} != {ann}' return r def __str__(self) -> str: alias_set = '|'.join(self.alias_set) + if self.alias_set_after: + alias_set = f'{alias_set}{" -> "}{self.alias_set_after}' is_write = '!' if self.is_write else '' return f'{alias_set}{is_write}' diff --git a/scripts/codegen/native_functions.yaml b/scripts/codegen/native_functions.yaml index 645804ca00..2753892b91 100644 --- a/scripts/codegen/native_functions.yaml +++ b/scripts/codegen/native_functions.yaml @@ -39,8 +39,7 @@ # Computes the gradient of current tensor w.r.t. graph leaves. - func: _backward(Tensor self, Tensor[] inputs, Tensor? gradient=None, bool? retain_graph=None, bool create_graph=False) -> () - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - manual_kernel_registration: True + manual_cpp_binding: True variants: method # DEPRECATED. Sets the tensor data held by this `Variable` to be the same as @@ -51,16 +50,16 @@ # where Variables *are* Tensors (as opposed to them containing tensors, which # is what the previous interpretation was.) - func: set_data(Tensor(a!) self, Tensor new_data) -> () - manual_kernel_registration: True + manual_cpp_binding: True variants: method - func: data(Tensor self) -> Tensor - manual_kernel_registration: True + manual_cpp_binding: True variants: method # True if this `Variable` is a leaf and thus does not have a `grad_fn`. - func: is_leaf(Tensor self) -> bool - manual_kernel_registration: True + manual_cpp_binding: True variants: method # Returns the output index of this variable from the forward operation that @@ -74,33 +73,76 @@ # assert y2.output_nr == 2 # - func: output_nr(Tensor self) -> int - manual_kernel_registration: True + manual_cpp_binding: True variants: method - func: _version(Tensor self) -> int - manual_kernel_registration: True + manual_cpp_binding: True variants: method - func: requires_grad_(Tensor(a!) self, bool requires_grad=True) -> Tensor(a!) - manual_kernel_registration: True + manual_cpp_binding: True variants: method # Enables .grad attribute for non-leaf Tensors. - func: retain_grad(Tensor(a!) self) -> () - manual_kernel_registration: True + manual_cpp_binding: True + variants: method + +- func: retains_grad(Tensor self) -> bool + manual_cpp_binding: True variants: method - func: _fw_primal(Tensor(a) self, int level) -> Tensor(a) variants: method dispatch: - DefaultBackend: _fw_primal + CompositeExplicitAutograd: _fw_primal - func: _make_dual(Tensor(a) primal, Tensor tangent, int level) -> Tensor(a) variants: function + dispatch: + CompositeExplicitAutograd: _make_dual - func: _unpack_dual(Tensor(a) dual, int level) -> (Tensor(a) primal, Tensor tangent) variants: function +# NOTE: [_new_zeros_with_same_feature_meta] +# This function creates a new tensor with the layout and TensorOptions +# of `other` but also takes into account the batch dimensions of `self` +# +# This function has a couple extra constraints because it is also used for `jvp` +# in functorch. +# - is used for forward AD because there is the restriction +# that the primal and tangent must have the same layout +# - We cannot assume that `self` and `other` have the same sizes or even dim +# because in the inplace over view case, `other` is the base tensor, and +# `self` is the forward grad with respect to the view, which can have an +# entirely different shape +# - takes the number of batch dims for `self` because we also handle +# some batching logic. We handle that here instead of a batching rule because +# we'd like to avoid calling as_strided in the batching rule (as to enable +# nested vmap in functorch). +# - needs to be CompositeExplicitAutograd for jvp support in functorch. +# functorch currently relies on TensorWrapper which does not have storage +# CompositeExplicitAutograd makes sure the TensorWrapper is unwrapped. +# - this function may eventually take on another int argument to store the +# the number of batch dims for other once we support that use case +- func: _new_zeros_with_same_feature_meta(Tensor self, Tensor other, *, int self_num_batch_dims=0) -> Tensor + variants: function + dispatch: + CompositeExplicitAutograd: _new_zeros_with_same_feature_meta + +# This function compares the storage numel of self with that of other, where +# storage numel is cumputed as: `other.storage().nbytes() / other.itemsize()`. +# We create this function for composite compliance purposes. The batching rule +# always returns true because vmapped as_strided does not support accessing +# storage locations not indexable by the input tensor. +# See the note above for more information. +- func: _has_same_storage_numel(Tensor self, Tensor other) -> bool + variants: function + dispatch: + CompositeExplicitAutograd: _has_same_storage_numel + - func: rename_(Tensor(a!) self, Dimname[]? names) -> Tensor(a!) variants: method @@ -118,14 +160,24 @@ - func: align_tensors(Tensor[] tensors) -> Tensor[] +# Not assert because it's a keyword; not Assert because FX already +# took that syntax +# TODO: need to specify this is side-effectful somehow +- func: _assert_async(Tensor self) -> () + dispatch: + CPU: _assert_async_cpu + CUDA: _assert_async_cuda + - func: refine_names(Tensor(a) self, Dimname[] names) -> Tensor(a) variants: method - func: _use_cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank) -> bool + device_check: NoCheck # Tensor arguments allowed to be on different devices, see also _cudnn_ctc_loss dispatch: CUDA: _use_cudnn_ctc_loss - func: _cudnn_ctc_loss(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank, bool deterministic, bool zero_infinity) -> (Tensor, Tensor) + device_check: NoCheck # log_probs is expected to be on CUDA while targets is expected to be on CPU dispatch: CUDA: _cudnn_ctc_loss @@ -136,17 +188,17 @@ CUDA: _cudnn_rnn_flatten_weight - func: _cudnn_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor? weight_buf, Tensor hx, Tensor? cx, int mode, int hidden_size, int proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + # rnn_tanh may or may not redispatch to _cudnn_rnn based on algorithm and build. Thus it might hit dispatch or kernel device check. + # Disable dispatch time device check for consistent behavior. + device_check: NoCheck dispatch: CUDA: _cudnn_rnn - func: _cudnn_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int proj_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[]) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: _cudnn_rnn_backward - func: _cudnn_init_dropout_state(float dropout, bool train, int dropout_seed, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: _cudnn_init_dropout_state @@ -163,6 +215,17 @@ dispatch: CUDA: masked_scale_cuda +- func: native_dropout(Tensor input, float p, bool? train) -> (Tensor, Tensor) + variants: function + dispatch: + CPU: native_dropout_cpu + CUDA: native_dropout_cuda + +- func: native_dropout_backward(Tensor grad_output, Tensor mask, float scale) -> Tensor + dispatch: + CPU: native_dropout_backward_cpu + CUDA: native_dropout_backward_cuda + - func: _sobol_engine_draw(Tensor quasi, int n, Tensor sobolstate, int dimension, int num_generated, ScalarType? dtype) -> (Tensor, Tensor) - func: _sobol_engine_ff_(Tensor(a!) self, int n, Tensor sobolstate, int dimension, int num_generated) -> Tensor(a!) @@ -192,19 +255,27 @@ - func: feature_alpha_dropout_(Tensor(a!) self, float p, bool train) -> Tensor(a!) - func: abs(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: abs + CompositeExplicitAutograd: abs + SparseCPU, SparseCUDA: abs_sparse + SparseCsrCPU, SparseCsrCUDA: abs_sparse_csr - func: abs_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: abs_ + CompositeExplicitAutograd: abs_ + SparseCPU, SparseCUDA: abs_sparse_ + SparseCsrCPU, SparseCsrCUDA: abs_sparse_csr_ - func: abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: abs_out + SparseCPU, SparseCUDA: abs_sparse_out + SparseCsrCPU, SparseCsrCUDA: abs_sparse_csr_out # Note [Adding an alias] # To add an alias do the following: @@ -216,40 +287,43 @@ # will stop it from "inheriting" the original operation's autograd behavior. # 2) Implement the corresponding functions and have them redispatch to the # original function. -# 3) Add entries for the alias (and original function, if needed) to -# aten/src/ATen/core/interned_strings.h -# (This may require removing an entry from ATen/core/aten_interned_strings.h.) -# 4) Add docstrings to the new function that reference the original function, +# 3) Add docstrings to the new function that reference the original function, # and document the method as usual (if it exists.) # (See torch/_torch_docs.py and docs/source/torch.rst if adding a function, # torch/_tensor_docs.py and docs/source/tensors.rst if adding a method, # or module-specific doc bindings (like torch/linalg/__init__.py) if # adding an alias in a namespace.) -# 5) Update torch/overrides.py consistent with the original function. -# 6) Update the alias_map in torch/csrc/jit/passes/normalize_ops.cpp. -# 7) Add entries to test/test_op_aliases.py's "alias_infos" +# 4) Update torch/overrides.py consistent with the original function. +# 5) Update the alias_map in torch/csrc/jit/passes/normalize_ops.cpp. +# 6) Add aliases argument to existing OpInfo/UnaryUfuncInfo or create new OpInfo/UnaryUfuncInfo entry +# in op_db list in torch/testing/_internal/common_methods_invocations.py # # See torch.absolute, an alias for torch.abs, as an example. # Absolute, alias for abs - func: absolute(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: absolute_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: absolute.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: angle(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: angle + CPU, CUDA: angle + SparseCsrCPU, SparseCsrCUDA: angle_sparse_csr - func: angle.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: angle_out + SparseCsrCPU, SparseCsrCUDA: angle_sparse_csr_out - func: view_as_real(Tensor(a) self) -> Tensor(a) variants: function @@ -263,51 +337,89 @@ - func: sgn(Tensor self) -> Tensor variants: function, method + structured_delegate: sgn.out dispatch: - DefaultBackend: sgn + SparseCPU, SparseCUDA: sgn_sparse + SparseCsrCPU, SparseCsrCUDA: sgn_sparse_csr - func: sgn_(Tensor(a!) self) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: method + structured_delegate: sgn.out dispatch: - DefaultBackend: sgn_ + SparseCPU, SparseCUDA: sgn_sparse_ + SparseCsrCPU, SparseCsrCUDA: sgn_sparse_csr_ - func: sgn.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sgn_out + SparseCPU, SparseCUDA: sgn_sparse_out + SparseCsrCPU, SparseCsrCUDA: sgn_sparse_csr_out - func: real(Tensor(a) self) -> Tensor(a) + device_check: NoCheck # TensorIterator variants: function - func: imag(Tensor(a) self) -> Tensor(a) + device_check: NoCheck # TensorIterator variants: function +- func: _conj(Tensor(a) self) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: _conj + - func: conj(Tensor(a) self) -> Tensor(a) variants: function, method + manual_cpp_binding: True -- func: conj.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _conj_physical(Tensor self) -> Tensor + variants: function, method dispatch: - CPU, CUDA: conj_out + CompositeExplicitAutograd: _conj_physical + SparseCsrCPU, SparseCsrCUDA: conj_physical_sparse_csr -- func: _conj(Tensor self) -> Tensor - variants: function +- func: conj_physical(Tensor self) -> Tensor + variants: function, method + +- func: conj_physical.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) dispatch: - DefaultBackend: _conj + CPU, CUDA: conj_physical_out + SparseCPU, SparseCUDA: conj_physical_out_sparse + SparseCsrCPU, SparseCsrCUDA: conj_physical_sparse_csr_out + +- func: conj_physical_(Tensor(a!) self) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: conj_physical_ + SparseCsrCPU, SparseCsrCUDA: conj_physical_sparse_csr_ + +- func: resolve_conj(Tensor(a) self) -> Tensor(a) + variants: function, method + +- func: resolve_neg(Tensor(a) self) -> Tensor(a) + variants: function, method + +- func: _neg_view(Tensor(a) self) -> Tensor(a) + variants: function, method + dispatch: + CompositeExplicitAutograd: _neg_view - func: acos(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: acos + structured_delegate: acos.out - func: acos_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: acos_ + structured_delegate: acos.out - func: acos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: acos_out @@ -319,7 +431,6 @@ variants: function, method - func: arccos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: avg_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, bool ceil_mode=False, bool count_include_pad=True) -> Tensor @@ -329,26 +440,34 @@ - func: adaptive_max_pool1d(Tensor self, int[1] output_size) -> (Tensor, Tensor) - func: add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator structured_delegate: add.out variants: function, method dispatch: SparseCPU, SparseCUDA: add_sparse + SparseCsrCPU, SparseCsrCUDA: add_sparse_csr MkldnnCPU: mkldnn_add + ZeroTensor: add_zerotensor - func: add_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method structured_delegate: add.out dispatch: SparseCPU, SparseCUDA: add_sparse_ + SparseCsrCPU, SparseCsrCUDA: add_sparse_csr_ MkldnnCPU: mkldnn_add_ - func: add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator structured: True structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: add_out SparseCPU: add_out_sparse_cpu SparseCUDA: add_out_sparse_cuda + SparseCsrCPU: add_out_sparse_csr_cpu + SparseCsrCUDA: add_out_sparse_csr_cuda MkldnnCPU: mkldnn_add_out - func: _add_relu.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor @@ -362,118 +481,127 @@ CPU: add_relu_ - func: _add_relu.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU: add_relu_out +- func: _add_relu.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + variants: function + dispatch: + CPU: add_relu + +- func: _add_relu_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + variants: function + dispatch: + CPU: add_relu_ + # For C++ only, until we have conversion from C++ numbers to Tensor - func: add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: add + CompositeExplicitAutograd: add - func: add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: add_ + CompositeExplicitAutograd: add_ - func: addmv(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor + structured_delegate: addmv.out variants: function, method - dispatch: - CPU, CUDA: addmv - func: addmv_(Tensor(a!) self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + structured_delegate: addmv.out variants: function, method - dispatch: - CPU, CUDA: addmv_ - func: addmv.out(Tensor self, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - CPU, CUDA: addmv_out - -- func: _addmv_impl_(Tensor(a!) self, Tensor self2, Tensor mat, Tensor vec, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) - dispatch: - CPU: addmv_impl_cpu - CUDA: addmv_impl_cuda + CPU: addmv_out_cpu + CUDA: addmv_out_cuda + SparseCsrCPU: addmv_out_sparse_csr + SparseCsrCUDA: addmv_out_sparse_csr_cuda - func: addr(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor variants: function, method dispatch: CPU, CUDA: addr - Math: math_addr + CompositeImplicitAutograd: math_addr - func: addr_(Tensor(a!) self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) variants: method dispatch: - DefaultBackend: addr_ + CompositeExplicitAutograd: addr_ - func: addr.out(Tensor self, Tensor vec1, Tensor vec2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: addr_out - Math: math_addr_out + CompositeImplicitAutograd: math_addr_out - func: affine_grid_generator(Tensor theta, int[] size, bool align_corners) -> Tensor variants: function dispatch: - DefaultBackend: affine_grid_generator + CompositeExplicitAutograd: affine_grid_generator - func: affine_grid_generator_backward(Tensor grad, int[] size, bool align_corners) -> Tensor variants: function - func: all.dim(Tensor self, int dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: all.out variants: function, method - dispatch: - CPU, CUDA: all - func: all.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + precomputed: + - dim -> int dim dispatch: CPU, CUDA: all_out - func: all.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: all.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: allclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> bool variants: function, method - func: any.dim(Tensor self, int dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: any.out variants: function, method - dispatch: - CPU, CUDA: any - func: any.out(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + precomputed: + - dim -> int dim dispatch: CPU, CUDA: any_out - func: any.dimname(Tensor self, Dimname dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: any.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: arange(Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: arange.start(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: arange.start_step(Scalar start, Scalar end, Scalar step, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: arange.out(Scalar end, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: arange.start_out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: arange_cpu_out + CPU, Meta: arange_out CUDA: arange_cuda_out # This function is a temporary hack to allow tracing of arange like constructs with dynamic @@ -484,37 +612,36 @@ - func: _dim_arange(Tensor like, int dim) -> Tensor - func: argmax(Tensor self, int? dim=None, bool keepdim=False) -> Tensor + structured_delegate: argmax.out + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: argmax - func: argmax.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: CPU, CUDA: argmax_out - func: argmin(Tensor self, int? dim=None, bool keepdim=False) -> Tensor + structured_delegate: argmin.out + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: argmin - func: argmin.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: CPU, CUDA: argmin_out - func: acosh(Tensor self) -> Tensor variants: function, method - dispatch: - DefaultBackend: acosh + structured_delegate: acosh.out - func: acosh_(Tensor(a!) self) -> Tensor(a!) variants: function, method - dispatch: - DefaultBackend: acosh_ + structured_delegate: acosh.out - func: acosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: acosh_out @@ -526,22 +653,28 @@ variants: function, method - func: arccosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: asinh(Tensor self) -> Tensor variants: function, method + structured_delegate: asinh.out dispatch: - DefaultBackend: asinh + SparseCPU, SparseCUDA: asinh_sparse + SparseCsrCPU, SparseCsrCUDA: asinh_sparse_csr - func: asinh_(Tensor(a!) self) -> Tensor(a!) variants: function, method + structured_delegate: asinh.out dispatch: - DefaultBackend: asinh_ + SparseCPU, SparseCUDA: asinh_sparse_ + SparseCsrCPU, SparseCsrCUDA: asinh_sparse_csr_ - func: asinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: asinh_out + SparseCPU, SparseCUDA: asinh_sparse_out + SparseCsrCPU, SparseCsrCUDA: asinh_sparse_csr_out # arcsinh, alias for asinh - func: arcsinh(Tensor self) -> Tensor @@ -551,22 +684,29 @@ variants: function, method - func: arcsinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: atanh(Tensor self) -> Tensor + structured_delegate: atanh.out variants: function, method dispatch: - DefaultBackend: atanh + CompositeExplicitAutograd: atanh + SparseCPU, SparseCUDA: atanh_sparse + SparseCsrCPU, SparseCsrCUDA: atanh_sparse_csr - func: atanh_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: atanh.out variants: function, method dispatch: - DefaultBackend: atanh_ + SparseCPU, SparseCUDA: atanh_sparse_ + SparseCsrCPU, SparseCsrCUDA: atanh_sparse_csr_ - func: atanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: atanh_out + SparseCPU, SparseCUDA: atanh_sparse_out + SparseCsrCPU, SparseCsrCUDA: atanh_sparse_csr_out # arctanh, alias for atanh - func: arctanh(Tensor self) -> Tensor @@ -576,39 +716,48 @@ variants: function, method - func: arctanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: as_strided(Tensor(a) self, int[] size, int[] stride, int? storage_offset=None) -> Tensor(a) variants: function, method dispatch: - CPU, CUDA: as_strided_tensorimpl + ZeroTensor, CPU, CUDA, Meta: as_strided_tensorimpl QuantizedCPU, QuantizedCUDA: as_strided_qtensorimpl + device_check: NoCheck device_guard: False - func: as_strided_(Tensor(a!) self, int[] size, int[] stride, int? storage_offset=None) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + use_const_ref_for_mutable_tensors: True variants: function, method + device_check: NoCheck device_guard: False + tags: inplace_view dispatch: - DefaultBackend: as_strided_ + CompositeExplicitAutograd: as_strided_ - func: asin(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + structured_delegate: asin.out dispatch: - CPU, CUDA: asin SparseCPU, SparseCUDA: asin_sparse + SparseCsrCPU, SparseCsrCUDA: asin_sparse_csr - func: asin_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method + structured_delegate: asin.out dispatch: - CPU, CUDA: asin_ SparseCPU, SparseCUDA: asin_sparse_ + SparseCsrCPU, SparseCsrCUDA: asin_sparse_csr_ - func: asin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: asin_out - SparseCPU, SparseCUDA: asin_out_sparse + SparseCPU, SparseCUDA: asin_sparse_out + SparseCsrCPU, SparseCsrCUDA: asin_sparse_csr_out # arcsin, alias of asin - func: arcsin(Tensor self) -> Tensor @@ -618,22 +767,31 @@ variants: function, method - func: arcsin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: atan(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: atan.out variants: function, method dispatch: - DefaultBackend: atan + SparseCPU, SparseCUDA: atan_sparse + SparseCsrCPU, SparseCsrCUDA: atan_sparse_csr - func: atan_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: atan.out variants: function, method dispatch: - DefaultBackend: atan_ + SparseCPU, SparseCUDA: atan_sparse_ + SparseCsrCPU, SparseCsrCUDA: atan_sparse_csr_ - func: atan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: atan_out + SparseCPU, SparseCUDA: atan_sparse_out + SparseCsrCPU, SparseCsrCUDA: atan_sparse_csr_out # arctan, alias of atan - func: arctan(Tensor self) -> Tensor @@ -643,7 +801,6 @@ variants: function, method - func: arctan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: atleast_1d(Tensor self) -> Tensor variants: function @@ -664,63 +821,54 @@ - func: baddbmm(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor variants: function, method - dispatch: - CPU: baddbmm_cpu - CUDA: baddbmm_cuda + structured_delegate: baddbmm.out - func: baddbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) variants: method - dispatch: - CPU: baddbmm__cpu - CUDA: baddbmm__cuda - -- func: _baddbmm_mkl_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) - variants: function + structured_delegate: baddbmm.out - func: baddbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True variants: function dispatch: CPU: baddbmm_out_cpu CUDA: baddbmm_out_cuda - func: bartlett_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: bartlett_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor - func: quantized_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor var, float eps, float output_scale, int output_zero_point) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: QuantizedCPU: quantized_batch_norm - func: _batch_norm_impl_index(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> (Tensor, Tensor, Tensor, Tensor, int) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: _batch_norm_impl_index_backward(int impl_index, Tensor input, Tensor grad_output, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var_transform, bool train, float eps, bool[3] output_mask, Tensor reservedSpace) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures # Sample bernoulli with values in `self` as probability. - func: bernoulli(Tensor self, *, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: bernoulli + CompositeExplicitAutograd: bernoulli - func: bernoulli.out(Tensor self, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: CPU, CUDA: bernoulli_out - func: bernoulli_.Tensor(Tensor(a!) self, Tensor p, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: bernoulli_ - func: bernoulli_.float(Tensor(a!) self, float p=0.5, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: bernoulli_ @@ -729,13 +877,13 @@ # There is no default valid on `p` here because it would introduce ambiguity # with `bernoulli(Tensor self, *, Generator? generator=None)` declaration. - func: bernoulli.p(Tensor self, float p, *, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: bilinear(Tensor input1, Tensor input2, Tensor weight, Tensor? bias) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: binary_cross_entropy(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn variants: function dispatch: @@ -743,7 +891,7 @@ CUDA: binary_cross_entropy_cuda - func: binary_cross_entropy.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn variants: function dispatch: @@ -751,7 +899,6 @@ CUDA: binary_cross_entropy_out_cuda - func: binary_cross_entropy_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn variants: function dispatch: @@ -759,7 +906,6 @@ CUDA: binary_cross_entropy_backward_cuda - func: binary_cross_entropy_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn variants: function dispatch: @@ -767,123 +913,149 @@ CUDA: binary_cross_entropy_backward_out_cuda - func: binary_cross_entropy_with_logits(Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: - DefaultBackend: binary_cross_entropy_with_logits + CompositeExplicitAutograd: binary_cross_entropy_with_logits - func: binary_cross_entropy_with_logits_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight=None, Tensor? pos_weight=None, int reduction=Mean) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - func: bincount(Tensor self, Tensor? weights=None, int minlength=0) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function, method dispatch: CPU: _bincount_cpu CUDA: _bincount_cuda - func: bitwise_not(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: bitwise_not.out variants: function, method - func: bitwise_not_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: bitwise_not.out variants: method - func: bitwise_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: bitwise_not_out -- func: copysign.Tensor(Tensor self, Tensor other) -> Tensor - variants: function, method - dispatch: - CPU, CUDA: copysign - -- func: copysign_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: copysign_ - - func: copysign.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: copysign_out +- func: copysign.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: copysign.out + +- func: copysign_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: copysign.out + - func: copysign.Scalar(Tensor self, Scalar other) -> Tensor variants: function, method dispatch: - CPU, CUDA: copysign + CompositeExplicitAutograd: copysign - func: copysign_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) variants: method dispatch: - CPU, CUDA: copysign_ + CompositeExplicitAutograd: copysign_ + +- func: copysign.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CompositeExplicitAutograd: copysign_out - func: logical_not(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + dispatch: + CompositeExplicitAutograd: logical_not - func: logical_not_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + dispatch: + CompositeExplicitAutograd: logical_not_ - func: logical_not.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: logical_not_out - func: logical_xor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + dispatch: + CompositeExplicitAutograd: logical_xor - func: logical_xor_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + dispatch: + CompositeExplicitAutograd: logical_xor_ - func: logical_xor.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: logical_xor_out - func: logical_and(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + dispatch: + CompositeExplicitAutograd: logical_and - func: logical_and_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + dispatch: + CompositeExplicitAutograd: logical_and_ - func: logical_and.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: logical_and_out - func: logical_or(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + dispatch: + CompositeExplicitAutograd: logical_or - func: logical_or_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + dispatch: + CompositeExplicitAutograd: logical_or_ - func: logical_or.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: logical_or_out - func: blackman_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: blackman_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: bmm(Tensor self, Tensor mat2) -> Tensor + structured_delegate: bmm.out variants: function, method dispatch: - CPU: bmm_cpu - CUDA: bmm_cuda SparseCPU: bmm_sparse_cpu SparseCUDA: bmm_sparse_cuda -- func: _bmm(Tensor self, Tensor mat2, *, bool deterministic=False) -> Tensor - variants: function - dispatch: - SparseCUDA: _bmm_sparse_cuda - - func: bmm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True variants: function dispatch: CPU: bmm_out_cpu @@ -891,246 +1063,350 @@ SparseCPU: bmm_out_sparse_cpu SparseCUDA: bmm_out_sparse_cuda -- func: _bmm.out(Tensor self, Tensor mat2, *, bool deterministic=False, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - variants: function - dispatch: - SparseCUDA: _bmm_out_sparse_cuda - - func: broadcast_tensors(Tensor[] tensors) -> Tensor[] + device_check: NoCheck device_guard: False - func: broadcast_to(Tensor(a) self, int[] size) -> Tensor(a) variants: function, method + +- func: _sparse_broadcast_to(Tensor(a) self, int[] size) -> Tensor(a) + variants: function dispatch: - Math: broadcast_to + SparseCPU, SparseCUDA: sparse_broadcast_to - func: cat(Tensor[] tensors, int dim=0) -> Tensor dispatch: - DefaultBackend: cat + CompositeExplicitAutograd: cat - func: cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: cat_out + CompositeExplicitAutograd: cat_out - func: cat.names(Tensor[] tensors, Dimname dim) -> Tensor - func: cat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + +# alias for torch.cat +- func: concat(Tensor[] tensors, int dim=0) -> Tensor + +- func: concat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) + +- func: concat.names(Tensor[] tensors, Dimname dim) -> Tensor + +- func: concat.names_out(Tensor[] tensors, Dimname dim, *, Tensor(a!) out) -> Tensor(a!) - func: block_diag(Tensor[] tensors) -> Tensor variants: function - func: ceil(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: ceil.out variants: function, method dispatch: - DefaultBackend: ceil + CompositeExplicitAutograd: ceil + SparseCPU, SparseCUDA: ceil_sparse + SparseCsrCPU, SparseCsrCUDA: ceil_sparse_csr - func: ceil_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: ceil.out variants: function, method dispatch: - DefaultBackend: ceil_ + CompositeExplicitAutograd: ceil_ + SparseCPU, SparseCUDA: ceil_sparse_ + SparseCsrCPU, SparseCsrCUDA: ceil_sparse_csr_ - func: ceil.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: ceil_out + SparseCPU, SparseCUDA: ceil_sparse_out + SparseCsrCPU, SparseCsrCUDA: ceil_sparse_csr_out +# alias for torch.linalg.multi_dot - func: chain_matmul(Tensor[] matrices) -> Tensor variants: function +# alias for torch.linalg.multi_dot +- func: chain_matmul.out(Tensor[] matrices, *, Tensor(a!) out) -> Tensor(a!) + - func: unsafe_chunk(Tensor self, int chunks, int dim=0) -> Tensor[] variants: function, method + device_check: NoCheck device_guard: False -- func: chunk(Tensor(a) self, int chunks, int dim=0) -> Tensor(a)[] +- func: chunk(Tensor(a -> *) self, int chunks, int dim=0) -> Tensor(a)[] variants: function, method + device_check: NoCheck device_guard: False -- func: tensor_split.sections(Tensor(a) self, int sections, int dim=0) -> Tensor(a)[] +- func: tensor_split.sections(Tensor(a -> *) self, int sections, int dim=0) -> Tensor(a)[] variants: function, method -- func: tensor_split.indices(Tensor(a) self, int[] indices, int dim=0) -> Tensor(a)[] +- func: tensor_split.indices(Tensor(a -> *) self, int[] indices, int dim=0) -> Tensor(a)[] variants: function, method -- func: tensor_split.tensor_indices_or_sections(Tensor(a) self, Tensor tensor_indices_or_sections, int dim=0) -> Tensor(a)[] +- func: tensor_split.tensor_indices_or_sections(Tensor(a -> *) self, Tensor tensor_indices_or_sections, int dim=0) -> Tensor(a)[] variants: function, method - func: clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ['min'] + structured_delegate: clamp.out + dispatch: + QuantizedCPU: clamp_quantized_cpu + +- func: clamp.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor variants: function, method dispatch: CPU, CUDA: clamp - QuantizedCPU: clamp_quantized_cpu - func: clamp_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function, method + cpp_no_default_args: ['min'] + structured_delegate: clamp.out + dispatch: + CompositeExplicitAutograd: clamp_ + +- func: clamp_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!) variants: function, method dispatch: - DefaultBackend: clamp_ + CompositeExplicitAutograd: clamp_ - func: clamp.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + cpp_no_default_args: ['min'] + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: clamp_out + +- func: clamp.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: clamp_out - func: clamp_max(Tensor self, Scalar max) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: clamp_max + CompositeExplicitAutograd: clamp_max + +- func: clamp_max.Tensor(Tensor self, Tensor max) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: clamp_max - func: clamp_max_(Tensor(a!) self, Scalar max) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: clamp_max_ + CompositeExplicitAutograd: clamp_max_ + +- func: clamp_max_.Tensor(Tensor(a!) self, Tensor max) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: clamp_max_ - func: clamp_max.out(Tensor self, Scalar max, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA: clamp_max_out + +- func: clamp_max.Tensor_out(Tensor self, Tensor max, *, Tensor(a!) out) -> Tensor(a!) dispatch: CPU, CUDA: clamp_max_out - func: clamp_min(Tensor self, Scalar min) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: clamp_min + CompositeExplicitAutograd: clamp_min + +- func: clamp_min.Tensor(Tensor self, Tensor min) -> Tensor + variants: function, method + dispatch: + CompositeExplicitAutograd: clamp_min - func: clamp_min_(Tensor(a!) self, Scalar min) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: clamp_min_ + CompositeExplicitAutograd: clamp_min_ + +- func: clamp_min_.Tensor(Tensor(a!) self, Tensor min) -> Tensor(a!) + variants: function, method + dispatch: + CompositeExplicitAutograd: clamp_min_ - func: clamp_min.out(Tensor self, Scalar min, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + dispatch: + CPU, CUDA: clamp_min_out + +- func: clamp_min.Tensor_out(Tensor self, Tensor min, *, Tensor(a!) out) -> Tensor(a!) dispatch: CPU, CUDA: clamp_min_out # clip is an alias for clamp - func: clip(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor + cpp_no_default_args: ['min'] + variants: function, method + +- func: clip.Tensor(Tensor self, Tensor? min=None, Tensor? max=None) -> Tensor variants: function, method - func: clip_(Tensor(a!) self, Scalar? min=None, Scalar? max=None) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + cpp_no_default_args: ['min'] + variants: function, method + +- func: clip_.Tensor(Tensor(a!) self, Tensor? min=None, Tensor? max=None) -> Tensor(a!) variants: function, method - func: clip.out(Tensor self, Scalar? min=None, Scalar? max=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + cpp_no_default_args: ['min'] + +- func: clip.Tensor_out(Tensor self, Tensor? min=None, Tensor? max=None, *, Tensor(a!) out) -> Tensor(a!) - func: cudnn_is_acceptable(Tensor self) -> bool + device_check: NoCheck device_guard: False - func: complex(Tensor real, Tensor imag) -> Tensor variants: function dispatch: - DefaultBackend: complex + CompositeExplicitAutograd: complex - func: complex.out(Tensor real, Tensor imag, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: complex_out - func: polar(Tensor abs, Tensor angle) -> Tensor variants: function dispatch: - DefaultBackend: polar + CompositeExplicitAutograd: polar - func: polar.out(Tensor abs, Tensor angle, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: polar_out - func: constant_pad_nd(Tensor self, int[] pad, Scalar value=0) -> Tensor variants: function dispatch: - DefaultBackend: constant_pad_nd + CompositeExplicitAutograd: constant_pad_nd - func: contiguous(Tensor(a) self, *, MemoryFormat memory_format=contiguous_format) -> Tensor(a) variants: method manual_cpp_binding: True - func: convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + dispatch: + CompositeExplicitAutograd: convolution + +- func: convolution_backward(Tensor grad_output, Tensor input, Tensor weight, int[]? bias_sizes, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) + dispatch: + CompositeExplicitAutograd, CUDA: convolution_backward - func: convolution_overrideable(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: convolution_overrideable + CompositeExplicitAutograd: convolution_overrideable - func: convolution_backward_overrideable(Tensor grad_output, Tensor input, Tensor weight, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) dispatch: - DefaultBackend: convolution_backward_overrideable + CompositeExplicitAutograd: convolution_backward_overrideable - func: _convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + dispatch: + CompositeExplicitAutograd: _convolution - func: _convolution.deprecated(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures -- func: _convolution_nogroup(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _convolution_mode(Tensor input, Tensor weight, Tensor? bias, int[] stride, str padding, int[] dilation, int groups) -> Tensor -- func: _convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor gO, Tensor weight, Tensor self, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _convolution_double_backward(Tensor? ggI, Tensor? ggW, Tensor? ggb, Tensor gO, Tensor weight, Tensor self, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - func: conv1d(Tensor input, Tensor weight, Tensor? bias=None, int[1] stride=1, int[1] padding=0, int[1] dilation=1, int groups=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: conv2d(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1, int groups=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: conv3d(Tensor input, Tensor weight, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] dilation=1, int groups=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + +- func: conv1d.padding(Tensor input, Tensor weight, Tensor? bias=None, int[1] stride=1, str padding="valid", int[1] dilation=1, int groups=1) -> Tensor + cpp_no_default_args: ['bias', 'stride', 'padding'] + +- func: conv2d.padding(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, str padding="valid", int[2] dilation=1, int groups=1) -> Tensor + cpp_no_default_args: ['bias', 'stride', 'padding'] + +- func: conv3d.padding(Tensor input, Tensor weight, Tensor? bias=None, int[3] stride=1, str padding="valid", int[3] dilation=1, int groups=1) -> Tensor + cpp_no_default_args: ['bias', 'stride', 'padding'] - func: conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad=0) -> Tensor dispatch: - DefaultBackend: conv_tbc + CompositeExplicitAutograd: conv_tbc - func: conv_tbc_backward(Tensor self, Tensor input, Tensor weight, Tensor bias, int pad) -> (Tensor, Tensor, Tensor) # NB: we inherit the goofy argument order from PyTorch torch.nn.functional - func: conv_transpose1d(Tensor input, Tensor weight, Tensor? bias=None, int[1] stride=1, int[1] padding=0, int[1] output_padding=0, int groups=1, int[1] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: conv_transpose2d.input(Tensor input, Tensor weight, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] output_padding=0, int groups=1, int[2] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: conv_transpose3d.input(Tensor input, Tensor weight, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] output_padding=0, int groups=1, int[3] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: copy_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: copy_ + MkldnnCPU: copy_mkldnn_ + SparseCPU, SparseCUDA, SparseHIP: copy_sparse_wrapper_ + CompositeExplicitAutograd: copy_ + SparseCsrCPU, SparseCsrCUDA: copy_sparse_csr_ - func: _copy_from(Tensor self, Tensor dst, bool non_blocking=False) -> Tensor dispatch: {} +# We need this to be able to properly copy from a CPU to an XLA tensor with different sizes. +# See https://github.com/pytorch/xla/issues/2881 +- func: _copy_from_and_resize(Tensor self, Tensor dst) -> Tensor + dispatch: {} + - func: cos(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: cos + structured_delegate: cos.out - func: cos_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: cos_ + structured_delegate: cos.out - func: cos.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: cos_out - func: cosh(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: cosh + structured_delegate: cosh.out - func: cosh_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: cosh_ + structured_delegate: cosh.out - func: cosh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: cosh_out @@ -1139,12 +1415,19 @@ - func: count_nonzero.dim_IntList(Tensor self, int[] dim) -> Tensor variants: function, method dispatch: - CPU, CUDA: count_nonzero + CPU: count_nonzero_cpu + CUDA: count_nonzero_cuda - func: count_nonzero(Tensor self, int? dim=None) -> Tensor variants: function, method dispatch: - DefaultBackend: count_nonzero + CompositeExplicitAutograd: count_nonzero + +- func: cov(Tensor self, *, int correction=1, Tensor? fweights=None, Tensor? aweights=None) -> Tensor + variants: function, method + +- func: corrcoef(Tensor self) -> Tensor + variants: function, method - func: cudnn_affine_grid_generator(Tensor theta, int N, int C, int H, int W) -> Tensor grid dispatch: @@ -1156,67 +1439,29 @@ CUDA: cudnn_affine_grid_generator_backward - func: cudnn_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: cudnn_batch_norm # NB: You can only use this if you used cudnn_batch_norm training=True - func: cudnn_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon, Tensor reserveSpace) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: cudnn_batch_norm_backward -- func: cudnn_convolution.deprecated(Tensor self, Tensor weight, Tensor? bias, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - CUDA: cudnn_convolution_deprecated - -- func: cudnn_convolution.deprecated2(Tensor self, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: cudnn_convolution_deprecated2 - - func: cudnn_convolution(Tensor self, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor dispatch: CUDA: cudnn_convolution -- func: cudnn_convolution_backward_input(int[] self_size, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor - dispatch: - CUDA: cudnn_convolution_backward_input - -- func: cudnn_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32, bool[2] output_mask) -> (Tensor, Tensor) - dispatch: - CUDA: cudnn_convolution_backward - -- func: cudnn_convolution_backward_weight(int[] weight_size, Tensor grad_output, Tensor self, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor - dispatch: - CUDA: cudnn_convolution_backward_weight - -- func: cudnn_convolution_transpose.deprecated(Tensor self, Tensor weight, Tensor? bias, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - CUDA: cudnn_convolution_transpose_deprecated - -- func: cudnn_convolution_transpose.deprecated2(Tensor self, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: cudnn_convolution_transpose_deprecated2 - - func: cudnn_convolution_transpose(Tensor self, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor dispatch: CUDA: cudnn_convolution_transpose -# NB: output_padding not strictly needed here, but it's helpful for the float -# backwards -- func: cudnn_convolution_transpose_backward(Tensor self, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32, bool[2] output_mask) -> (Tensor, Tensor) +- func: cudnn_convolution_relu(Tensor self, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor dispatch: - CUDA: cudnn_convolution_transpose_backward + CUDA: cudnn_convolution_relu -- func: cudnn_convolution_transpose_backward_input(Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor +- func: cudnn_convolution_add_relu(Tensor self, Tensor weight, Tensor z, Scalar? alpha, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor dispatch: - CUDA: cudnn_convolution_transpose_backward_input - -- func: cudnn_convolution_transpose_backward_weight(int[] weight_size, Tensor grad_output, Tensor self, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor - dispatch: - CUDA: cudnn_convolution_transpose_backward_weight + CUDA: cudnn_convolution_add_relu # NB: input is special cased in a way I don't quite understand - func: cudnn_grid_sampler(Tensor self, Tensor grid) -> Tensor output @@ -1228,46 +1473,48 @@ CUDA: cudnn_grid_sampler_backward - func: cummax(Tensor self, int dim) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: cummax + CompositeExplicitAutograd: cummax - func: cummax.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: cummax_out + CompositeExplicitAutograd: cummax_out - func: cummax.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: function, method - func: cummax.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: _cummax_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> () - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU: cummax_helper_cpu CUDA: cummax_helper_cuda - func: cummin(Tensor self, int dim) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: cummin + CompositeExplicitAutograd: cummin - func: cummin.out(Tensor self, int dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: cummin_out + CompositeExplicitAutograd: cummin_out - func: cummin.dimname(Tensor self, Dimname dim) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: function, method - func: cummin.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: _cummin_helper(Tensor self, Tensor(a!) values, Tensor(b!) indices, int dim) -> () - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU: cummin_helper_cpu @@ -1275,59 +1522,67 @@ - func: cummaxmin_backward(Tensor grad, Tensor input, Tensor indices, int dim) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: cumprod(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + structured_delegate: cumprod.out + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: cumprod - func: cumprod_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!) + structured_delegate: cumprod.out variants: method - dispatch: - DefaultBackend: cumprod_ - func: cumprod.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: cumprod_out + CPU, CUDA: cumprod_out - func: cumprod.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: cumprod_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!) variants: method - func: cumprod.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator -- func: cumprod_backward(Tensor grad, Tensor input, int dim) -> Tensor +- func: cumprod_backward(Tensor grad, Tensor input, int dim, Tensor output) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: cumsum(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + structured_delegate: cumsum.out + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - DefaultBackend: cumsum - func: cumsum_(Tensor(a!) self, int dim, *, ScalarType? dtype=None) -> Tensor(a!) + structured_delegate: cumsum.out variants: method - dispatch: - DefaultBackend: cumsum_ - func: cumsum.out(Tensor self, int dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: cumsum_out + CPU, CUDA: cumsum_out - func: cumsum.dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: cumsum_.dimname(Tensor(a!) self, Dimname dim, *, ScalarType? dtype=None) -> Tensor(a!) variants: method - func: cumsum.dimname_out(Tensor self, Dimname dim, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: cumulative_trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor + +- func: cumulative_trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor - func: ctc_loss.IntList(Tensor log_probs, Tensor targets, int[] input_lengths, int[] target_lengths, int blank=0, int reduction=Mean, bool zero_infinity=False) -> Tensor @@ -1353,79 +1608,118 @@ - func: diagonal(Tensor(a) self, int offset=0, int dim1=0, int dim2=1) -> Tensor(a) variants: function, method dispatch: - DefaultBackend: diagonal + CompositeExplicitAutograd: diagonal + +- func: linalg_diagonal(Tensor(a) A, *, int offset=0, int dim1=-2, int dim2=-1) -> Tensor(a) + python_module: linalg + variants: function - func: diagonal.Dimname(Tensor(a) self, *, Dimname outdim, Dimname dim1, Dimname dim2, int offset=0) -> Tensor(a) variants: function, method -- func: diagonal_backward(Tensor grad, int[] input_sizes, int offset, int dim1, int dim2) -> Tensor +- func: diagonal_backward(Tensor grad_output, int[] input_sizes, int offset, int dim1, int dim2) -> Tensor variants: function + device_check: NoCheck device_guard: False + dispatch: + CompositeExplicitAutograd: diagonal_backward - func: fill_diagonal_(Tensor(a!) self, Scalar fill_value, bool wrap=False) -> Tensor(a!) variants: method - func: diff(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None) -> Tensor variants: function, method - dispatch: - Math: diff - func: diff.out(Tensor self, int n=1, int dim=-1, Tensor? prepend=None, Tensor? append=None, *, Tensor(a!) out) -> Tensor(a!) variants: function - dispatch: - Math: diff_out + +- func: gradient.scalarint(Tensor self, *, Scalar? spacing=None, int? dim=None, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.scalararray(Tensor self, *, Scalar spacing, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.array(Tensor self, *, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.scalarrayint(Tensor self, *, Scalar[] spacing, int? dim=None, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.scalarrayarray(Tensor self, *, Scalar[] spacing, int[] dim, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.tensorarrayint(Tensor self, *, Tensor[] spacing, int? dim=None, int edge_order=1) -> Tensor[] + variants: function + +- func: gradient.tensorarray(Tensor self, *, Tensor[] spacing, int[] dim, int edge_order=1) -> Tensor[] + variants: function - func: div.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + structured_delegate: div.out dispatch: - CPU, CUDA: div SparseCPU, SparseCUDA: div_sparse - func: div_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + structured_delegate: div.out dispatch: - CPU, CUDA: div_ SparseCPU, SparseCUDA: div_sparse_ - func: div.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: div_out SparseCPU, SparseCUDA: div_out_sparse_zerodim -- func: div.Tensor_mode(Tensor self, Tensor other, *, str rounding_mode) -> Tensor +- func: div.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + structured_delegate: div.out_mode dispatch: - CPU, CUDA: div + SparseCPU, SparseCUDA: div_sparse -- func: div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str rounding_mode) -> Tensor(a!) +- func: div_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + structured_delegate: div.out_mode dispatch: - CPU, CUDA: div_ + SparseCPU, SparseCUDA: div_sparse_ -- func: div.out_mode(Tensor self, Tensor other, *, str rounding_mode, Tensor(a!) out) -> Tensor(a!) +- func: div.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: - CPU, CUDA: div_out + CPU, CUDA: div_out_mode + SparseCPU, SparseCUDA: div_out_sparse_zerodim # For C++ only, until we have conversion from C++ numbers to Tensor - func: div.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: div + CompositeExplicitAutograd: div - func: div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: div_ + CompositeExplicitAutograd: div_ -- func: div.Scalar_mode(Tensor self, Scalar other, *, str rounding_mode) -> Tensor +- func: div.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor variants: function, method dispatch: - DefaultBackend: div + CompositeExplicitAutograd: div -- func: div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str rounding_mode) -> Tensor(a!) +- func: div_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!) variants: method dispatch: - DefaultBackend: div_ + CompositeExplicitAutograd: div_ # divide, alias for div - func: divide.Tensor(Tensor self, Tensor other) -> Tensor @@ -1435,7 +1729,6 @@ variants: method - func: divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: divide.Scalar(Tensor self, Scalar other) -> Tensor variants: function, method @@ -1443,34 +1736,38 @@ - func: divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) variants: method -- func: divide.Tensor_mode(Tensor self, Tensor other, *, str rounding_mode) -> Tensor +- func: divide.Tensor_mode(Tensor self, Tensor other, *, str? rounding_mode) -> Tensor variants: function, method -- func: divide_.Tensor_mode(Tensor(a!) self, Tensor other, *, str rounding_mode) -> Tensor(a!) +- func: divide_.Tensor_mode(Tensor(a!) self, Tensor other, *, str? rounding_mode) -> Tensor(a!) variants: method -- func: divide.out_mode(Tensor self, Tensor other, *, str rounding_mode, Tensor(a!) out) -> Tensor(a!) +- func: divide.out_mode(Tensor self, Tensor other, *, str? rounding_mode, Tensor(a!) out) -> Tensor(a!) -- func: divide.Scalar_mode(Tensor self, Scalar other, *, str rounding_mode) -> Tensor +- func: divide.Scalar_mode(Tensor self, Scalar other, *, str? rounding_mode) -> Tensor variants: function, method -- func: divide_.Scalar_mode(Tensor(a!) self, Scalar other, *, str rounding_mode) -> Tensor(a!) +- func: divide_.Scalar_mode(Tensor(a!) self, Scalar other, *, str? rounding_mode) -> Tensor(a!) variants: method # true_divide, an alias for div - func: true_divide.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: true_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: true_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: true_divide.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: true_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: dot(Tensor self, Tensor tensor) -> Tensor @@ -1480,9 +1777,8 @@ CUDA: dot_cuda - func: dot.out(Tensor self, Tensor tensor, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: dot_out + CompositeExplicitAutograd: dot_out - func: vdot(Tensor self, Tensor other) -> Tensor variants: function, method @@ -1491,15 +1787,14 @@ CUDA: vdot_cuda - func: vdot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: vdot_out + CompositeExplicitAutograd: vdot_out - func: einsum(str equation, Tensor[] tensors) -> Tensor - func: embedding(Tensor weight, Tensor indices, int padding_idx=-1, bool scale_grad_by_freq=False, bool sparse=False) -> Tensor dispatch: - DefaultBackend: embedding + CompositeExplicitAutograd: embedding - func: embedding_backward(Tensor grad, Tensor indices, int num_weights, int padding_idx, bool scale_grad_by_freq, bool sparse) -> Tensor @@ -1525,8 +1820,7 @@ # The backward functions apply a check that these input tensors are contiguous. -- func: _embedding_bag_forward_only(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _embedding_bag_forward_only(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor) dispatch: CPU: _embedding_bag_forward_only_cpu CUDA: _embedding_bag_forward_only_cuda @@ -1535,71 +1829,72 @@ # row_stack is the alias of vstack - func: row_stack(Tensor[] tensors) -> Tensor - dispatch: - Math: row_stack - func: row_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: row_stack_out - func: embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures -- func: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False) -> (Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +# To keep backward and forward compatibility, and to avoid ambiguity with the +# original signature above, scale_grad_by_freq, mode, sparse, +# per_sample_weights, and include_last_offset parameters do not have default +# values. Once the original signature is removed, default values can be added. +- func: embedding_bag.padding_idx(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, bool include_last_offset, int? padding_idx) -> (Tensor, Tensor, Tensor, Tensor) + +- func: _embedding_bag(Tensor weight, Tensor indices, Tensor offsets, bool scale_grad_by_freq=False, int mode=0, bool sparse=False, Tensor? per_sample_weights=None, bool include_last_offset=False, int padding_idx=-1) -> (Tensor, Tensor, Tensor, Tensor) dispatch: CPU: _embedding_bag_cpu CUDA: _embedding_bag_cuda -- func: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, int num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _embedding_bag_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, int num_weights, bool scale_grad_by_freq, int mode, bool sparse, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor -- func: _embedding_bag_sparse_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, int num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _embedding_bag_sparse_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, int num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor -- func: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offsets, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, int num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _embedding_bag_dense_backward(Tensor grad, Tensor indices, Tensor offset2bag, Tensor bag_size, Tensor maximum_indices, int num_weights, bool scale_grad_by_freq, int mode, Tensor? per_sample_weights, int padding_idx=-1) -> Tensor dispatch: CPU: _embedding_bag_dense_backward_cpu CUDA: _embedding_bag_dense_backward_cuda -- func: _embedding_bag_per_sample_weights_backward(Tensor grad, Tensor weight, Tensor indices, Tensor offsets, Tensor offset2bag, int mode) -> Tensor +- func: _embedding_bag_per_sample_weights_backward(Tensor grad, Tensor weight, Tensor indices, Tensor offsets, Tensor offset2bag, int mode, int padding_idx=-1) -> Tensor dispatch: CPU: _embedding_bag_per_sample_weights_backward_cpu CUDA: _embedding_bag_per_sample_weights_backward_cuda -- func: empty_meta(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - - func: empty.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: empty.memory_format(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor dispatch: CPU: empty_cpu CUDA: empty_cuda + Meta: empty_meta MkldnnCPU: empty_mkldnn SparseCPU, SparseCUDA: empty_sparse + SparseCsrCPU, SparseCsrCUDA: empty_sparse_csr +# We do not make new_empty a composite that calls into new_empty_strided, as the strided version +# is significantly more difficult to implement by different backends - func: new_empty(Tensor self, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor variants: method + dispatch: + CompositeExplicitAutograd: new_empty - func: new_empty_strided(Tensor self, int[] size, int[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: method + dispatch: + CompositeExplicitAutograd: new_empty_strided - func: new_full(Tensor self, int[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: method - func: new_zeros(Tensor self, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + variants: method + +- func: new_ones(Tensor self, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor variants: method # other overrides are to provide a more helpful error message that dtype is required - func: _empty_affine_quantized(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, float scale=1, int zero_point=0, MemoryFormat? memory_format=contiguous_format) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: empty_affine_quantized_other_backends_stub QuantizedCPU, QuantizedCUDA: empty_affine_quantized @@ -1607,138 +1902,166 @@ # it's a factory function receiving a tensor argument, thus overriding explicitly # other overrides are to provide a more helpful error message that dtype is required - func: _empty_per_channel_affine_quantized(int[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures category_override: factory dispatch: CPU: empty_per_channel_affine_quantized_other_backends_stub QuantizedCPU, QuantizedCUDA: empty_per_channel_affine_quantized - func: resize_(Tensor(a!) self, int[] size, *, MemoryFormat? memory_format=None) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True variants: method + device_check: NoCheck device_guard: False dispatch: - CPU: resize_ + CPU, Meta: resize_ CUDA: resize_cuda_ QuantizedCPU: quantized_resize_cpu_ - Meta: resize_meta_ + SparseCsrCPU, SparseCsrCUDA: resize_sparse_csr_ -- func: empty_quantized(int[] size, Tensor qtensor) -> Tensor +- func: empty_quantized(int[] size, Tensor qtensor, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor + category_override: factory variants: function dispatch: QuantizedCPU, QuantizedCUDA: empty_quantized - func: empty.out(int[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: empty_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False + dispatch: + CompositeExplicitAutograd: empty_like + SparseCPU, SparseCUDA: empty_like_sparse_coo + SparseCsrCPU, SparseCsrCUDA: empty_like_sparse_csr - func: empty_strided(int[] size, int[] stride, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor dispatch: CPU: empty_strided_cpu CUDA: empty_strided_cuda + Meta: empty_strided_meta - func: erf(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: erf.out variants: function, method dispatch: - DefaultBackend: erf + SparseCPU, SparseCUDA: erf_sparse + SparseCsrCPU, SparseCsrCUDA: erf_sparse_csr - func: erf_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: erf.out variants: function, method dispatch: - DefaultBackend: erf_ + SparseCPU, SparseCUDA: erf_sparse_ + SparseCsrCPU, SparseCsrCUDA: erf_sparse_csr_ - func: erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: erf_out + SparseCPU, SparseCUDA: erf_sparse_out + SparseCsrCPU, SparseCsrCUDA: erf_sparse_csr_out - func: erfc(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: erfc.out variants: function, method - dispatch: - DefaultBackend: erfc - func: erfc_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: erfc.out variants: function, method - dispatch: - DefaultBackend: erfc_ - func: erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: erfc_out - func: exp(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: exp.out variants: function, method - dispatch: - DefaultBackend: exp - func: exp_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: exp.out variants: function, method - dispatch: - DefaultBackend: exp_ - func: exp.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: exp_out - func: exp2(Tensor self) -> Tensor + structured_delegate: exp2.out variants: function, method - dispatch: - DefaultBackend: exp2 - func: exp2_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: exp2.out variants: function, method - dispatch: - DefaultBackend: exp2_ - func: exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: exp2_out - func: expm1(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: expm1.out variants: function, method dispatch: - DefaultBackend: expm1 + SparseCPU, SparseCUDA: expm1_sparse + SparseCsrCPU, SparseCsrCUDA: expm1_sparse_csr - func: expm1_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: expm1.out variants: function, method dispatch: - DefaultBackend: expm1_ + SparseCPU, SparseCUDA: expm1_sparse_ + SparseCsrCPU, SparseCsrCUDA: expm1_sparse_csr_ - func: expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: expm1_out + SparseCPU, SparseCUDA: expm1_sparse_out + SparseCsrCPU, SparseCsrCUDA: expm1_sparse_csr_out - func: expand(Tensor(a) self, int[] size, *, bool implicit=False) -> Tensor(a) variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: expand + CompositeExplicitAutograd: expand - func: expand_as(Tensor(a) self, Tensor other) -> Tensor(a) variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. + device_check: NoCheck device_guard: False - func: eye(int n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: eye.m(int n, int m, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: eye.out(int n, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: eye_out_cpu CUDA: eye_out_cuda - func: eye.m_out(int n, int m, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: eye_out_cpu CUDA: eye_out_cuda @@ -1762,107 +2085,131 @@ variants: method - func: fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: fill_ + CPU, CUDA, QuantizedCPU, QuantizedCUDA: fill_ + Meta: fill_meta_ - func: fill_.Tensor(Tensor(a!) self, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: fill_ + CPU, CUDA, QuantizedCPU, QuantizedCUDA: fill_ + Meta: fill_meta_ - func: floor(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: floor.out variants: function, method dispatch: - DefaultBackend: floor + CompositeExplicitAutograd: floor + SparseCPU, SparseCUDA: floor_sparse + SparseCsrCPU, SparseCsrCUDA: floor_sparse_csr - func: floor_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: floor.out variants: function, method dispatch: - DefaultBackend: floor_ + CompositeExplicitAutograd: floor_ + SparseCPU, SparseCUDA: floor_sparse_ + SparseCsrCPU, SparseCsrCUDA: floor_sparse_csr_ - func: floor.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: floor_out + SparseCPU, SparseCUDA: floor_sparse_out + SparseCsrCPU, SparseCsrCUDA: floor_sparse_csr_out - func: floor_divide(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: floor_divide SparseCPU, SparseCUDA: floor_divide_sparse - func: floor_divide_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: floor_divide_ SparseCPU, SparseCUDA: floor_divide_sparse_ - func: floor_divide.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: floor_divide_out SparseCPU, SparseCUDA: floor_divide_out_sparse_zerodim - func: floor_divide.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: floor_divide_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: frac(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: frac.out variants: function, method - dispatch: - DefaultBackend: frac - func: frac_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: frac.out variants: function, method - dispatch: - DefaultBackend: frac_ - func: frac.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: frac_out - func: full.names(int[] size, Scalar fill_value, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: full(int[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: full.out(int[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: full_like(Tensor self, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: from_file(str filename, bool? shared=None, int? size=0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: from_file - func: gcd.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: gcd_out - func: gcd(Tensor self, Tensor other) -> Tensor + structured_delegate: gcd.out variants: function, method - func: gcd_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: gcd.out variants: function, method - func: lcm.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: lcm_out - func: lcm(Tensor self, Tensor other) -> Tensor + structured_delegate: lcm.out variants: function, method - func: lcm_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: lcm.out variants: function, method # NOTE [ grid_sampler Native Functions ] @@ -1884,10 +2231,13 @@ - func: grid_sampler_2d(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor dispatch: - CPU: grid_sampler_2d_cpu + CPU, QuantizedCPU: grid_sampler_2d_cpu CUDA: grid_sampler_2d_cuda -- func: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor) +# `grid_sampler_2d_backward` takes in `output_mask` to optimize performance for +# the case where `input` doesn't require gradient. Gradient for `grid` is always +# computed (only `output_mask[0]` is checked by the implementations). +- func: grid_sampler_2d_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, bool[2] output_mask) -> (Tensor, Tensor) dispatch: CPU: grid_sampler_2d_backward_cpu CUDA: grid_sampler_2d_backward_cuda @@ -1895,7 +2245,7 @@ # See NOTE [ grid_sample CPU fallback ] - func: _grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor dispatch: - DefaultBackend: _grid_sampler_2d_cpu_fallback + CompositeExplicitAutograd: _grid_sampler_2d_cpu_fallback - func: _grid_sampler_2d_cpu_fallback_backward(Tensor grad_output, Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> (Tensor, Tensor) @@ -1910,45 +2260,33 @@ CUDA: grid_sampler_3d_backward_cuda - func: hann_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: hann_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: hamming_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: hamming_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: hamming_window.periodic_alpha(int window_length, bool periodic, float alpha, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: hamming_window.periodic_alpha_beta(int window_length, bool periodic, float alpha, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: kaiser_window(int window_length, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: kaiser_window.periodic(int window_length, bool periodic, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: kaiser_window.beta(int window_length, bool periodic, float beta, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: hinge_embedding_loss(Tensor self, Tensor target, float margin=1.0, int reduction=Mean) -> Tensor - func: group_norm(Tensor input, int num_groups, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enabled=True) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: native_group_norm(Tensor input, Tensor? weight, Tensor? bias, int N, int C, int HxW, int group, float eps) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: native_group_norm - Math: math_group_norm + CompositeImplicitAutograd: math_group_norm - func: native_group_norm_backward(Tensor grad_out, Tensor input, Tensor mean, Tensor rstd, Tensor? weight, int N, int C, int HxW, int group, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: native_group_norm_backward @@ -1960,7 +2298,6 @@ CUDA: _fft_r2c_cufft - func: _fft_r2c.out(Tensor self, int[] dim, int normalization, bool onesided, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU: _fft_r2c_mkl_out @@ -1974,7 +2311,6 @@ CUDA: _fft_c2r_cufft - func: _fft_c2r.out(Tensor self, int[] dim, int normalization, int last_dim_size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU: _fft_c2r_mkl_out @@ -1988,7 +2324,6 @@ CUDA: _fft_c2c_cufft - func: _fft_c2c.out(Tensor self, int[] dim, int normalization, bool forward, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU: _fft_c2c_mkl_out @@ -2003,6 +2338,7 @@ - func: _cufft_clear_plan_cache(int device_index) -> () - func: index.Tensor(Tensor self, Tensor?[] indices) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: index @@ -2015,7 +2351,7 @@ - func: index_copy_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!) variants: method dispatch: - DefaultBackend: index_copy_ + CompositeExplicitAutograd: index_copy_ - func: index_copy(Tensor self, int dim, Tensor index, Tensor source) -> Tensor variants: function, method @@ -2027,9 +2363,10 @@ variants: function, method - func: index_put_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor(a!) + device_check: NoCheck # delegate to _index_put_impl_, which leverages TensorIterator variants: function, method dispatch: - DefaultBackend: index_put_ + CompositeExplicitAutograd: index_put_ # NB: The following functions are declared in aten/src/ATen/templates/TensorBody.h and defined in aten/src/ATen/TensorIndexing.cpp: # - Tensor & Tensor::index_put_(ArrayRef indices, Tensor const & rhs) # - Tensor & Tensor::index_put_(ArrayRef indices, Scalar v) @@ -2037,73 +2374,129 @@ # - Tensor & Tensor::index_put_(std::initializer_list indices, Scalar v) - func: index_put(Tensor self, Tensor?[] indices, Tensor values, bool accumulate=False) -> Tensor + device_check: NoCheck # delegate to _index_put_impl_ after clone, which leverages TensorIterator variants: function, method - func: _index_put_impl_(Tensor(a!) self, Tensor?[] indices, Tensor values, bool accumulate=False, bool unsafe=False) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function dispatch: CPU, CUDA: _index_put_impl_ - func: instance_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool use_input_stats, float momentum, float eps, bool cudnn_enabled) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - func: inverse(Tensor self) -> Tensor variants: function, method dispatch: - DefaultBackend: inverse + CompositeExplicitAutograd: inverse - func: inverse.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: inverse_out - -- func: _inverse_helper(Tensor self) -> Tensor - variants: function - dispatch: - CPU: _inverse_helper_cpu - CUDA: _inverse_helper_cuda + CompositeExplicitAutograd: inverse_out - func: isclose(Tensor self, Tensor other, float rtol=1e-05, float atol=1e-08, bool equal_nan=False) -> Tensor variants: function, method +- func: isin.Tensor_Tensor_out(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!) + variants: function + structured: True + dispatch: + CPU, CUDA: isin_Tensor_Tensor_out + +- func: isin.Tensor_Tensor(Tensor elements, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor + variants: function + structured_delegate: isin.Tensor_Tensor_out + +- func: isin.Tensor_Scalar_out(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!) + variants: function + structured: True + dispatch: + CPU, CUDA: isin_Tensor_Scalar_out + +- func: isin.Tensor_Scalar(Tensor elements, Scalar test_element, *, bool assume_unique=False, bool invert=False) -> Tensor + variants: function + structured_delegate: isin.Tensor_Scalar_out + +- func: isin.Scalar_Tensor_out(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False, Tensor(a!) out) -> Tensor(a!) + variants: function + structured: True + dispatch: + CPU, CUDA: isin_Scalar_Tensor_out + +- func: isin.Scalar_Tensor(Scalar element, Tensor test_elements, *, bool assume_unique=False, bool invert=False) -> Tensor + variants: function + structured_delegate: isin.Scalar_Tensor_out + - func: isnan(Tensor self) -> Tensor variants: function, method + device_check: NoCheck device_guard: False dispatch: CPU, CUDA: isnan SparseCPU, SparseCUDA: isnan_sparse + SparseCsrCPU, SparseCsrCUDA: isnan_sparse_csr - func: is_distributed(Tensor self) -> bool variants: function, method + device_check: NoCheck device_guard: False - func: is_floating_point(Tensor self) -> bool variants: function, method + device_check: NoCheck device_guard: False + manual_cpp_binding: True - func: is_complex(Tensor self) -> bool variants: function, method + device_check: NoCheck device_guard: False + manual_cpp_binding: True + +- func: is_conj(Tensor self) -> bool + variants: function, method + device_guard: False + manual_cpp_binding: True + +- func: _is_zerotensor(Tensor self) -> bool + variants: function, method + device_guard: False + manual_cpp_binding: True + +- func: is_neg(Tensor self) -> bool + variants: function, method + device_guard: False + manual_cpp_binding: True - func: isreal(Tensor self) -> Tensor variants: function, method - func: is_nonzero(Tensor self) -> bool variants: function, method + device_check: NoCheck device_guard: False - func: is_same_size(Tensor self, Tensor other) -> bool variants: function, method + device_check: NoCheck device_guard: False - func: is_signed(Tensor self) -> bool variants: function, method + device_check: NoCheck device_guard: False + manual_cpp_binding: True + +- func: is_inference(Tensor self) -> bool + variants: function, method + device_check: NoCheck + device_guard: False + manual_cpp_binding: True - func: kl_div(Tensor self, Tensor target, int reduction=Mean, *, bool log_target=False) -> Tensor dispatch: - DefaultBackend: kl_div + CompositeExplicitAutograd: kl_div - func: kl_div_backward(Tensor grad_output, Tensor self, Tensor target, int reduction=Mean, *, bool log_target=False) -> Tensor dispatch: @@ -2112,21 +2505,15 @@ - func: kron(Tensor self, Tensor other) -> Tensor variants: function, method - dispatch: - Math: kron - func: kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: kron_out - func: kthvalue(Tensor self, int k, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) variants: function, method dispatch: - DefaultBackend: kthvalue + CompositeExplicitAutograd: kthvalue - func: kthvalue.values(Tensor self, int k, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: kthvalue_out_cpu CUDA: kthvalue_out_cuda @@ -2135,20 +2522,21 @@ variants: function, method - func: kthvalue.dimname_out(Tensor self, int k, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: layer_norm(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05, bool cudnn_enable=True) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: native_layer_norm(Tensor input, int[] normalized_shape, Tensor? weight, Tensor? bias, float eps) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: layer_norm_cpu CUDA: layer_norm_cuda - Math: math_native_layer_norm + CompositeImplicitAutograd: math_native_layer_norm + +- func: native_multi_head_self_attention(Tensor query, Tensor qkv_weight, Tensor qkv_bias, Tensor proj_weight, Tensor proj_bias, Tensor? mask=None) -> Tensor + dispatch: + CPU: multi_head_self_attention_cpu + CUDA: multi_head_self_attention_cuda - func: native_layer_norm_backward(Tensor grad_out, Tensor input, int[] normalized_shape, Tensor mean, Tensor rstd, Tensor? weight, Tensor? bias, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: layer_norm_backward_cpu CUDA: layer_norm_backward_cuda @@ -2156,40 +2544,40 @@ - func: nan_to_num(Tensor self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor variants: function, method dispatch: - DefaultBackend: nan_to_num + CompositeExplicitAutograd: nan_to_num + SparseCPU, SparseCUDA: nan_to_num_sparse - func: nan_to_num_(Tensor(a!) self, float? nan=None, float? posinf=None, float? neginf=None) -> Tensor(a!) variants: function, method dispatch: - DefaultBackend: nan_to_num_ + CompositeExplicitAutograd: nan_to_num_ + SparseCPU, SparseCUDA: nan_to_num_sparse_ - func: nan_to_num.out(Tensor self, float? nan=None, float? posinf=None, float? neginf=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: nan_to_num_out + CPU, CUDA: nan_to_num_out + SparseCPU, SparseCUDA: nan_to_num_sparse_out - func: linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + python_module: nn + +- func: linear.out(Tensor input, Tensor weight, Tensor? bias=None, *, Tensor(a!) out) -> Tensor(a!) python_module: nn - func: mkldnn_linear(Tensor self, Tensor weight, Tensor? bias=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: MkldnnCPU: mkldnn_linear - func: mkldnn_linear_backward_input(int[] input_size, Tensor grad_output, Tensor weight) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - MkldnnCPU: mkldnn_linear_backward_input + MkldnnCPU: mkldnn_linear_backward_input - func: mkldnn_linear_backward_weights(Tensor grad_output, Tensor input, Tensor weight, bool bias_defined) -> (Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: MkldnnCPU: mkldnn_linear_backward_weights - func: mkldnn_linear_backward(Tensor self, Tensor grad_output, Tensor weight, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: MkldnnCPU: mkldnn_linear_backward @@ -2216,157 +2604,176 @@ variants: function, method - func: ldexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: linspace(Scalar start, Scalar end, int? steps=None, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: linspace.out(Scalar start, Scalar end, int? steps=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: linspace_cpu_out + CPU, Meta: linspace_out CUDA: linspace_cuda_out - func: log(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log.out variants: function, method - dispatch: - DefaultBackend: log - func: log_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log.out variants: function, method - dispatch: - DefaultBackend: log_ - func: log.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: log_out - func: log10(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log10.out variants: function, method dispatch: - DefaultBackend: log10 + CompositeExplicitAutograd: log10 - func: log10_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log10.out variants: function, method - dispatch: - DefaultBackend: log10_ - func: log10.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: log10_out - func: log1p(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log1p.out variants: function, method dispatch: - CPU, CUDA: log1p SparseCPU, SparseCUDA: log1p_sparse + SparseCsrCPU, SparseCsrCUDA: log1p_sparse_csr - func: log1p_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log1p.out variants: function, method dispatch: - CPU, CUDA: log1p_ SparseCPU, SparseCUDA: log1p_sparse_ + SparseCsrCPU, SparseCsrCUDA: log1p_sparse_csr_ - func: log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: log1p_out - SparseCPU, SparseCUDA: log1p_out_sparse + SparseCPU, SparseCUDA: log1p_sparse_out + SparseCsrCPU, SparseCsrCUDA: log1p_sparse_csr_out - func: log2(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: log2.out variants: function, method - dispatch: - DefaultBackend: log2 - func: log2_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: log2.out variants: function, method - dispatch: - DefaultBackend: log2_ - func: log2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: log2_out - func: logaddexp.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: logaddexp_out - func: logaddexp(Tensor self, Tensor other) -> Tensor variants: method, function + structured_delegate: logaddexp.out dispatch: - DefaultBackend: logaddexp + CompositeExplicitAutograd: logaddexp - func: logaddexp2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: logaddexp2_out - func: logaddexp2(Tensor self, Tensor other) -> Tensor variants: method, function + structured_delegate: logaddexp2.out dispatch: - DefaultBackend: logaddexp2 + CompositeExplicitAutograd: logaddexp2 - func: xlogy.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: xlogy.OutTensor variants: function, method - dispatch: - CPU, CUDA: xlogy - func: xlogy.Scalar_Self(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function dispatch: - CPU, CUDA: xlogy + CompositeExplicitAutograd: xlogy - func: xlogy.Scalar_Other(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - CPU, CUDA: xlogy + CompositeExplicitAutograd: xlogy # xlogy: inplace variant - func: xlogy_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: xlogy_ + structured_delegate: xlogy.OutTensor - func: xlogy_.Scalar_Other(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: - CPU, CUDA: xlogy_ + CompositeExplicitAutograd: xlogy_ # xlogy: out variant - func: xlogy.OutTensor(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase variants: function dispatch: CPU, CUDA: xlogy_out - func: xlogy.OutScalar_Self(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: - CPU, CUDA: xlogy_out + CompositeExplicitAutograd: xlogy_out - func: xlogy.OutScalar_Other(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: - CPU, CUDA: xlogy_out + CompositeExplicitAutograd: xlogy_out - func: logdet(Tensor self) -> Tensor variants: function, method dispatch: - DefaultBackend: logdet + CompositeExplicitAutograd: logdet - func: logspace(Scalar start, Scalar end, int? steps=None, float base=10.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: logspace.out(Scalar start, Scalar end, int? steps=None, float base=10.0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: logspace_cpu_out + CPU, Meta: logspace_out CUDA: logspace_cuda_out # log_softmax allows positional dtype, unlike most operators, because kwonly is BC-breaking when loading jit models. @@ -2377,14 +2784,22 @@ variants: function, method - func: _log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor - dispatch: - CPU: log_softmax_cpu - CUDA: log_softmax_cuda + structured_delegate: _log_softmax.out -- func: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor +- func: _log_softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!) + structured: True dispatch: - CPU: log_softmax_backward_cpu - CUDA: log_softmax_backward_cuda + CPU: log_softmax_cpu_out + CUDA: log_softmax_cuda_out + +- func: _log_softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor + structured_delegate: _log_softmax_backward_data.out + +- func: _log_softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: log_softmax_backward_cpu_out + CUDA: log_softmax_backward_cuda_out - func: _logcumsumexp(Tensor self, int dim) -> Tensor dispatch: @@ -2392,7 +2807,6 @@ CUDA: _logcumsumexp_cuda - func: _logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: _logcumsumexp_out_cpu CUDA: _logcumsumexp_out_cuda @@ -2400,34 +2814,34 @@ - func: logcumsumexp(Tensor self, int dim) -> Tensor variants: function, method dispatch: - DefaultBackend: logcumsumexp + CompositeExplicitAutograd: logcumsumexp - func: logcumsumexp.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: logcumsumexp_out + CompositeExplicitAutograd: logcumsumexp_out - func: logcumsumexp.dimname(Tensor self, Dimname dim) -> Tensor variants: function, method - func: logcumsumexp.dimname_out(Tensor self, Dimname dim, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: logsumexp + CompositeExplicitAutograd: logsumexp - func: logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: logsumexp_out + CompositeExplicitAutograd: logsumexp_out - func: logsumexp.names(Tensor self, Dimname[1] dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: logsumexp.names_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: margin_ranking_loss(Tensor input1, Tensor input2, Tensor target, float margin=0.0, int reduction=Mean) -> Tensor @@ -2435,68 +2849,87 @@ variants: function, method - func: matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: matrix_rank.tol(Tensor self, float tol, bool symmetric=False) -> Tensor - func: matrix_rank(Tensor self, bool symmetric=False) -> Tensor +# Alias to linalg.matrix_power - func: matrix_power(Tensor self, int n) -> Tensor variants: function, method +# Alias to linalg.matrix_power +- func: matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!) + +# Alias to linalg.matrix_exp - func: matrix_exp(Tensor self) -> Tensor variants: function, method - dispatch: - CPU, CUDA: matrix_exp +# This function should be deprecated in favor of differential_analytic_matrix_function in FunctionsManual.cpp - func: matrix_exp_backward(Tensor self, Tensor grad) -> Tensor +# DEPRECATED: Use torch.aminmax instead - func: _aminmax(Tensor self) -> (Tensor, Tensor) - variants: function dispatch: CPU, CUDA: _aminmax_all +# DEPRECATED: Use torch.aminmax instead - func: _aminmax.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor, Tensor) - variants: function dispatch: CPU, CUDA: _aminmax +- func: aminmax(Tensor self, *, int? dim=None, bool keepdim=False) -> (Tensor min, Tensor max) + device_check: NoCheck # TensorIterator + structured_delegate: aminmax.out + variants: function, method + +- func: aminmax.out(Tensor self, *, int? dim=None, bool keepdim=False, Tensor(a!) min, Tensor(b!) max) -> (Tensor(a!) min, Tensor(b!) max) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA: aminmax_out + - func: _compute_linear_combination(Tensor input, Tensor coefficients) -> Tensor dispatch: CPU, CUDA: _compute_linear_combination - func: _compute_linear_combination.out(Tensor input, Tensor coefficients, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: _compute_linear_combination_out - func: max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + structured_delegate: max.dim_max variants: function, method dispatch: - DefaultBackend: max + QuantizedCPU, QuantizedCUDA: qmax - func: max.dim_max(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + precomputed: + - dim -> int dim dispatch: CPU, CUDA: max_out - func: max.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: function, method - func: max.names_dim_max(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) max, Tensor(b!) max_values) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: value_selecting_reduction_backward(Tensor grad, int dim, Tensor indices, int[] sizes, bool keepdim) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: amax(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor variants: function, method dispatch: - DefaultBackend: amax + CompositeExplicitAutograd: amax - func: amax.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: amax_out @@ -2505,16 +2938,28 @@ - func: max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor +- func: _max_pool1d_cpu_forward(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + CPU: _max_pool1d_cpu_forward + - func: max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor - func: mkldnn_max_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor dispatch: MkldnnCPU: mkldnn_max_pool2d +- func: mkldnn_max_pool2d_backward(Tensor grad_output, Tensor output, Tensor input, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MkldnnCPU: mkldnn_max_pool2d_backward + - func: mkldnn_max_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor dispatch: MkldnnCPU: mkldnn_max_pool3d +- func: mkldnn_max_pool3d_backward(Tensor grad_output, Tensor output, Tensor input, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False) -> Tensor + dispatch: + MkldnnCPU: mkldnn_max_pool3d_backward + - func: quantized_max_pool1d(Tensor self, int[1] kernel_size, int[1] stride=[], int[1] padding=0, int[1] dilation=1, bool ceil_mode=False) -> Tensor dispatch: QuantizedCPU: quantized_max_pool1d @@ -2528,28 +2973,38 @@ # The CPU and GPU dispatch variants are named weirdly here because otherwise there # are namespacing issues in C++ - func: mean(Tensor self, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - CPU, CUDA: mean_cpu_gpu - QuantizedCPU: mean_quantized_cpu + CompositeExplicitAutograd: mean - func: mean.dim(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + structured_delegate: mean.out + device_check: NoCheck # TensorIterator variants: function, method dispatch: - CPU, CUDA: mean_cpu_gpu QuantizedCPU: mean_quantized_cpu - func: mean.out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: mean_out_cpu_gpu + CPU, CUDA: mean_out QuantizedCPU: mean_out_quantized_cpu - func: mean.names_dim(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: mean.names_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: nanmean(Tensor self, int[1] dim=[], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # Composite + variants: function, method + +- func: nanmean.out(Tensor self, int[1] dim=[], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # Composite - func: median(Tensor self) -> Tensor variants: function, method @@ -2560,10 +3015,9 @@ - func: median.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) variants: function, method dispatch: - DefaultBackend: median + CompositeExplicitAutograd: median - func: median.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: median_out_cpu CUDA: median_out_cuda @@ -2572,7 +3026,6 @@ variants: function, method - func: median.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: nanmedian(Tensor self) -> Tensor variants: function, method @@ -2583,10 +3036,9 @@ - func: nanmedian.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) variants: function, method dispatch: - DefaultBackend: nanmedian + CompositeExplicitAutograd: nanmedian - func: nanmedian.dim_values(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: nanmedian_out_cpu CUDA: nanmedian_out_cuda @@ -2595,137 +3047,84 @@ variants: function, method - func: nanmedian.names_dim_values(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator + structured_delegate: min.dim_min variants: function, method dispatch: - DefaultBackend: min + QuantizedCPU, QuantizedCUDA: qmin - func: min.dim_min(Tensor self, int dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + precomputed: + - dim -> int dim dispatch: CPU, CUDA: min_out - func: min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: function, method - func: min.names_dim_min(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) min, Tensor(b!) min_indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: amin(Tensor self, int[1] dim=[], bool keepdim=False) -> Tensor variants: function, method dispatch: - DefaultBackend: amin + CompositeExplicitAutograd: amin - func: amin.out(Tensor self, int[1] dim=[], bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: amin_out - func: mkldnn_convolution(Tensor self, Tensor weight, Tensor? bias, int[] padding, int[] stride, int[] dilation, int groups) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: mkldnn_convolution - -- func: mkldnn_convolution_backward_input(int[] self_size, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool bias_defined) -> Tensor - -- func: mkldnn_convolution_backward_weights(int[] weight_size, Tensor grad_output, Tensor self, int[] padding, int[] stride, int[] dilation, int groups, bool bias_defined) -> (Tensor, Tensor) - -- func: mkldnn_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - dispatch: - DefaultBackend: mkldnn_convolution_backward + CompositeExplicitAutograd: mkldnn_convolution - func: miopen_batch_norm(Tensor input, Tensor weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float exponential_average_factor, float epsilon) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_batch_norm - func: miopen_batch_norm_backward(Tensor input, Tensor grad_output, Tensor weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_var, float epsilon) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_batch_norm_backward - func: miopen_convolution(Tensor self, Tensor weight, Tensor? bias, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_convolution -- func: miopen_convolution_backward_input(int[] self_size, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: miopen_convolution_backward_input - -- func: miopen_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - dispatch: - CUDA: miopen_convolution_backward - -- func: miopen_convolution_backward_bias(Tensor grad_output) -> Tensor - dispatch: - CUDA: miopen_convolution_backward_bias - -- func: miopen_convolution_backward_weight(int[] weight_size, Tensor grad_output, Tensor self, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: miopen_convolution_backward_weight - - func: miopen_convolution_transpose(Tensor self, Tensor weight, Tensor? bias, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_convolution_transpose -# NB: output_padding not strictly needed here, but it's helpful for the float -# backwards -- func: miopen_convolution_transpose_backward(Tensor self, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - dispatch: - CUDA: miopen_convolution_transpose_backward - -- func: miopen_convolution_transpose_backward_input(Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: miopen_convolution_transpose_backward_input - -- func: miopen_convolution_transpose_backward_weight(int[] weight_size, Tensor grad_output, Tensor self, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: miopen_convolution_transpose_backward_weight - - func: miopen_depthwise_convolution(Tensor self, Tensor weight, Tensor? bias, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_depthwise_convolution -- func: miopen_depthwise_convolution_backward_input(int[] self_size, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: miopen_depthwise_convolution_backward_input - -- func: miopen_depthwise_convolution_backward(Tensor self, Tensor grad_output, Tensor weight, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - dispatch: - CUDA: miopen_depthwise_convolution_backward - -- func: miopen_depthwise_convolution_backward_weight(int[] weight_size, Tensor grad_output, Tensor self, int[] padding, int[] stride, int[] dilation, int groups, bool benchmark, bool deterministic) -> Tensor - dispatch: - CUDA: miopen_depthwise_convolution_backward_weight - - func: miopen_rnn(Tensor input, Tensor[] weight, int weight_stride0, Tensor hx, Tensor? cx, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state) -> (Tensor, Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_rnn - func: miopen_rnn_backward(Tensor input, Tensor[] weight, int weight_stride0, Tensor weight_buf, Tensor hx, Tensor? cx, Tensor output, Tensor? grad_output, Tensor? grad_hy, Tensor? grad_cy, int mode, int hidden_size, int num_layers, bool batch_first, float dropout, bool train, bool bidirectional, int[] batch_sizes, Tensor? dropout_state, Tensor reserve, bool[4] output_mask) -> (Tensor, Tensor, Tensor, Tensor[]) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: miopen_rnn_backward - func: mm(Tensor self, Tensor mat2) -> Tensor + structured_delegate: mm.out variants: function, method dispatch: - CPU: mm_cpu - CUDA: mm_cuda SparseCPU, SparseCUDA: _sparse_mm + SparseCsrCPU, SparseCsrCUDA: _sparse_csr_mm - func: mm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - CPU: mm_cpu_out + CPU: mm_out_cpu CUDA: mm_out_cuda SparseCPU, SparseCUDA: _sparse_mm_out + SparseCsrCPU, SparseCsrCUDA: _sparse_csr_mm_out - func: _sparse_mm(Tensor sparse, Tensor dense) -> Tensor @@ -2734,10 +3133,10 @@ SparseCPU: sparse_sparse_matmul_cpu SparseCUDA: sparse_sparse_matmul_cuda -- func: _sparse_matrix_mask_helper(Tensor t, Tensor mask_indices) -> Tensor +- func: _sparse_mask_helper(Tensor t, Tensor mask_indices) -> Tensor dispatch: - SparseCPU: sparse_matrix_mask_helper_cpu - SparseCUDA: sparse_matrix_mask_helper_cuda + SparseCPU: sparse_mask_helper_cpu + SparseCUDA: sparse_mask_helper_cuda - func: mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor values, Tensor indices) variants: function, method @@ -2745,32 +3144,35 @@ CPU, CUDA: mode - func: mode.values(Tensor self, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: mode_out + CompositeExplicitAutograd: mode_out - func: mode.dimname(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) variants: function, method - func: mode.dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: mul.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: mul.out variants: function, method dispatch: - CPU, CUDA: mul SparseCPU, SparseCUDA: mul_sparse MkldnnCPU: mkldnn_mul + ZeroTensor: mul_zerotensor - func: mul_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: mul.out variants: method dispatch: - CPU, CUDA: mul_ SparseCPU, SparseCUDA: mul_sparse_ MkldnnCPU: mkldnn_mul_ - func: mul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: mul_out SparseCPU: mul_out_sparse_cpu @@ -2779,14 +3181,16 @@ # For C++ only, until we have conversion from C++ numbers to Tensor - func: mul.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: mul + CompositeExplicitAutograd: mul - func: mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: mul_ + CompositeExplicitAutograd: mul_ # multiply, alias for mul - func: multiply.Tensor(Tensor self, Tensor other) -> Tensor @@ -2796,7 +3200,6 @@ variants: method - func: multiply.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: multiply.Scalar(Tensor self, Scalar other) -> Tensor variants: function, method @@ -2807,30 +3210,35 @@ - func: mv(Tensor self, Tensor vec) -> Tensor variants: function, method dispatch: - CPU, CUDA: mv + CompositeExplicitAutograd: mv SparseCPU, SparseCUDA: mv_sparse - func: mv.out(Tensor self, Tensor vec, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: mv_out + CompositeExplicitAutograd: mv_out + +- func: mvlgamma.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA: mvlgamma_out - func: mvlgamma(Tensor self, int p) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: mvlgamma + CompositeExplicitAutograd: mvlgamma - func: mvlgamma_(Tensor(a!) self, int p) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: mvlgamma_ + CompositeExplicitAutograd: mvlgamma_ - func: narrow_copy(Tensor self, int dim, int start, int length) -> Tensor variants: function, method dispatch: CPU: narrow_copy_dense_cpu SparseCPU, SparseCUDA: narrow_copy_sparse - DefaultBackend: narrow_copy_dense + CompositeExplicitAutograd: narrow_copy_dense - func: narrow_copy.out(Tensor self, int dim, int start, int length, *, Tensor(a!) out) -> Tensor(a!) dispatch: @@ -2838,21 +3246,21 @@ - func: narrow(Tensor(a) self, int dim, int start, int length) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: narrow.Tensor(Tensor(a) self, int dim, Tensor start, int length) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: native_batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: batch_norm_cpu CUDA: batch_norm_cuda MkldnnCPU: mkldnn_batch_norm - func: native_batch_norm.out(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, *, Tensor(a!) out, Tensor(b!) save_mean, Tensor(c!) save_invstd) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: batch_norm_cuda_out @@ -2861,44 +3269,37 @@ CUDA: batch_norm_stats_cuda - func: batch_norm_elemt(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: batch_norm_elemt_cuda - func: batch_norm_elemt.out(Tensor input, Tensor? weight, Tensor? bias, Tensor mean, Tensor invstd, float eps, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: batch_norm_elemt_cuda_out # for backward compatibility - func: batch_norm_gather_stats(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, int count) -> (Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: batch_norm_gather_stats_cuda - func: batch_norm_gather_stats_with_counts(Tensor input, Tensor mean, Tensor invstd, Tensor? running_mean, Tensor? running_var, float momentum, float eps, Tensor counts) -> (Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: batch_norm_gather_stats_with_counts_cuda - func: native_batch_norm_backward(Tensor grad_out, Tensor input, Tensor? weight, Tensor? running_mean, Tensor? running_var, Tensor? save_mean, Tensor? save_invstd, bool train, float eps, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: batch_norm_backward_cpu CUDA: batch_norm_backward_cuda + MkldnnCPU: mkldnn_batch_norm_backward - func: batch_norm_backward_reduce(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, bool input_g, bool weight_g, bool bias_g) -> (Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: batch_norm_backward_reduce_cuda -- func: batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor mean_dy, Tensor mean_dy_xmu) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: batch_norm_backward_elemt(Tensor grad_out, Tensor input, Tensor mean, Tensor invstd, Tensor? weight, Tensor mean_dy, Tensor mean_dy_xmu, Tensor count) -> Tensor dispatch: CUDA: batch_norm_backward_elemt_cuda - func: batch_norm_update_stats(Tensor input, Tensor? running_mean, Tensor? running_var, float momentum) -> (Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: batch_norm_update_stats_cpu CUDA: batch_norm_update_stats_cuda @@ -2908,32 +3309,19 @@ - func: _nnpack_available() -> bool - func: _nnpack_spatial_convolution(Tensor input, Tensor weight, Tensor? bias, int[2] padding, int[2] stride=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: - DefaultBackend: _nnpack_spatial_convolution - -- func: _nnpack_spatial_convolution_backward(Tensor input, Tensor grad_output, Tensor weight, int[2] padding, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - variants: function - -- func: _nnpack_spatial_convolution_backward_input(Tensor input, Tensor grad_output, Tensor weight, int[2] padding) -> Tensor - variants: function - -- func: _nnpack_spatial_convolution_backward_weight(Tensor input, int[] weightsize, Tensor grad_output, int[2] padding) -> Tensor - variants: function + CompositeExplicitAutograd: _nnpack_spatial_convolution - func: ones.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: ones(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: ones.out(int[] size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: ones_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: pairwise_distance(Tensor x1, Tensor x2, float p=2, float eps=1e-06, bool keepdim=False) -> Tensor @@ -2941,7 +3329,7 @@ - func: _euclidean_dist(Tensor x1, Tensor x2) -> Tensor dispatch: - DefaultBackend: _euclidean_dist + CompositeExplicitAutograd: _euclidean_dist - func: _cdist_forward(Tensor x1, Tensor x2, float p, int? compute_mode) -> Tensor dispatch: @@ -2965,9 +3353,9 @@ variants: function - func: permute(Tensor(a) self, int[] dims) -> Tensor(a) - variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. + variants: function, method dispatch: - DefaultBackend: permute + CompositeExplicitAutograd: permute - func: movedim.intlist(Tensor(a) self, int[] source, int[] destination) -> Tensor(a) variants: function, method @@ -2992,6 +3380,21 @@ - func: numpy_T(Tensor(a) self) -> Tensor(a) variants: method +# Exposed on Python as an attribute 'H' +- func: matrix_H(Tensor(a) self) -> Tensor(a) + variants: method + +# Exposed on Python as an attribute 'mT' +- func: mT(Tensor(a) self) -> Tensor(a) + variants: method + +# Exposed on Python as an attribute 'mH' +- func: mH(Tensor(a) self) -> Tensor(a) + variants: method + +- func: adjoint(Tensor(a) self) -> Tensor(a) + variants: function, method + - func: pixel_shuffle(Tensor self, int upscale_factor) -> Tensor - func: pixel_unshuffle(Tensor self, int downscale_factor) -> Tensor @@ -3001,11 +3404,26 @@ CPU: channel_shuffle QuantizedCPU: channel_shuffle_quantized_cpu -- func: is_pinned(Tensor self) -> bool +- func: native_channel_shuffle(Tensor self, int groups) -> Tensor + dispatch: + CPU: channel_shuffle_cpu + CompositeImplicitAutograd: math_channel_shuffle + +- func: is_pinned(Tensor self, Device? device=None) -> bool + variants: method + dispatch: + CUDA: is_pinned_cuda + CompositeExplicitAutograd: is_pinned_default + +# TODO: add a copy kwarg that guarantees that the tensor is put into fresh +# pinned memory +- func: pin_memory(Tensor(a) self, Device? device=None) -> Tensor(a) variants: method -- func: pin_memory(Tensor(a) self) -> Tensor(a) - variants: method +# Unlike pin_memory, this is guaranteed to give a new non-aliasing tensor +- func: _pin_memory(Tensor self, Device? device=None) -> Tensor + dispatch: + CUDA: _pin_memory_cuda - func: pinverse(Tensor self, float rcond=1e-15) -> Tensor variants: function, method @@ -3016,173 +3434,156 @@ - func: rad2deg(Tensor self) -> Tensor variants: function, method dispatch: - DefaultBackend: rad2deg + CompositeExplicitAutograd: rad2deg + SparseCsrCPU, SparseCsrCUDA: rad2deg_sparse_csr - func: rad2deg_(Tensor(a!) self) -> Tensor(a!) variants: function, method dispatch: - DefaultBackend: rad2deg_ + CompositeExplicitAutograd: rad2deg_ + SparseCsrCPU, SparseCsrCUDA: rad2deg_sparse_csr_ - func: rad2deg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: rad2deg_out + CompositeExplicitAutograd: rad2deg_out + SparseCsrCPU, SparseCsrCUDA: rad2deg_sparse_csr_out - func: deg2rad(Tensor self) -> Tensor variants: function, method dispatch: - DefaultBackend: deg2rad + CompositeExplicitAutograd: deg2rad - func: deg2rad_(Tensor(a!) self) -> Tensor(a!) variants: function, method dispatch: - DefaultBackend: deg2rad_ + CompositeExplicitAutograd: deg2rad_ - func: deg2rad.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: deg2rad_out + CompositeExplicitAutograd: deg2rad_out - func: scalar_tensor(Scalar s, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rand.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: rand.generator_with_names(int[] size, *, Generator? generator, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: rand(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rand.generator(int[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rand.out(int[] size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rand.generator_out(int[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rand_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint(int high, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.generator(int high, int[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.low(int low, int high, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.low_generator(int low, int high, int[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.out(int high, int[] size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.generator_out(int high, int[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.low_out(int low, int high, int[] size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint.low_generator_out(int low, int high, int[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint_like(Tensor self, int high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randint_like.low_dtype(Tensor self, int low, int high, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randn(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randn.generator(int[] size, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randn.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: randn.generator_with_names(int[] size, *, Generator? generator, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False - func: randn.out(int[] size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randn.generator_out(int[] size, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randn_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures -- func: randperm(int n, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: randperm(int n, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor -- func: randperm.generator(int n, *, Generator? generator, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: randperm.generator(int n, *, Generator? generator, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - func: randperm.out(int n, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: randperm.generator_out(int n, *, Generator? generator, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: randperm_out_cpu CUDA: randperm_out_cuda - func: range.step(Scalar start, Scalar end, Scalar step=1, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: range(Scalar start, Scalar end, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: range.out(Scalar start, Scalar end, Scalar step=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: range_cpu_out + CPU, Meta: range_out CUDA: range_cuda_out - func: ravel(Tensor(a) self) -> Tensor(a) variants: function, method - func: reciprocal(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: reciprocal.out variants: function, method - dispatch: - DefaultBackend: reciprocal - func: reciprocal_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: reciprocal.out variants: function, method - dispatch: - DefaultBackend: reciprocal_ - func: reciprocal.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: reciprocal_out - func: neg(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: neg.out variants: function, method dispatch: - DefaultBackend: neg + SparseCPU, SparseCUDA: neg_sparse + SparseCsrCPU, SparseCsrCUDA: neg_sparse_csr - func: neg_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: neg.out variants: function, method dispatch: - CPU, CUDA: neg_ SparseCPU, SparseCUDA: neg_sparse_ + SparseCsrCPU, SparseCsrCUDA: neg_sparse_csr_ - func: neg.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: neg_out SparseCPU, SparseCUDA: neg_out_sparse + SparseCsrCPU, SparseCsrCUDA: neg_sparse_csr_out # Alias for neg - func: negative(Tensor self) -> Tensor @@ -3192,59 +3593,103 @@ variants: function, method - func: negative.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: repeat(Tensor self, int[] repeats) -> Tensor variants: method # This is method-only to match the previous tensor API. In the future we could make this a function too. dispatch: - DefaultBackend: repeat + CompositeExplicitAutograd: repeat -- func: repeat_interleave.Tensor(Tensor repeats) -> Tensor +- func: repeat_interleave.Tensor(Tensor repeats, *, int? output_size=None) -> Tensor variants: function dispatch: CPU: repeat_interleave_cpu CUDA: repeat_interleave_cuda -- func: repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None) -> Tensor +- func: repeat_interleave.self_Tensor(Tensor self, Tensor repeats, int? dim=None, *, int? output_size=None) -> Tensor variants: function, method -- func: repeat_interleave.self_int(Tensor self, int repeats, int? dim=None) -> Tensor +- func: repeat_interleave.self_int(Tensor self, int repeats, int? dim=None, *, int? output_size=None) -> Tensor variants: function, method - func: reshape(Tensor(a) self, int[] shape) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False +# NOTE [ _reshape_alias ] is meant to be used in the implementation of reshape. +# They are not user-facing, hence the leading underscore. Please don't use it +# anywhere else. +- func: _reshape_alias(Tensor(a) self, int[] size, int[] stride) -> Tensor(a) + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CPU, CUDA, Meta, QuantizedCPU, QuantizedCUDA, ZeroTensor: _reshape_alias + # We don't need to support mkldnn since this is handled explicitly by the reshape operator. + - func: _mkldnn_reshape(Tensor self, int[] shape) -> Tensor + device_check: NoCheck device_guard: False dispatch: MkldnnCPU: mkldnn_reshape - func: reshape_as(Tensor(a) self, Tensor other) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False - func: round(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: round.out variants: function, method dispatch: - DefaultBackend: round + SparseCPU, SparseCUDA: round_sparse + SparseCsrCPU, SparseCsrCUDA: round_sparse_csr - func: round_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: round.out variants: function, method dispatch: - DefaultBackend: round_ + SparseCPU, SparseCUDA: round_sparse_ + SparseCsrCPU, SparseCsrCUDA: round_sparse_csr_ - func: round.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU: round_out CUDA: round_out + SparseCPU, SparseCUDA: round_sparse_out + SparseCsrCPU, SparseCsrCUDA: round_sparse_csr_out + +- func: round.decimals(Tensor self, *, int decimals) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: round.decimals_out + variants: function, method + +- func: round_.decimals(Tensor(a!) self, *, int decimals) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: round.decimals_out + variants: function, method + +- func: round.decimals_out(Tensor self, *, int decimals, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU: round_decimals_out + CUDA: round_decimals_out - func: rrelu(Tensor self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator - func: rrelu_(Tensor(a!) self, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator - func: relu(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: relu @@ -3252,12 +3697,19 @@ QuantizedCPU: relu_quantized_cpu - func: relu_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: relu_ MkldnnCPU: mkldnn_relu_ QuantizedCPU: relu_quantized_cpu_ +- func: relu6(Tensor self) -> Tensor + python_module: nn + +- func: relu6_(Tensor(a!) self) -> Tensor(a!) + python_module: nn + - func: prelu(Tensor self, Tensor weight) -> Tensor variants: function, method dispatch: @@ -3270,111 +3722,193 @@ CPU: prelu_backward_cpu CUDA: prelu_backward_cuda -- func: gelu(Tensor self) -> Tensor +- func: gelu.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator python_module: nn dispatch: - CPU: gelu_cpu - CUDA: gelu_cuda + CPU: gelu_out_cpu + CUDA: gelu_out_cuda + +- func: gelu(Tensor self) -> Tensor + structured_delegate: gelu.out + device_check: NoCheck # TensorIterator + python_module: nn + dispatch: + MkldnnCPU: mkldnn_gelu + QuantizedCPU: gelu_quantized_cpu + +- func: gelu_backward.grad_input(Tensor grad, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU: gelu_backward_out_cpu + CUDA: gelu_backward_out_cuda - func: gelu_backward(Tensor grad, Tensor self) -> Tensor + structured_delegate: gelu_backward.grad_input python_module: nn dispatch: - CPU: gelu_backward_cpu - CUDA: gelu_backward_cuda + MkldnnCPU: mkldnn_gelu_backward - func: infinitely_differentiable_gelu_backward(Tensor grad, Tensor self) -> Tensor variants: function python_module: nn + device_check: NoCheck device_guard: False -- func: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor - variants: function, method +- func: hardshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: hardshrink + CPU, CUDA: hardshrink_out + +- func: hardshrink(Tensor self, Scalar lambd=0.5) -> Tensor + structured_delegate: hardshrink.out + device_check: NoCheck # TensorIterator + variants: function, method + +- func: hardshrink_backward.grad_input(Tensor grad_out, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: hardshrink_backward_out - func: hardshrink_backward(Tensor grad_out, Tensor self, Scalar lambd) -> Tensor + structured_delegate: hardshrink_backward.grad_input variants: function, method - dispatch: - CPU, CUDA: hardshrink_backward - func: rsqrt(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: rsqrt.out variants: function, method - dispatch: - DefaultBackend: rsqrt - func: rsqrt_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: rsqrt.out variants: function, method - dispatch: - DefaultBackend: rsqrt_ - func: rsqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: rsqrt_out - func: select.Dimname(Tensor(a) self, Dimname dim, int index) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: select.int(Tensor(a) self, int dim, int index) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: select + CompositeExplicitAutograd: select -- func: select_backward(Tensor grad, int[] input_sizes, int dim, int index) -> Tensor +- func: select_backward(Tensor grad_output, int[] input_sizes, int dim, int index) -> Tensor variants: function + device_check: NoCheck device_guard: False + dispatch: + CompositeExplicitAutograd: select_backward - func: selu(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator - func: selu_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator - func: celu(Tensor self, Scalar alpha=1.0) -> Tensor + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: celu + CompositeExplicitAutograd: celu - func: celu_(Tensor(a!) self, Scalar alpha=1.0) -> Tensor(a!) + device_check: NoCheck # TensorIterator dispatch: - DefaultBackend: celu_ + CompositeExplicitAutograd: celu_ - func: silu(Tensor self) -> Tensor + structured_delegate: silu.out python_module: nn dispatch: - DefaultBackend: silu + CompositeExplicitAutograd: silu - func: silu_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: silu.out python_module: nn dispatch: - DefaultBackend: silu_ + CompositeExplicitAutograd: silu_ - func: silu.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: CPU, CUDA: silu_out -- func: silu_backward(Tensor grad_output, Tensor self) -> Tensor +- func: silu_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: - CPU, CUDA: silu_backward - Math: math_silu_backward + CPU, CUDA: silu_backward_out + +- func: silu_backward(Tensor grad_output, Tensor self) -> Tensor + structured_delegate: silu_backward.grad_input + python_module: nn + dispatch: + CompositeImplicitAutograd: math_silu_backward + +- func: mish(Tensor self) -> Tensor + structured_delegate: mish.out + python_module: nn + dispatch: + CompositeExplicitAutograd: mish + +- func: mish_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: mish.out + python_module: nn + dispatch: + CompositeExplicitAutograd: mish_ + +- func: mish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: nn + dispatch: + CPU, CUDA: mish_out + +- func: mish_backward(Tensor grad_output, Tensor self) -> Tensor + python_module: nn + dispatch: + CPU, CUDA: mish_backward + CompositeImplicitAutograd: math_mish_backward - func: sigmoid(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sigmoid.out variants: function, method dispatch: - CPU, CUDA: sigmoid QuantizedCPU: sigmoid_quantized_cpu MkldnnCPU: mkldnn_sigmoid - func: sigmoid_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sigmoid.out variants: function, method dispatch: - CPU, CUDA: sigmoid_ MkldnnCPU: mkldnn_sigmoid_ - func: sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sigmoid_out @@ -3389,54 +3923,72 @@ CPU, CUDA: logit_ - func: logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: logit_out - func: sin(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sin.out variants: function, method dispatch: - DefaultBackend: sin + SparseCsrCPU, SparseCsrCUDA: sin_sparse_csr + SparseCPU, SparseCUDA: sin_sparse - func: sin_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sin.out variants: function, method dispatch: - DefaultBackend: sin_ + SparseCsrCPU, SparseCsrCUDA: sin_sparse_csr_ + SparseCPU, SparseCUDA: sin_sparse_ - func: sin.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sin_out + SparseCsrCPU, SparseCsrCUDA: sin_sparse_csr_out + SparseCPU, SparseCUDA: sin_sparse_out - func: sinc(Tensor self) -> Tensor + structured_delegate: sinc.out variants: function, method - dispatch: - DefaultBackend: sinc - func: sinc_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: sinc.out variants: function, method - dispatch: - DefaultBackend: sinc_ - func: sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sinc_out - func: sinh(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sinh.out variants: function, method dispatch: - DefaultBackend: sinh + SparseCPU, SparseCUDA: sinh_sparse + SparseCsrCPU, SparseCsrCUDA: sinh_sparse_csr - func: sinh_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sinh.out variants: function, method dispatch: - DefaultBackend: sinh_ + SparseCPU, SparseCUDA: sinh_sparse_ + SparseCsrCPU, SparseCsrCUDA: sinh_sparse_csr_ - func: sinh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sinh_out + SparseCPU, SparseCUDA: sinh_sparse_out + SparseCsrCPU, SparseCsrCUDA: sinh_sparse_csr_out # Returns a copy of this `Variable` that is detached from its autograd graph. # This method is OK to call if the `Variable` is a view. @@ -3452,39 +4004,67 @@ - func: detach(Tensor(a) self) -> Tensor(a) variants: function, method dispatch: - DefaultBackend: detach + CompositeExplicitAutograd: detach # Like `detach()`, but modifies this `Variable` in-place. This method may # only be called on non-view `Variable`s. You can use `is_view()` to check # this. If this `Variable` is a view, throws an `std::runtime_error()`. - func: detach_(Tensor(a!) self) -> Tensor(a!) variants: function, method + tags: inplace_view dispatch: - DefaultBackend: detach_ + CompositeExplicitAutograd: detach_ - func: size.int(Tensor self, int dim) -> int variants: function + device_check: NoCheck device_guard: False manual_cpp_binding: True - func: size.Dimname(Tensor self, Dimname dim) -> int variants: function, method + device_check: NoCheck device_guard: False -- func: slice.Tensor(Tensor(a) self, int dim=0, int? start=0, int? end=9223372036854775807, int step=1) -> Tensor(a) +- func: slice.Tensor(Tensor(a) self, int dim=0, int? start=None, int? end=None, int step=1) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: slice + CompositeExplicitAutograd: slice -- func: slice_backward(Tensor grad, int[] input_sizes, int dim, int start, int end, int step) -> Tensor +- func: slice_backward(Tensor grad_output, int[] input_sizes, int dim, int start, int end, int step) -> Tensor variants: function + device_check: NoCheck device_guard: False + dispatch: + CompositeExplicitAutograd: slice_backward + +- func: slice_scatter(Tensor self, Tensor src, int dim=0, int? start=None, int? end=None, int step=1) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: slice_scatter + +- func: select_scatter(Tensor self, Tensor src, int dim, int index) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: select_scatter + +- func: diagonal_scatter(Tensor self, Tensor src, int offset=0, int dim1=0, int dim2=1) -> Tensor + variants: function, method + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: diagonal_scatter - func: slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet) variants: function, method dispatch: - DefaultBackend: slogdet + CompositeExplicitAutograd: slogdet - func: smm(Tensor self, Tensor mat2) -> Tensor variants: function, method @@ -3497,77 +4077,116 @@ variants: function, method - func: _softmax(Tensor self, int dim, bool half_to_float) -> Tensor + structured_delegate: _softmax.out dispatch: - CPU: softmax_cpu - CUDA: softmax_cuda MkldnnCPU: mkldnn_softmax -- func: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, Tensor self) -> Tensor +- func: _softmax.out(Tensor self, int dim, bool half_to_float, *, Tensor(a!) out) -> Tensor(a!) + structured: True dispatch: - CPU: softmax_backward_cpu - CUDA: softmax_backward_cuda + CPU: softmax_cpu_out + CUDA: softmax_cuda_out + +- func: _softmax_backward_data(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype) -> Tensor + structured_delegate: _softmax_backward_data.out + +- func: _softmax_backward_data.out(Tensor grad_output, Tensor output, int dim, ScalarType input_dtype, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + dispatch: + CPU: softmax_backward_cpu_out + CUDA: softmax_backward_cuda_out - func: unsafe_split.Tensor(Tensor self, int split_size, int dim=0) -> Tensor[] variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: unsafe_split + CompositeExplicitAutograd: unsafe_split -- func: split.Tensor(Tensor(a) self, int split_size, int dim=0) -> Tensor(a)[] +- func: split.Tensor(Tensor(a -> *) self, int split_size, int dim=0) -> Tensor(a)[] variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: split + CompositeExplicitAutograd: split - func: unsafe_split_with_sizes(Tensor self, int[] split_sizes, int dim=0) -> Tensor[] variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: unsafe_split_with_sizes + CompositeExplicitAutograd: unsafe_split_with_sizes -- func: split_with_sizes(Tensor(a) self, int[] split_sizes, int dim=0) -> Tensor(a)[] +- func: split_with_sizes(Tensor(a -> *) self, int[] split_sizes, int dim=0) -> Tensor(a)[] variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: split_with_sizes + CompositeExplicitAutograd: split_with_sizes + +- func: hsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] + variants: function, method + +- func: hsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] + variants: function, method + +- func: vsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] + variants: function, method + +- func: vsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] + variants: function, method + +- func: dsplit.int(Tensor(a -> *) self, int sections) -> Tensor(a)[] + variants: function, method + +- func: dsplit.array(Tensor(a -> *) self, int[] indices) -> Tensor(a)[] + variants: function, method - func: squeeze(Tensor(a) self) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: squeeze + CompositeExplicitAutograd: squeeze - func: squeeze.dim(Tensor(a) self, int dim) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: squeeze + CompositeExplicitAutograd: squeeze - func: squeeze.dimname(Tensor(a) self, Dimname dim) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: squeeze_(Tensor(a!) self) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view dispatch: - DefaultBackend: squeeze_ + CompositeExplicitAutograd: squeeze_ - func: squeeze_.dim(Tensor(a!) self, int dim) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view dispatch: - DefaultBackend: squeeze_ + CompositeExplicitAutograd: squeeze_ - func: squeeze_.dimname(Tensor(a!) self, Dimname dim) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view - func: sspaddmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor variants: function, method - func: sspaddmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: _sspaddmm_out_only_sparse CUDA: _sspaddmm_out_only_sparse_cuda @@ -3576,79 +4195,78 @@ - func: stack(Tensor[] tensors, int dim=0) -> Tensor dispatch: - DefaultBackend: stack + CompositeExplicitAutograd: stack - func: stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: stack_out + CompositeExplicitAutograd: stack_out - func: _stack(Tensor[] tensors, int dim=0) -> Tensor dispatch: # match the backends supported by _cat CPU: _stack_cpu - DefaultBackend: _stack + CompositeExplicitAutograd: _stack - func: _stack.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) dispatch: # match the backends supported by _cat_out CPU: _stack_out_cpu - DefaultBackend: _stack_out + CompositeExplicitAutograd: _stack_out - func: hstack(Tensor[] tensors) -> Tensor - func: hstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: vstack(Tensor[] tensors) -> Tensor - func: vstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: dstack(Tensor[] tensors) -> Tensor - func: dstack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures # The signature is designed to be consistent with librosa except that it is # missing the `pad_mode` and `center` arguments, which are taken care of at # `torch.functional.py`. They shall be moved here once we have mapping between # Python strings and C++ Enum in codegen. - func: stft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool normalized=False, bool? onesided=None, bool? return_complex=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function, method - func: istft(Tensor self, int n_fft, int? hop_length=None, int? win_length=None, Tensor? window=None, bool center=True, bool normalized=False, bool? onesided=None, int? length=None, bool return_complex=False) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function, method - func: stride.int(Tensor self, int dim) -> int variants: function + device_check: NoCheck device_guard: False manual_cpp_binding: True - func: stride.Dimname(Tensor self, Dimname dim) -> int variants: function, method + device_check: NoCheck device_guard: False - func: sum(Tensor self, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - CPU, CUDA: sum + CompositeExplicitAutograd: sum - func: sum.dim_IntList(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + structured_delegate: sum.IntList_out + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: sum - func: sum.dim_DimnameList(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: sum.IntList_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: sum_out - func: sum.DimnameList_out(Tensor self, Dimname[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: nansum(Tensor self, *, ScalarType? dtype=None) -> Tensor variants: function, method @@ -3661,195 +4279,273 @@ CPU, CUDA: nansum - func: nansum.IntList_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: nansum_out - func: sum_to_size(Tensor self, int[] size) -> Tensor variants: method + device_check: NoCheck device_guard: False - func: sqrt(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sqrt.out variants: function, method dispatch: - CPU, CUDA: sqrt SparseCPU, SparseCUDA: sqrt_sparse + SparseCsrCPU, SparseCsrCUDA: sqrt_sparse_csr - func: sqrt_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sqrt.out variants: function, method dispatch: - CPU, CUDA: sqrt_ + SparseCPU, SparseCUDA: sqrt_sparse_ + SparseCsrCPU, SparseCsrCUDA: sqrt_sparse_csr_ - func: sqrt.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sqrt_out - SparseCPU, SparseCUDA: sqrt_out_sparse + SparseCPU, SparseCUDA: sqrt_sparse_out + SparseCsrCPU, SparseCsrCUDA: sqrt_sparse_csr_out - func: square(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: square_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function, method +- func: square.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + dispatch: + CPU, CUDA: square_out + - func: std(Tensor self, bool unbiased=True) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: std - func: std.dim(Tensor self, int[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: std.correction(Tensor self, int[1]? dim, *, int? correction, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: std - func: std_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator variants: function - dispatch: - CPU, CUDA: std_mean - func: std_mean.dim(Tensor self, int[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + +- func: std_mean.correction(Tensor self, int[1]? dim, *, int? correction, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator variants: function dispatch: CPU, CUDA: std_mean - func: std_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + +- func: std_mean.correction_names(Tensor self, Dimname[1] dim, *, int? correction, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator variants: function - func: std.out(Tensor self, int[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: std.correction_out(Tensor self, int[1]? dim, *, int? correction, bool keepdim=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: std_out - func: std.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: std.names_out(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: std.correction_names(Tensor self, Dimname[1] dim, *, int? correction, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: std.correction_names_out(Tensor self, Dimname[1] dim, *, int? correction, bool keepdim=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function - func: prod(Tensor self, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: prod - func: prod.dim_int(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + structured_delegate: prod.int_out + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: prod - func: prod.int_out(Tensor self, int dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: prod_out - func: prod.dim_Dimname(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: prod.Dimname_out(Tensor self, Dimname dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: t(Tensor(a) self) -> Tensor(a) + device_check: NoCheck device_guard: False variants: function, method dispatch: - DefaultBackend: t + CompositeExplicitAutograd: t - func: t_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck device_guard: False variants: method + tags: inplace_view dispatch: - DefaultBackend: t_ + CompositeExplicitAutograd: t_ - func: tan(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: tan.out variants: function, method dispatch: - DefaultBackend: tan + SparseCPU, SparseCUDA: tan_sparse + SparseCsrCPU, SparseCsrCUDA: tan_sparse_csr - func: tan_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: tan.out variants: function, method dispatch: - DefaultBackend: tan_ + SparseCPU, SparseCUDA: tan_sparse_ + SparseCsrCPU, SparseCsrCUDA: tan_sparse_csr_ - func: tan.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: tan_out + SparseCPU, SparseCUDA: tan_sparse_out + SparseCsrCPU, SparseCsrCUDA: tan_sparse_csr_out - func: tanh(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: tanh.out variants: function, method dispatch: - CPU, CUDA: tanh QuantizedCPU: tanh_quantized_cpu + MkldnnCPU: mkldnn_tanh + SparseCPU, SparseCUDA: tanh_sparse + SparseCsrCPU, SparseCsrCUDA: tanh_sparse_csr - func: tanh_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: tanh.out variants: function, method dispatch: - DefaultBackend: tanh_ + MkldnnCPU: mkldnn_tanh_ + SparseCPU, SparseCUDA: tanh_sparse_ + SparseCsrCPU, SparseCsrCUDA: tanh_sparse_csr_ - func: tanh.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: tanh_out + SparseCPU, SparseCUDA: tanh_sparse_out + SparseCsrCPU, SparseCsrCUDA: tanh_sparse_csr_out - func: tensordot(Tensor self, Tensor other, int[] dims_self, int[] dims_other) -> Tensor variants: function - func: tensordot.out(Tensor self, Tensor other, int[] dims_self, int[] dims_other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function dispatch: CPU, CUDA: tensordot_out # TODO: namespace threshold in 'nn' - func: threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator variants: function + structured_delegate: threshold.out dispatch: - CPU: threshold - CUDA: threshold_cuda QuantizedCPU: threshold_quantized_cpu - func: threshold_(Tensor(a!) self, Scalar threshold, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: function - dispatch: - CPU: threshold_ - CUDA: threshold__cuda + structured_delegate: threshold.out - func: threshold.out(Tensor self, Scalar threshold, Scalar value, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: - CPU: threshold_out - CUDA: threshold_out_cuda + CPU, CUDA: threshold_out + +- func: threshold_backward.grad_input(Tensor grad_output, Tensor self, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: threshold_backward_out - func: threshold_backward(Tensor grad_output, Tensor self, Scalar threshold) -> Tensor variants: function + structured_delegate: threshold_backward.grad_input dispatch: - CPU: threshold_backward - CUDA: threshold_backward_cuda + MkldnnCPU: mkldnn_relu_backward - func: tile(Tensor self, int[] dims) -> Tensor variants: function, method - func: transpose.int(Tensor(a) self, int dim0, int dim1) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: transpose + CompositeExplicitAutograd: transpose - func: transpose.Dimname(Tensor(a) self, Dimname dim0, Dimname dim1) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: _mkldnn_transpose(Tensor self, int dim0, int dim1) -> Tensor + device_check: NoCheck device_guard: False dispatch: MkldnnCPU: mkldnn_transpose - func: transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view dispatch: - DefaultBackend: transpose_ + CompositeExplicitAutograd: transpose_ - func: _mkldnn_transpose_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) + device_check: NoCheck device_guard: False dispatch: MkldnnCPU: mkldnn_transpose_ @@ -3861,8 +4557,7 @@ - func: flip(Tensor self, int[] dims) -> Tensor variants: function, method dispatch: - CPU, QuantizedCPU: flip_cpu - CUDA: flip_cuda + CPU, QuantizedCPU, CUDA, QuantizedCUDA: flip - func: fliplr(Tensor self) -> Tensor variants: function, method @@ -3881,7 +4576,11 @@ - func: rot90(Tensor self, int k=1, int[] dims=[0,1]) -> Tensor variants: function, method dispatch: - DefaultBackend: rot90 + CompositeExplicitAutograd: rot90 + +- func: trapezoid.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor + +- func: trapezoid.dx(Tensor y, *, Scalar dx=1, int dim=-1) -> Tensor - func: trapz.x(Tensor y, Tensor x, *, int dim=-1) -> Tensor @@ -3889,24 +4588,36 @@ - func: _trilinear(Tensor i1, Tensor i2, Tensor i3, int[] expand1, int[] expand2, int[] expand3, int[] sumdim, int unroll_dim=1) -> Tensor dispatch: - DefaultBackend: _trilinear + CompositeExplicitAutograd: _trilinear - func: triplet_margin_loss(Tensor anchor, Tensor positive, Tensor negative, float margin=1.0, float p=2, float eps=1e-06, bool swap=False, int reduction=Mean) -> Tensor - func: trunc(Tensor self) -> Tensor + structured_delegate: trunc.out + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: trunc + CompositeExplicitAutograd: trunc + SparseCPU, SparseCUDA: trunc_sparse + SparseCsrCPU, SparseCsrCUDA: trunc_sparse_csr - func: trunc_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: trunc.out + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: trunc_ + CompositeExplicitAutograd: trunc_ + SparseCPU, SparseCUDA: trunc_sparse_ + SparseCsrCPU, SparseCsrCUDA: trunc_sparse_csr_ - func: trunc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: trunc_out + SparseCPU, SparseCUDA: trunc_sparse_out + SparseCsrCPU, SparseCsrCUDA: trunc_sparse_csr_out # Alias for trunc - func: fix(Tensor self) -> Tensor @@ -3916,7 +4627,6 @@ variants: function, method - func: fix.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: type_as(Tensor self, Tensor other) -> Tensor variants: method @@ -3960,64 +4670,96 @@ - func: _unsafe_view(Tensor self, int[] size) -> Tensor dispatch: - DefaultBackend: _unsafe_view + CompositeExplicitAutograd: _unsafe_view - func: unsqueeze(Tensor(a) self, int dim) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: unsqueeze + CPU, CUDA: unsqueeze + SparseCPU, SparseCUDA: unsqueeze_sparse + QuantizedCPU, QuantizedCUDA: unsqueeze_quantized - func: unsqueeze_(Tensor(a!) self, int dim) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view dispatch: - DefaultBackend: unsqueeze_ + CompositeExplicitAutograd: unsqueeze_ - func: vander(Tensor x, int? N=None, bool increasing=False) -> Tensor - func: var(Tensor self, bool unbiased=True) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - dispatch: - CPU, CUDA: var - func: var.dim(Tensor self, int[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: var.correction(Tensor self, int[1]? dim, *, int? correction, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: CPU, CUDA: var - func: var.out(Tensor self, int[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: var.correction_out(Tensor self, int[1]? dim, *, int? correction, bool keepdim=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: var_out - func: var.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: var.names_out(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: var.correction_names(Tensor self, Dimname[1] dim, *, int? correction, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: var.correction_names_out(Tensor self, Dimname[1] dim, *, int? correction, bool keepdim=False, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function - func: var_mean(Tensor self, bool unbiased=True) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator variants: function - dispatch: - CPU, CUDA: var_mean - func: var_mean.dim(Tensor self, int[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + +- func: var_mean.correction(Tensor self, int[1]? dim, *, int? correction, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator variants: function dispatch: CPU, CUDA: var_mean - func: var_mean.names_dim(Tensor self, Dimname[1] dim, bool unbiased=True, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator + variants: function + +- func: var_mean.correction_names(Tensor self, Dimname[1] dim, *, int? correction, bool keepdim=False) -> (Tensor, Tensor) + device_check: NoCheck # TensorIterator variants: function - func: view_as(Tensor(a) self, Tensor other) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False # we define both of these because 'where' does the broadcast and '_s_where' doesn't; # this allows us to implicitly calculate the broadcast derivative, while only dealing with the # _s_where derivative. - func: where.self(Tensor condition, Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: where.ScalarSelf(Tensor condition, Scalar self, Tensor other) -> Tensor @@ -4030,6 +4772,7 @@ variants: function - func: where(Tensor condition) -> Tensor[] + device_check: NoCheck # TensorIterator variants: function - func: _s_where(Tensor condition, Tensor self, Tensor other) -> Tensor @@ -4059,17 +4802,18 @@ variants: function - func: zeros.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck device_guard: False +- func: _efficientzerotensor(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + dispatch: + CompositeExplicitAutograd: _efficientzerotensor + - func: zeros(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: zeros.out(int[] size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: zeros_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: _standard_gamma_grad(Tensor self, Tensor output) -> Tensor variants: function @@ -4095,11 +4839,13 @@ CUDA: _s_dirichlet_cuda - func: poisson(Tensor self, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator dispatch: CPU: _s_poisson_cpu CUDA: _s_poisson_cuda - func: binomial(Tensor count, Tensor prob, Generator? generator=None) -> Tensor + device_check: NoCheck # TensorIterator dispatch: CPU: _s_binomial_cpu CUDA: _s_binomial_cuda @@ -4122,7 +4868,7 @@ - func: _sparse_sum.dim(Tensor self, int[1] dim) -> Tensor dispatch: - DefaultBackend: _sparse_sum + CompositeExplicitAutograd: _sparse_sum - func: _sparse_sum.dim_dtype(Tensor self, int[1] dim, *, ScalarType dtype) -> Tensor @@ -4132,12 +4878,15 @@ SparseCUDA: _sparse_sum_backward_cuda - func: _sparse_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + python_module: sparse variants: function - func: _sparse_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor + python_module: sparse variants: function - func: _sparse_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + python_module: sparse dispatch: SparseCPU: softmax_sparse_cpu SparseCUDA: softmax_sparse_cuda @@ -4148,12 +4897,15 @@ SparseCUDA: softmax_backward_sparse_cuda - func: _sparse_log_softmax.int(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + python_module: sparse variants: function - func: _sparse_log_softmax.Dimname(Tensor self, Dimname dim, *, ScalarType? dtype=None) -> Tensor + python_module: sparse variants: function - func: _sparse_log_softmax(Tensor self, int dim, bool half_to_float) -> Tensor + python_module: sparse dispatch: SparseCPU: log_softmax_sparse_cpu SparseCUDA: log_softmax_sparse_cuda @@ -4164,46 +4916,66 @@ SparseCUDA: log_softmax_backward_sparse_cuda - func: norm.ScalarOpt_dtype(Tensor self, Scalar? p, *, ScalarType dtype) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: norm + CompositeExplicitAutograd: norm - func: norm.Scalar(Tensor self, Scalar p=2) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: norm + CompositeExplicitAutograd: norm - func: norm.ScalarOpt_dim_dtype(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor + structured_delegate: norm.dtype_out + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: norm + SparseCPU, SparseCUDA: sparse_dtype_norm - func: norm.ScalarOpt_dim(Tensor self, Scalar? p, int[1] dim, bool keepdim=False) -> Tensor + structured_delegate: norm.out + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: norm + SparseCPU, SparseCUDA: sparse_norm - func: norm.dtype_out(Tensor self, Scalar? p, int[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: norm_out + CPU, CUDA: norm_dtype_out - func: norm.out(Tensor self, Scalar? p, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: norm_out +# These four redispatch in their implementation, so OK to be CompositeImplicitAutograd - func: norm.names_ScalarOpt_dim_dtype(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: norm.names_ScalarOpt_dim(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: norm.names_dtype_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim, *, ScalarType dtype, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: norm.names_out(Tensor self, Scalar? p, Dimname[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + +- func: frexp.Tensor(Tensor self) -> (Tensor mantissa, Tensor exponent) + variants: method, function + dispatch: + CompositeExplicitAutograd: frexp + +- func: frexp.Tensor_out(Tensor self, *, Tensor(a!) mantissa, Tensor(b!) exponent) -> (Tensor(a!) mantissa, Tensor(b!) exponent) + dispatch: + CPU, CUDA: frexp_out - func: frobenius_norm(Tensor self) -> Tensor variants: function @@ -4212,75 +4984,91 @@ variants: function - func: frobenius_norm.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - func: nuclear_norm(Tensor self, bool keepdim=False) -> Tensor variants: function - func: nuclear_norm.out(Tensor self, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - func: nuclear_norm.dim(Tensor self, int[2] dim, bool keepdim=False) -> Tensor variants: function - func: nuclear_norm.dim_out(Tensor self, int[2] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - func: clone(Tensor self, *, MemoryFormat? memory_format=None) -> Tensor variants: function, method dispatch: - CPU, CUDA: clone + CompositeExplicitAutograd: clone SparseCPU, SparseCUDA: clone_sparse + SparseCsrCPU, SparseCsrCUDA: clone_sparse_csr MkldnnCPU: mkldnn_clone QuantizedCPU, QuantizedCUDA: quantized_clone +- func: positive(Tensor(a) self) -> Tensor(a) + variants: function, method + - func: resize_as_(Tensor(a!) self, Tensor the_template, *, MemoryFormat? memory_format=None) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True variants: function, method dispatch: - DefaultBackend: resize_as_ + CompositeExplicitAutograd: resize_as_ + +- func: resize_as_sparse_(Tensor(a!) self, Tensor the_template) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + variants: function + dispatch: + SparseCPU, SparseCUDA: resize_as_sparse_ + SparseCsrCPU, SparseCsrCUDA: resize_as_sparse_csr_ - func: zero_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: zero_ + Meta: zero_meta_ SparseCPU, SparseCUDA: zero_sparse_ MkldnnCPU: mkldnn_zero_ - func: sub.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sub_out SparseCPU, SparseCUDA: sub_out_sparse - func: sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + structured_delegate: sub.out dispatch: - CPU, CUDA: sub SparseCPU, SparseCUDA: sub_sparse - func: sub_.Tensor(Tensor(a!) self, Tensor other, *, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + structured_delegate: sub.out dispatch: - CPU, CUDA: sub_ SparseCPU, SparseCUDA: sub_sparse_ # For C++ only, until we have conversion from C++ numbers to Tensor - func: sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: - DefaultBackend: sub + CompositeExplicitAutograd: sub - func: sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: sub_ + CompositeExplicitAutograd: sub_ # subtract, alias for sub - func: subtract.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: subtract.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor variants: function, method @@ -4296,55 +5084,74 @@ variants: method - func: rsub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator variants: function dispatch: CPU, CUDA: rsub - func: heaviside.out(Tensor self, Tensor values, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: heaviside_out - func: heaviside(Tensor self, Tensor values) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method + structured_delegate: heaviside.out - func: heaviside_(Tensor(a!) self, Tensor values) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: method + structured_delegate: heaviside.out # For C++ only, until we have conversion from C++ numbers to Tensor - func: rsub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor + device_check: NoCheck # TensorIterator variants: function dispatch: - DefaultBackend: rsub + CompositeExplicitAutograd: rsub # Functionally the same as addmm, but we give it a different derivative formula # that doesn't propagate gradients to non-present entries on sparse. - func: _sparse_addmm(Tensor self, Tensor sparse, Tensor dense, *, Scalar beta=1, Scalar alpha=1) -> Tensor + python_module: sparse dispatch: - DefaultBackend: _sparse_addmm + CompositeExplicitAutograd: _sparse_addmm + +- func: sparse_sampled_addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + python_module: sparse + dispatch: + SparseCsrCUDA: sparse_sampled_addmm_out_sparse_csr_cuda + +- func: sparse_sampled_addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + python_module: sparse + dispatch: + SparseCsrCUDA: sparse_sampled_addmm_sparse_csr_cuda - func: addmm.out(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - CPU: addmm_cpu_out + CPU: addmm_out_cpu CUDA: addmm_out_cuda SparseCPU: addmm_out_sparse_dense_cpu SparseCUDA: addmm_out_sparse_dense_cuda + SparseCsrCPU: addmm_out_sparse_csr_cpu + SparseCsrCUDA: addmm_out_sparse_csr_cuda - func: addmm(Tensor self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor + structured_delegate: addmm.out variants: function, method dispatch: - CPU: addmm_cpu - CUDA: addmm_cuda SparseCPU: addmm_sparse_dense_cpu SparseCUDA: addmm_sparse_dense_cuda + SparseCsrCPU, SparseCsrCUDA: addmm_sparse_csr_dense - func: addmm_(Tensor(a!) self, Tensor mat1, Tensor mat2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) + structured_delegate: addmm.out variants: method dispatch: - CPU: addmm_cpu_ - CUDA: addmm__cuda # Warning! For whatever reason, the inplace sparse addmm is NON # broadcasting SparseCPU: s_addmm_sparse_dense_cpu_ @@ -4458,23 +5265,27 @@ # the view relation is not tracked by autograd, but the version counter is still # shared. In other words, their outputs are non-differentiable views of the # sparse tensor. - # FIXME: would be nicer if TensorOptions was optional based; not adding default arguments for options given # the default would never make sense. + +- func: sparse_csr_tensor.crow_col_value_size(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + +- func: sparse_csr_tensor.crow_col_value(Tensor crow_indices, Tensor col_indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor + +- func: _sparse_csr_tensor_unsafe(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + - func: sparse_coo_tensor.size(int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: sparse_coo_tensor.indices(Tensor indices, Tensor values, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: sparse_coo_tensor.indices_size(Tensor indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: _sparse_coo_tensor_unsafe(Tensor indices, Tensor values, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: _validate_sparse_coo_tensor_args(Tensor indices, Tensor values, int[] size) -> () +- func: _validate_sparse_csr_tensor_args(Tensor crow_indices, Tensor col_indices, Tensor values, int[] size) -> () + - func: _sparse_coo_tensor_with_dims(int sparse_dim, int dense_dim, int[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=False) -> Tensor dispatch: SparseCPU, SparseCUDA: new_with_dims_sparse @@ -4484,11 +5295,13 @@ SparseCPU, SparseCUDA: new_with_dims_and_tensor_sparse - func: sparse_resize_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True variants: method dispatch: SparseCPU, SparseCUDA: sparse_resize_ - func: sparse_resize_and_clear_(Tensor(a!) self, int[] size, int sparse_dim, int dense_dim) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True variants: method dispatch: SparseCPU, SparseCUDA: sparse_resize_and_clear_ @@ -4499,10 +5312,13 @@ SparseCPU: sparse_mask_cpu SparseCUDA: sparse_mask_cuda +- func: _to_cpu(Tensor[] tensors) -> Tensor[] + variants: function + - func: to_dense(Tensor self, ScalarType? dtype=None) -> Tensor variants: method dispatch: - SparseCPU, SparseCUDA: sparse_to_dense + SparseCPU, SparseCUDA, SparseCsrCPU, SparseCsrCUDA: sparse_to_dense MkldnnCPU: mkldnn_to_dense - func: to_dense_backward(Tensor grad, Tensor input) -> Tensor @@ -4511,6 +5327,7 @@ variants: method dispatch: SparseCPU, SparseCUDA: sparse_dim_sparse + device_check: NoCheck device_guard: False # legacy method @@ -4518,12 +5335,14 @@ variants: method dispatch: SparseCPU, SparseCUDA: sparse_dim_sparse + device_check: NoCheck device_guard: False - func: dense_dim(Tensor self) -> int variants: method dispatch: SparseCPU, SparseCUDA: dense_dim_sparse + device_check: NoCheck device_guard: False # legacy method @@ -4531,36 +5350,49 @@ variants: method dispatch: SparseCPU, SparseCUDA: dense_dim_sparse + device_check: NoCheck device_guard: False - func: _nnz(Tensor self) -> int variants: method dispatch: SparseCPU, SparseCUDA: _nnz_sparse + SparseCsrCPU, SparseCsrCUDA: _nnz_sparse_csr + device_check: NoCheck device_guard: False -- func: coalesce(Tensor self) -> Tensor +# NOTE: [ coalesce autograd ] +# coalesce returns self directly for already coalesced sparse tensors. +# This means coalesce cannot have a derivative registered, otherwise it creates +# circular references in the autograd graph (see gh-52874). +# Instead, the derivative is registered on the slow-path "_coalesce" +- func: coalesce(Tensor(a) self) -> Tensor(a) variants: method + +- func: _coalesce(Tensor self) -> Tensor dispatch: - SparseCPU: coalesce_sparse_cpu - SparseCUDA: coalesce_sparse_cuda + SparseCPU: _coalesce_sparse_cpu + SparseCUDA: _coalesce_sparse_cuda - func: is_coalesced(Tensor self) -> bool variants: method dispatch: SparseCPU, SparseCUDA: is_coalesced_sparse + device_check: NoCheck device_guard: False - func: _indices(Tensor(a) self) -> Tensor(a) variants: method dispatch: SparseCPU, SparseCUDA: _indices_sparse + device_check: NoCheck device_guard: False - func: _values(Tensor(a) self) -> Tensor(a) variants: method dispatch: SparseCPU, SparseCUDA: _values_sparse + device_check: NoCheck device_guard: False # This method doesn't do any check but only directly sets the flag. So it can be @@ -4570,22 +5402,39 @@ variants: method dispatch: SparseCPU, SparseCUDA: _coalesced_sparse_ + device_check: NoCheck device_guard: False - func: indices(Tensor(a) self) -> Tensor(a) variants: method dispatch: SparseCPU, SparseCUDA: indices_sparse + device_check: NoCheck device_guard: False - func: values(Tensor(a) self) -> Tensor(a) variants: method dispatch: SparseCPU, SparseCUDA: values_sparse + SparseCsrCPU, SparseCsrCUDA: values_sparse_csr + device_check: NoCheck + device_guard: False + +- func: crow_indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCsrCPU, SparseCsrCUDA: crow_indices_sparse_csr + device_check: NoCheck + device_guard: False + +- func: col_indices(Tensor(a) self) -> Tensor(a) + variants: method + dispatch: + SparseCsrCPU, SparseCsrCUDA: col_indices_sparse_csr + device_check: NoCheck device_guard: False - func: hspmm.out(Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: SparseCPU: hspmm_out_sparse_cpu SparseCUDA: hspmm_out_sparse_cuda @@ -4596,16 +5445,17 @@ SparseCUDA: hspmm_sparse_cuda - func: copy_sparse_to_sparse_(Tensor(a!) self, Tensor src, bool non_blocking=False) -> Tensor(a!) + device_check: NoCheck # Allows copy into different device variants: function dispatch: SparseCPU, SparseCUDA: copy_sparse_ -- func: unbind.int(Tensor(a) self, int dim=0) -> Tensor(a)[] +- func: unbind.int(Tensor(a -> *) self, int dim=0) -> Tensor(a)[] variants: function, method dispatch: - DefaultBackend: unbind + CompositeExplicitAutograd: unbind -- func: unbind.Dimname(Tensor(a) self, Dimname dim) -> Tensor(a)[] +- func: unbind.Dimname(Tensor(a -> *) self, Dimname dim) -> Tensor(a)[] variants: function, method - func: to_sparse.sparse_dim(Tensor self, int sparse_dim) -> Tensor @@ -4637,11 +5487,21 @@ - func: to_mkldnn_backward(Tensor grad, Tensor input) -> Tensor +- func: quantize_per_tensor_dynamic(Tensor self, ScalarType dtype, bool reduce_range) -> Tensor + variants: function + dispatch: + CPU, CUDA: quantize_per_tensor_dynamic + - func: quantize_per_tensor(Tensor self, float scale, int zero_point, ScalarType dtype) -> Tensor variants: function dispatch: CPU, CUDA: quantize_per_tensor +- func: quantize_per_tensor.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, ScalarType dtype) -> Tensor + variants: function + dispatch: + CPU, CUDA: quantize_per_tensor_tensor_qparams + - func: quantize_per_tensor.tensors(Tensor[] tensors, Tensor scales, Tensor zero_points, ScalarType dtype) -> Tensor[] variants: function dispatch: @@ -4650,12 +5510,13 @@ - func: quantize_per_channel(Tensor self, Tensor scales, Tensor zero_points, int axis, ScalarType dtype) -> Tensor variants: function dispatch: - CPU: quantize_per_channel_cpu + CPU, CUDA: quantize_per_channel - func: dequantize.self(Tensor self) -> Tensor variants: function, method dispatch: - QuantizedCPU, QuantizedCUDA: dequantize_quant + CPU, CUDA: dequantize_cpu_or_cuda + QuantizedCPU, QuantizedCUDA: dequantize_quantized - func: dequantize.tensors(Tensor[] tensors) -> Tensor[] variants: function @@ -4688,6 +5549,7 @@ QuantizedCPU, QuantizedCUDA: q_per_channel_axis - func: int_repr(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method dispatch: QuantizedCPU: int_repr_quantized_cpu @@ -4701,6 +5563,7 @@ - func: _make_per_channel_quantized_tensor(Tensor self, Tensor scale, Tensor zero_point, int axis) -> Tensor dispatch: CPU: make_per_channel_quantized_tensor_cpu + CUDA: make_per_channel_quantized_tensor_cuda - func: qscheme(Tensor self) -> QScheme variants: method @@ -4708,15 +5571,23 @@ QuantizedCPU, QuantizedCUDA: qscheme_quant - func: fake_quantize_per_tensor_affine(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + +- func: fake_quantize_per_tensor_affine.tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, int quant_min, int quant_max) -> Tensor + device_check: NoCheck # TensorIterator variants: function - dispatch: - Math: fake_quantize_per_tensor_affine - func: fake_quantize_per_tensor_affine_cachemask(Tensor self, float scale, int zero_point, int quant_min, int quant_max) -> (Tensor output, Tensor mask) variants: function dispatch: CPU, CUDA: fake_quantize_per_tensor_affine_cachemask +- func: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams(Tensor self, Tensor scale, Tensor zero_point, Tensor fake_quant_enabled, int quant_min, int quant_max) -> (Tensor output, Tensor mask) + variants: function + dispatch: + CPU, CUDA: _fake_quantize_per_tensor_affine_cachemask_tensor_qparams + - func: fake_quantize_per_tensor_affine_cachemask_backward(Tensor grad, Tensor mask) -> Tensor variants: function @@ -4729,9 +5600,8 @@ variants: function - func: fake_quantize_per_channel_affine(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> Tensor + device_check: NoCheck # TensorIterator variants: function - dispatch: - Math: fake_quantize_per_channel_affine - func: fake_quantize_per_channel_affine_cachemask(Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max) -> (Tensor output, Tensor mask) variants: function @@ -4749,6 +5619,15 @@ - func: _fake_quantize_learnable_per_channel_affine_backward(Tensor grad, Tensor self, Tensor scale, Tensor zero_point, int axis, int quant_min, int quant_max, float grad_factor=1.0) -> (Tensor, Tensor, Tensor) variants: function +- func: fused_moving_avg_obs_fake_quant(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> Tensor + variants: function + +- func: _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask) + dispatch: + CPU: fused_moving_avg_obs_fake_quant_cpu + CUDA: fused_moving_avg_obs_fake_quant_cuda + + - func: _choose_qparams_per_tensor(Tensor self, bool reduce_range=False) -> (float, int) variants: function @@ -4758,28 +5637,50 @@ - func: choose_qparams_optimized(Tensor input, int numel, int n_bins, float ratio, int bit_width) -> (Tensor, Tensor) variants: function +- func: _autocast_to_reduced_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) -> Tensor(a) + variants: method + device_guard: False + +- func: _autocast_to_full_precision(Tensor(a) self, bool cuda_enabled, bool cpu_enabled) -> Tensor(a) + variants: method + device_guard: False + +- func: _to_copy(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, MemoryFormat? memory_format=None) -> Tensor + device_check: NoCheck + device_guard: False + dispatch: + CompositeExplicitAutograd: _to_copy + # to(Device) must not exist because all constructors of Device also works for # TensorOptions. Otherwise, an ambiguity error is thrown. # See NOTE [ TensorOptions Constructors ]. -- func: to.dtype_layout(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: to.dtype_layout(Tensor(a) self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False -- func: to.device(Tensor self, Device device, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor +- func: to.device(Tensor(a) self, Device device, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False -- func: to.dtype(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor +- func: to.dtype(Tensor(a) self, ScalarType dtype, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False -- func: to.other(Tensor self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor +- func: to.other(Tensor(a) self, Tensor other, bool non_blocking=False, bool copy=False, MemoryFormat? memory_format=None) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False - func: meshgrid(Tensor[] tensors) -> Tensor[] +# TODO: Two weeks after this lands, combine these two overloads, +# making "indexing" optional. These are temporarily distinct for +# forward-compatibility reasons. +- func: meshgrid.indexing(Tensor[] tensors, *, str indexing) -> Tensor[] + - func: cartesian_prod(Tensor[] tensors) -> Tensor variants: function @@ -4815,20 +5716,16 @@ # Fused RNN kernels - func: _thnn_fused_lstm_cell(Tensor input_gates, Tensor hidden_gates, Tensor cx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: _thnn_fused_lstm_cell_cuda - func: _thnn_fused_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor cx, Tensor cy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: _thnn_fused_lstm_cell_backward_cuda - func: _thnn_differentiable_lstm_cell_backward(Tensor? grad_hy, Tensor? grad_cy, Tensor input_gates, Tensor hidden_gates, Tensor? input_bias, Tensor? hidden_bias, Tensor cx, Tensor cy) -> (Tensor, Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: _thnn_fused_gru_cell(Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias=None, Tensor? hidden_bias=None) -> (Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CUDA: _thnn_fused_gru_cell_cuda @@ -4837,7 +5734,6 @@ CUDA: _thnn_fused_gru_cell_backward_cuda - func: _thnn_differentiable_gru_cell_backward(Tensor grad_hy, Tensor input_gates, Tensor hidden_gates, Tensor hx, Tensor? input_bias, Tensor? hidden_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures # RNN cells and layers - func: lstm.input(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor) @@ -4857,16 +5753,12 @@ - func: rnn_relu.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) - func: lstm_cell(Tensor input, Tensor[] hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> (Tensor, Tensor) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: gru_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rnn_tanh_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: rnn_relu_cell(Tensor input, Tensor hx, Tensor w_ih, Tensor w_hh, Tensor? b_ih=None, Tensor? b_hh=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures # Quantized RNN layer registration has been moved to C10 dispatch in `RNN.cpp` @@ -4897,7 +5789,7 @@ # PackedSequence utilities - func: _pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first) -> (Tensor, Tensor) dispatch: - DefaultBackend: _pack_padded_sequence + CompositeExplicitAutograd: _pack_padded_sequence - func: _pack_padded_sequence_backward(Tensor grad, int[] input_size, Tensor batch_sizes, bool batch_first) -> Tensor @@ -4907,12 +5799,14 @@ - func: set_.source_Storage(Tensor(a!) self, Storage source) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False dispatch: CPU, CUDA: set_ - func: set_.source_Storage_storage_offset(Tensor(a!) self, Storage source, int storage_offset, int[] size, int[] stride=[]) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False dispatch: CPU: set_storage_cpu_ @@ -4921,6 +5815,7 @@ - func: set_.source_Tensor(Tensor(a!) self, Tensor source) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False dispatch: CPU, CUDA: set_tensor_ @@ -4933,26 +5828,31 @@ - func: is_set_to(Tensor self, Tensor tensor) -> bool variants: method + device_check: NoCheck device_guard: False dispatch: CPU, CUDA: is_set_to - func: masked_fill_.Scalar(Tensor(a!) self, Tensor mask, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU: masked_fill__cpu CUDA: masked_fill__cuda - func: masked_fill.Scalar(Tensor self, Tensor mask, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: masked_fill_.Tensor(Tensor(a!) self, Tensor mask, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU: masked_fill__cpu CUDA: masked_fill__cuda - func: masked_fill.Tensor(Tensor self, Tensor mask, Tensor value) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: masked_scatter_(Tensor(a!) self, Tensor mask, Tensor source) -> Tensor(a!) @@ -4964,11 +5864,17 @@ - func: masked_scatter(Tensor self, Tensor mask, Tensor source) -> Tensor variants: function, method +- func: _masked_softmax(Tensor self, Tensor mask) -> Tensor + dispatch: + CUDA: masked_softmax_cuda + CPU: masked_softmax_cpu + - func: view(Tensor(a) self, int[] size) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False dispatch: - CPU, CUDA, QuantizedCPU, QuantizedCUDA: view + ZeroTensor, CPU, CUDA, Meta, QuantizedCPU, QuantizedCUDA: view MkldnnCPU: mkldnn_view # Warning: If you want to change the name or overload name of this @@ -4979,320 +5885,472 @@ # https://github.com/pytorch/pytorch/issues/47964 - func: view.dtype(Tensor(a) self, ScalarType dtype) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False dispatch: - DefaultBackend: view_dtype + CompositeExplicitAutograd: view_dtype - func: put_(Tensor(a!) self, Tensor index, Tensor source, bool accumulate=False) -> Tensor(a!) variants: method dispatch: - CPU: legacy::cpu::_th_put_ - CUDA: legacy::cuda::_th_put_ + CPU, CUDA: put_ -- func: index_add_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!) - variants: method - dispatch: - CPU: index_add_cpu_ - CUDA: index_add_cuda_ - -- func: index_add(Tensor self, int dim, Tensor index, Tensor source) -> Tensor +- func: put(Tensor self, Tensor index, Tensor source, bool accumulate=False) -> Tensor variants: function, method -- func: index_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor source) -> Tensor +- func: index_add.out(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + precomputed: + - dim -> int dim + dispatch: + CPU: index_add_cpu_out + CUDA: index_add_cuda_out + +- func: index_add_(Tensor(a!) self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor(a!) + structured_delegate: index_add.out + variants: method + +- func: index_add(Tensor self, int dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor + structured_delegate: index_add.out + variants: function, method + +- func: index_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor source, *, Scalar alpha=1) -> Tensor variants: function, method - func: index_fill_.int_Scalar(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU: index_fill_ CUDA: index_fill_ - func: index_fill.int_Scalar(Tensor self, int dim, Tensor index, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: index_fill_.int_Tensor(Tensor(a!) self, int dim, Tensor index, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: index_fill_ - func: index_fill.int_Tensor(Tensor self, int dim, Tensor index, Tensor value) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: index_fill_.Dimname_Scalar(Tensor(a!) self, Dimname dim, Tensor index, Scalar value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: index_fill_.Dimname_Tensor(Tensor(a!) self, Dimname dim, Tensor index, Tensor value) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: index_fill.Dimname_Scalar(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor + device_check: NoCheck # TensorIterator variants: function, method - func: index_fill.Dimname_Tensor(Tensor self, Dimname dim, Tensor index, Tensor value) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + +- func: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor + structured_delegate: scatter.src_out variants: function, method - func: scatter_.src(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!) + structured_delegate: scatter.src_out variants: method - dispatch: - CPU, CUDA: scatter_ -- func: scatter.src(Tensor self, int dim, Tensor index, Tensor src) -> Tensor +- func: scatter.src_out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA: scatter_src_out + +- func: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor + structured_delegate: scatter.value_out variants: function, method - func: scatter_.value(Tensor(a!) self, int dim, Tensor index, Scalar value) -> Tensor(a!) + structured_delegate: scatter.value_out variants: method - dispatch: - CPU, CUDA: scatter_fill_ -- func: scatter.value(Tensor self, int dim, Tensor index, Scalar value) -> Tensor +- func: scatter.value_out(Tensor self, int dim, Tensor index, Scalar value, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA: scatter_value_out + +- func: scatter.reduce(Tensor self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor + structured_delegate: scatter.reduce_out variants: function, method +- func: scatter_.reduce(Tensor(a!) self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor(a!) + structured_delegate: scatter.reduce_out + variants: method + +- func: scatter.reduce_out(Tensor self, int dim, Tensor index, Tensor src, *, str reduce, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA: scatter_reduce_out + +- func: scatter.value_reduce(Tensor self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor + structured_delegate: scatter.value_reduce_out + variants: function, method + +- func: scatter_.value_reduce(Tensor(a!) self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor(a!) + structured_delegate: scatter.value_reduce_out + variants: method + +- func: scatter.value_reduce_out(Tensor self, int dim, Tensor index, Scalar value, *, str reduce, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA: scatter_value_reduce_out + - func: scatter.dimname_src(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor variants: function, method - func: scatter.dimname_value(Tensor self, Dimname dim, Tensor index, Scalar value) -> Tensor variants: function, method -- func: scatter_.reduce(Tensor(a!) self, int dim, Tensor index, Tensor src, *, str reduce) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: scatter_reduce_ - -- func: scatter_.value_reduce(Tensor(a!) self, int dim, Tensor index, Scalar value, *, str reduce) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: scatter_scalar_reduce_ +- func: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor + structured_delegate: scatter_add.out + variants: function, method - func: scatter_add_(Tensor(a!) self, int dim, Tensor index, Tensor src) -> Tensor(a!) + structured_delegate: scatter_add.out variants: method - dispatch: - CPU, CUDA: scatter_add_ -- func: scatter_add(Tensor self, int dim, Tensor index, Tensor src) -> Tensor - variants: function, method +- func: scatter_add.out(Tensor self, int dim, Tensor index, Tensor src, *, Tensor(a!) out) -> Tensor(a!) + structured: True + variants: function + dispatch: + CPU, CUDA: scatter_add - func: scatter_add.dimname(Tensor self, Dimname dim, Tensor index, Tensor src) -> Tensor variants: function, method +- func: scatter_reduce.two(Tensor self, int dim, Tensor index, str reduce, *, int? output_size=None) -> Tensor + variants: function, method + dispatch: + CPU: scatter_reduce_two_cpu + - func: eq_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: eq.Scalar_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: eq_ + CompositeExplicitAutograd: eq_ - func: eq_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: eq.Tensor_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: eq_ + CompositeExplicitAutograd: eq_ - func: bitwise_and.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase variants: function dispatch: CPU, CUDA: bitwise_and_out - func: bitwise_and.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: - CPU, CUDA: bitwise_and_out + CompositeExplicitAutograd: bitwise_and_out - func: bitwise_and.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function + dispatch: + CompositeExplicitAutograd: bitwise_and - func: bitwise_and.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function + structured_delegate: bitwise_and.Tensor_out - func: bitwise_and_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: bitwise_and_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + structured_delegate: bitwise_and.Tensor_out - func: __and__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: __and__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: __iand__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: __iand__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: bitwise_or.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase variants: function dispatch: CPU, CUDA: bitwise_or_out - func: bitwise_or.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: - CPU, CUDA: bitwise_or_out + CompositeExplicitAutograd: bitwise_or_out - func: bitwise_or.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: bitwise_or.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function + structured_delegate: bitwise_or.Tensor_out - func: bitwise_or_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: bitwise_or_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + structured_delegate: bitwise_or.Tensor_out - func: __or__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: __or__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: __ior__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: __ior__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: bitwise_xor.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase variants: function dispatch: CPU, CUDA: bitwise_xor_out - func: bitwise_xor.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator variants: function dispatch: - CPU, CUDA: bitwise_xor_out + CompositeExplicitAutograd: bitwise_xor_out - func: bitwise_xor.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: bitwise_xor.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function + structured_delegate: bitwise_xor.Tensor_out - func: bitwise_xor_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: bitwise_xor_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method + structured_delegate: bitwise_xor.Tensor_out - func: __xor__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: __xor__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: __ixor__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: __ixor__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - func: __lshift__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: __lshift__ - func: __lshift__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: __lshift__ - func: __ilshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: __ilshift__ - func: __ilshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: __ilshift__ +- func: bitwise_left_shift.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: bitwise_left_shift.Tensor_out + +- func: bitwise_left_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_left_shift.Tensor_out + +- func: bitwise_left_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: bitwise_left_shift_out + +- func: bitwise_left_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA: bitwise_left_shift + +- func: bitwise_left_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CPU, CUDA: bitwise_left_shift_ + +- func: bitwise_left_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA: bitwise_left_shift_out + +- func: bitwise_left_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA: bitwise_left_shift + - func: __rshift__.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: __rshift__ - func: __rshift__.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: __rshift__ - func: __irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: __irshift__ - func: __irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: __irshift__ -- func: atan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) +- func: bitwise_right_shift.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function, method + structured_delegate: bitwise_right_shift.Tensor_out + +- func: bitwise_right_shift_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: bitwise_right_shift.Tensor_out + +- func: bitwise_right_shift.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: bitwise_right_shift_out + +- func: bitwise_right_shift.Tensor_Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CPU, CUDA: bitwise_right_shift + +- func: bitwise_right_shift_.Tensor_Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - CPU, CUDA: atan2_ + CPU, CUDA: bitwise_right_shift_ + +- func: bitwise_right_shift.Tensor_Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA: bitwise_right_shift_out + +- func: bitwise_right_shift.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function + dispatch: + CPU, CUDA: bitwise_right_shift - func: tril_(Tensor(a!) self, int diagonal=0) -> Tensor(a!) + structured_delegate: tril.out variants: method - dispatch: - CPU: tril_cpu_ - CUDA: tril_cuda_ - func: triu_(Tensor(a!) self, int diagonal=0) -> Tensor(a!) + structured_delegate: triu.out variants: method - dispatch: - CPU: triu_cpu_ - CUDA: triu_cuda_ - func: digamma_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: digamma.out variants: method - dispatch: - CPU, CUDA: digamma_ - -- func: polygamma_(Tensor(a!) self, int n) -> Tensor(a!) - variants: method - -- func: renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!) - variants: method - dispatch: - CPU: legacy::cpu::_th_renorm_ - CUDA: legacy::cuda::_th_renorm_ - func: lerp_.Scalar(Tensor(a!) self, Tensor end, Scalar weight) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - dispatch: - CPU: lerp_cpu_scalar_ - CUDA: lerp_cuda_scalar_ + structured_delegate: lerp.Scalar_out - func: lerp_.Tensor(Tensor(a!) self, Tensor end, Tensor weight) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method - dispatch: - CPU: lerp_cpu_tensor_ - CUDA: lerp_cuda_tensor_ - -- func: fmod_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: fmod_ - -- func: fmod_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: fmod_ - -- func: remainder_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: remainder_ - -- func: remainder_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) - variants: method - dispatch: - CPU, CUDA: remainder_ + structured_delegate: lerp.Tensor_out - func: addbmm_(Tensor(a!) self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1) -> Tensor(a!) variants: method @@ -5300,7 +6358,6 @@ CPU, CUDA: addbmm_ - func: addbmm.out(Tensor self, Tensor batch1, Tensor batch2, *, Scalar beta=1, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: addbmm_out @@ -5309,47 +6366,54 @@ dispatch: CPU, CUDA: addbmm -- func: addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) - variants: method - dispatch: - DefaultBackend: addcdiv_ - - func: random_.from(Tensor(a!) self, int from, int? to, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: random_ + Meta: random_meta_ - func: random_.to(Tensor(a!) self, int to, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: random_ + Meta: random_meta_ - func: random_(Tensor(a!) self, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: random_ + Meta: random_meta_ - func: uniform_(Tensor(a!) self, float from=0, float to=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: uniform_ + Meta: uniform_meta_ - func: cauchy_(Tensor(a!) self, float median=0, float sigma=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: cauchy_ - func: log_normal_(Tensor(a!) self, float mean=1, float std=2, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: log_normal_ - func: exponential_(Tensor(a!) self, float lambd=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: exponential_ - func: geometric_(Tensor(a!) self, float p, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: geometric_ @@ -5357,7 +6421,6 @@ # wrappers for TH functions - func: diag.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: diag_cpu_out CUDA: diag_cuda_out @@ -5365,43 +6428,37 @@ - func: diag(Tensor self, int diagonal=0) -> Tensor variants: method, function dispatch: - DefaultBackend: diag + CompositeExplicitAutograd: diag - func: diag_backward(Tensor grad, int[] input_sizes, int diagonal) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: cross.out(Tensor self, Tensor other, int? dim=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - CPU, CUDA: cross_out - func: cross(Tensor self, Tensor other, int? dim=None) -> Tensor variants: method, function - dispatch: - CPU, CUDA: cross - func: triu.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - CPU: triu_cpu_out - CUDA: triu_cuda_out + CPU: triu_cpu + CUDA: triu_cuda - func: triu(Tensor self, int diagonal=0) -> Tensor + structured_delegate: triu.out variants: method, function - dispatch: - DefaultBackend: triu - func: tril.out(Tensor self, int diagonal=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - CPU: tril_cpu_out - CUDA: tril_cuda_out + CPU: tril_cpu + CUDA: tril_cuda - func: tril(Tensor self, int diagonal=0) -> Tensor + structured_delegate: tril.out variants: method, function - dispatch: - DefaultBackend: tril - func: tril_indices(int row, int col, int offset=0, *, ScalarType? dtype=long, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor dispatch: @@ -5421,51 +6478,60 @@ - func: trace_backward(Tensor grad, int[] sizes) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: ne.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: ne_out + CPU, CUDA: ne_Scalar_out QuantizedCPU: ne_out_quantized_cpu - func: ne.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: ne.Scalar_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: ne QuantizedCPU: ne_quantized_cpu - func: ne.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: ne_out + CPU, CUDA: ne_Tensor_out QuantizedCPU: ne_out_quantized_cpu - func: ne.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: ne.Tensor_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: ne QuantizedCPU: ne_quantized_cpu - func: ne_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: ne.Scalar_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: ne_ + CompositeExplicitAutograd: ne_ - func: ne_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: ne.Tensor_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: ne_ + CompositeExplicitAutograd: ne_ # not_equal, alias for torch.ne - func: not_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: not_equal.Scalar(Tensor self, Scalar other) -> Tensor variants: method, function - func: not_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: not_equal.Tensor(Tensor self, Tensor other) -> Tensor variants: method, function @@ -5477,72 +6543,86 @@ variants: method - func: eq.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: eq_out + CPU, CUDA: eq_Scalar_out QuantizedCPU: eq_out_quantized_cpu - func: eq.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: eq.Scalar_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: eq QuantizedCPU: eq_quantized_cpu - func: eq.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: eq_out + CPU, CUDA: eq_Tensor_out QuantizedCPU: eq_out_quantized_cpu - func: eq.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: eq.Tensor_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: eq QuantizedCPU: eq_quantized_cpu - func: ge.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: ge_out + CPU, CUDA: ge_Scalar_out QuantizedCPU: ge_out_quantized_cpu - func: ge.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: ge.Scalar_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: ge QuantizedCPU: ge_quantized_cpu - func: ge.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: ge_out + CPU, CUDA: ge_Tensor_out QuantizedCPU: ge_out_quantized_cpu - func: ge.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: ge.Tensor_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: ge QuantizedCPU: ge_quantized_cpu - func: ge_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: ge.Scalar_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: ge_ + CompositeExplicitAutograd: ge_ - func: ge_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: ge.Tensor_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: ge_ + CompositeExplicitAutograd: ge_ # greater_equal, alias for torch.ge - func: greater_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: greater_equal.Scalar(Tensor self, Scalar other) -> Tensor variants: method, function - func: greater_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: greater_equal.Tensor(Tensor self, Tensor other) -> Tensor variants: method, function @@ -5554,48 +6634,56 @@ variants: method - func: le.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: le_out + CPU, CUDA: le_Scalar_out QuantizedCPU: le_out_quantized_cpu - func: le.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: le.Scalar_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: le QuantizedCPU: le_quantized_cpu - func: le.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: le_out + CPU, CUDA: le_Tensor_out QuantizedCPU: le_out_quantized_cpu - func: le.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: le.Tensor_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: le QuantizedCPU: le_quantized_cpu - func: le_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: le.Scalar_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: le_ + CompositeExplicitAutograd: le_ - func: le_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: le.Tensor_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: le_ + CompositeExplicitAutograd: le_ # less_equal, alias for torch.le - func: less_equal.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: less_equal.Scalar(Tensor self, Scalar other) -> Tensor variants: method, function - func: less_equal.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: less_equal.Tensor(Tensor self, Tensor other) -> Tensor variants: method, function @@ -5607,48 +6695,56 @@ variants: method - func: gt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: gt_out + CPU, CUDA: gt_Scalar_out QuantizedCPU: gt_out_quantized_cpu - func: gt.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: gt.Scalar_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: gt QuantizedCPU: gt_quantized_cpu - func: gt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: gt_out + CPU, CUDA: gt_Tensor_out QuantizedCPU: gt_out_quantized_cpu - func: gt.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: gt.Tensor_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: gt QuantizedCPU: gt_quantized_cpu - func: gt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: gt.Scalar_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: gt_ + CompositeExplicitAutograd: gt_ - func: gt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: gt.Tensor_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: gt_ + CompositeExplicitAutograd: gt_ # greater, alias for torch.gt - func: greater.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: greater.Scalar(Tensor self, Scalar other) -> Tensor variants: method, function - func: greater.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: greater.Tensor(Tensor self, Tensor other) -> Tensor variants: method, function @@ -5660,48 +6756,56 @@ variants: method - func: lt.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: lt_out + CPU, CUDA: lt_Scalar_out QuantizedCPU: lt_out_quantized_cpu - func: lt.Scalar(Tensor self, Scalar other) -> Tensor + structured_delegate: lt.Scalar_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: lt QuantizedCPU: lt_quantized_cpu - func: lt.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: - CPU, CUDA: lt_out + CPU, CUDA: lt_Tensor_out QuantizedCPU: lt_out_quantized_cpu - func: lt.Tensor(Tensor self, Tensor other) -> Tensor + structured_delegate: lt.Tensor_out + device_check: NoCheck # TensorIterator variants: method, function dispatch: - CPU, CUDA: lt QuantizedCPU: lt_quantized_cpu - func: lt_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + structured_delegate: lt.Scalar_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: lt_ + CompositeExplicitAutograd: lt_ - func: lt_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: lt.Tensor_out + device_check: NoCheck # TensorIterator variants: method dispatch: - DefaultBackend: lt_ + CompositeExplicitAutograd: lt_ # less, alias for torch.lt - func: less.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: less.Scalar(Tensor self, Scalar other) -> Tensor variants: method, function - func: less.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: less.Tensor(Tensor self, Tensor other) -> Tensor variants: method, function @@ -5713,47 +6817,43 @@ variants: method - func: take.out(Tensor self, Tensor index, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: take_out_cpu - CUDA: take_out_cuda + CPU, CUDA: take_out - func: take(Tensor self, Tensor index) -> Tensor variants: method, function dispatch: - CPU: take_cpu - CUDA: take_cuda + CPU, CUDA: take -- func: take_backward(Tensor grad, Tensor input, Tensor index) -> Tensor - variants: function - device_guard: False +- func: take_along_dim.out(Tensor self, Tensor indices, int? dim=None, *, Tensor(a!) out) -> Tensor(a!) + +- func: take_along_dim(Tensor self, Tensor indices, int? dim=None) -> Tensor + variants: method, function - func: index_select.out(Tensor self, int dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: index_select_out_cpu_ - CUDA: index_select_out_cuda + CPU, QuantizedCPU: index_select_out_cpu_ + CUDA, QuantizedCUDA: index_select_out_cuda - func: index_select(Tensor self, int dim, Tensor index) -> Tensor variants: method, function dispatch: - CPU: index_select_cpu_ - CUDA: index_select_cuda + CPU, QuantizedCPU: index_select_cpu_ + CUDA, QuantizedCUDA: index_select_cuda SparseCPU: index_select_sparse SparseCUDA: index_select_sparse - func: index_select.dimname_out(Tensor self, Dimname dim, Tensor index, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: index_select.dimname(Tensor self, Dimname dim, Tensor index) -> Tensor variants: method, function - func: index_select_backward(Tensor grad, int[] self_sizes, int dim, Tensor index) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: masked_select.out(Tensor self, Tensor mask, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: masked_select_out_cpu CUDA: masked_select_out_cuda @@ -5766,40 +6866,41 @@ - func: masked_select_backward(Tensor grad, Tensor input, Tensor mask) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: nonzero.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: legacy::cpu::_th_nonzero_out + CPU: nonzero_out_cpu CUDA: nonzero_out_cuda - func: nonzero(Tensor self) -> Tensor variants: method, function dispatch: - CPU: legacy::cpu::_th_nonzero + CPU: nonzero_cpu CUDA: nonzero_cuda - func: nonzero_numpy(Tensor self) -> Tensor[] variants: method, function +- func: argwhere(Tensor self) -> Tensor + variants: method, function + - func: gather.out(Tensor self, int dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - CPU: gather_out_cpu_cuda - CUDA: gather_out_cpu_cuda + CPU, CUDA: gather_out - func: gather(Tensor self, int dim, Tensor index, *, bool sparse_grad=False) -> Tensor variants: method, function - dispatch: - CPU, CUDA: gather + structured_delegate: gather.out - func: gather_backward(Tensor grad, Tensor self, int dim, Tensor index, bool sparse_grad) -> Tensor variants: function + device_check: NoCheck device_guard: False - func: gather.dimname_out(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: gather.dimname(Tensor self, Dimname dim, Tensor index, *, bool sparse_grad=False) -> Tensor variants: method, function @@ -5807,67 +6908,87 @@ - func: _gather_sparse_backward(Tensor self, int dim, Tensor index, Tensor grad) -> Tensor - func: addcmul.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: addcmul_out - func: addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor + structured_delegate: addcmul.out + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - DefaultBackend: addcmul - func: addcmul_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) + structured_delegate: addcmul.out + device_check: NoCheck # TensorIterator variants: method - dispatch: - DefaultBackend: addcmul_ - func: addcdiv.out(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: addcdiv_out - func: addcdiv(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor + structured_delegate: addcdiv.out + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - DefaultBackend: addcdiv + +- func: addcdiv_(Tensor(a!) self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor(a!) + structured_delegate: addcdiv.out + device_check: NoCheck # TensorIterator + variants: method + +- func: cross_entropy_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, int ignore_index=-100, float label_smoothing=0.0) -> Tensor + python_module: nn - func: lstsq.X(Tensor self, Tensor A, *, Tensor(a!) X, Tensor(b!) qr) -> (Tensor(a!) solution, Tensor(b!) QR) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: legacy::cpu::_th_gels_out - CUDA: legacy::cuda::_th_gels_out + CPU: legacy_lstsq_out + CUDA: legacy_lstsq_out_cuda - func: lstsq(Tensor self, Tensor A) -> (Tensor solution, Tensor QR) variants: method, function dispatch: - CPU: legacy::cpu::_th_gels - CUDA: legacy::cuda::_th_gels + CPU: legacy_lstsq + CUDA: legacy_lstsq_cuda - func: triangular_solve.X(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False, *, Tensor(a!) X, Tensor(b!) M) -> (Tensor(a!) solution, Tensor(b!) cloned_coefficient) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: - DefaultBackend: triangular_solve_out + CPU, CUDA: triangular_solve_out + SparseCsrCPU: triangular_solve_out_sparse_csr_cpu + SparseCsrCUDA: triangular_solve_out_sparse_csr_cuda - func: triangular_solve(Tensor self, Tensor A, bool upper=True, bool transpose=False, bool unitriangular=False) -> (Tensor solution, Tensor cloned_coefficient) + structured_delegate: triangular_solve.X + variants: method, function + +- func: _linalg_check_errors(Tensor info, str api_name, *, bool is_matrix) -> () + dispatch: + CompositeExplicitAutograd: _linalg_check_errors + +- func: linalg_solve_triangular.out(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA: linalg_solve_triangular_out + +- func: linalg_solve_triangular(Tensor self, Tensor B, *, bool upper, bool left=True, bool unitriangular=False) -> Tensor + python_module: linalg variants: method, function dispatch: - DefaultBackend: triangular_solve - -- func: _triangular_solve_helper(Tensor self, Tensor A, bool upper, bool transpose, bool unitriangular) -> (Tensor, Tensor) - variants: function - dispatch: - CPU: _triangular_solve_helper_cpu - CUDA: _triangular_solve_helper_cuda + CPU, CUDA: linalg_solve_triangular - func: symeig.e(Tensor self, bool eigenvectors=False, bool upper=True, *, Tensor(a!) e, Tensor(b!) V) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: symeig_out + CompositeExplicitAutograd: symeig_out - func: symeig(Tensor self, bool eigenvectors=False, bool upper=True) -> (Tensor eigenvalues, Tensor eigenvectors) variants: method, function dispatch: - DefaultBackend: symeig + CompositeExplicitAutograd: symeig - func: _symeig_helper(Tensor self, bool eigenvectors, bool upper) -> (Tensor, Tensor) variants: function @@ -5876,74 +6997,60 @@ CUDA: _symeig_helper_cuda - func: eig.e(Tensor self, bool eigenvectors=False, *, Tensor(a!) e, Tensor(b!) v) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: eig_out + CompositeExplicitAutograd: eig_out - func: eig(Tensor self, bool eigenvectors=False) -> (Tensor eigenvalues, Tensor eigenvectors) variants: method, function dispatch: - DefaultBackend: eig + CompositeExplicitAutograd: eig - func: svd.U(Tensor self, bool some=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: svd_out - func: svd(Tensor self, bool some=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V) variants: method, function - dispatch: - Math: svd - -- func: _svd_helper(Tensor self, bool some, bool compute_uv) -> (Tensor U, Tensor S, Tensor V) - variants: function - dispatch: - CPU: _svd_helper_cpu - CUDA: _svd_helper_cuda # swapaxes, alias for transpose - func: swapaxes(Tensor(a) self, int axis0, int axis1) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: swapaxes_(Tensor(a!) self, int axis0, int axis1) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view # swapdims, alias for transpose - func: swapdims(Tensor(a) self, int dim0, int dim1) -> Tensor(a) variants: function, method + device_check: NoCheck device_guard: False - func: swapdims_(Tensor(a!) self, int dim0, int dim1) -> Tensor(a!) variants: method + device_check: NoCheck device_guard: False + tags: inplace_view - func: cholesky.out(Tensor self, bool upper=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: cholesky_out + CPU, CUDA: cholesky_out - func: cholesky(Tensor self, bool upper=False) -> Tensor variants: method, function dispatch: - DefaultBackend: cholesky - -- func: _cholesky_helper(Tensor self, bool upper) -> Tensor - variants: function - dispatch: - CPU: _cholesky_helper_cpu - CUDA: _cholesky_helper_cuda + CPU, CUDA: cholesky - func: cholesky_solve.out(Tensor self, Tensor input2, bool upper=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: cholesky_solve_out + CompositeExplicitAutograd: cholesky_solve_out - func: cholesky_solve(Tensor self, Tensor input2, bool upper=False) -> Tensor variants: method, function dispatch: - DefaultBackend: cholesky_solve + CompositeExplicitAutograd: cholesky_solve - func: _cholesky_solve_helper(Tensor self, Tensor A, bool upper) -> Tensor variants: function @@ -5954,12 +7061,11 @@ - func: solve(Tensor self, Tensor A) -> (Tensor solution, Tensor LU) variants: function, method dispatch: - DefaultBackend: solve + CompositeExplicitAutograd: solve - func: solve.solution(Tensor self, Tensor A, *, Tensor(a!) solution, Tensor(b!) lu) -> (Tensor(a!) solution, Tensor(b!) LU) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: solve_out + CompositeExplicitAutograd: solve_out - func: _solve_helper(Tensor self, Tensor A) -> (Tensor, Tensor) variants: function @@ -5977,71 +7083,58 @@ CPU, CUDA: cholesky_inverse_out - func: qr.Q(Tensor self, bool some=True, *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: qr_out - func: qr(Tensor self, bool some=True) -> (Tensor Q, Tensor R) variants: method, function - dispatch: - Math: qr - func: geqrf.a(Tensor self, *, Tensor(a!) a, Tensor(b!) tau) -> (Tensor(a!) a, Tensor(b!) tau) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: legacy::cpu::_th_geqrf_out - CUDA: legacy::cuda::_th_geqrf_out + CPU, CUDA: geqrf_out - func: geqrf(Tensor self) -> (Tensor a, Tensor tau) variants: method, function dispatch: - CPU: legacy::cpu::_th_geqrf - CUDA: legacy::cuda::_th_geqrf - -- func: orgqr.out(Tensor self, Tensor input2, *, Tensor(a!) out) -> Tensor(a!) - dispatch: - CPU: orgqr_out + CPU, CUDA: geqrf +# orgqr, alias for linalg_householder_product - func: orgqr(Tensor self, Tensor input2) -> Tensor variants: method, function - dispatch: - CPU: orgqr + +- func: orgqr.out(Tensor self, Tensor input2, *, Tensor(a!) out) -> Tensor(a!) - func: ormqr.out(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: legacy::cpu::_th_ormqr_out + CPU, CUDA: ormqr_out - func: ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor variants: method, function dispatch: - CPU: legacy::cpu::_th_ormqr + CPU, CUDA: ormqr -- func: _lu_with_info(Tensor self, bool pivot=True, bool check_errors=True) -> (Tensor, Tensor, Tensor) +- func: _lu_with_info(Tensor self, bool pivot=True, bool check_errors=True) -> (Tensor LU, Tensor pivots, Tensor info) variants: function - dispatch: - CPU: _lu_with_info_cpu - CUDA: _lu_with_info_cuda - func: lu_solve.out(Tensor self, Tensor LU_data, Tensor LU_pivots, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: lu_solve_out + CPU, CUDA: lu_solve_out - func: lu_solve(Tensor self, Tensor LU_data, Tensor LU_pivots) -> Tensor variants: method, function dispatch: - DefaultBackend: lu_solve + CPU, CUDA: lu_solve -- func: _lu_solve_helper(Tensor self, Tensor LU_data, Tensor LU_pivots) -> Tensor +- func: lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U) variants: function dispatch: - CPU: _lu_solve_helper_cpu - CUDA: _lu_solve_helper_cuda + CPU, CUDA: lu_unpack + +- func: lu_unpack.out(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True, *, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) + variants: function + dispatch: + CPU, CUDA: lu_unpack_out # TODO: remove dispatch section when porting TH CUDA to ATen - func: multinomial.out(Tensor self, int num_samples, bool replacement=False, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: multinomial_out @@ -6051,410 +7144,567 @@ CPU, CUDA: multinomial - func: lgamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: lgamma_out - func: lgamma_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: lgamma.out variants: method - dispatch: - CPU, CUDA: lgamma_ - func: lgamma(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: lgamma.out variants: method, function - dispatch: - CPU, CUDA: lgamma - func: digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: digamma_out - func: digamma(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: digamma.out variants: method, function - dispatch: - CPU, CUDA: digamma - func: polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: polygamma_out - func: polygamma(int n, Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: polygamma.out variants: method, function - dispatch: - DefaultBackend: polygamma -- func: erfinv(Tensor self) -> Tensor - variants: method, function - dispatch: - CPU, CUDA: erfinv - -- func: erfinv_(Tensor(a!) self) -> Tensor(a!) +- func: polygamma_(Tensor(a!) self, int n) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: - CPU, CUDA: erfinv_ + CompositeExplicitAutograd: polygamma_ + +- func: erfinv(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: erfinv.out + variants: method, function + dispatch: + SparseCPU, SparseCUDA: erfinv_sparse + SparseCsrCPU, SparseCsrCUDA: erfinv_sparse_csr + +- func: erfinv_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: erfinv.out + variants: method + dispatch: + SparseCPU, SparseCUDA: erfinv_sparse_ + SparseCsrCPU, SparseCsrCUDA: erfinv_sparse_csr_ - func: erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: erfinv_out + SparseCPU, SparseCUDA: erfinv_sparse_out + SparseCsrCPU, SparseCsrCUDA: erfinv_sparse_csr_out - func: i0(Tensor self) -> Tensor + structured_delegate: i0.out variants: function, method - dispatch: - DefaultBackend: i0 - func: i0_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: i0.out variants: function, method - dispatch: - DefaultBackend: i0_ - func: i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: i0_out - func: sign(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: sign.out variants: function, method dispatch: - DefaultBackend: sign + CompositeExplicitAutograd: sign + SparseCPU, SparseCUDA: sign_sparse + SparseCsrCPU, SparseCsrCUDA: sign_sparse_csr - func: sign_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: sign.out variants: method dispatch: - DefaultBackend: sign_ + CompositeExplicitAutograd: sign_ + SparseCPU, SparseCUDA: sign_sparse_ + SparseCsrCPU, SparseCsrCUDA: sign_sparse_csr_ - func: sign.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sign_out + SparseCPU, SparseCUDA: sign_sparse_out + SparseCsrCPU, SparseCsrCUDA: sign_sparse_csr_out - func: signbit(Tensor self) -> Tensor variants: function, method + structured_delegate: signbit.out + dispatch: + SparseCPU, SparseCUDA: signbit_sparse + SparseCsrCPU, SparseCsrCUDA: signbit_sparse_csr - func: signbit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU: signbit_out CUDA: signbit_out + SparseCPU, SparseCUDA: signbit_sparse_out + SparseCsrCPU, SparseCsrCUDA: signbit_sparse_csr_out - func: dist(Tensor self, Tensor other, Scalar p=2) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: - DefaultBackend: dist + CompositeExplicitAutograd: dist - func: atan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: atan2_out +- func: atan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: atan2.out + variants: method + - func: atan2(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: atan2.out variants: method, function - dispatch: - CPU, CUDA: atan2 + +# arctan2, alias of atan2 +- func: arctan2(Tensor self, Tensor other) -> Tensor + variants: method, function + +- func: arctan2.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + +- func: arctan2_(Tensor(a!) self, Tensor other) -> Tensor(a!) + variants: method - func: lerp.Scalar_out(Tensor self, Tensor end, Scalar weight, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: - CPU: lerp_cpu_scalar_out - CUDA: lerp_cuda_scalar_out + CPU, CUDA: lerp_Scalar - func: lerp.Tensor_out(Tensor self, Tensor end, Tensor weight, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: - CPU: lerp_cpu_tensor_out - CUDA: lerp_cuda_tensor_out + CPU, CUDA: lerp_Tensor - func: lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU: lerp_cpu_scalar - CUDA: lerp_cuda_scalar + structured_delegate: lerp.Scalar_out - func: lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU: lerp_cpu_tensor - CUDA: lerp_cuda_tensor + structured_delegate: lerp.Tensor_out - func: histc.out(Tensor self, int bins=100, Scalar min=0, Scalar max=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU: legacy::cpu::_th_histc_out + CPU: histogram_histc_cpu_out CUDA: _histc_out_cuda - func: histc(Tensor self, int bins=100, Scalar min=0, Scalar max=0) -> Tensor variants: method, function dispatch: - CPU: legacy::cpu::_th_histc + CPU: histogram_histc_cpu CUDA: _histc_cuda -- func: fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: histogram.bins_tensor_out(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges) dispatch: - CPU, CUDA: fmod_out + CPU: histogram_out_cpu -- func: fmod.Scalar(Tensor self, Scalar other) -> Tensor +- func: histogram.bins_tensor(Tensor self, Tensor bins, *, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges) variants: method, function dispatch: - CPU, CUDA: fmod + CPU: histogram_cpu + +- func: histogram.bin_ct_out(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False, Tensor(a!) hist, Tensor(b!) bin_edges) -> (Tensor(a!) hist, Tensor(b!) bin_edges) + dispatch: + CPU: histogram_out_cpu + +- func: histogram.bin_ct(Tensor self, int bins=100, *, float[]? range=None, Tensor? weight=None, bool density=False) -> (Tensor hist, Tensor bin_edges) + variants: method, function + dispatch: + CPU: histogram_cpu + +- func: _histogramdd_bin_edges(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor[] + dispatch: + CPU: histogramdd_bin_edges_cpu + +- func: _histogramdd_from_bin_cts(Tensor self, int[] bins, *, float[]? range=None, Tensor? weight=None, bool density=False) -> Tensor + dispatch: + CPU: histogramdd_cpu + +- func: _histogramdd_from_bin_tensors(Tensor self, Tensor[] bins, *, Tensor? weight=None, bool density=False) -> Tensor + dispatch: + CPU: histogramdd_cpu + +- func: fmod.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + dispatch: + CompositeExplicitAutograd: fmod_out + +- func: fmod.Scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + variants: method, function + dispatch: + CompositeExplicitAutograd: fmod + +- func: fmod_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + dispatch: + CompositeExplicitAutograd: fmod_ - func: fmod.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: fmod_out - func: fmod.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: fmod.Tensor_out variants: method, function - dispatch: - CPU, CUDA: fmod + + +- func: fmod_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: fmod.Tensor_out - func: hypot.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: hypot_out - func: hypot(Tensor self, Tensor other) -> Tensor + structured_delegate: hypot.out variants: method, function - dispatch: - CPU, CUDA: hypot - func: hypot_(Tensor(a!) self, Tensor other) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured_delegate: hypot.out variants: method dispatch: - DefaultBackend: hypot_ + CompositeExplicitAutograd: hypot_ - func: igamma.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: igamma_out - func: igamma(Tensor self, Tensor other) -> Tensor + structured_delegate: igamma.out variants: method, function - dispatch: - CPU, CUDA: igamma - func: igamma_(Tensor(a!) self, Tensor other) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured_delegate: igamma.out variants: method - dispatch: - CPU, CUDA: igamma_ - func: igammac.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: igammac_out - func: igammac(Tensor self, Tensor other) -> Tensor + structured_delegate: igammac.out variants: method, function - dispatch: - CPU, CUDA: igammac - func: igammac_(Tensor(a!) self, Tensor other) -> Tensor(a!) + structured_delegate: igammac.out variants: method - dispatch: - CPU, CUDA: igammac_ - func: nextafter.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: nextafter_out - func: nextafter(Tensor self, Tensor other) -> Tensor + structured_delegate: nextafter.out variants: method, function - dispatch: - CPU, CUDA: nextafter - func: nextafter_(Tensor(a!) self, Tensor other) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured_delegate: nextafter.out variants: method dispatch: - DefaultBackend: nextafter_ + CompositeExplicitAutograd: nextafter_ - func: remainder.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - CPU, CUDA: remainder_out + CompositeExplicitAutograd: remainder_out - func: remainder.Scalar(Tensor self, Scalar other) -> Tensor variants: method, function dispatch: - CPU, CUDA: remainder + CompositeExplicitAutograd: remainder + +- func: remainder_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!) + variants: method + dispatch: + CompositeExplicitAutograd: remainder_ - func: remainder.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: remainder_out - func: remainder.Tensor(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: remainder.Tensor_out variants: method, function + +- func: remainder_.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: remainder.Tensor_out + variants: method + +- func: remainder.Scalar_Tensor(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + variants: function dispatch: CPU, CUDA: remainder - func: min(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: min QuantizedCPU: min_quantized_cpu - func: fmin(Tensor self, Tensor other) -> Tensor + structured_delegate: fmin.out + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU, CUDA: fmin - func: fmin.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: fmin_out - func: max(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU, CUDA: max QuantizedCPU: max_quantized_cpu - func: fmax(Tensor self, Tensor other) -> Tensor + structured_delegate: fmax.out + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU, CUDA: fmax - func: fmax.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: fmax_out - func: maximum(Tensor self, Tensor other) -> Tensor + structured_delegate: maximum.out + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU, CUDA: maximum - func: maximum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: maximum_out # binary max, alias of maximum # NOTE: max is not an alias for maximum, since there is also unary max - func: max.other(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: max.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: minimum(Tensor self, Tensor other) -> Tensor + structured_delegate: minimum.out + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU, CUDA: minimum - func: minimum.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator dispatch: CPU, CUDA: minimum_out # binary min, alias for minimum # NOTE: min is not an alias for minimum, since there is also unary min - func: min.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator - func: min.other(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function -- func: quantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - -- func: quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False) -> Tensor +- func: quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor variants: method, function -- func: quantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: quantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) -- func: quantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False) -> Tensor +- func: quantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor variants: method, function -- func: nanquantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: quantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) -- func: nanquantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False) -> Tensor +- func: nanquantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor variants: method, function -- func: nanquantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: nanquantile.out(Tensor self, Tensor q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) -- func: nanquantile(Tensor self, Tensor q, int? dim=None, bool keepdim=False) -> Tensor +- func: nanquantile.scalar(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear') -> Tensor variants: method, function +- func: nanquantile.scalar_out(Tensor self, float q, int? dim=None, bool keepdim=False, *, str interpolation='linear', Tensor(a!) out) -> Tensor(a!) + - func: sort.values(Tensor self, int dim=-1, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator dispatch: CPU: sort_out_cpu - CUDA: legacy::cuda::_th_sort_out + CUDA: sort_out_cuda + +- func: sort.values_stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) + dispatch: + CPU: sort_out_cpu_stable + CUDA: sort_out_stable_cuda - func: sort(Tensor self, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) + device_check: NoCheck # TensorIterator variants: method, function dispatch: CPU: sort_cpu - CUDA: legacy::cuda::_th_sort + CUDA: sort_cuda QuantizedCPU: sort_quantized_cpu +- func: sort.stable(Tensor self, *, bool? stable, int dim=-1, bool descending=False) -> (Tensor values, Tensor indices) + variants: method, function + dispatch: + CPU: sort_cpu_stable + CUDA: sort_stable_cuda + QuantizedCPU: sort_quantized_cpu_stable + - func: sort.dimname_values(Tensor self, Dimname dim, bool descending=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + +- func: sort.dimname_values_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - func: sort.dimname(Tensor self, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices) variants: method, function +- func: sort.dimname_stable(Tensor self, *, bool? stable, Dimname dim, bool descending=False) -> (Tensor values, Tensor indices) + variants: method, function + - func: msort.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: msort_out - func: msort(Tensor self) -> Tensor variants: method, function - dispatch: - Math: msort - func: argsort(Tensor self, int dim=-1, bool descending=False) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - func: argsort.dimname(Tensor self, Dimname dim, bool descending=False) -> Tensor variants: method, function - func: topk.values(Tensor self, int k, int dim=-1, bool largest=True, bool sorted=True, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!) values, Tensor(b!) indices) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True dispatch: CPU: topk_out_cpu - CUDA: legacy::cuda::_th_topk_out + CUDA: topk_out_cuda - func: topk(Tensor self, int k, int dim=-1, bool largest=True, bool sorted=True) -> (Tensor values, Tensor indices) variants: method, function + structured_delegate: topk.values dispatch: - CPU, CUDA: topk QuantizedCPU: topk_quantized_cpu - func: all(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: all.all_out variants: method, function + +- func: all.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + structured: True dispatch: - CPU, CUDA: all + CPU, CUDA: all_all_out - func: any(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: any.all_out variants: method, function dispatch: - CPU, CUDA: any SparseCPU, SparseCUDA: any_sparse -- func: renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: any.all_out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck + structured: True dispatch: - CPU: legacy::cpu::_th_renorm_out - CUDA: legacy::cuda::_th_renorm_out + CPU, CUDA: any_all_out + +- func: renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + dispatch: + CPU, CUDA: renorm_out - func: renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor + device_check: NoCheck # TensorIterator variants: method, function - dispatch: - CPU: legacy::cpu::_th_renorm - CUDA: legacy::cuda::_th_renorm + structured_delegate: renorm.out + +- func: renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!) + device_check: NoCheck # TensorIterator + variants: method + structured_delegate: renorm.out - func: unfold(Tensor(a) self, int dimension, int size, int step) -> Tensor(a) variants: method + device_check: NoCheck device_guard: False dispatch: CPU, CUDA: unfold @@ -6473,92 +7723,81 @@ QuantizedCPU: equal_quantized_cpu - func: pow.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: - CPU, CUDA: pow_out + CPU, CUDA: pow_Tensor_Tensor_out - func: pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Tensor_out variants: method, function - dispatch: - CPU, CUDA: pow - func: pow.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True dispatch: - CPU, CUDA: pow_out + CPU, CUDA: pow_Scalar_out - func: pow.Scalar(Scalar self, Tensor exponent) -> Tensor - dispatch: - CPU, CUDA: pow + device_check: NoCheck # TensorIterator + structured_delegate: pow.Scalar_out - func: pow.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase dispatch: - CPU, CUDA: pow_out + CPU, CUDA: pow_Tensor_Scalar_out SparseCPU, SparseCUDA: pow_out_sparse_scalar - func: pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Scalar_out variants: function, method dispatch: - CPU, CUDA: pow SparseCPU, SparseCUDA: pow_sparse_scalar - func: pow_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Scalar_out variants: method - dispatch: - CPU, CUDA: pow_ - func: pow_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured_delegate: pow.Tensor_Tensor_out variants: method - dispatch: - CPU, CUDA: pow_ - func: float_power.Tensor_Tensor_out(Tensor self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: float_power_out - func: float_power.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor variants: function, method - dispatch: - Math: float_power - func: float_power.Scalar_out(Scalar self, Tensor exponent, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: float_power_out - func: float_power.Scalar(Scalar self, Tensor exponent) -> Tensor - dispatch: - Math: float_power - func: float_power.Tensor_Scalar_out(Tensor self, Scalar exponent, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: float_power_out - func: float_power.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor variants: function, method - dispatch: - Math: float_power - func: float_power_.Scalar(Tensor(a!) self, Scalar exponent) -> Tensor(a!) variants: method - dispatch: - Math: float_power_ - func: float_power_.Tensor(Tensor(a!) self, Tensor exponent) -> Tensor(a!) variants: method - dispatch: - Math: float_power_ - func: normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!) + device_check: NoCheck # TensorIterator variants: method dispatch: CPU, CUDA: normal_ + Meta: normal_meta_ + SparseCsrCPU, SparseCsrCUDA: normal_sparse_csr_ - func: normal.Tensor_float_out(Tensor mean, float std=1, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: normal_out @@ -6567,7 +7806,6 @@ CPU, CUDA: normal - func: normal.float_Tensor_out(float mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: normal_out @@ -6576,7 +7814,6 @@ CPU, CUDA: normal - func: normal.Tensor_Tensor_out(Tensor mean, Tensor std, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU, CUDA: normal_out @@ -6585,60 +7822,28 @@ CPU, CUDA: normal - func: normal.float_float(float mean, float std, int[] size, *, Generator? generator=None, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: normal.float_float_out(float mean, float std, int[] size, *, Generator? generator=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - func: alias(Tensor(a) self) -> Tensor(a) variants: method, function dispatch: - DefaultBackend: alias + CompositeExplicitAutograd: alias - func: _index_copy_(Tensor(a!) self, int dim, Tensor index, Tensor source) -> Tensor(a!) dispatch: - CPU: legacy::cpu::_th_index_copy_ - CUDA: legacy::cuda::_th_index_copy_ - -- func: _cumsum(Tensor self, int dim) -> Tensor - dispatch: - CPU: _cumsum_cpu - CUDA: _cumsum_cuda - -- func: _cumsum.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - CPU: _cumsum_out_cpu - CUDA: _cumsum_out_cuda - -- func: _cumprod(Tensor self, int dim) -> Tensor - dispatch: - CPU: _cumprod_cpu - CUDA: _cumprod_cuda - -- func: _cumprod.out(Tensor self, int dim, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - CPU: _cumprod_out_cpu - CUDA: _cumprod_out_cuda - -- func: _var(Tensor self, bool unbiased=True) -> Tensor - dispatch: - CPU: legacy::cpu::_th_var - -- func: _std(Tensor self, bool unbiased=True) -> Tensor - dispatch: - CPU: legacy::cpu::_th_std + CPU: _index_copy_impl_ + CUDA: _index_copy_impl_ - func: _amp_foreach_non_finite_check_and_unscale_(Tensor(a!)[] self, Tensor(b!) found_inf, Tensor inv_scale) -> () variants: function dispatch: CUDA: _amp_foreach_non_finite_check_and_unscale_cuda_ -- func: _amp_update_scale(Tensor(a!) growth_tracker, Tensor current_scale, Tensor found_inf, float scale_growth_factor, float scale_backoff_factor, int growth_interval) -> Tensor +- func: _amp_update_scale_(Tensor(a!) self, Tensor(b!) growth_tracker, Tensor found_inf, float scale_growth_factor, float scale_backoff_factor, int growth_interval) -> Tensor(a!) variants: function dispatch: - CUDA: _amp_update_scale_cuda + CUDA: _amp_update_scale_cuda_ - func: _cat(Tensor[] tensors, int dim=0) -> Tensor dispatch: @@ -6647,568 +7852,654 @@ QuantizedCPU: cat_quantized_cpu - func: _cat.out(Tensor[] tensors, int dim=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: _cat_out_cpu CUDA: cat_out_cuda QuantizedCPU: cat_out_quantized_cpu - func: _foreach_add.Scalar(Tensor[] tensors, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_add_scalar_kernel_slow CUDA: foreach_tensor_add_scalar_kernel_cuda - func: _foreach_add_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_add_scalar_kernel_slow_ CUDA: foreach_tensor_add_scalar_kernel_cuda_ - func: _foreach_sub.Scalar(Tensor[] tensors, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sub_scalar_kernel_slow CUDA: foreach_tensor_sub_scalar_kernel_cuda - func: _foreach_sub_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sub_scalar_kernel_slow_ CUDA: foreach_tensor_sub_scalar_kernel_cuda_ - func: _foreach_mul.Scalar(Tensor[] tensors, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_mul_scalar_kernel_slow CUDA: foreach_tensor_mul_scalar_kernel_cuda - func: _foreach_mul_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_mul_scalar_kernel_slow_ CUDA: foreach_tensor_mul_scalar_kernel_cuda_ - func: _foreach_div.Scalar(Tensor[] tensors, Scalar scalar) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_div_scalar_kernel_slow CUDA: foreach_tensor_div_scalar_kernel_cuda - func: _foreach_div_.Scalar(Tensor(a!)[] self, Scalar scalar) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_div_scalar_kernel_slow_ CUDA: foreach_tensor_div_scalar_kernel_cuda_ - func: _foreach_add.List(Tensor[] tensors1, Tensor[] tensors2, *, Scalar alpha=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_add_list_kernel_slow CUDA: foreach_tensor_add_list_kernel_cuda - func: _foreach_add_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_add_list_kernel_slow_ CUDA: foreach_tensor_add_list_kernel_cuda_ - func: _foreach_sub.List(Tensor[] tensors1, Tensor[] tensors2, *, Scalar alpha=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sub_list_kernel_slow CUDA: foreach_tensor_sub_list_kernel_cuda - func: _foreach_sub_.List(Tensor(a!)[] self, Tensor[] other, *, Scalar alpha=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sub_list_kernel_slow_ CUDA: foreach_tensor_sub_list_kernel_cuda_ - func: _foreach_mul.List(Tensor[] tensors1, Tensor[] tensors2) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_mul_list_kernel_slow CUDA: foreach_tensor_mul_list_kernel_cuda - func: _foreach_mul_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_mul_list_kernel_slow_ CUDA: foreach_tensor_mul_list_kernel_cuda_ - func: _foreach_div.List(Tensor[] tensors1, Tensor[] tensors2) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_div_list_kernel_slow CUDA: foreach_tensor_div_list_kernel_cuda - func: _foreach_div_.List(Tensor(a!)[] self, Tensor[] other) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_div_list_kernel_slow_ CUDA: foreach_tensor_div_list_kernel_cuda_ -- func: _foreach_add.ScalarList(Tensor[] tensors, float[] scalars) -> Tensor[] +- func: _foreach_add.ScalarList(Tensor[] tensors, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_add_scalarlist_kernel_slow CUDA: foreach_tensor_add_scalarlist_kernel_cuda -- func: _foreach_add_.ScalarList(Tensor(a!)[] self, float[] scalars) -> () +- func: _foreach_add_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_add_scalarlist_kernel_slow_ CUDA: foreach_tensor_add_scalarlist_kernel_cuda_ -- func: _foreach_sub.ScalarList(Tensor[] tensors, float[] scalars) -> Tensor[] +- func: _foreach_sub.ScalarList(Tensor[] tensors, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sub_scalarlist_kernel_slow CUDA: foreach_tensor_sub_scalarlist_kernel_cuda -- func: _foreach_sub_.ScalarList(Tensor(a!)[] self, float[] scalars) -> () +- func: _foreach_sub_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sub_scalarlist_kernel_slow_ CUDA: foreach_tensor_sub_scalarlist_kernel_cuda_ -- func: _foreach_div.ScalarList(Tensor[] tensors, float[] scalars) -> Tensor[] +- func: _foreach_div.ScalarList(Tensor[] tensors, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_div_scalarlist_kernel_slow CUDA: foreach_tensor_div_scalarlist_kernel_cuda -- func: _foreach_div_.ScalarList(Tensor(a!)[] self, float[] scalars) -> () +- func: _foreach_div_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_div_scalarlist_kernel_slow_ CUDA: foreach_tensor_div_scalarlist_kernel_cuda_ -- func: _foreach_mul.ScalarList(Tensor[] tensors, float[] scalars) -> Tensor[] +- func: _foreach_mul.ScalarList(Tensor[] tensors, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_mul_scalarlist_kernel_slow CUDA: foreach_tensor_mul_scalarlist_kernel_cuda -- func: _foreach_mul_.ScalarList(Tensor(a!)[] self, float[] scalars) -> () +- func: _foreach_mul_.ScalarList(Tensor(a!)[] self, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_mul_scalarlist_kernel_slow_ CUDA: foreach_tensor_mul_scalarlist_kernel_cuda_ - func: _foreach_exp(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_exp_slow CUDA: foreach_tensor_exp_cuda - func: _foreach_zero_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_zero_slow_ CUDA: foreach_tensor_zero_cuda_ - func: _foreach_exp_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_exp_slow_ CUDA: foreach_tensor_exp_cuda_ - func: _foreach_sqrt(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sqrt_slow CUDA: foreach_tensor_sqrt_cuda - func: _foreach_sqrt_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sqrt_slow_ CUDA: foreach_tensor_sqrt_cuda_ - func: _foreach_abs(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_abs_slow CUDA: foreach_tensor_abs_cuda - func: _foreach_abs_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_abs_slow_ CUDA: foreach_tensor_abs_cuda_ - func: _foreach_acos(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_acos_slow CUDA: foreach_tensor_acos_cuda - func: _foreach_acos_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_acos_slow_ CUDA: foreach_tensor_acos_cuda_ - func: _foreach_asin(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_asin_slow CUDA: foreach_tensor_asin_cuda - func: _foreach_asin_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_asin_slow_ CUDA: foreach_tensor_asin_cuda_ - func: _foreach_atan(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_atan_slow CUDA: foreach_tensor_atan_cuda - func: _foreach_atan_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_atan_slow_ CUDA: foreach_tensor_atan_cuda_ - func: _foreach_ceil(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_ceil_slow CUDA: foreach_tensor_ceil_cuda - func: _foreach_ceil_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_ceil_slow_ CUDA: foreach_tensor_ceil_cuda_ - func: _foreach_cos(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_cos_slow CUDA: foreach_tensor_cos_cuda - func: _foreach_cos_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_cos_slow_ CUDA: foreach_tensor_cos_cuda_ - func: _foreach_cosh(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_cosh_slow CUDA: foreach_tensor_cosh_cuda - func: _foreach_cosh_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_cosh_slow_ CUDA: foreach_tensor_cosh_cuda_ - func: _foreach_erf(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_erf_slow CUDA: foreach_tensor_erf_cuda - func: _foreach_erf_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_erf_slow_ CUDA: foreach_tensor_erf_cuda_ - func: _foreach_erfc(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_erfc_slow CUDA: foreach_tensor_erfc_cuda - func: _foreach_erfc_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_erfc_slow_ CUDA: foreach_tensor_erfc_cuda_ - func: _foreach_expm1(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_expm1_slow CUDA: foreach_tensor_expm1_cuda - func: _foreach_expm1_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_expm1_slow_ CUDA: foreach_tensor_expm1_cuda_ - func: _foreach_floor(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_floor_slow CUDA: foreach_tensor_floor_cuda - func: _foreach_floor_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_floor_slow_ CUDA: foreach_tensor_floor_cuda_ - func: _foreach_log(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log_slow CUDA: foreach_tensor_log_cuda - func: _foreach_log_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log_slow_ CUDA: foreach_tensor_log_cuda_ - func: _foreach_log10(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log10_slow CUDA: foreach_tensor_log10_cuda - func: _foreach_log10_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log10_slow_ CUDA: foreach_tensor_log10_cuda_ - func: _foreach_log1p(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log1p_slow CUDA: foreach_tensor_log1p_cuda - func: _foreach_log1p_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log1p_slow_ CUDA: foreach_tensor_log1p_cuda_ - func: _foreach_log2(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log2_slow CUDA: foreach_tensor_log2_cuda - func: _foreach_log2_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_log2_slow_ CUDA: foreach_tensor_log2_cuda_ - func: _foreach_neg(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_neg_slow CUDA: foreach_tensor_neg_cuda - func: _foreach_neg_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_neg_slow_ CUDA: foreach_tensor_neg_cuda_ - func: _foreach_tan(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_tan_slow CUDA: foreach_tensor_tan_cuda - func: _foreach_tan_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_tan_slow_ CUDA: foreach_tensor_tan_cuda_ - func: _foreach_tanh(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_tanh_slow CUDA: foreach_tensor_tanh_cuda - func: _foreach_tanh_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_tanh_slow_ CUDA: foreach_tensor_tanh_cuda_ - func: _foreach_sin(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sin_slow CUDA: foreach_tensor_sin_cuda - func: _foreach_sin_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sin_slow_ CUDA: foreach_tensor_sin_cuda_ - func: _foreach_sinh(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sinh_slow CUDA: foreach_tensor_sinh_cuda - func: _foreach_sinh_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sinh_slow_ CUDA: foreach_tensor_sinh_cuda_ - func: _foreach_round(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_round_slow CUDA: foreach_tensor_round_cuda - func: _foreach_round_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_round_slow_ CUDA: foreach_tensor_round_cuda_ - func: _foreach_lgamma(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_lgamma_slow CUDA: foreach_tensor_lgamma_cuda - func: _foreach_lgamma_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_lgamma_slow_ CUDA: foreach_tensor_lgamma_cuda_ - func: _foreach_frac(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_frac_slow CUDA: foreach_tensor_frac_cuda - func: _foreach_frac_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_frac_slow_ CUDA: foreach_tensor_frac_cuda_ - func: _foreach_reciprocal(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_reciprocal_slow CUDA: foreach_tensor_reciprocal_cuda - func: _foreach_reciprocal_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_reciprocal_slow_ CUDA: foreach_tensor_reciprocal_cuda_ - func: _foreach_sigmoid(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sigmoid_slow CUDA: foreach_tensor_sigmoid_cuda - func: _foreach_sigmoid_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_sigmoid_slow_ CUDA: foreach_tensor_sigmoid_cuda_ - func: _foreach_trunc(Tensor[] tensors) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_trunc_slow CUDA: foreach_tensor_trunc_cuda - func: _foreach_trunc_(Tensor(a!)[] self) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_trunc_slow_ CUDA: foreach_tensor_trunc_cuda_ - func: _foreach_addcdiv_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcdiv_scalar_slow_ CUDA: foreach_tensor_addcdiv_scalar_cuda_ - func: _foreach_addcmul_.Scalar(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcmul_scalar_slow_ CUDA: foreach_tensor_addcmul_scalar_cuda_ -- func: _foreach_addcdiv_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, float[] scalars) -> () +- func: _foreach_addcdiv_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcdiv_scalarlist_slow_ CUDA: foreach_tensor_addcdiv_scalarlist_cuda_ -- func: _foreach_addcmul_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, float[] scalars) -> () +- func: _foreach_addcmul_.ScalarList(Tensor(a!)[] self, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> () + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcmul_scalarlist_slow_ CUDA: foreach_tensor_addcmul_scalarlist_cuda_ - func: _foreach_addcdiv.Scalar(Tensor[] input, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcdiv_scalar_slow CUDA: foreach_tensor_addcdiv_scalar_cuda - func: _foreach_addcmul.Scalar(Tensor[] input, Tensor[] tensor1, Tensor[] tensor2, Scalar value=1) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcmul_scalar_slow CUDA: foreach_tensor_addcmul_scalar_cuda -- func: _foreach_addcdiv.ScalarList(Tensor[] input, Tensor[] tensor1, Tensor[] tensor2, float[] scalars) -> Tensor[] +- func: _foreach_addcdiv.ScalarList(Tensor[] input, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcdiv_scalarlist_slow CUDA: foreach_tensor_addcdiv_scalarlist_cuda -- func: _foreach_addcmul.ScalarList(Tensor[] input, Tensor[] tensor1, Tensor[] tensor2, float[] scalars) -> Tensor[] +- func: _foreach_addcmul.ScalarList(Tensor[] input, Tensor[] tensor1, Tensor[] tensor2, Scalar[] scalars) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_addcmul_scalarlist_slow CUDA: foreach_tensor_addcmul_scalarlist_cuda - func: _foreach_maximum.List(Tensor[] tensors1, Tensor[] tensors2) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_maximum_slow CUDA: foreach_tensor_maximum_cuda - func: _foreach_minimum.List(Tensor[] tensors1, Tensor[] tensors2) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices variants: function dispatch: CPU: foreach_tensor_minimum_slow CUDA: foreach_tensor_minimum_cuda -- func: _mode(Tensor self, int dim=-1, bool keepdim=False) -> (Tensor, Tensor) +- func: _foreach_norm.Scalar(Tensor[] tensors, Scalar ord=2) -> Tensor[] + device_check: NoCheck # foreach kernels fall back to slow path when tensor are on different devices + variants: function dispatch: - CPU: legacy::cpu::_th_mode - CUDA: legacy::cuda::_th_mode - -- func: _mode.values(Tensor self, int dim=-1, bool keepdim=False, *, Tensor(a!) values, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - CPU: legacy::cpu::_th_mode_out - CUDA: legacy::cuda::_th_mode_out + CPU: foreach_tensor_norm_slow + CUDA: foreach_tensor_norm_cuda - func: bucketize.Tensor(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor dispatch: @@ -7216,7 +8507,6 @@ CUDA: bucketize_cuda - func: bucketize.Tensor_out(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: CPU: bucketize_out_cpu CUDA: bucketize_out_cuda @@ -7226,37 +8516,64 @@ CPU: bucketize_cpu CUDA: bucketize_cuda -- func: searchsorted.Tensor(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False) -> Tensor +- func: searchsorted.Tensor(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor dispatch: CPU: searchsorted_cpu CUDA: searchsorted_cuda -- func: searchsorted.Tensor_out(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +# [Note about _torch_cuda_cu_linker_symbol_op and torch_cuda_cu] +# This is a DUMMY function to force the linking against torch_cuda_cu on Windows. +# Otherwise, the Windows linker will optimize and not include torch_cuda_cu even when we +# want it to be included. This is similar to what we do with warp_size for torch_cuda_cpp, +# described as the solution to this issue: https://github.com/pytorch/pytorch/issues/31611 +# This op should NOT be used or exposed or edited or else Windows builds (with BUILD_SPLIT_CUDA) will break. +- func: _torch_cuda_cu_linker_symbol_op(Tensor self) -> Tensor + dispatch: + CUDA: _torch_cuda_cu_linker_symbol_op_cuda + +- func: searchsorted.Tensor_out(Tensor sorted_sequence, Tensor self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None, Tensor(a!) out) -> Tensor(a!) dispatch: CPU: searchsorted_out_cpu CUDA: searchsorted_out_cuda -- func: searchsorted.Scalar(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False) -> Tensor +- func: searchsorted.Scalar(Tensor sorted_sequence, Scalar self, *, bool out_int32=False, bool right=False, str? side=None, Tensor? sorter=None) -> Tensor dispatch: CPU: searchsorted_cpu CUDA: searchsorted_cuda +- func: _convert_indices_from_coo_to_csr(Tensor self, int size, *, bool out_int32=False) -> Tensor + structured_delegate: _convert_indices_from_coo_to_csr.out + +- func: _convert_indices_from_coo_to_csr.out(Tensor self, int size, *, bool out_int32=False, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: _convert_indices_from_coo_to_csr_structured_cpu + CUDA: _convert_indices_from_coo_to_csr_structured_cuda + +- func: _convert_indices_from_csr_to_coo(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False) -> Tensor + structured_delegate: _convert_indices_from_csr_to_coo.out + +- func: _convert_indices_from_csr_to_coo.out(Tensor crow_indices, Tensor col_indices, *, bool out_int32=False, bool transpose=False, Tensor(a!) out) -> Tensor(a!) + structured: True + dispatch: + CPU: _convert_indices_from_csr_to_coo_structured_cpu + CUDA: _convert_indices_from_csr_to_coo_structured_cuda + ## NN wrappers - func: mse_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: mse_loss_out - func: mse_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: mse_loss - func: mse_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU, CUDA: mse_loss_backward_out @@ -7267,18 +8584,16 @@ CPU, CUDA: mse_loss_backward - func: l1_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: - DefaultBackend: l1_loss_out + CompositeExplicitAutograd: l1_loss_out - func: l1_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor python_module: nn dispatch: - DefaultBackend: l1_loss + CompositeExplicitAutograd: l1_loss - func: l1_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU, CUDA: l1_loss_backward_out @@ -7286,155 +8601,137 @@ - func: l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor python_module: nn dispatch: - DefaultBackend: l1_loss_backward + CompositeExplicitAutograd: l1_loss_backward - func: multi_margin_loss.out(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: multi_margin_loss_cpu_out - CUDA: legacy::cuda::_thnn_multi_margin_loss_forward_out + CUDA: multi_margin_loss_cuda_out - func: multi_margin_loss(Tensor self, Tensor target, Scalar p=1, Scalar margin=1, Tensor? weight=None, int reduction=Mean) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: multi_margin_loss_cpu - CUDA: legacy::cuda::_thnn_multi_margin_loss_forward + CUDA: multi_margin_loss_cuda - func: multi_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: multi_margin_loss_cpu_backward_out - CUDA: legacy::cuda::_thnn_multi_margin_loss_backward_out + CUDA: multi_margin_loss_cuda_backward_out - func: multi_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, Scalar p, Scalar margin, Tensor? weight=None, int reduction=Mean) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: multi_margin_loss_cpu_backward - CUDA: legacy::cuda::_thnn_multi_margin_loss_backward + CUDA: multi_margin_loss_cuda_backward - func: multilabel_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - func: multilabel_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor python_module: nn - func: multilabel_margin_loss_forward.output(Tensor self, Tensor target, int reduction, *, Tensor(a!) output, Tensor(b!) is_target) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: multilabel_margin_loss_forward_out_cpu - CUDA: legacy::cuda::_thnn_multilabel_margin_loss_forward_out + CUDA: multilabel_margin_loss_forward_out_cuda - func: multilabel_margin_loss_forward(Tensor self, Tensor target, int reduction) -> (Tensor output, Tensor is_target) python_module: nn dispatch: CPU: multilabel_margin_loss_forward_cpu - CUDA: legacy::cuda::_thnn_multilabel_margin_loss_forward + CUDA: multilabel_margin_loss_forward_cuda - func: multilabel_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: multilabel_margin_loss_backward_cpu_out - CUDA: legacy::cuda::_thnn_multilabel_margin_loss_backward_out + CUDA: multilabel_margin_loss_backward_cuda_out - func: multilabel_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, Tensor is_target) -> Tensor python_module: nn dispatch: CPU: multilabel_margin_loss_backward_cpu - CUDA: legacy::cuda::_thnn_multilabel_margin_loss_backward + CUDA: multilabel_margin_loss_backward_cuda - func: nll_loss.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, int ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + python_module: nn + +- func: nll_loss_nd(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, int ignore_index=-100) -> Tensor python_module: nn - func: nll_loss(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, int ignore_index=-100) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - func: nll_loss_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: nll_loss_forward_out_cpu - CUDA: legacy::cuda::_thnn_nll_loss_forward_out + CUDA: nll_loss_forward_out_cuda - func: nll_loss_forward(Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index) -> (Tensor output, Tensor total_weight) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - dispatch: - CPU: nll_loss_forward_cpu - CUDA: legacy::cuda::_thnn_nll_loss_forward + structured_delegate: nll_loss_forward.output - func: nll_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: nll_loss_backward_out_cpu - CUDA: legacy::cuda::_thnn_nll_loss_backward_out + CUDA: nll_loss_backward_out_cuda - func: nll_loss_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index, Tensor total_weight) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - dispatch: - CPU: nll_loss_backward_cpu - CUDA: legacy::cuda::_thnn_nll_loss_backward + structured_delegate: nll_loss_backward.grad_input - func: nll_loss2d.out(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, int ignore_index=-100, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - func: nll_loss2d(Tensor self, Tensor target, Tensor? weight=None, int reduction=Mean, int ignore_index=-100) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - func: nll_loss2d_forward.output(Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index, *, Tensor(a!) output, Tensor(b!) total_weight) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: nll_loss2d_forward_out_cpu - CUDA: legacy::cuda::_thnn_nll_loss2d_forward_out + CUDA: nll_loss2d_forward_out_cuda - func: nll_loss2d_forward(Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index) -> (Tensor output, Tensor total_weight) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: nll_loss2d_forward_cpu - CUDA: legacy::cuda::_thnn_nll_loss2d_forward + CUDA: nll_loss2d_forward_cuda - func: nll_loss2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index, Tensor total_weight, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: nll_loss2d_backward_out_cpu - CUDA: legacy::cuda::_thnn_nll_loss2d_backward_out + CUDA: nll_loss2d_backward_out_cuda - func: nll_loss2d_backward(Tensor grad_output, Tensor self, Tensor target, Tensor? weight, int reduction, int ignore_index, Tensor total_weight) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: nll_loss2d_backward_cpu - CUDA: legacy::cuda::_thnn_nll_loss2d_backward + CUDA: nll_loss2d_backward_cuda - func: smooth_l1_loss.out(Tensor self, Tensor target, int reduction=Mean, float beta=1.0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: - CPU: smooth_l1_loss_out - CUDA: smooth_l1_loss_out + CPU, CUDA: smooth_l1_loss_out - func: smooth_l1_loss(Tensor self, Tensor target, int reduction=Mean, float beta=1.0) -> Tensor + device_check: NoCheck # TensorIterator + structured_delegate: smooth_l1_loss.out python_module: nn - dispatch: - CPU, CUDA: smooth_l1_loss - func: smooth_l1_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: smooth_l1_loss_backward_out @@ -7443,114 +8740,150 @@ - func: smooth_l1_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float beta) -> Tensor python_module: nn dispatch: - DefaultBackend: smooth_l1_loss_backward + CompositeExplicitAutograd: smooth_l1_loss_backward -- func: soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: huber_loss.out(Tensor self, Tensor target, int reduction=Mean, float delta=1.0, *, Tensor(a!) out) -> Tensor(a!) python_module: nn dispatch: - DefaultBackend: soft_margin_loss_out + CPU, CUDA: huber_loss_out + +- func: huber_loss(Tensor self, Tensor target, int reduction=Mean, float delta=1.0) -> Tensor + python_module: nn + dispatch: + CPU, CUDA: huber_loss + +- func: huber_loss_backward.out(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + dispatch: + CPU, CUDA: huber_loss_backward_out + +- func: huber_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction, float delta) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: huber_loss_backward + +- func: soft_margin_loss.out(Tensor self, Tensor target, int reduction=Mean, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + dispatch: + CompositeExplicitAutograd: soft_margin_loss_out - func: soft_margin_loss(Tensor self, Tensor target, int reduction=Mean) -> Tensor python_module: nn dispatch: - DefaultBackend: soft_margin_loss + CompositeExplicitAutograd: soft_margin_loss - func: soft_margin_loss_backward.grad_input(Tensor grad_output, Tensor self, Tensor target, int reduction, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: - DefaultBackend: soft_margin_loss_backward_out + CompositeExplicitAutograd: soft_margin_loss_backward_out - func: soft_margin_loss_backward(Tensor grad_output, Tensor self, Tensor target, int reduction) -> Tensor python_module: nn dispatch: - DefaultBackend: soft_margin_loss_backward + CompositeExplicitAutograd: soft_margin_loss_backward - func: elu.out(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: elu_out - func: elu(Tensor self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor + structured_delegate: elu.out + device_check: NoCheck # TensorIterator + python_module: nn + +- func: elu_backward.grad_input(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: - CPU, CUDA: elu + CPU, CUDA: elu_backward_out - func: elu_backward(Tensor grad_output, Scalar alpha, Scalar scale, Scalar input_scale, bool is_result, Tensor self_or_result) -> Tensor + structured_delegate: elu_backward.grad_input python_module: nn - dispatch: - CPU, CUDA: elu_backward - func: elu_(Tensor(a!) self, Scalar alpha=1, Scalar scale=1, Scalar input_scale=1) -> Tensor(a!) + structured_delegate: elu.out + device_check: NoCheck # TensorIterator python_module: nn dispatch: - DefaultBackend: elu_ + CompositeExplicitAutograd: elu_ - func: glu.out(Tensor self, int dim=-1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: - CPU: glu_out - CUDA: legacy::cuda::_thnn_glu_forward_out + CPU, CUDA: glu_out - func: glu(Tensor self, int dim=-1) -> Tensor + structured_delegate: glu.out + device_check: NoCheck # TensorIterator python_module: nn - dispatch: - CPU: glu - CUDA: legacy::cuda::_thnn_glu_forward - func: glu_backward.grad_input(Tensor grad_output, Tensor self, int dim, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: - CPU: glu_backward_out - CUDA: legacy::cuda::_thnn_glu_backward_out + CPU: glu_backward_cpu_out + CUDA: glu_backward_cuda_out - func: glu_backward(Tensor grad_output, Tensor self, int dim) -> Tensor python_module: nn dispatch: - CPU: glu_backward - CUDA: legacy::cuda::_thnn_glu_backward + CPU: glu_backward_cpu + CUDA: glu_backward_cuda - func: hardsigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardsigmoid_out + QuantizedCPU: hardsigmoid_out_quantized_cpu - func: hardsigmoid(Tensor self) -> Tensor + structured_delegate: hardsigmoid.out + device_check: NoCheck # TensorIterator python_module: nn dispatch: - CPU, CUDA: hardsigmoid QuantizedCPU: hardsigmoid_quantized_cpu - func: hardsigmoid_(Tensor(a!) self) -> Tensor(a!) + structured_delegate: hardsigmoid.out + device_check: NoCheck # TensorIterator + python_module: nn + +- func: hardsigmoid_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: - CPU, CUDA: hardsigmoid_ + CPU, CUDA: hardsigmoid_backward_out - func: hardsigmoid_backward(Tensor grad_output, Tensor self) -> Tensor + structured_delegate: hardsigmoid_backward.grad_input python_module: nn - dispatch: - CPU, CUDA: hardsigmoid_backward - func: hardtanh.out(Tensor self, Scalar min_val=-1, Scalar max_val=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardtanh_out QuantizedCPU: hardtanh_out_quantized_cpu - func: hardtanh(Tensor self, Scalar min_val=-1, Scalar max_val=1) -> Tensor + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardtanh QuantizedCPU: hardtanh_quantized_cpu - func: hardtanh_backward.grad_input(Tensor grad_output, Tensor self, Scalar min_val, Scalar max_val, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU, CUDA: hardtanh_backward_out @@ -7561,23 +8894,26 @@ CPU, CUDA: hardtanh_backward - func: hardtanh_(Tensor(a!) self, Scalar min_val=-1, Scalar max_val=1) -> Tensor(a!) + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardtanh_ QuantizedCPU: hardtanh_quantized_cpu_ - func: hardswish.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardswish_out - func: hardswish(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardswish - func: hardswish_(Tensor(a!) self) -> Tensor(a!) + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: hardswish_ @@ -7588,135 +8924,149 @@ CPU, CUDA: hardswish_backward - func: leaky_relu.out(Tensor self, Scalar negative_slope=0.01, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: leaky_relu_out QuantizedCPU: leaky_relu_out_quantized_cpu - func: leaky_relu(Tensor self, Scalar negative_slope=0.01) -> Tensor + structured_delegate: leaky_relu.out + device_check: NoCheck # TensorIterator python_module: nn dispatch: - CPU, CUDA: leaky_relu QuantizedCPU: leaky_relu_quantized_cpu -- func: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor +- func: leaky_relu_backward.grad_input(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: - CPU, CUDA: leaky_relu_backward + CPU, CUDA: leaky_relu_backward_out + +- func: leaky_relu_backward(Tensor grad_output, Tensor self, Scalar negative_slope, bool self_is_result) -> Tensor + structured_delegate: leaky_relu_backward.grad_input + python_module: nn - func: leaky_relu_(Tensor(a!) self, Scalar negative_slope=0.01) -> Tensor(a!) + structured_delegate: leaky_relu.out + device_check: NoCheck # TensorIterator python_module: nn dispatch: - CPU, CUDA: leaky_relu_ QuantizedCPU: leaky_relu_quantized_cpu_ - func: log_sigmoid.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn - func: log_sigmoid(Tensor self) -> Tensor + device_check: NoCheck # TensorIterator python_module: nn - func: log_sigmoid_forward.output(Tensor self, *, Tensor(a!) output, Tensor(b!) buffer) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU: log_sigmoid_forward_out_cpu - CUDA: legacy::cuda::_thnn_log_sigmoid_forward_out + CUDA: log_sigmoid_forward_out_cuda - func: log_sigmoid_forward(Tensor self) -> (Tensor output, Tensor buffer) + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU: log_sigmoid_forward_cpu - CUDA: legacy::cuda::_thnn_log_sigmoid_forward + CUDA: log_sigmoid_forward_cuda - func: log_sigmoid_backward.grad_input(Tensor grad_output, Tensor self, Tensor buffer, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: - CPU: log_sigmoid_backward_out_cpu - CUDA: legacy::cuda::_thnn_log_sigmoid_backward_out + CPU: log_sigmoid_backward_cpu_out + CUDA: log_sigmoid_backward_cuda_out - func: log_sigmoid_backward(Tensor grad_output, Tensor self, Tensor buffer) -> Tensor python_module: nn dispatch: CPU: log_sigmoid_backward_cpu - CUDA: legacy::cuda::_thnn_log_sigmoid_backward + CUDA: log_sigmoid_backward_cuda - func: rrelu_with_noise.out(Tensor self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: rrelu_with_noise_out_cpu - CUDA: legacy::cuda::_thnn_rrelu_with_noise_forward_out + CUDA: rrelu_with_noise_out_cuda - func: rrelu_with_noise(Tensor self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor python_module: nn dispatch: CPU: rrelu_with_noise_cpu - CUDA: legacy::cuda::_thnn_rrelu_with_noise_forward + CUDA: rrelu_with_noise_cuda - func: rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor python_module: nn dispatch: - DefaultBackend: rrelu_with_noise_backward + CompositeExplicitAutograd: rrelu_with_noise_backward - func: rrelu_with_noise_(Tensor(a!) self, Tensor noise, Scalar lower=0.125, Scalar upper=0.3333333333333333, bool training=False, Generator? generator=None) -> Tensor(a!) python_module: nn dispatch: CPU: rrelu_with_noise_cpu_ - CUDA: legacy::cuda::_thnn_rrelu_with_noise_forward_ + CUDA: rrelu_with_noise_cuda_ - func: softplus.out(Tensor self, Scalar beta=1, Scalar threshold=20, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: softplus_out - func: softplus(Tensor self, Scalar beta=1, Scalar threshold=20) -> Tensor + structured_delegate: softplus.out + device_check: NoCheck # TensorIterator python_module: nn - dispatch: - CPU, CUDA: softplus -- func: softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: softplus_backward.grad_input(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, *, Tensor(a!) grad_input) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: CPU, CUDA: softplus_backward_out -- func: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold, Tensor output) -> Tensor +- func: softplus_backward(Tensor grad_output, Tensor self, Scalar beta, Scalar threshold) -> Tensor + structured_delegate: softplus_backward.grad_input python_module: nn - dispatch: - CPU, CUDA: softplus_backward - func: softshrink.out(Tensor self, Scalar lambd=0.5, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase + device_check: NoCheck # TensorIterator python_module: nn dispatch: CPU, CUDA: softshrink_out - func: softshrink(Tensor self, Scalar lambd=0.5) -> Tensor + structured_delegate: softshrink.out + device_check: NoCheck # TensorIterator python_module: nn - dispatch: - CPU, CUDA: softshrink - func: softshrink_backward.grad_input(Tensor grad_output, Tensor self, Scalar lambd, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase python_module: nn dispatch: CPU, CUDA: softshrink_backward_out - func: softshrink_backward(Tensor grad_output, Tensor self, Scalar lambd) -> Tensor + structured_delegate: softshrink_backward.grad_input python_module: nn - dispatch: - CPU, CUDA: softshrink_backward - func: adaptive_avg_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: - CPU, CUDA: adaptive_avg_pool2d_out_cpu + CPU: adaptive_avg_pool2d_out_cpu + CUDA: adaptive_avg_pool2d_out_cuda MkldnnCPU: mkldnn_adaptive_avg_pool2d_out - func: adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor @@ -7726,6 +9076,10 @@ dispatch: MkldnnCPU: mkldnn_adaptive_avg_pool2d +- func: mkldnn_adaptive_avg_pool2d_backward(Tensor grad_output, Tensor self) -> Tensor + dispatch: + MkldnnCPU: mkldnn_adaptive_avg_pool2d_backward + - func: _adaptive_avg_pool2d(Tensor self, int[2] output_size) -> Tensor dispatch: CPU: adaptive_avg_pool2d_cpu @@ -7739,7 +9093,6 @@ CUDA: adaptive_avg_pool2d_backward_cuda - func: adaptive_avg_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: adaptive_avg_pool3d_out_cpu @@ -7748,19 +9101,20 @@ - func: adaptive_avg_pool3d(Tensor self, int[3] output_size) -> Tensor python_module: nn + +- func: _adaptive_avg_pool3d(Tensor self, int[3] output_size) -> Tensor dispatch: CPU: adaptive_avg_pool3d_cpu CUDA: adaptive_avg_pool3d_cuda QuantizedCPU: adaptive_avg_pool3d_quantized_cpu - func: adaptive_avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: adaptive_avg_pool3d_backward_out_cpu CUDA: adaptive_avg_pool3d_backward_out_cuda -- func: adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor +- func: _adaptive_avg_pool3d_backward(Tensor grad_output, Tensor self) -> Tensor python_module: nn dispatch: CPU: adaptive_avg_pool3d_backward_cpu @@ -7768,8 +9122,8 @@ # Return: (Tensor output, Tensor indices) - func: adaptive_max_pool2d.out(Tensor self, int[2] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: adaptive_max_pool2d_out_cpu CUDA: adaptive_max_pool2d_out_cuda @@ -7777,27 +9131,23 @@ # Return: (Tensor output, Tensor indices) - func: adaptive_max_pool2d(Tensor self, int[2] output_size) -> (Tensor, Tensor) python_module: nn - dispatch: - CPU: adaptive_max_pool2d_cpu - CUDA: adaptive_max_pool2d_cuda + structured_delegate: adaptive_max_pool2d.out - func: adaptive_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: adaptive_max_pool2d_backward_out_cpu CUDA: adaptive_max_pool2d_backward_out_cuda - func: adaptive_max_pool2d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor python_module: nn - dispatch: - CPU: adaptive_max_pool2d_backward_cpu - CUDA: adaptive_max_pool2d_backward_cuda + structured_delegate: adaptive_max_pool2d_backward.grad_input # Return: (Tensor output, Tensor indices) - func: adaptive_max_pool3d.out(Tensor self, int[3] output_size, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: adaptive_max_pool3d_out_cpu CUDA: adaptive_max_pool3d_out_cuda @@ -7805,26 +9155,26 @@ # Return: (Tensor output, Tensor indices) - func: adaptive_max_pool3d(Tensor self, int[3] output_size) -> (Tensor, Tensor) python_module: nn - dispatch: - CPU: adaptive_max_pool3d_cpu - CUDA: adaptive_max_pool3d_cuda + structured_delegate: adaptive_max_pool3d.out - func: adaptive_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: adaptive_max_pool3d_backward_out_cpu CUDA: adaptive_max_pool3d_backward_out_cuda - func: adaptive_max_pool3d_backward(Tensor grad_output, Tensor self, Tensor indices) -> Tensor python_module: nn - dispatch: - CPU: adaptive_max_pool3d_backward_cpu - CUDA: adaptive_max_pool3d_backward_cuda + structured_delegate: adaptive_max_pool3d_backward.grad_input - func: avg_pool2d.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True + precomputed: + - kernel_size -> int kH, int kW + - stride -> int dH, int dW + - padding -> int padH, int padW dispatch: CPU: avg_pool2d_out_cpu CUDA: avg_pool2d_out_cuda @@ -7832,28 +9182,28 @@ - func: avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor python_module: nn + structured_delegate: avg_pool2d.out dispatch: - CPU: avg_pool2d_cpu - CUDA: avg_pool2d_cuda MkldnnCPU: mkldnn_avg_pool2d QuantizedCPU: avg_pool2d_quantized_cpu - func: avg_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: avg_pool2d_backward_out_cpu CUDA: avg_pool2d_backward_out_cuda + MkldnnCPU: mkldnn_avg_pool2d_backward_out - func: avg_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor python_module: nn + structured_delegate: avg_pool2d_backward.grad_input dispatch: - CPU: avg_pool2d_backward_cpu - CUDA: avg_pool2d_backward_cuda + MkldnnCPU: mkldnn_avg_pool2d_backward - func: avg_pool3d.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: avg_pool3d_out_cpu CUDA: avg_pool3d_out_cuda @@ -7861,29 +9211,29 @@ - func: avg_pool3d(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor python_module: nn + structured_delegate: avg_pool3d.out dispatch: - CPU: avg_pool3d_cpu - CUDA: avg_pool3d_cuda MkldnnCPU: mkldnn_avg_pool3d QuantizedCPU: avg_pool3d_quantized_cpu - func: avg_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: avg_pool3d_backward_out_cpu CUDA: avg_pool3d_backward_out_cuda + MkldnnCPU: mkldnn_avg_pool3d_backward_out - func: avg_pool3d_backward(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor python_module: nn + structured_delegate: avg_pool3d_backward.grad_input dispatch: - CPU: avg_pool3d_backward_cpu - CUDA: avg_pool3d_backward_cuda + MkldnnCPU: mkldnn_avg_pool3d_backward # Return: (Tensor output, Tensor indices) - func: fractional_max_pool2d.output(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: fractional_max_pool2d_out_cpu CUDA: fractional_max_pool2d_out_cuda @@ -7891,27 +9241,26 @@ # Return: (Tensor output, Tensor indices) - func: fractional_max_pool2d(Tensor self, int[2] kernel_size, int[2] output_size, Tensor random_samples) -> (Tensor, Tensor) python_module: nn - dispatch: - CPU: fractional_max_pool2d_cpu - CUDA: fractional_max_pool2d_cuda + structured_delegate: fractional_max_pool2d.output - func: fractional_max_pool2d_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - python_module: nn - dispatch: - CPU: fractional_max_pool2d_backward_out_cpu - CUDA: fractional_max_pool2d_backward_out_cuda - -- func: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor python_module: nn + structured: True dispatch: CPU: fractional_max_pool2d_backward_cpu CUDA: fractional_max_pool2d_backward_cuda +- func: fractional_max_pool2d_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] output_size, Tensor indices) -> Tensor + python_module: nn + structured_delegate: fractional_max_pool2d_backward.grad_input + # Return: (Tensor output, Tensor indices) - func: fractional_max_pool3d.output(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples, *, Tensor(a!) output, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True + precomputed: + - kernel_size -> int poolSizeT, int poolSizeH, int poolSizeW + - output_size -> int outputT, int outputH, int outputW dispatch: CPU: fractional_max_pool3d_out_cpu CUDA: fractional_max_pool3d_out_cuda @@ -7919,12 +9268,9 @@ # Return: (Tensor output, Tensor indices) - func: fractional_max_pool3d(Tensor self, int[3] kernel_size, int[3] output_size, Tensor random_samples) -> (Tensor, Tensor) python_module: nn - dispatch: - CPU: fractional_max_pool3d_cpu - CUDA: fractional_max_pool3d_cuda + structured_delegate: fractional_max_pool3d.output - func: fractional_max_pool3d_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] output_size, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: fractional_max_pool3d_backward_out_cpu @@ -7938,8 +9284,8 @@ # Return: (Tensor output, Tensor indices) - func: max_pool2d_with_indices.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: max_pool2d_with_indices_out_cpu CUDA: max_pool2d_with_indices_out_cuda @@ -7947,26 +9293,21 @@ # Return: (Tensor output, Tensor indices) - func: max_pool2d_with_indices(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, int[2] dilation=1, bool ceil_mode=False) -> (Tensor, Tensor) python_module: nn - dispatch: - CPU: max_pool2d_with_indices_cpu - CUDA: max_pool2d_with_indices_cuda + structured_delegate: max_pool2d_with_indices.out - func: max_pool2d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: max_pool2d_with_indices_backward_out_cpu CUDA: max_pool2d_with_indices_backward_out_cuda - func: max_pool2d_with_indices_backward(Tensor grad_output, Tensor self, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool ceil_mode, Tensor indices) -> Tensor python_module: nn - dispatch: - CPU: max_pool2d_with_indices_backward_cpu - CUDA: max_pool2d_with_indices_backward_cuda + structured_delegate: max_pool2d_with_indices_backward.grad_input # Return: (Tensor output, Tensor indices) - func: max_pool3d_with_indices.out(Tensor self, int[3] kernel_size, int[3] stride=[], int[3] padding=0, int[3] dilation=1, bool ceil_mode=False, *, Tensor(a!) out, Tensor(b!) indices) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: max_pool3d_with_indices_out_cpu @@ -7980,7 +9321,6 @@ CUDA: max_pool3d_with_indices_cuda - func: max_pool3d_with_indices_backward.grad_input(Tensor grad_output, Tensor self, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool ceil_mode, Tensor indices, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: max_pool3d_with_indices_backward_out_cpu @@ -7993,7 +9333,6 @@ CUDA: max_pool3d_with_indices_backward_cuda - func: max_unpool2d.out(Tensor self, Tensor indices, int[2] output_size, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: max_unpooling2d_forward_out_cpu @@ -8006,7 +9345,6 @@ CUDA: max_unpooling2d_forward_cuda - func: max_unpool2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, int[2] output_size, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: max_unpooling2d_backward_out_cpu @@ -8019,7 +9357,6 @@ CUDA: max_unpooling2d_backward_cuda - func: max_unpool3d.out(Tensor self, Tensor indices, int[3] output_size, int[3] stride, int[3] padding, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: max_unpooling3d_forward_out_cpu @@ -8032,7 +9369,6 @@ CUDA: max_unpooling3d_forward_cuda - func: max_unpool3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor indices, int[3] output_size, int[3] stride, int[3] padding, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: max_unpooling3d_backward_out_cpu @@ -8045,33 +9381,30 @@ CUDA: max_unpooling3d_backward_cuda - func: reflection_pad1d.out(Tensor self, int[2] padding, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU, QuantizedCPU: reflection_pad1d_out_cpu CUDA: reflection_pad1d_out_cuda - func: reflection_pad1d(Tensor self, int[2] padding) -> Tensor python_module: nn + structured_delegate: reflection_pad1d.out dispatch: - CPU, QuantizedCPU: reflection_pad1d_cpu - CUDA: reflection_pad1d_cuda + QuantizedCPU: reflection_pad1d_cpu - func: reflection_pad1d_backward.grad_input(Tensor grad_output, Tensor self, int[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: reflection_pad1d_backward_out_cpu CUDA: reflection_pad1d_backward_out_cuda - func: reflection_pad1d_backward(Tensor grad_output, Tensor self, int[2] padding) -> Tensor python_module: nn - dispatch: - CPU: reflection_pad1d_backward_cpu - CUDA: reflection_pad1d_backward_cuda + structured_delegate: reflection_pad1d_backward.grad_input - func: reflection_pad2d.out(Tensor self, int[4] padding, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU, QuantizedCPU: reflection_pad2d_out_cpu @@ -8084,7 +9417,6 @@ CUDA: reflection_pad2d_cuda - func: reflection_pad2d_backward.grad_input(Tensor grad_output, Tensor self, int[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: reflection_pad2d_backward_out_cpu @@ -8096,47 +9428,62 @@ CPU: reflection_pad2d_backward_cpu CUDA: reflection_pad2d_backward_cuda -- func: replication_pad1d.out(Tensor self, int[2] padding, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: reflection_pad3d.out(Tensor self, int[6] padding, *, Tensor(a!) out) -> Tensor(a!) python_module: nn + structured: True + dispatch: + CPU: reflection_pad3d_out_cpu + CUDA: reflection_pad3d_out_cuda + +- func: reflection_pad3d(Tensor self, int[6] padding) -> Tensor + python_module: nn + structured_delegate: reflection_pad3d.out + +- func: reflection_pad3d_backward.grad_input(Tensor grad_output, Tensor self, int[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: reflection_pad3d_backward_out_cpu + CUDA: reflection_pad3d_backward_out_cuda + +- func: reflection_pad3d_backward(Tensor grad_output, Tensor self, int[6] padding) -> Tensor + python_module: nn + structured_delegate: reflection_pad3d_backward.grad_input + +- func: replication_pad1d.out(Tensor self, int[2] padding, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True dispatch: CPU: replication_pad1d_out_cpu CUDA: replication_pad1d_out_cuda - func: replication_pad1d(Tensor self, int[2] padding) -> Tensor python_module: nn - dispatch: - CPU: replication_pad1d_cpu - CUDA: replication_pad1d_cuda + structured_delegate: replication_pad1d.out - func: replication_pad1d_backward.grad_input(Tensor grad_output, Tensor self, int[2] padding, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: replication_pad1d_backward_out_cpu CUDA: replication_pad1d_backward_out_cuda - func: replication_pad1d_backward(Tensor grad_output, Tensor self, int[2] padding) -> Tensor python_module: nn - dispatch: - CPU: replication_pad1d_backward_cpu - CUDA: replication_pad1d_backward_cuda + structured_delegate: replication_pad1d_backward.grad_input - func: replication_pad2d.out(Tensor self, int[4] padding, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: replication_pad2d_out_cpu CUDA: replication_pad2d_out_cuda - func: replication_pad2d(Tensor self, int[4] padding) -> Tensor python_module: nn - dispatch: - CPU: replication_pad2d_cpu - CUDA: replication_pad2d_cuda + structured_delegate: replication_pad2d.out - func: replication_pad2d_backward.grad_input(Tensor grad_output, Tensor self, int[4] padding, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: replication_pad2d_backward_out_cpu @@ -8149,20 +9496,17 @@ CUDA: replication_pad2d_backward_cuda - func: replication_pad3d.out(Tensor self, int[6] padding, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: replication_pad3d_out_cpu CUDA: replication_pad3d_out_cuda - func: replication_pad3d(Tensor self, int[6] padding) -> Tensor python_module: nn - dispatch: - CPU: replication_pad3d_cpu - CUDA: replication_pad3d_cuda + structured_delegate: replication_pad3d.out - func: replication_pad3d_backward.grad_input(Tensor grad_output, Tensor self, int[6] padding, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: replication_pad3d_backward_out_cpu @@ -8177,71 +9521,102 @@ - func: upsample_linear1d.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_linear1d_cpu - CUDA: upsample_linear1d_cuda + CompositeExplicitAutograd: upsample_linear1d - func: upsample_linear1d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_linear1d_backward_cpu - CUDA: upsample_linear1d_backward_cuda + CompositeExplicitAutograd: upsample_linear1d_backward - func: upsample_bilinear2d.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_bilinear2d_cpu - CUDA: upsample_bilinear2d_cuda - QuantizedCPU: upsample_bilinear2d_quantized_cpu + CompositeExplicitAutograd: upsample_bilinear2d - func: upsample_bilinear2d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_bilinear2d_backward_cpu - CUDA: upsample_bilinear2d_backward_cuda + CompositeExplicitAutograd: upsample_bilinear2d_backward + +- func: _upsample_bilinear2d_aa.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_bilinear2d_aa + +- func: _upsample_bilinear2d_aa_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_bilinear2d_aa_backward - func: upsample_trilinear3d.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_trilinear3d_cpu - CUDA: upsample_trilinear3d_cuda + CompositeExplicitAutograd: upsample_trilinear3d - func: upsample_trilinear3d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_trilinear3d_backward_cpu - CUDA: upsample_trilinear3d_backward_cuda + CompositeExplicitAutograd: upsample_trilinear3d_backward - func: upsample_bicubic2d.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_bicubic2d_cpu - CUDA: upsample_bicubic2d_cuda + CompositeExplicitAutograd: upsample_bicubic2d - func: upsample_bicubic2d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, bool align_corners, float[]? scale_factors) -> Tensor python_module: nn dispatch: - CPU: upsample_bicubic2d_backward_cpu - CUDA: upsample_bicubic2d_backward_cuda + CompositeExplicitAutograd: upsample_bicubic2d_backward + +- func: _upsample_bicubic2d_aa.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_bicubic2d_aa + +- func: _upsample_bicubic2d_aa_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, bool align_corners, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_bicubic2d_aa_backward - func: upsample_nearest1d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> Tensor python_module: nn dispatch: - DefaultBackend: upsample_nearest1d + CompositeExplicitAutograd: upsample_nearest1d + +- func: _upsample_nearest_exact1d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_nearest_exact1d - func: upsample_nearest1d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, float[]? scale_factors) -> Tensor python_module: nn dispatch: - DefaultBackend: upsample_nearest1d_backward + CompositeExplicitAutograd: upsample_nearest1d_backward + +- func: _upsample_nearest_exact1d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_nearest_exact1d_backward - func: upsample_nearest2d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> Tensor python_module: nn dispatch: - DefaultBackend: upsample_nearest2d + CompositeExplicitAutograd: upsample_nearest2d + +- func: _upsample_nearest_exact2d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_nearest_exact2d - func: upsample_nearest2d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, float[]? scale_factors) -> Tensor python_module: nn dispatch: - DefaultBackend: upsample_nearest2d_backward + CompositeExplicitAutograd: upsample_nearest2d_backward + +- func: _upsample_nearest_exact2d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _upsample_nearest_exact2d_backward - func: upsample_nearest3d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> Tensor python_module: nn @@ -8250,117 +9625,159 @@ CUDA: upsample_nearest3d_cuda QuantizedCPU: upsample_nearest3d_quantized_cpu +- func: _upsample_nearest_exact3d.vec(Tensor input, int[]? output_size, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CPU: _upsample_nearest_exact3d_cpu + CUDA: _upsample_nearest_exact3d_cuda + QuantizedCPU: _upsample_nearest_exact3d_quantized_cpu + - func: upsample_nearest3d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, float[]? scale_factors) -> Tensor python_module: nn dispatch: CPU: upsample_nearest3d_backward_cpu CUDA: upsample_nearest3d_backward_cuda +- func: _upsample_nearest_exact3d_backward.vec(Tensor grad_output, int[]? output_size, int[] input_size, float[]? scale_factors) -> Tensor + python_module: nn + dispatch: + CPU: _upsample_nearest_exact3d_backward_cpu + CUDA: _upsample_nearest_exact3d_backward_cuda + # NOTE: all of the non-"vec" upsample overloads are only kept for backward compatibility. - func: upsample_linear1d.out(Tensor self, int[1] output_size, bool align_corners, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_linear1d_out_cpu CUDA: upsample_linear1d_out_cuda - func: upsample_linear1d(Tensor self, int[1] output_size, bool align_corners, float? scales=None) -> Tensor python_module: nn - dispatch: - CPU: upsample_linear1d_cpu - CUDA: upsample_linear1d_cuda + structured_delegate: upsample_linear1d.out - func: upsample_linear1d_backward.grad_input(Tensor grad_output, int[1] output_size, int[3] input_size, bool align_corners, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_linear1d_backward_out_cpu CUDA: upsample_linear1d_backward_out_cuda - func: upsample_linear1d_backward(Tensor grad_output, int[1] output_size, int[3] input_size, bool align_corners, float? scales=None) -> Tensor python_module: nn - dispatch: - CPU: upsample_linear1d_backward_cpu - CUDA: upsample_linear1d_backward_cuda + structured_delegate: upsample_linear1d_backward.grad_input - func: upsample_bilinear2d.out(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_bilinear2d_out_cpu CUDA: upsample_bilinear2d_out_cuda - func: upsample_bilinear2d(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn + structured_delegate: upsample_bilinear2d.out dispatch: - CPU: upsample_bilinear2d_cpu - CUDA: upsample_bilinear2d_cuda QuantizedCPU: upsample_bilinear2d_quantized_cpu - func: upsample_bilinear2d_backward.grad_input(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_bilinear2d_backward_out_cpu CUDA: upsample_bilinear2d_backward_out_cuda - func: upsample_bilinear2d_backward(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn + structured_delegate: upsample_bilinear2d_backward.grad_input + +- func: _upsample_bilinear2d_aa.out(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True dispatch: - CPU: upsample_bilinear2d_backward_cpu - CUDA: upsample_bilinear2d_backward_cuda + CPU: _upsample_bilinear2d_aa_out_cpu + CUDA: _upsample_bilinear2d_aa_out_cuda + +- func: _upsample_bilinear2d_aa(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bilinear2d_aa.out + +- func: _upsample_bilinear2d_aa_backward.grad_input(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_bilinear2d_aa_backward_out_cpu + CUDA: _upsample_bilinear2d_aa_backward_out_cuda + +- func: _upsample_bilinear2d_aa_backward(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bilinear2d_aa_backward.grad_input - func: upsample_bicubic2d.out(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_bicubic2d_out_cpu CUDA: upsample_bicubic2d_out_cuda - func: upsample_bicubic2d(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn - dispatch: - CPU: upsample_bicubic2d_cpu - CUDA: upsample_bicubic2d_cuda + structured_delegate: upsample_bicubic2d.out - func: upsample_bicubic2d_backward.grad_input(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_bicubic2d_backward_out_cpu CUDA: upsample_bicubic2d_backward_out_cuda - func: upsample_bicubic2d_backward(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn + structured_delegate: upsample_bicubic2d_backward.grad_input + +- func: _upsample_bicubic2d_aa.out(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True dispatch: - CPU: upsample_bicubic2d_backward_cpu - CUDA: upsample_bicubic2d_backward_cuda + CPU: _upsample_bicubic2d_aa_out_cpu + CUDA: _upsample_bicubic2d_aa_out_cuda + +- func: _upsample_bicubic2d_aa(Tensor self, int[2] output_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bicubic2d_aa.out + +- func: _upsample_bicubic2d_aa_backward.grad_input(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_bicubic2d_aa_backward_out_cpu + CUDA: _upsample_bicubic2d_aa_backward_out_cuda + +- func: _upsample_bicubic2d_aa_backward(Tensor grad_output, int[2] output_size, int[4] input_size, bool align_corners, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_bicubic2d_aa_backward.grad_input - func: upsample_trilinear3d.out(Tensor self, int[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_trilinear3d_out_cpu CUDA: upsample_trilinear3d_out_cuda - func: upsample_trilinear3d(Tensor self, int[3] output_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn - dispatch: - CPU: upsample_trilinear3d_cpu - CUDA: upsample_trilinear3d_cuda + structured_delegate: upsample_trilinear3d.out - func: upsample_trilinear3d_backward.grad_input(Tensor grad_output, int[3] output_size, int[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: CPU: upsample_trilinear3d_backward_out_cpu CUDA: upsample_trilinear3d_backward_out_cuda - func: upsample_trilinear3d_backward(Tensor grad_output, int[3] output_size, int[5] input_size, bool align_corners, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn - dispatch: - CPU: upsample_trilinear3d_backward_cpu - CUDA: upsample_trilinear3d_backward_cuda + structured_delegate: upsample_trilinear3d_backward.grad_input - func: upsample_nearest1d.out(Tensor self, int[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) python_module: nn @@ -8369,10 +9786,21 @@ CPU: upsample_nearest1d_out_cpu CUDA: upsample_nearest1d_out_cuda +- func: _upsample_nearest_exact1d.out(Tensor self, int[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact1d_out_cpu + CUDA: _upsample_nearest_exact1d_out_cuda + - func: upsample_nearest1d(Tensor self, int[1] output_size, float? scales=None) -> Tensor python_module: nn structured_delegate: upsample_nearest1d.out +- func: _upsample_nearest_exact1d(Tensor self, int[1] output_size, float? scales=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact1d.out + - func: upsample_nearest1d_backward.grad_input(Tensor grad_output, int[1] output_size, int[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) python_module: nn structured: True @@ -8380,10 +9808,21 @@ CPU: upsample_nearest1d_backward_out_cpu CUDA: upsample_nearest1d_backward_out_cuda +- func: _upsample_nearest_exact1d_backward.grad_input(Tensor grad_output, int[1] output_size, int[3] input_size, float? scales=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact1d_backward_out_cpu + CUDA: _upsample_nearest_exact1d_backward_out_cuda + - func: upsample_nearest1d_backward(Tensor grad_output, int[1] output_size, int[3] input_size, float? scales=None) -> Tensor python_module: nn structured_delegate: upsample_nearest1d_backward.grad_input +- func: _upsample_nearest_exact1d_backward(Tensor grad_output, int[1] output_size, int[3] input_size, float? scales=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact1d_backward.grad_input + - func: upsample_nearest2d.out(Tensor self, int[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) python_module: nn structured: True @@ -8391,12 +9830,25 @@ CPU: upsample_nearest2d_out_cpu CUDA: upsample_nearest2d_out_cuda +- func: _upsample_nearest_exact2d.out(Tensor self, int[2] output_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact2d_out_cpu + CUDA: _upsample_nearest_exact2d_out_cuda + - func: upsample_nearest2d(Tensor self, int[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn structured_delegate: upsample_nearest2d.out dispatch: QuantizedCPU: upsample_nearest2d_quantized_cpu +- func: _upsample_nearest_exact2d(Tensor self, int[2] output_size, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact2d.out + dispatch: + QuantizedCPU: _upsample_nearest_exact2d_quantized_cpu + - func: upsample_nearest2d_backward.grad_input(Tensor grad_output, int[2] output_size, int[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) python_module: nn structured: True @@ -8404,69 +9856,101 @@ CPU: upsample_nearest2d_backward_out_cpu CUDA: upsample_nearest2d_backward_out_cuda +- func: _upsample_nearest_exact2d_backward.grad_input(Tensor grad_output, int[2] output_size, int[4] input_size, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact2d_backward_out_cpu + CUDA: _upsample_nearest_exact2d_backward_out_cuda + - func: upsample_nearest2d_backward(Tensor grad_output, int[2] output_size, int[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn structured_delegate: upsample_nearest2d_backward.grad_input -- func: upsample_nearest3d.out(Tensor self, int[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _upsample_nearest_exact2d_backward(Tensor grad_output, int[2] output_size, int[4] input_size, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn + structured_delegate: _upsample_nearest_exact2d_backward.grad_input + +- func: upsample_nearest3d.out(Tensor self, int[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True dispatch: CPU: upsample_nearest3d_out_cpu CUDA: upsample_nearest3d_out_cuda +- func: _upsample_nearest_exact3d.out(Tensor self, int[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact3d_out_cpu + CUDA: _upsample_nearest_exact3d_out_cuda + - func: upsample_nearest3d(Tensor self, int[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn + structured_delegate: upsample_nearest3d.out dispatch: - CPU: upsample_nearest3d_cpu - CUDA: upsample_nearest3d_cuda QuantizedCPU: upsample_nearest3d_quantized_cpu -- func: upsample_nearest3d_backward.grad_input(Tensor grad_output, int[3] output_size, int[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _upsample_nearest_exact3d(Tensor self, int[3] output_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn + structured_delegate: _upsample_nearest_exact3d.out + dispatch: + QuantizedCPU: _upsample_nearest_exact3d_quantized_cpu + +- func: upsample_nearest3d_backward.grad_input(Tensor grad_output, int[3] output_size, int[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True dispatch: CPU: upsample_nearest3d_backward_out_cpu CUDA: upsample_nearest3d_backward_out_cuda +- func: _upsample_nearest_exact3d_backward.grad_input(Tensor grad_output, int[3] output_size, int[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None, *, Tensor(a!) grad_input) -> Tensor(a!) + python_module: nn + structured: True + dispatch: + CPU: _upsample_nearest_exact3d_backward_out_cpu + CUDA: _upsample_nearest_exact3d_backward_out_cuda + - func: upsample_nearest3d_backward(Tensor grad_output, int[3] output_size, int[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor python_module: nn - dispatch: - CPU: upsample_nearest3d_backward_cpu - CUDA: upsample_nearest3d_backward_cuda + structured_delegate: upsample_nearest3d_backward.grad_input + +- func: _upsample_nearest_exact3d_backward(Tensor grad_output, int[3] output_size, int[5] input_size, float? scales_d=None, float? scales_h=None, float? scales_w=None) -> Tensor + python_module: nn + structured_delegate: _upsample_nearest_exact3d_backward.grad_input - func: sigmoid_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: sigmoid_backward_out - func: sigmoid_backward(Tensor grad_output, Tensor output) -> Tensor python_module: nn - dispatch: - CPU, CUDA: sigmoid_backward + structured_delegate: sigmoid_backward.grad_input - func: logit_backward.grad_input(Tensor grad_output, Tensor self, float? eps=None, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: logit_backward_out - func: logit_backward(Tensor grad_output, Tensor self, float? eps=None) -> Tensor python_module: nn - dispatch: - CPU, CUDA: logit_backward + structured_delegate: logit_backward.grad_input - func: tanh_backward.grad_input(Tensor grad_output, Tensor output, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: tanh_backward_out - func: tanh_backward(Tensor grad_output, Tensor output) -> Tensor python_module: nn - dispatch: - CPU, CUDA: tanh_backward + structured_delegate: tanh_backward.grad_input # What's a thnn_conv_ versus a slow_conv_? # @@ -8487,184 +9971,103 @@ # make the operational distinction clear. - func: slow_conv_transpose2d.out(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] output_padding=0, int[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn + structured: True dispatch: - CPU: slow_conv_transpose2d_out_cpu - CUDA: slow_conv_transpose2d_out_cuda + CPU: slow_conv_transpose2d_structured_cpu + CUDA: slow_conv_transpose2d_structured_cuda - func: slow_conv_transpose2d(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] output_padding=0, int[2] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - dispatch: - CPU: slow_conv_transpose2d_cpu - CUDA: slow_conv_transpose2d_cuda - -- func: slow_conv_transpose2d_backward.grad_output(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, int[2] output_padding, int[2] dilation, Tensor columns, Tensor ones, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - python_module: nn - dispatch: - CPU: slow_conv_transpose2d_backward_out_cpu - CUDA: slow_conv_transpose2d_backward_out_cuda - -- func: slow_conv_transpose2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, int[2] output_padding, int[2] dilation, Tensor columns, Tensor ones, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) - python_module: nn - dispatch: - CPU: slow_conv_transpose2d_backward_cpu - CUDA: slow_conv_transpose2d_backward_cuda + structured_delegate: slow_conv_transpose2d.out - func: slow_conv_transpose3d.out(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] output_padding=0, int[3] dilation=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: slow_conv_transpose3d_out_cpu CUDA: slow_conv_transpose3d_out_cuda - func: slow_conv_transpose3d(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] output_padding=0, int[3] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: slow_conv_transpose3d_cpu CUDA: slow_conv_transpose3d_cuda -- func: slow_conv_transpose3d_backward.grad_output(Tensor grad_output, Tensor self, Tensor weight, int[3] kernel_size, int[3] stride, int[3] padding, int[3] output_padding, int[3] dilation, Tensor finput, Tensor fgrad_input, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - python_module: nn - dispatch: - CPU: slow_conv_transpose3d_backward_out_cpu - CUDA: slow_conv_transpose3d_backward_out_cuda - -- func: slow_conv_transpose3d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, int[3] kernel_size, int[3] stride, int[3] padding, int[3] output_padding, int[3] dilation, Tensor finput, Tensor fgrad_input, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) - python_module: nn - dispatch: - CPU: slow_conv_transpose3d_backward_cpu - CUDA: slow_conv_transpose3d_backward_cuda - - func: thnn_conv2d.out(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - func: thnn_conv2d(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn -- func: thnn_conv2d_forward.output(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding, *, Tensor(a!) output, Tensor(b!) finput, Tensor(c!) fgrad_input) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _slow_conv2d_forward.output(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding, *, Tensor(a!) output) -> Tensor(a!) python_module: nn dispatch: CPU: slow_conv2d_forward_out_cpu - CUDA: legacy::cuda::_thnn_conv2d_forward_out + CUDA: slow_conv2d_forward_out_cuda -- func: thnn_conv2d_forward(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding) -> (Tensor output, Tensor finput, Tensor fgrad_input) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _slow_conv2d_forward(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding) -> Tensor python_module: nn dispatch: CPU: slow_conv2d_forward_cpu - CUDA: legacy::cuda::_thnn_conv2d_forward + CUDA: slow_conv2d_forward_cuda -- func: thnn_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, Tensor finput, Tensor fgrad_input, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _slow_conv2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) python_module: nn dispatch: CPU: slow_conv2d_backward_out_cpu CUDA: slow_conv2d_backward_out_cuda -- func: thnn_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, Tensor finput, Tensor fgrad_input, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) +- func: _slow_conv2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) python_module: nn dispatch: CPU: slow_conv2d_backward_cpu CUDA: slow_conv2d_backward_cuda -- func: thnn_conv_depthwise2d.out(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - python_module: nn - -- func: thnn_conv_depthwise2d(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - python_module: nn - -- func: thnn_conv_depthwise2d_forward.out(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding, int[2] dilation, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _conv_depthwise2d.out(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding, int[2] dilation, *, Tensor(a!) out) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True python_module: nn dispatch: - CUDA: legacy::cuda::_thnn_conv_depthwise2d_forward_out + CUDA: conv_depthwise2d_cuda_out -- func: thnn_conv_depthwise2d_forward(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding, int[2] dilation) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: _conv_depthwise2d(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias, int[2] stride, int[2] padding, int[2] dilation) -> Tensor python_module: nn dispatch: - CUDA: legacy::cuda::_thnn_conv_depthwise2d_forward + CUDA: conv_depthwise2d_cuda -- func: thnn_conv_depthwise2d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, *, Tensor(a!) grad_input, Tensor(b!) grad_weight) -> (Tensor(a!), Tensor(b!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: conv_depthwise3d(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding, int[3] dilation) -> Tensor python_module: nn dispatch: - CUDA: thnn_conv_depthwise2d_backward_out - -- func: thnn_conv_depthwise2d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool[2] output_mask) -> (Tensor grad_input, Tensor grad_weight) - python_module: nn - dispatch: - CUDA: thnn_conv_depthwise2d_backward + CUDA: conv_depthwise3d_cuda - func: slow_conv3d.out(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn - func: slow_conv3d(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn -- func: slow_conv3d_forward.output(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding, *, Tensor(a!) output, Tensor(b!) finput, Tensor(c!) fgrad_input) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: slow_conv3d_forward.output(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding, *, Tensor(a!) output) -> Tensor(a!) python_module: nn dispatch: CPU: slow_conv3d_forward_out_cpu -- func: slow_conv3d_forward(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding) -> (Tensor output, Tensor finput, Tensor fgrad_input) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: slow_conv3d_forward(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias, int[3] stride, int[3] padding) -> Tensor python_module: nn dispatch: CPU: slow_conv3d_forward_cpu -- func: slow_conv3d_backward.grad_input(Tensor grad_output, Tensor self, Tensor weight, int[3] kernel_size, int[3] stride, int[3] padding, Tensor finput, Tensor fgrad_input, *, Tensor(a!) grad_input, Tensor(b!) grad_weight, Tensor(c!) grad_bias) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - python_module: nn - dispatch: - CPU: slow_conv3d_backward_out_cpu - -- func: slow_conv3d_backward.output_mask(Tensor grad_output, Tensor self, Tensor weight, int[3] kernel_size, int[3] stride, int[3] padding, Tensor finput, Tensor fgrad_input, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) - python_module: nn - dispatch: - CPU: slow_conv3d_backward_cpu - - func: slow_conv_dilated2d(Tensor self, Tensor weight, int[2] kernel_size, Tensor? bias=None, int[2] stride=1, int[2] padding=0, int[2] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: slow_conv_dilated2d_cpu CUDA: slow_conv_dilated2d_cuda -- func: slow_conv_dilated2d_backward(Tensor grad_output, Tensor self, Tensor weight, int[2] kernel_size, int[2] stride, int[2] padding, int[2] dilation, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) - python_module: nn - dispatch: - CPU: slow_conv_dilated2d_backward_cpu - CUDA: slow_conv_dilated2d_backward_cuda - - func: slow_conv_dilated3d(Tensor self, Tensor weight, int[3] kernel_size, Tensor? bias=None, int[3] stride=1, int[3] padding=0, int[3] dilation=1) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: slow_conv_dilated3d_cpu CUDA: slow_conv_dilated3d_cuda -- func: slow_conv_dilated3d_backward(Tensor grad_output, Tensor self, Tensor weight, int[3] kernel_size, int[3] stride, int[3] padding, int[3] dilation, bool[3] output_mask) -> (Tensor grad_input, Tensor grad_weight, Tensor grad_bias) - python_module: nn - dispatch: - CPU: slow_conv_dilated3d_backward_cpu - CUDA: slow_conv_dilated3d_backward_cuda - - func: col2im.out(Tensor self, int[2] output_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: col2im_out_cpu @@ -8677,7 +10080,6 @@ CUDA: col2im_cuda - func: col2im_backward.grad_input(Tensor grad_output, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: col2im_backward_out_cpu @@ -8690,16 +10092,10 @@ CUDA: col2im_backward_cuda - func: column_stack(Tensor[] tensors) -> Tensor - dispatch: - Math: column_stack - func: column_stack.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - Math: column_stack_out - func: im2col.out(Tensor self, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: im2col_out_cpu @@ -8712,7 +10108,6 @@ CUDA: im2col_cuda - func: im2col_backward.grad_input(Tensor grad_output, int[2] input_size, int[2] kernel_size, int[2] dilation, int[2] padding, int[2] stride, *, Tensor(a!) grad_input) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: nn dispatch: CPU: im2col_backward_out_cpu @@ -8726,11 +10121,17 @@ - func: isfinite(Tensor self) -> Tensor variants: function, method + device_check: NoCheck device_guard: False - func: isinf(Tensor self) -> Tensor variants: function, method + device_check: NoCheck device_guard: False + dispatch: + CompositeExplicitAutograd: isinf + SparseCPU, SparseCUDA: isinf_sparse + SparseCsrCPU, SparseCsrCUDA: isinf_sparse_csr - func: record_stream(Tensor(a!) self, Stream s) -> () variants: method @@ -8739,19 +10140,33 @@ - func: isposinf(Tensor self) -> Tensor variants: function, method + structured_delegate: isposinf.out + dispatch: + SparseCPU, SparseCUDA: isposinf_sparse + SparseCsrCPU, SparseCsrCUDA: isposinf_sparse_csr - func: isposinf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: isposinf_out + SparseCPU, SparseCUDA: isposinf_sparse_out + SparseCsrCPU, SparseCsrCUDA: isposinf_sparse_csr_out - func: isneginf(Tensor self) -> Tensor variants: function, method + structured_delegate: isneginf.out + dispatch: + SparseCPU, SparseCUDA: isneginf_sparse + SparseCsrCPU, SparseCsrCUDA: isneginf_sparse_csr - func: isneginf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + structured: True + structured_inherits: TensorIteratorBase dispatch: CPU, CUDA: isneginf_out + SparseCPU, SparseCUDA: isneginf_sparse_out + SparseCsrCPU, SparseCsrCUDA: isneginf_sparse_csr_out # NOTE [_add_batch_dim and _remove_batch_dim] # _add_batch_dim and _remove_batch_dim are meant to be used in the implementation @@ -8764,6 +10179,368 @@ - func: _remove_batch_dim(Tensor self, int level, int batch_size, int out_dim) -> Tensor variants: function +## Functions related to the `torch.special` namespace +# Note [special namespace binding] +# Functions in the special python module should have their names start with +# "special_" underscore and be bound to the desired Python name in +# torch/special/__init__.py, and the desired C++ name in torch/csrc/api/include/torch/special.h. +# The "special_" names should be hidden from the user and not documented. + +- func: special_entr(Tensor self) -> Tensor + structured_delegate: special_entr.out + python_module: special + variants: function + +- func: special_entr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA: special_entr_out + +- func: special_ndtri(Tensor self) -> Tensor + structured_delegate: special_ndtri.out + python_module: special + variants: function + +- func: special_ndtri.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA: special_ndtri_out + +- func: special_expm1(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_expm1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_exp2(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_exp2.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_psi(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_psi.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_digamma(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_digamma.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_gammaln(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_gammaln.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_erf(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_erf.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_erfc(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_erfc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_erfcx(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_erfcx.out + +- func: special_erfcx.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: special_erfcx_out + +- func: special_erfinv(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_erfinv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_ndtr(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_ndtr.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_xlog1py(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + structured_delegate: special_xlog1py.out + +- func: special_xlog1py.self_scalar(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py + +- func: special_xlog1py.other_scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py + +- func: special_xlog1py.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA: special_xlog1py_out + +- func: special_xlog1py.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py_out + +- func: special_xlog1py.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_xlog1py_out + +- func: special_xlogy(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.self_scalar(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.other_scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_xlogy.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + +- func: special_zeta(Tensor self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + structured_delegate: special_zeta.out + dispatch: + CompositeExplicitAutograd: special_zeta + +- func: special_zeta.self_scalar(Scalar self, Tensor other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta + +- func: special_zeta.other_scalar(Tensor self, Scalar other) -> Tensor + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta + +- func: special_zeta.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + structured: True + structured_inherits: TensorIteratorBase + python_module: special + variants: function + dispatch: + CPU, CUDA: special_zeta_out + +- func: special_zeta.self_scalar_out(Scalar self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta_out + +- func: special_zeta.other_scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!) + device_check: NoCheck # TensorIterator + python_module: special + variants: function + dispatch: + CompositeExplicitAutograd: special_zeta_out + +- func: special_i0(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_i0e(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_i0e.out + +- func: special_i0e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: special_i0e_out + +- func: special_i1(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_i1.out + +- func: special_i1.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: special_i1_out + +- func: special_i1e(Tensor self) -> Tensor + python_module: special + variants: function + structured_delegate: special_i1e.out + +- func: special_i1e.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + structured: True + structured_inherits: TensorIteratorBase + dispatch: + CPU, CUDA: special_i1e_out + +- func: special_logit(Tensor self, float? eps=None) -> Tensor + python_module: special + variants: function + +- func: special_logit.out(Tensor self, float? eps=None, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_polygamma(int n, Tensor self) -> Tensor + python_module: special + variants: function, method + +- func: special_polygamma.out(int n, Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_logsumexp(Tensor self, int[1] dim, bool keepdim=False) -> Tensor + python_module: special + variants: function + +- func: special_logsumexp.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + +- func: special_expit(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_expit.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_sinc(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_round(Tensor self, *, int decimals=0) -> Tensor + python_module: special + variants: function + +- func: special_round.out(Tensor self, *, int decimals=0, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_log1p(Tensor self) -> Tensor + python_module: special + variants: function + +- func: special_log1p.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_log_softmax(Tensor self, int dim, *, ScalarType? dtype=None) -> Tensor + python_module: special + variants: function + +- func: special_gammainc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_gammainc(Tensor self, Tensor other) -> Tensor + python_module: special + variants: function + +- func: special_gammaincc.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_gammaincc(Tensor self, Tensor other) -> Tensor + python_module: special + variants: function + +- func: special_multigammaln(Tensor self, int p) -> Tensor + python_module: special + variants: function + +- func: special_multigammaln.out(Tensor self, int p, *, Tensor(a!) out) -> Tensor(a!) + python_module: special + variants: function + +- func: special_softmax(Tensor self, int dim, ScalarType? dtype=None) -> Tensor + python_module: special + variants: function + ## Functions related to the fast Fourier transform and the torch.fft namespace # Note [FFT namespace binding] # Functions in the fft python module should have their names start with @@ -8780,7 +10557,6 @@ variants: function - func: fft_fft.out(Tensor self, int? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8789,7 +10565,6 @@ variants: function - func: fft_ifft.out(Tensor self, int? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8798,7 +10573,6 @@ variants: function - func: fft_rfft.out(Tensor self, int? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8807,7 +10581,6 @@ variants: function - func: fft_irfft.out(Tensor self, int? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8816,7 +10589,6 @@ variants: function - func: fft_hfft.out(Tensor self, int? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8825,7 +10597,6 @@ variants: function - func: fft_ihfft.out(Tensor self, int? n=None, int dim=-1, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8834,7 +10605,6 @@ variants: function - func: fft_fft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8843,7 +10613,6 @@ variants: function - func: fft_ifft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8852,7 +10621,6 @@ variants: function - func: fft_rfft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8861,7 +10629,26 @@ variants: function - func: fft_irfft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + python_module: fft + variants: function + +- func: fft_hfft2(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + +- func: fft_hfft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + +- func: fft_ihfft2(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + +- func: fft_ihfft2.out(Tensor self, int[1]? s=None, int[1] dim=[-2,-1], str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True python_module: fft variants: function @@ -8870,7 +10657,6 @@ variants: function - func: fft_fftn.out(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8879,7 +10665,6 @@ variants: function - func: fft_ifftn.out(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8888,7 +10673,6 @@ variants: function - func: fft_rfftn.out(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8897,27 +10681,42 @@ variants: function - func: fft_irfftn.out(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures + python_module: fft + variants: function + +- func: fft_hfftn(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + +- func: fft_hfftn.out(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + +- func: fft_ihfftn(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor + use_const_ref_for_mutable_tensors: True + python_module: fft + variants: function + +- func: fft_ihfftn.out(Tensor self, int[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!) + use_const_ref_for_mutable_tensors: True python_module: fft variants: function - func: fft_fftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function - func: fft_fftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function - func: fft_rfftfreq(int n, float d=1.0, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function - func: fft_rfftfreq.out(int n, float d=1.0, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: fft variants: function @@ -8938,28 +10737,105 @@ # # See linalg_det as an example. -- func: linalg_cholesky(Tensor self) -> Tensor +# "_ex" stands for experimental +- func: linalg_cholesky_ex(Tensor self, *, bool upper=False, bool check_errors=False) -> (Tensor L, Tensor info) python_module: linalg variants: function dispatch: - DefaultBackend: linalg_cholesky + CPU, CUDA: linalg_cholesky_ex -- func: linalg_cholesky.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: linalg_cholesky_ex.L(Tensor self, *, bool upper=False, bool check_errors=False, Tensor(a!) L, Tensor(b!) info) -> (Tensor(a!) L, Tensor(b!) info) python_module: linalg variants: function dispatch: - DefaultBackend: linalg_cholesky_out + CPU, CUDA: linalg_cholesky_ex_out + +- func: linalg_cholesky(Tensor self, *, bool upper=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_cholesky.out(Tensor self, *, bool upper=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_cross(Tensor self, Tensor other, *, int dim=-1) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_cross + +- func: linalg_cross.out(Tensor self, Tensor other, *, int dim=-1, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA: linalg_cross_out + +# linalg.lu_factor +- func: linalg_lu_factor(Tensor A, *, bool pivot=True) -> (Tensor LU, Tensor pivots) + python_module: linalg + variants: function + +- func: linalg_lu_factor.out(Tensor A, *, bool pivot=True, Tensor(a!) LU, Tensor(b!) pivots) -> (Tensor(a!) LU, Tensor(b!) pivots) + python_module: linalg + variants: function + +- func: linalg_lu_factor_ex(Tensor A, *, bool pivot=True, bool check_errors=False) -> (Tensor LU, Tensor pivots, Tensor info) + python_module: linalg + structured_delegate: linalg_lu_factor_ex.out + variants: function + +- func: linalg_lu_factor_ex.out(Tensor A, *, bool pivot=True, bool check_errors=False, Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info) -> (Tensor(a!) LU, Tensor(b!) pivots, Tensor(c!) info) + python_module: linalg + variants: function + structured: True + dispatch: + CPU, CUDA: linalg_lu_factor_ex_out -# torch.linalg.det, alias for torch.det - func: linalg_det(Tensor self) -> Tensor python_module: linalg variants: function +- func: linalg_det.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +# torch.det, alias for torch.linalg.det - func: det(Tensor self) -> Tensor variants: function, method + +- func: _det_lu_based_helper(Tensor self) -> (Tensor det, Tensor lu, Tensor pivs) + variants: function dispatch: - DefaultBackend: det + CPU, CUDA: _det_lu_based_helper + +- func: _det_lu_based_helper_backward_helper(Tensor det_grad, Tensor det, Tensor self, Tensor lu, Tensor pivs) -> Tensor + variants: function + dispatch: + CPU, CUDA: _det_lu_based_helper_backward_helper + +- func: linalg_lstsq(Tensor self, Tensor b, float? rcond=None, *, str? driver=None) -> (Tensor solution, Tensor residuals, Tensor rank, Tensor singular_values) + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg_lstsq + +- func: linalg_lstsq.out(Tensor self, Tensor b, float? rcond=None, *, str? driver=None, Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values) -> (Tensor(a!) solution, Tensor(b!) residuals, Tensor(c!) rank, Tensor(d!) singular_values) + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_lstsq_out + +# torch.linalg.matmul, alias for torch.matmul +- func: linalg_matmul(Tensor self, Tensor other) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matmul.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_matrix_exp(Tensor self) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_matrix_exp - func: linalg_slogdet(Tensor self) -> (Tensor sign, Tensor logabsdet) python_module: linalg @@ -8972,35 +10848,53 @@ dispatch: CPU, CUDA: linalg_slogdet_out -- func: _syevd_helper(Tensor self, bool compute_eigenvectors, str uplo) -> (Tensor, Tensor) +- func: linalg_eig(Tensor self) -> (Tensor eigenvalues, Tensor eigenvectors) + python_module: linalg variants: function dispatch: - CPU: _syevd_helper_cpu - CUDA: _syevd_helper_cuda + CPU, CUDA: linalg_eig + +- func: linalg_eig.out(Tensor self, *, Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) + python_module: linalg + dispatch: + CPU, CUDA: linalg_eig_out + +- func: linalg_eigvals(Tensor self) -> Tensor + python_module: linalg + +- func: linalg_eigvals.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg - func: linalg_eigh(Tensor self, str UPLO="L") -> (Tensor eigenvalues, Tensor eigenvectors) python_module: linalg variants: function dispatch: - DefaultBackend: linalg_eigh + CPU, CUDA: linalg_eigh - func: linalg_eigh.eigvals(Tensor self, str UPLO="L", *, Tensor(a!) eigvals, Tensor(b!) eigvecs) -> (Tensor(a!) eigenvalues, Tensor(b!) eigenvectors) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg dispatch: - DefaultBackend: linalg_eigh_out + CPU, CUDA: linalg_eigh_out - func: linalg_eigvalsh(Tensor self, str UPLO="L") -> Tensor python_module: linalg variants: function - dispatch: - DefaultBackend: linalg_eigvalsh - func: linalg_eigvalsh.out(Tensor self, str UPLO='L', *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg dispatch: - DefaultBackend: linalg_eigvalsh_out + CPU, CUDA: linalg_eigvalsh_out + +- func: linalg_householder_product(Tensor input, Tensor tau) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_householder_product + +- func: linalg_householder_product.out(Tensor input, Tensor tau, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA: linalg_householder_product_out - func: _linalg_inv_out_helper_(Tensor(a!) self, Tensor(b!) infos_lu, Tensor(c!) infos_getri) -> Tensor(a!) variants: function @@ -9008,41 +10902,41 @@ CPU: _linalg_inv_out_helper_cpu CUDA: _linalg_inv_out_helper_cuda +- func: linalg_inv_ex(Tensor self, *, bool check_errors=False) -> (Tensor inverse, Tensor info) + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg_inv_ex + +- func: linalg_inv_ex.inverse(Tensor self, *, bool check_errors=False, Tensor(a!) inverse, Tensor(b!) info) -> (Tensor(a!) inverse, Tensor(b!) info) + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg_inv_ex_out + - func: linalg_inv(Tensor self) -> Tensor python_module: linalg variants: function - dispatch: - DefaultBackend: linalg_inv - func: linalg_inv.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) python_module: linalg - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - dispatch: - DefaultBackend: linalg_inv_out - func: inner(Tensor self, Tensor other) -> Tensor variants: function, method - func: inner.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures -# torch.outer, alias for torch.ger - func: outer(Tensor self, Tensor vec2) -> Tensor variants: function, method - func: outer.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +# torch.ger, alias for torch.outer - func: ger(Tensor self, Tensor vec2) -> Tensor variants: function, method - dispatch: - DefaultBackend: ger - func: ger.out(Tensor self, Tensor vec2, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures - dispatch: - DefaultBackend: ger_out - func: linalg_norm(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor python_module: linalg @@ -9053,151 +10947,207 @@ variants: function - func: linalg_norm.out(Tensor self, Scalar? ord=None, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function - func: linalg_norm.ord_str_out(Tensor self, str ord, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function -- func: linalg_svd.U(Tensor self, bool full_matrices=True, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) V) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: linalg_vector_norm(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + variants: function + dispatch: + CPU, CUDA: linalg_vector_norm + +- func: linalg_vector_norm.out(Tensor self, Scalar ord=2, int[1]? dim=None, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + dispatch: + CPU, CUDA: linalg_vector_norm_out + +- func: linalg_matrix_norm(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor python_module: linalg -- func: linalg_svd(Tensor self, bool full_matrices=True, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor V) +- func: linalg_matrix_norm.out(Tensor self, Scalar ord, int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_matrix_norm.str_ord(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None) -> Tensor + python_module: linalg + +- func: linalg_matrix_norm.str_ord_out(Tensor self, str ord='fro', int[] dim=[-2,-1], bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +# This function is exposes the `compute_uv` flag, which is then used to implement `linalg.svd` and +# `linalg.svdvals` as composite functions that call this one +- func: _linalg_svd(Tensor A, bool full_matrices=False, bool compute_uv=True) -> (Tensor U, Tensor S, Tensor Vh) + variants: function + structured_delegate: _linalg_svd.U + +- func: _linalg_svd.U(Tensor A, bool full_matrices=False, bool compute_uv=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) + structured: True + dispatch: + CPU, CUDA: _linalg_svd_out + +- func: linalg_svd(Tensor A, bool full_matrices=True) -> (Tensor U, Tensor S, Tensor Vh) + python_module: linalg + variants: function + +- func: linalg_svd.U(Tensor A, bool full_matrices=True, *, Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) -> (Tensor(a!) U, Tensor(b!) S, Tensor(c!) Vh) + python_module: linalg + variants: function + +- func: linalg_svdvals(Tensor A) -> Tensor + python_module: linalg + variants: function + +- func: linalg_svdvals.out(Tensor A, *, Tensor(a!) out) -> Tensor(a!) python_module: linalg variants: function - func: linalg_cond(Tensor self, Scalar? p=None) -> Tensor python_module: linalg variants: function - dispatch: - Math: linalg_cond - func: linalg_cond.out(Tensor self, Scalar? p=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function - dispatch: - Math: linalg_cond_out - func: linalg_cond.p_str(Tensor self, str p) -> Tensor python_module: linalg variants: function - dispatch: - Math: linalg_cond - func: linalg_cond.p_str_out(Tensor self, str p, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function - dispatch: - Math: linalg_cond_out -- func: linalg_pinv(Tensor self, float rcond=1e-15, bool hermitian=False) -> Tensor +- func: linalg_pinv.atol_rtol_tensor(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor python_module: linalg variants: function dispatch: - Math: linalg_pinv + CompositeExplicitAutograd: linalg_pinv + +- func: linalg_pinv.atol_rtol_tensor_out(Tensor self, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + dispatch: + CompositeExplicitAutograd: linalg_pinv_out + +- func: linalg_pinv.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_pinv.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_pinv(Tensor self, float rcond, bool hermitian=False) -> Tensor + python_module: linalg + variants: function - func: linalg_pinv.rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False) -> Tensor python_module: linalg variants: function - dispatch: - Math: linalg_pinv -- func: linalg_pinv.out(Tensor self, float rcond=1e-15, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) +- func: linalg_pinv.out(Tensor self, float rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) python_module: linalg - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - dispatch: - Math: linalg_pinv_out - func: linalg_pinv.out_rcond_tensor(Tensor self, Tensor rcond, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) python_module: linalg - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures variants: function - dispatch: - Math: linalg_pinv_out - -- func: _linalg_solve_out_helper_(Tensor(a!) self, Tensor(b!) other, Tensor(c!) infos) -> Tensor(a!) - variants: function - dispatch: - CPU: _linalg_solve_out_helper_cpu - CUDA: _linalg_solve_out_helper_cuda - func: linalg_solve(Tensor input, Tensor other) -> Tensor python_module: linalg variants: function dispatch: - DefaultBackend: linalg_solve + CPU, CUDA: linalg_solve - func: linalg_solve.out(Tensor input, Tensor other, *, Tensor(a!) out) -> Tensor(a!) python_module: linalg - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures dispatch: - DefaultBackend: linalg_solve_out + CPU, CUDA: linalg_solve_out - func: linalg_tensorinv(Tensor self, int ind=2) -> Tensor - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function - dispatch: - Math: linalg_tensorinv - func: linalg_tensorinv.out(Tensor self, int ind=2, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function - dispatch: - Math: linalg_tensorinv_out - func: linalg_tensorsolve(Tensor self, Tensor other, int[]? dims=None) -> Tensor python_module: linalg variants: function - dispatch: - Math: linalg_tensorsolve - func: linalg_tensorsolve.out(Tensor self, Tensor other, int[]? dims=None, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function - dispatch: - Math: linalg_tensorsolve_out - func: linalg_qr(Tensor self, str mode='reduced') -> (Tensor Q, Tensor R) python_module: linalg variants: function dispatch: - DefaultBackend: linalg_qr + CompositeExplicitAutograd: linalg_qr - func: linalg_qr.out(Tensor self, str mode='reduced', *, Tensor(a!) Q, Tensor(b!) R) -> (Tensor(a!) Q, Tensor(b!) R) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures python_module: linalg variants: function dispatch: - DefaultBackend: linalg_qr_out + CompositeExplicitAutograd: linalg_qr_out - func: _linalg_qr_helper(Tensor self, str mode) -> (Tensor, Tensor) variants: function dispatch: - CPU: _linalg_qr_helper_cpu + CPU: _linalg_qr_helper_default CUDA: _linalg_qr_helper_cuda -- func: linalg_matrix_rank(Tensor self, float? tol=None, bool hermitian=False) -> Tensor +- func: linalg_matrix_power(Tensor self, int n) -> Tensor python_module: linalg - variants: function - dispatch: - Math: linalg_matrix_rank -- func: linalg_matrix_rank.out(Tensor self, float? tol=None, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) - use_c10_dispatcher: hacky_wrapper_for_legacy_signatures +- func: linalg_matrix_power.out(Tensor self, int n, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + +- func: linalg_matrix_rank.atol_rtol_tensor(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False) -> Tensor python_module: linalg variants: function - dispatch: - Math: linalg_matrix_rank_out + +- func: linalg_matrix_rank.atol_rtol_tensor_out(Tensor input, *, Tensor? atol=None, Tensor? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_matrix_rank.atol_rtol_float(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False) -> Tensor + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_matrix_rank.atol_rtol_float_out(Tensor self, *, float? atol=None, float? rtol=None, bool hermitian=False, Tensor(a!) out) -> Tensor(a!) + cpp_no_default_args: ['atol', 'rtol'] + python_module: linalg + variants: function + +- func: linalg_matrix_rank(Tensor self, float tol, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matrix_rank.out(Tensor self, float tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_matrix_rank.tol_tensor(Tensor input, Tensor tol, bool hermitian=False) -> Tensor + python_module: linalg + variants: function + +- func: linalg_matrix_rank.out_tol_tensor(Tensor input, Tensor tol, bool hermitian=False, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg + variants: function + +- func: linalg_multi_dot(Tensor[] tensors) -> Tensor + python_module: linalg + +- func: linalg_multi_dot.out(Tensor[] tensors, *, Tensor(a!) out) -> Tensor(a!) + python_module: linalg ## Functions that are only for testing # It is undocumented and should not be used outside of tests. @@ -9233,3 +11183,31 @@ - func: _test_ambiguous_defaults.b(Tensor dummy, int a=2, str b="2") -> Tensor cpp_no_default_args: ['a', 'b'] python_module: nn + +# Note: this function is only for testing. +- func: _test_warn_in_autograd(Tensor self) -> Tensor + python_module: nn + dispatch: + CompositeExplicitAutograd: _test_warn_in_autograd + +- func: segment_reduce(Tensor data, str reduce, *, Tensor? lengths=None, Tensor? indices=None, int axis=0, bool unsafe=False, Scalar? initial=None) -> Tensor + variants: function + dispatch: + CPU, CUDA: segment_reduce_kernel + +- func: _segment_reduce_backward(Tensor grad, Tensor output, Tensor data, str reduce, *, Tensor? lengths=None, int axis=0) -> Tensor + variants: function + dispatch: + CPU, CUDA: _segment_reduce_backward_kernel + +- func: pad_sequence(Tensor[] sequences, bool batch_first=False, float padding_value=0.0) -> Tensor + python_module: nn + variants: function + +- func: flatten_dense_tensors(Tensor[] tensors) -> Tensor + variants: function + python_module: nn + +- func: unflatten_dense_tensors(Tensor flat, Tensor[] tensors) -> Tensor[] + variants: function + python_module: nn diff --git a/scripts/codegen/templates/RegisterDispatchKey.cpp b/scripts/codegen/templates/RegisterDispatchKey.cpp index cb81dca771..7a5b48957c 100644 --- a/scripts/codegen/templates/RegisterDispatchKey.cpp +++ b/scripts/codegen/templates/RegisterDispatchKey.cpp @@ -33,7 +33,6 @@ #include #include #include -#include #include #include #include @@ -46,11 +45,10 @@ #include #include -#include +// #include #include #include "torch_npu/csrc/profiler/utils.h" -$legacy_th_headers $external_backend_headers $namespaced_headers diff --git a/scripts/codegen/templates/python_custom_functions.cpp b/scripts/codegen/templates/python_custom_functions.cpp index 54455aead3..645f398940 100644 --- a/scripts/codegen/templates/python_custom_functions.cpp +++ b/scripts/codegen/templates/python_custom_functions.cpp @@ -37,7 +37,7 @@ #include #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/utils/LazyInit.h" using at::Tensor; @@ -67,7 +67,6 @@ static PyObject* THPVariableFunctionsModule = NULL; ${py_forwards} -${py_device_forwards} // Wrapper converts a raised TypeError into returning NotImplemented // Used to implement binary arithmetic operators @@ -452,7 +451,6 @@ static PyMethodDef torch_functions[] = { {"randint", castPyCFunctionWithKeywords(THPVariable_randint), METH_VARARGS | METH_KEYWORDS | METH_STATIC, NULL}, {"range", castPyCFunctionWithKeywords(THPVariable_range), METH_VARARGS | METH_KEYWORDS | METH_STATIC, NULL}, ${py_method_defs} - ${py_device_method_defs} {NULL} }; @@ -520,6 +518,4 @@ void initTorchFunctions(PyObject* module) { ${py_methods} -${py_device_methods} - }} // namespace torch_npu::autograd diff --git a/scripts/codegen/utils.py b/scripts/codegen/utils.py index c85a05140d..5a3f162115 100644 --- a/scripts/codegen/utils.py +++ b/scripts/codegen/utils.py @@ -15,11 +15,21 @@ # limitations under the License. import re -from typing import Tuple, List, Iterable, Iterator, Callable, Sequence, TypeVar, Optional +import functools +import os +from typing import Tuple, List, Iterable, Iterator, Callable, Sequence, TypeVar, Optional, Dict, Any, Union, Set, NoReturn from enum import Enum import contextlib import textwrap +from codegen.code_template import CodeTemplate + +# Safely load fast C Yaml loader/dumper if they are available +try: + from yaml import CSafeLoader as Loader +except ImportError: + from yaml import SafeLoader as Loader # type: ignore[misc] + try: from yaml import CSafeDumper as Dumper except ImportError: @@ -92,3 +102,149 @@ def context(msg_fn: Callable[[], str]) -> Iterator[None]: msg = f'{e.args[0]}\n{msg}' if e.args else msg e.args = (msg,) + e.args[1:] raise + +# A little trick from https://github.com/python/mypy/issues/6366 +# for getting mypy to do exhaustiveness checking +# TODO: put this somewhere else, maybe +def assert_never(x: NoReturn) -> NoReturn: + raise AssertionError("Unhandled type: {}".format(type(x).__name__)) + +@functools.lru_cache(maxsize=None) +def _read_template(template_fn: str) -> CodeTemplate: + return CodeTemplate.from_file(template_fn) + +# Map over function that may return None; omit Nones from output sequence +def mapMaybe(func: Callable[[T], Optional[S]], xs: Iterable[T]) -> Iterator[S]: + for x in xs: + r = func(x) + if r is not None: + yield r + +# A custom loader for YAML that errors on duplicate keys. +# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165 +class YamlLoader(Loader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call] + assert key not in mapping, f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}" + mapping.append(key) + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + return mapping + +# 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] + + 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 + + def _write_if_changed(self, 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: + # Create output directory if it doesn't exist + os.makedirs(os.path.dirname(filename), exist_ok=True) + with open(filename, '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 + 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, variable_name: str, filename: str) -> None: + """Write a file containing the list of all outputs which are + generated by this script.""" + content = 'set({}\n {})'.format( + variable_name, '\n '.join('"' + name + '"' for name in sorted(self.filenames))) + self._write_if_changed(filename, content) diff --git a/scripts/generate_code.sh b/scripts/generate_code.sh index b761a3fb38..b339679f42 100644 --- a/scripts/generate_code.sh +++ b/scripts/generate_code.sh @@ -17,17 +17,14 @@ CDIR="$(cd "$(dirname "$0")" ; pwd -P)" NDIR="$CDIR/.." -TOCPU=$1 cd $NDIR/scripts cp -f codegen/native_functions.yaml codegen/native_functions.yaml_bk -sed -i '/ _foreach/a\ device_check: NoCheck' codegen/native_functions.yaml # Only for pytorch 1.8.1 python3 -m codegen.gen_backend_stubs \ - --to_cpu=${TOCPU} \ --output_dir="$NDIR/torch_npu/csrc/aten/" \ --source_yaml="$NDIR/torch_npu/csrc/aten/npu_native_functions.yaml" \ --impl_path="$NDIR/torch_npu/csrc/aten" # Used to double-check the yaml file definitions. @@ -41,7 +38,6 @@ fi python3 -m codegen.gen_python_functions \ --output_dir="$NDIR/torch_npu/csrc/aten/" \ --source_yaml="$NDIR/torch_npu/csrc/aten/npu_native_functions.yaml" \ - --native_yaml="$NDIR/scripts/codegen/native_functions.yaml" \ --template_path="$NDIR/scripts/codegen/templates" if [ $? -ne 0 ]; then diff --git a/setup.py b/setup.py index 56e125df1a..9d3ca8ba59 100644 --- a/setup.py +++ b/setup.py @@ -36,7 +36,7 @@ from setuptools.command.build_clib import build_clib from setuptools.command.egg_info import egg_info BASE_DIR = os.path.dirname(os.path.abspath(__file__)) -VERSION = '1.8.1rc2' +VERSION = '1.11.0rc3' def which(thefile): @@ -90,7 +90,6 @@ def _get_build_mode(): if not sys.argv[i].startswith('-'): return sys.argv[i] - raise RuntimeError("Run setup.py without build mode.") def get_pytorch_dir(): try: @@ -102,8 +101,8 @@ def get_pytorch_dir(): return os.path.dirname(frame_summary.filename) -def generate_bindings_code(base_dir, verbose): - generate_code_cmd = ["sh", os.path.join(base_dir, 'scripts', 'generate_code.sh'), verbose] +def generate_bindings_code(base_dir): + generate_code_cmd = ["sh", os.path.join(base_dir, 'scripts', 'generate_code.sh')] if subprocess.call(generate_code_cmd) != 0: print( 'Failed to generate ATEN bindings: {}'.format(generate_code_cmd), @@ -167,10 +166,6 @@ class Clean(distutils.command.clean.clean): # It's an old-style class in Python 2.7... distutils.command.clean.clean.run(self) - os.remove('torch_npu/csrc/aten/RegisterCPU.cpp') - os.remove('torch_npu/csrc/aten/RegisterNPU.cpp') - os.remove('torch_npu/csrc/aten/RegisterAutogradNPU.cpp') - class CPPLibBuild(build_clib, object): def run(self): cmake = get_cmake_command() @@ -235,13 +230,10 @@ def get_src_py_and_dst(): ret.append((src, dst)) header_files = [ - "torch_npu/csrc/*.h", - "torch_npu/csrc/*/*.h", - "torch_npu/csrc/*/*/*.h", - "torch_npu/csrc/*/*/*/*.h", - "torch_npu/csrc/*/*/*/*/*.h", - "third_party/acl/inc/*/*.h", - "third_party/acl/inc/*/*/*.h" + "torch_npu/csrc/core/npu/*.h", + "torch_npu/csrc/core/npu/*/*.h", + "torch_npu/csrc/aten/*.h", + "third_party/acl/inc/*/*.h" ] glob_header_files = [] for regex_pattern in header_files: @@ -290,11 +282,10 @@ class PythonPackageBuild(build_py, object): self.copy_file(src, dst) super(PythonPackageBuild, self).finalize_options() -to_cpu = os.getenv('NPU_TOCPU', default='TRUE') build_mode = _get_build_mode() if build_mode not in ['clean']: - # Generate bindings code, including RegisterNPU.cpp & NPUNativeFunctions.h. - generate_bindings_code(BASE_DIR, to_cpu) + # Generate bindings code, including RegisterNPU.cpp & XLANativeFunctions.h. + generate_bindings_code(BASE_DIR) build_stub(BASE_DIR) # Setup include directories folders. diff --git a/test/test_api/test_torch/test_serialization.py b/test/test_api/test_torch/test_serialization.py index 6b1e5ff673..7ab320911b 100644 --- a/test/test_api/test_torch/test_serialization.py +++ b/test/test_api/test_torch/test_serialization.py @@ -68,7 +68,7 @@ class TestSerialization(TestCase): with tempfile.TemporaryDirectory() as tmpdir: path = os.path.join(tmpdir, 'data.pt') torch.save(x, path) - self.assertExpectedInline(str(x.device), f'{torch_npu.npu.native_device}:0') + self.assertExpectedInline(str(x.device), '''npu:0''') x_loaded = torch.load(path, map_location="npu:0") x_loaded = x_loaded.npu() self.assertRtolEqual(x.cpu(), x_loaded.cpu()) diff --git a/test/test_api/test_torch/test_tensors.py b/test/test_api/test_torch/test_tensors.py index 585d8c7fcc..b13cfdb490 100644 --- a/test/test_api/test_torch/test_tensors.py +++ b/test/test_api/test_torch/test_tensors.py @@ -151,31 +151,10 @@ class TestCreationOps(TestCase): self.assertRtolEqual(cpu_output3.numpy(), npu_output3.cpu().numpy()) def test_as_tensor(self): - # numpy ndarray to cpu/npu tensor a = np.array([1, 2, 3]) cpu_output = torch.as_tensor(a, device=torch.device('cpu')) - npu_output1 = torch.as_tensor(a, device="npu:0") - npu_output2 = torch.as_tensor(a, device="npu") - npu_output3 = torch.as_tensor(a, device=torch.device("npu")) - self.assertRtolEqual(cpu_output.numpy(), npu_output1.cpu().numpy()) - self.assertRtolEqual(cpu_output.numpy(), npu_output2.cpu().numpy()) - self.assertRtolEqual(cpu_output.numpy(), npu_output3.cpu().numpy()) - - # cpu tesor to npu tensor - a = np.array([1, 2, 3]) - cpu_input = torch.as_tensor(a, device=torch.device('cpu')) - npu_output1 = torch.as_tensor(cpu_input, device="npu:0") - npu_output2 = torch.as_tensor(cpu_input, device="npu") - npu_output3 = torch.as_tensor(cpu_input, device=torch.device("npu")) - self.assertRtolEqual(cpu_input.numpy(), npu_output1.cpu().numpy()) - self.assertRtolEqual(cpu_input.numpy(), npu_output2.cpu().numpy()) - self.assertRtolEqual(cpu_input.numpy(), npu_output3.cpu().numpy()) - - # npu tesor to cpu tensor - a = np.array([1, 2, 3]) - npu_input = torch.as_tensor(a, device=torch.device('npu')) - cpu_output = torch.as_tensor(npu_input, device="cpu") - self.assertRtolEqual(cpu_output.numpy(), npu_input.cpu().numpy()) + npu_output = torch.as_tensor(a, device=device) + self.assertRtolEqual(cpu_output.numpy(), npu_output.cpu().numpy()) def test_as_strided(self): x = torch.randn(3, 3, device='npu:0') diff --git a/test/test_api/test_torch_npu.py b/test/test_api/test_torch_npu.py index 37be17c939..8c0559011d 100644 --- a/test/test_api/test_torch_npu.py +++ b/test/test_api/test_torch_npu.py @@ -166,15 +166,6 @@ class TorchNPUApiTestCase(TestCase): res = torch_npu.npu.reset_max_memory_cached() self.assertIsNone(res) - def test_npu_get_device_name(self): - res = torch_npu.npu.get_device_name(0) - self.assertIsInstance(res, str) - - def test_npu_get_device_properties(self): - name = torch_npu.npu.get_device_properties(0).name - self.assertIsInstance(name, str) - total_memory = torch_npu.npu.get_device_properties(0).total_memory - self.assertIsInstance(total_memory, int) if __name__ == "__main__": run_tests() diff --git a/test/test_distributed/run_test.py b/test/test_distributed/run_test.py index 2323f4d1f8..8032a89b6e 100644 --- a/test/test_distributed/run_test.py +++ b/test/test_distributed/run_test.py @@ -1,25 +1,25 @@ #!/usr/bin/env python +from __future__ import print_function import argparse from datetime import datetime +import modulefinder import os import shutil import signal +import subprocess import sys import tempfile import time import unittest import torch -import torch._six -import torch.distributed as dist - -from torch.testing._internal.common_utils import TEST_WITH_ROCM, shell - import torch_npu - - +import torch._six +from torch.utils import cpp_extension +from torch.testing._internal.common_utils import TEST_WITH_ROCM, shell +import torch.distributed as dist PY2 = sys.version_info <= (3,) PY33 = sys.version_info >= (3, 3) PY36 = sys.version_info >= (3, 6) diff --git a/test/test_distributed/test_all_to_all_single.py b/test/test_distributed/test_all_to_all_single.py deleted file mode 100644 index ecd60afd44..0000000000 --- a/test/test_distributed/test_all_to_all_single.py +++ /dev/null @@ -1,217 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 data 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 os -import torch -import torch.distributed as dist -import torch.multiprocessing as mp -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests - -class HcclAlltoAllSingleTest(TestCase): - world_size_2p = 2 - world_size_4p = 4 - data = torch.randn(10, 20) - - @classmethod - def _init_dist_hccl(cls, rank, world_size): - os.environ['MASTER_ADDR'] = '127.0.0.1' - os.environ['MASTER_PORT'] = '29500' - os.environ['HCCL_WHITELIST_DISABLE'] = '1' - os.environ['HCCL_ALGO'] = "level0:fullmesh;level1:fullmesh" - torch_npu.npu.set_device(rank) - dist.init_process_group(backend='hccl', world_size=world_size, rank=rank) - return dist - - @classmethod - def _test_alltoall_single_2p( - cls, rank, data, world_size, init_pg, c2p, p2c): - pg = init_pg(rank, world_size) - input1 = torch.arange(2) + rank * 2 - input1 = input1.float().npu() - input1 = input1.npu_format_cast(29) - output = torch.empty(2).float().npu() - output = output.npu_format_cast(29) - cout = 0 - pg.all_to_all_single(output, input1) - c2p.put((rank, output.cpu(), cout)) - - @classmethod - def _test_alltoall_single_2p_size( - cls, rank, data, world_size, init_pg, c2p, p2c): - pg = init_pg(rank, world_size) - input1 = data.float().npu() - input1 = input1.npu_format_cast(29) - output = torch.empty(200).float().npu() - output = output.npu_format_cast(29) - inputsize1 = [100, 100] - inputsize2 = [100, 100] - outsize1 = [100, 100] - outsize2 = [100, 100] - inputsize = [inputsize1, inputsize2] - outsize = [outsize1, outsize2] - cout = 1 - pg.all_to_all_single(output, input1, outsize[rank], inputsize[rank]) - if torch.get_npu_format(output.npu()) != 29: - raise RuntimeError("format error!") - c2p.put((rank, output.cpu(), cout)) - - def _test_multiprocess_2p(self, f, init_pg): - ws = self.world_size_2p - data = self.data - # file store will delete the test file on destruction - ctx = mp.get_context('spawn') - c2p = ctx.Queue(2) - p2c = ctx.Queue(2) - expected = [] - ps = [] - for i in range(ws): - p = ctx.Process( - target=f, - args=(i, data, ws, init_pg, c2p, p2c)) - p.start() - ps.append(p) - - for _ in range(ws): - rank, output, cout = c2p.get() - res = data.cpu().float() - exp = [] - if rank == 0: - exp = res[0] - for i in range(1, 5): - exp = torch.cat((exp, res[i]), dim=0) - else: - exp = res[5] - for i in range(6, 10): - exp = torch.cat((exp, res[i]), dim=0) - exp_2p = torch.arange(2) * 2 + rank - exp_format = torch.cat((exp, exp), dim=0) - expected = exp_2p if cout == 0 else exp_format - self.assertEqual( - output, - expected, - ( - "rank {} Expect receive tensor {} but got {}." - ).format(rank, expected, output) - ) - - for _ in range(ws): - p2c.put(0) - - for p in ps: - p.join(2) - - def test_alltoall_single_2p_dist(self): - self._test_multiprocess_2p( - HcclAlltoAllSingleTest._test_alltoall_single_2p, - HcclAlltoAllSingleTest._init_dist_hccl) - - def test_alltoall_single_2p_size_dist(self): - self._test_multiprocess_2p( - HcclAlltoAllSingleTest._test_alltoall_single_2p_size, - HcclAlltoAllSingleTest._init_dist_hccl) - - @classmethod - def _test_alltoall_single_4p( - cls, rank, world_size, init_pg, c2p, p2c): - pg = init_pg(rank, world_size) - input1 = torch.arange(4) + rank * 4 - input1 = input1.float().npu() - output = torch.empty(4).float().npu() - cout = 0 - pg.all_to_all_single(output, input1) - c2p.put((rank, output.cpu(), cout)) - - @classmethod - def _test_alltoall_single_4p_size( - cls, rank, world_size, init_pg, c2p, p2c): - pg = init_pg(rank, world_size) - input1 = torch.arange(7) + rank * 4 - input1 = input1.float().npu() - x = 7 - if rank == 1: - x = 9 - elif rank == 3: - x = 5 - output = torch.empty(x).float().npu() - inputsize1 = [1, 2, 2, 2] - inputsize2 = [1, 3, 2, 1] - inputsize3 = [2, 3, 1, 1] - inputsize4 = [3, 1, 2, 1] - outsize1 = [1, 1, 2, 3] - outsize2 = [2, 3, 3, 1] - outsize3 = [2, 2, 1, 2] - outsize4 = [2, 1, 1, 1] - inputsize = [inputsize1, inputsize2, inputsize3, inputsize4] - outsize = [outsize1, outsize2, outsize3, outsize4] - cout = 1 - pg.all_to_all_single(output, input1, outsize[rank], inputsize[rank]) - c2p.put((rank, output.cpu(), cout)) - - def _test_multiprocess_4p(self, f, init_pg): - ws = self.world_size_4p - # file store will delete the test file on destruction - ctx = mp.get_context('spawn') - c2p = ctx.Queue(4) - p2c = ctx.Queue(4) - ps = [] - expected = [] - for i in range(ws): - p = ctx.Process( - target=f, - args=(i, ws, init_pg, c2p, p2c)) - p.start() - ps.append(p) - - for _ in range(ws): - rank, output, cout = c2p.get() - if cout == 0: - expected = torch.arange(4) * 4 + rank - else: - if rank == 0: - expected = [0, 4, 8, 9, 12, 13, 14] - elif rank == 1: - expected = [1, 2, 5, 6, 7, 10, 11, 12, 15] - elif rank == 2: - expected = [3, 4, 8, 9, 13, 16, 17] - elif rank == 3: - expected = [5, 6, 10, 14, 18] - - self.assertEqual( - output, - expected, - ( - "rank {} Expect receive tensor {} but got {}." - ).format(rank, expected, output) - ) - - for _ in range(ws): - p2c.put(0) - - for p in ps: - p.join(4) - - def test_alltoall_single_4p_dist(self): - self._test_multiprocess_4p( - HcclAlltoAllSingleTest._test_alltoall_single_4p, - HcclAlltoAllSingleTest._init_dist_hccl) - - def test_alltoall_single_4p_size_dist(self): - self._test_multiprocess_4p( - HcclAlltoAllSingleTest._test_alltoall_single_4p_size, - HcclAlltoAllSingleTest._init_dist_hccl) - -if __name__ == '__main__': - run_tests() diff --git a/test/test_distributed/test_distributed.py b/test/test_distributed/test_distributed.py index 6af629a88d..2de8c5214f 100644 --- a/test/test_distributed/test_distributed.py +++ b/test/test_distributed/test_distributed.py @@ -16,6 +16,7 @@ from collections import namedtuple from multiprocessing import Manager import torch +import torch_npu import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F @@ -23,9 +24,6 @@ from torch.testing._internal.common_utils import TestCase, run_tests from torch._utils_internal import TEST_MASTER_ADDR as MASTER_ADDR from torch._utils_internal import TEST_MASTER_PORT as MASTER_PORT -import torch_npu - - try: import torchvision HAS_TORCHVISION = True diff --git a/test/test_graph_mode/test_add.py b/test/test_graph_mode/test_add.py new file mode 100644 index 0000000000..29ad0eb3ae --- /dev/null +++ b/test/test_graph_mode/test_add.py @@ -0,0 +1,111 @@ +# 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 torch +import numpy as np +import torch_npu + +from torch_npu.testing.testcase import TestCase, run_tests +from torch_npu.testing.decorator import instantiate_tests, graph_mode +from torch_npu.testing.common_utils import create_common_tensor + +@instantiate_tests +class TestAdd(TestCase): + + def cpu_op_exec(self, input1, input2): + output = input1 + input2 + output = output.numpy() + return output + + def npu_op_exec(self, input1, input2): + output = input1 + input2 + output = output.to("cpu") + output = output.numpy() + return output + + @graph_mode + def test_add_common_shape_format(self): + shape_format = [ + [[np.float32, -1, (4, 3)], [np.float32, -1, (4, 3)]], + [[np.float32, -1, (4, 3, 1)], [np.float32, -1, (4, 1, 5)]], + [[np.int32, -1, (2, 3)], [np.int32, -1, (2, 3)]], + [[np.int32, -1, (4, 3, 1)], [np.int32, -1, (4, 1, 5)]] + ] + for item in shape_format: + cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100) + cpu_input2, npu_input2 = create_common_tensor(item[1], 1, 100) + cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) + npu_output = self.npu_op_exec(npu_input1, npu_input2) + self.assertRtolEqual(cpu_output, npu_output) + + @graph_mode + def test_add_float16_shape_format(self): + def cpu_op_exec_fp16(input1, input2): + input1 = input1.to(torch.float32) + input2 = input2.to(torch.float32) + output = input1 + input2 + output = output.numpy() + output = output.astype(np.float16) + return output + + shape_format = [ + [[np.float16, -1, (4, 3)], [np.float16, -1, (4, 3)]], + [[np.float16, -1, (4, 3, 1)], [np.float16, -1, (4, 1, 5)]], + ] + + for item in shape_format: + cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100) + cpu_input2, npu_input2 = create_common_tensor(item[1], 1, 100) + cpu_output = cpu_op_exec_fp16(cpu_input1, cpu_input2) + npu_output = self.npu_op_exec(npu_input1, npu_input2) + self.assertRtolEqual(cpu_output, npu_output) + + @graph_mode + def test_add_float32_out(self): + def npu_op_exec_out(input1, input2, input3): + input1 = input1.to("npu") + input2 = input2.to("npu") + output = input3.to("npu") + torch.add(input1, input2, out=output) + output = output.to("cpu") + output = output.numpy() + return output + + shape_format = [ + [[np.float16, -1, (4, 3)], [np.float16, -1, (4, 3)], [np.float16, -1, (4, 3)]], + [[np.float16, -1, (4, 3, 1)], [np.float16, -1, (4, 1, 5)], [np.float16, -1, (4, 1, 5)]], + ] + + for item in shape_format: + cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100) + cpu_input2, npu_input2 = create_common_tensor(item[1], 1, 100) + cpu_input3, npu_input3 = create_common_tensor(item[2], 1, 100) + cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) + npu_output = npu_op_exec_out(npu_input1, npu_input2, npu_input3) + self.assertRtolEqual(cpu_output, npu_output) + + ''' + currently do not support scalar dtype + @graph_mode + def test_add_scalar_float32(self): + npu_input1, npu_input2 = self.generate_data(0, 100, (2,3), np.float32) + cpu_output = self.cpu_op_exec(npu_input1, 1) + npu_output = self.npu_op_exec_scalar(npu_input1, 1) + self.assertRtolEqual(cpu_output, npu_output) + ''' + +if __name__ == "__main__": + run_tests() diff --git a/test/test_network_ops/test_as_strided.py b/test/test_graph_mode/test_div.py similarity index 54% rename from test/test_network_ops/test_as_strided.py rename to test/test_graph_mode/test_div.py index 5a238ad6ed..a65e549ee6 100644 --- a/test/test_network_ops/test_as_strided.py +++ b/test/test_graph_mode/test_div.py @@ -14,39 +14,43 @@ # See the License for the specific language governing permissions and # limitations under the License. -import sys import torch -import torch_npu import numpy as np +import torch_npu + from torch_npu.testing.testcase import TestCase, run_tests +from torch_npu.testing.decorator import instantiate_tests, graph_mode from torch_npu.testing.common_utils import create_common_tensor -class TestAsStrided(TestCase): - def cpu_op_exec(self, input1, size, stride, storage_offset): - output = torch.as_strided(input1, size, stride, storage_offset) - output = output.numpy() +@instantiate_tests +class TestDiv(TestCase): + + def cpu_op_exec(self, input1, input2): + output = torch.div(input1, input2) return output - def npu_op_exec(self,input1, size, stride, storage_offset): - output = torch.as_strided(input1, size, stride, storage_offset) - output = output.cpu().numpy() + def npu_op_exec(self, input1, input2): + output = torch.div(input1, input2) + output = output.to("cpu") return output - def test_as_strided(self, device='npu'): + @graph_mode + def test_div_shape_format(self): shape_format = [ - [[np.float32, 0, [3, 3]], (2, 2), (1, 2), 0], - [[np.float16, 0, [13, 23]], (10, 15), (1, 2), 1], - [[np.int32, 0, [5, 5]], (3, 3), (1, 2), 1], - [[np.float32, 2, [32, 8, 2]], (8, 6, 2), (5, 4, 1), 1], + [[np.float32, 0, 1], [np.float32, 0, 1]], + [[np.float32, 0, (64, 10)], [np.float32, 0, 1]], + [[np.float32, 3, (256, 2048, 7, 7)], [np.float32, 0, 1]], + [[np.float32, 4, (32, 1, 3, 3)], [np.float32, 4, (32, 1, 3, 3)]], + [[np.float32, 29, (10, 128)], [np.float32, 29, (10, 128)]] ] for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = self.cpu_op_exec(cpu_input1, item[1], item[2], item[3]) - npu_output = self.npu_op_exec(npu_input1, item[1], item[2], item[3]) + cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100) + cpu_input2, npu_input2 = create_common_tensor(item[1], 1, 100) + cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) + npu_output = self.npu_op_exec(npu_input1, npu_input2) self.assertRtolEqual(cpu_output, npu_output) - - + if __name__ == "__main__": run_tests() diff --git a/test/test_graph_mode/test_exp.py b/test/test_graph_mode/test_exp.py new file mode 100644 index 0000000000..676e7f33bf --- /dev/null +++ b/test/test_graph_mode/test_exp.py @@ -0,0 +1,62 @@ +# 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 torch +import numpy as np +import torch_npu + +from torch_npu.testing.testcase import TestCase, run_tests +from torch_npu.testing.decorator import instantiate_tests, graph_mode +from torch_npu.testing.common_utils import create_common_tensor + + +@instantiate_tests +class TestExp(TestCase): + + def cpu_op_exec(self, input_data): + dt = input_data.dtype + input_data = input_data.to(torch.float32) + output = torch.exp(input_data) + output = output.to(dt) + output = output.numpy() + return output + + def npu_op_exec(self, input_data): + output = torch.exp(input_data) + output = output.to("cpu") + output = output.numpy() + return output + + @graph_mode + def test_exp_common_shape_format(self): + shape_format = [ + [np.float32, -1, (1, )], + [np.float32, -1, (4, 3)], + [np.float32, -1, (20, 13)], + [np.float16, -1, (1, )], + [np.float16, -1, (64, 10)], + [np.float16, -1, (31, 1, 3)] + ] + + for item in shape_format: + cpu_input, npu_input = create_common_tensor(item, 1, 10) + cpu_output = self.cpu_op_exec(cpu_input) + npu_output = self.npu_op_exec(npu_input) + self.assertRtolEqual(cpu_output, npu_output) + + +if __name__ == "__main__": + run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_mean.py b/test/test_graph_mode/test_mean.py similarity index 95% rename from test/test_network_ops/test_mean.py rename to test/test_graph_mode/test_mean.py index cc678401b9..31117ef77f 100644 --- a/test/test_network_ops/test_mean.py +++ b/test/test_graph_mode/test_mean.py @@ -19,10 +19,11 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode +from torch_npu.testing.decorator import instantiate_tests, graph_mode from torch_npu.testing.common_utils import create_common_tensor +@instantiate_tests class TestMean(TestCase): def cpu_op_exec(self,input1, dtype): diff --git a/test/test_network_ops/test_pow.py b/test/test_graph_mode/test_pow.py similarity index 91% rename from test/test_network_ops/test_pow.py rename to test/test_graph_mode/test_pow.py index cc51517959..42df4fd320 100644 --- a/test/test_network_ops/test_pow.py +++ b/test/test_graph_mode/test_pow.py @@ -19,10 +19,11 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode +from torch_npu.testing.decorator import instantiate_tests, graph_mode from torch_npu.testing.common_utils import create_common_tensor +@instantiate_tests class TestPow(TestCase): def cpu_op_exec(self, input1, input2): output = torch.pow(input1, input2) @@ -122,74 +123,74 @@ class TestPow(TestCase): # scalar_tensor------------------------------------------------------- @graph_mode - def test_pow_shape_format_scalar_tensor_fp16_1d(self, device): + def test_pow_shape_format_scalar_tensor_fp16_1d(self): format_list = [-1, 0, 3] shape_format = [[np.float16, i, [18]] for i in format_list] self.pow_result_scalar_tensor(shape_format) @graph_mode - def test_pow_shape_format_scalar_tensor_fp32_1d(self, device): + def test_pow_shape_format_scalar_tensor_fp32_1d(self): format_list = [-1, 0, 3] shape_format = [[np.float32, i, [18]] for i in format_list] self.pow_result_scalar_tensor(shape_format) @graph_mode - def test_pow_shape_format_scalar_tensor_fp16_2d(self, device): + def test_pow_shape_format_scalar_tensor_fp16_2d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float16, i, [18, 64]] for i in format_list] self.pow_result_scalar_tensor(shape_format) @graph_mode - def test_pow_shape_format_scalar_tensor_fp32_2d(self, device): + def test_pow_shape_format_scalar_tensor_fp32_2d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float32, i, [18, 64]] for i in format_list] self.pow_result_scalar_tensor(shape_format) @graph_mode - def test_pow_shape_format_scalar_tensor_fp16_3d(self, device): + def test_pow_shape_format_scalar_tensor_fp16_3d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float16, i, [18, 64, 128]] for i in format_list] self.pow_result_scalar_tensor(shape_format) @graph_mode - def test_pow_shape_format_scalar_tensor_fp32_3d(self, device): + def test_pow_shape_format_scalar_tensor_fp32_3d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float32, i, [18, 64, 128]] for i in format_list] self.pow_result_scalar_tensor(shape_format) # tensor_scalar----------------------------------------------------------- @graph_mode - def test_pow_shape_format_tensor_scala_fp16_1d(self, device): + def test_pow_shape_format_tensor_scala_fp16_1d(self): format_list = [-1, 0, 3] shape_format = [[np.float16, i, [18]] for i in format_list] self.pow_result_tensor_scalar_(shape_format) @graph_mode - def test_pow_shape_format_tensor_scalar_fp32_1d(self, device): + def test_pow_shape_format_tensor_scalar_fp32_1d(self): format_list = [-1, 0, 3] shape_format = [[np.float32, i, [18]] for i in format_list] self.pow_result_tensor_scalar_(shape_format) @graph_mode - def test_pow_shape_format_tensor_scala_fp16_2d(self, device): + def test_pow_shape_format_tensor_scala_fp16_2d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float16, i, [18, 64]] for i in format_list] self.pow_result_tensor_scalar_(shape_format) @graph_mode - def test_pow_shape_format_tensor_scalar_fp32_2d(self, device): + def test_pow_shape_format_tensor_scalar_fp32_2d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float32, i, [18, 64]] for i in format_list] self.pow_result_tensor_scalar_(shape_format) @graph_mode - def test_pow_shape_format_tensor_scala_fp16_3d(self, device): + def test_pow_shape_format_tensor_scala_fp16_3d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float16, i, [18, 64, 128]] for i in format_list] self.pow_result_tensor_scalar_(shape_format) @graph_mode - def test_pow_shape_format_tensor_scalar_fp32_3d(self, device): + def test_pow_shape_format_tensor_scalar_fp32_3d(self): format_list = [-1, 0, 3, 29] shape_format = [[np.float32, i, [18, 64, 128]] for i in format_list] self.pow_result_tensor_scalar_(shape_format) diff --git a/test/test_network_ops/test_sqrt.py b/test/test_graph_mode/test_sqrt.py similarity index 98% rename from test/test_network_ops/test_sqrt.py rename to test/test_graph_mode/test_sqrt.py index 0d75786994..c98dcf6029 100644 --- a/test/test_network_ops/test_sqrt.py +++ b/test/test_graph_mode/test_sqrt.py @@ -19,9 +19,10 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode +from torch_npu.testing.decorator import instantiate_tests, graph_mode from torch_npu.testing.common_utils import create_common_tensor +@instantiate_tests class TestSqrt(TestCase): def cpu_op_exec(self, input1): diff --git a/test/test_network_ops/test_sub.py b/test/test_graph_mode/test_sub.py similarity index 97% rename from test/test_network_ops/test_sub.py rename to test/test_graph_mode/test_sub.py index 7f70584709..d15872cab4 100644 --- a/test/test_network_ops/test_sub.py +++ b/test/test_graph_mode/test_sub.py @@ -19,9 +19,11 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode +from torch_npu.testing.decorator import instantiate_tests, graph_mode from torch_npu.testing.common_utils import create_common_tensor + +@instantiate_tests class TestSub(TestCase): def cpu_op_exec(self, input1, input2): diff --git a/test/test_hooks/test_acc_cmp_module_hook.py b/test/test_hooks/test_acc_cmp_module_hook.py deleted file mode 100644 index 139e9bf19a..0000000000 --- a/test/test_hooks/test_acc_cmp_module_hook.py +++ /dev/null @@ -1,69 +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. - - -import os -import torch -import torch.nn as nn - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook -from torch_npu.hooks.tools import compare - - -class TestModuleOP(nn.Module): - - def __init__(self) -> None: - super().__init__() - self.linear_1 = nn.Linear(in_features=2, out_features=2) - self.linear_2 = nn.Linear(in_features=2, out_features=1) - self.relu = nn.ReLU() - - def forward(self, x): - x1 = self.linear_1(x) - x2 = self.linear_2(x1) - r1 = self.relu(x2) - return r1 - - -class TestModuleAccCmpHook(TestCase): - - def test_module_op(self): - module = TestModuleOP() - register_acc_cmp_hook(module) - seed_all() - set_dump_path("./cpu_module_tensor_op.pkl") - x = torch.randn(2, 2) - out = module(x) - loss = out.sum() - loss.backward() - set_dump_path("./npu_module_tensor_op.pkl") - module.npu() - x = x.npu() - out = module(x) - loss = out.sum() - loss.backward() - assert os.path.exists("./cpu_module_tensor_op.pkl") and os.path.exists("./npu_module_tensor_op.pkl") - compare("./npu_module_tensor_op.pkl", "./cpu_module_tensor_op.pkl", "./module_tensor_op_result.csv") - assert os.path.exists("./module_tensor_op_result.csv") - - def tearDown(self) -> None: - for filename in os.listdir('./'): - if filename.endswith(".pkl") or filename.endswith(".csv"): - os.remove("./" + filename) - - -if __name__ == '__main__': - run_tests() diff --git a/test/test_hooks/test_acc_cmp_tensor_hook.py b/test/test_hooks/test_acc_cmp_tensor_hook.py deleted file mode 100644 index 59d87f53e0..0000000000 --- a/test/test_hooks/test_acc_cmp_tensor_hook.py +++ /dev/null @@ -1,100 +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. - - -import os -import torch -import torch.nn as nn - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook -from torch_npu.hooks.tools import compare - - -class TestTensorBuiltinOP(nn.Module): - - def forward(self, x, y): - z_add = x + y - z_sub = x - y - z = z_add * z_sub - return z - - -class TestTensorMethodOP(nn.Module): - - def forward(self, x, y): - z_add = x.add(y) - z_abs = z_add.abs() - z = z_abs.softmax(dim=0) - return z - - -class TestTensorAccCmpHook(TestCase): - - def test_tensor_bulitin_op(self): - module = TestTensorBuiltinOP() - register_acc_cmp_hook(module) - seed_all() - set_dump_path("./cpu_tensor_builtin_op.pkl") - x = torch.randn(2, 3, 4) - y = torch.randn(2, 3, 4) - x.requires_grad = True - y.requires_grad = True - out = module(x, y) - loss = out.sum() - loss.backward() - set_dump_path("./npu_tensor_builtin_op.pkl") - module.npu() - x = x.npu() - y = y.npu() - out = module(x, y) - loss = out.sum() - loss.backward() - assert os.path.exists("./cpu_tensor_builtin_op.pkl") and os.path.exists("./npu_tensor_builtin_op.pkl") - compare("./npu_tensor_builtin_op.pkl", "./cpu_tensor_builtin_op.pkl", "./tensor_builtin_op_result.csv") - assert os.path.exists("./tensor_builtin_op_result.csv") - - def test_tensor_method_op(self): - module = TestTensorMethodOP() - register_acc_cmp_hook(module) - seed_all() - set_dump_path("./cpu_tensor_method_op.pkl") - x = torch.randn(2, 3, 4) - y = torch.randn(2, 3, 4) - x.requires_grad = True - y.requires_grad = True - out = module(x, y) - loss = out.sum() - loss.backward() - set_dump_path("./npu_tensor_method_op.pkl") - module.npu() - x = x.npu() - y = y.npu() - out = module(x, y) - loss = out.sum() - loss.backward() - assert os.path.exists("./cpu_tensor_method_op.pkl") and os.path.exists("./npu_tensor_method_op.pkl") - compare("./npu_tensor_method_op.pkl", "./cpu_tensor_method_op.pkl", "./tensor_method_op_result.csv") - assert os.path.exists("./tensor_method_op_result.csv") - - def tearDown(self) -> None: - for filename in os.listdir('./'): - if filename.endswith(".pkl") or filename.endswith(".csv"): - os.remove("./" + filename) - - -if __name__ == '__main__': - run_tests() - diff --git a/test/test_hooks/test_acc_cmp_torch_hook.py b/test/test_hooks/test_acc_cmp_torch_hook.py deleted file mode 100644 index eab39c3a85..0000000000 --- a/test/test_hooks/test_acc_cmp_torch_hook.py +++ /dev/null @@ -1,101 +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. - - -import os -import torch - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.hooks import set_dump_path, seed_all, register_acc_cmp_hook -from torch_npu.hooks.tools import compare - - -class TestTorchOP(torch.nn.Module): - - def forward(self, x, y): - z_add = torch.add(x, y) - z_sub = torch.sub(x, y) - z_relu = torch.relu(z_add) - z = torch.add(z_sub, z_relu) - return z - - -class TestModuleOP(torch.nn.Module): - - def __init__(self) -> None: - super().__init__() - self.conv = torch.nn.Conv2d(3, 4, 1) - self.relu = torch.nn.ReLU() - self.bn = torch.nn.BatchNorm2d(4) - - def forward(self, x): - x1 = self.conv(x) - x2 = self.relu(x1) - r1 = self.bn(x2) - return r1 - - -class TestTorchAccCmpHook(TestCase): - - def test_tensor_op(self): - module = TestTorchOP() - register_acc_cmp_hook(module) - seed_all() - set_dump_path("./cpu_torch_op.pkl") - x = torch.randn(2, 3, 4) - y = torch.randn(2, 3, 4) - x.requires_grad = True - y.requires_grad = True - out = module(x, y) - loss = torch.sum(out) - loss.backward() - set_dump_path("./npu_torch_op.pkl") - module.npu() - x = x.npu() - y = y.npu() - out = module(x, y) - loss = out.sum() - loss.backward() - assert os.path.exists("./cpu_torch_op.pkl") and os.path.exists("./npu_torch_op.pkl") - compare("./npu_torch_op.pkl", "./cpu_torch_op.pkl", "./torch_op_result.csv") - assert os.path.exists("./torch_op_result.csv") - - def test_module_op(self): - module = TestModuleOP() - register_acc_cmp_hook(module) - seed_all() - set_dump_path("./cpu_module_torch_op.pkl") - x = torch.randn(2, 3, 12, 12) - out = module(x) - loss = torch.sum(out) - loss.backward() - set_dump_path("./npu_module_torch_op.pkl") - module.npu() - x = x.npu() - out = module(x) - loss = out.sum() - loss.backward() - assert os.path.exists("./cpu_module_torch_op.pkl") and os.path.exists("./npu_module_torch_op.pkl") - compare("./npu_module_torch_op.pkl", "./cpu_module_torch_op.pkl", "./module_torch_op_result.csv") - assert os.path.exists("./module_torch_op_result.csv") - - def tearDown(self) -> None: - for filename in os.listdir('./'): - if filename.endswith(".pkl"): - os.remove("./" + filename) - - -if __name__ == '__main__': - run_tests() diff --git a/test/test_network_ops/test___and__.py b/test/test_network_ops/test___and__.py index 4faf308244..f65ebd2cd0 100644 --- a/test/test_network_ops/test___and__.py +++ b/test/test_network_ops/test___and__.py @@ -22,7 +22,7 @@ from torch_npu.testing.common_utils import create_common_tensor class Test__And__(TestCase): - def cpu_op_exec(self, input1, input2): + def cpu_op_exec(self, input1, input2): output = input1.__and__(input2) if output.dtype != torch.int32: output = output.to(torch.int32) @@ -47,7 +47,7 @@ class Test__And__(TestCase): ] for item in shape_format: - if len(item[1]) > 1: + if len(item[1]) > 1: cpu_input1, npu_input1 = create_common_tensor(item[0], 0, 100) cpu_input2, npu_input2 = create_common_tensor(item[1], 0, 100) cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) @@ -61,4 +61,4 @@ class Test__And__(TestCase): if __name__ == "__main__": - run_tests() \ No newline at end of file + run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_add.py b/test/test_network_ops/test_add.py index 014b373081..8700e39e62 100644 --- a/test/test_network_ops/test_add.py +++ b/test/test_network_ops/test_add.py @@ -17,7 +17,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor @@ -143,8 +142,7 @@ class TestAdd(TestCase): self.assertRtolEqual(cpu_output, npu_output) - @graph_mode - def test_add_scalar_shape_format_fp16_1d(self): + def test_add_scalar_shape_format_fp16_1d(self, device="npu"): format_list = [0, 3] scalar_list = [0,1] shape_format = [ @@ -152,17 +150,15 @@ class TestAdd(TestCase): ] self.add_scalar_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_1d(self): + def test_add_scalar_shape_format_fp32_1d(self, device="npu"): format_list = [0, 3] scalar_list = [0,1] shape_format = [ [[np.float32, i, [18]], k] for i in format_list for k in scalar_list ] self.add_scalar_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_2d(self): + + def test_add_scalar_shape_format_fp16_2d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -170,17 +166,15 @@ class TestAdd(TestCase): ] self.add_scalar_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_2d(self): + def test_add_scalar_shape_format_fp32_2d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ [[np.float32, i, [5, 256]], k] for i in format_list for k in scalar_list ] self.add_scalar_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_3d(self): + + def test_add_scalar_shape_format_fp16_3d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -188,17 +182,15 @@ class TestAdd(TestCase): ] self.add_scalar_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_3d(self): + def test_add_scalar_shape_format_fp32_3d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ [[np.float32, i, [32, 3, 3]], k] for i in format_list for k in scalar_list ] self.add_scalar_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_4d(self): + + def test_add_scalar_shape_format_fp16_4d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -206,17 +198,15 @@ class TestAdd(TestCase): ] self.add_scalar_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_4d(self): + def test_add_scalar_shape_format_fp32_4d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ [[np.float32, i, [64, 112, 7, 7]], k] for i in format_list for k in scalar_list ] self.add_scalar_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_1d(self): + + def test_add_scalar_shape_format_fp16_1d(self, device="npu"): format_list = [0, 3] scalar_list = [0,1] shape_format = [ @@ -224,17 +214,15 @@ class TestAdd(TestCase): ] self.add_scalar_alpha_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_1d(self): + def test_add_scalar_shape_format_fp32_1d(self, device="npu"): format_list = [0, 3] scalar_list = [0,1] shape_format = [ [[np.float32, i, [18]], k] for i in format_list for k in scalar_list ] self.add_scalar_alpha_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_2d(self): + + def test_add_scalar_shape_format_fp16_2d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -242,17 +230,15 @@ class TestAdd(TestCase): ] self.add_scalar_alpha_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_2d(self): + def test_add_scalar_shape_format_fp32_2d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ [[np.float32, i, [5, 256]], k] for i in format_list for k in scalar_list ] self.add_scalar_alpha_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_3d(self): + + def test_add_scalar_shape_format_fp16_3d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -260,17 +246,15 @@ class TestAdd(TestCase): ] self.add_scalar_alpha_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_3d(self): + def test_add_scalar_shape_format_fp32_3d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ [[np.float32, i, [32, 3, 3]], k] for i in format_list for k in scalar_list ] self.add_scalar_alpha_result(shape_format) - - @graph_mode - def test_add_scalar_shape_format_fp16_4d(self): + + def test_add_scalar_shape_format_fp16_4d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -278,8 +262,7 @@ class TestAdd(TestCase): ] self.add_scalar_alpha_result(shape_format) - @graph_mode - def test_add_scalar_shape_format_fp32_4d(self): + def test_add_scalar_shape_format_fp32_4d(self, device="npu"): format_list = [0, 3, 29] scalar_list = [0,1] shape_format = [ @@ -287,136 +270,119 @@ class TestAdd(TestCase): ] self.add_scalar_alpha_result(shape_format) - @graph_mode - def test_add_shape_format_fp16_1d(self): + def test_add_shape_format_fp16_1d(self, device="npu"): format_list = [0, 3] shape_format = [ [np.float16, i, [64]] for i in format_list ] self.add_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_1d(self): + def test_add_shape_format_fp32_1d(self, device="npu"): format_list = [0, 3] shape_format = [ [np.float32, i, [64]] for i in format_list ] self.add_result(shape_format) - - @graph_mode - def test_add_shape_format_fp16_2d(self): + + def test_add_shape_format_fp16_2d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float16, i, [5, 256]] for i in format_list ] self.add_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_2d(self): + def test_add_shape_format_fp32_2d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float32, i, [5, 256]] for i in format_list ] self.add_result(shape_format) - - @graph_mode - def test_add_shape_format_fp16_3d(self): + + def test_add_shape_format_fp16_3d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float16, i, [32, 3, 3]] for i in format_list ] self.add_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_3d(self): + def test_add_shape_format_fp32_3d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float32, i, [32, 3, 3]] for i in format_list ] self.add_result(shape_format) - - @graph_mode - def test_add_shape_format_fp16_4d(self): + + def test_add_shape_format_fp16_4d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float16, i, [64, 112, 7, 7]] for i in format_list ] self.add_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_4d(self): + def test_add_shape_format_fp32_4d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float32, i, [64, 112, 7, 7]] for i in format_list ] self.add_result(shape_format) - @graph_mode - def test_add_shape_format_fp16_1d(self): + def test_add_shape_format_fp16_1d(self, device="npu"): format_list = [0, 3] shape_format = [ [np.float16, i, [64]] for i in format_list ] self.add_alpha_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_1d(self): + def test_add_shape_format_fp32_1d(self, device="npu"): format_list = [0, 3] shape_format = [ [np.float32, i, [64]] for i in format_list ] self.add_alpha_result(shape_format) - - @graph_mode - def test_add_shape_format_fp16_2d(self): + + def test_add_shape_format_fp16_2d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float16, i, [5, 256]] for i in format_list ] self.add_alpha_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_2d(self): + def test_add_shape_format_fp32_2d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float32, i, [5, 256]] for i in format_list ] self.add_alpha_result(shape_format) - - @graph_mode - def test_add_shape_format_fp16_3d(self): + + def test_add_shape_format_fp16_3d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float16, i, [32, 3, 3]] for i in format_list ] self.add_alpha_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_3d(self): + def test_add_shape_format_fp32_3d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float32, i, [32, 3, 3]] for i in format_list ] self.add_alpha_result(shape_format) - - @graph_mode - def test_add_shape_format_fp16_4d(self): + + def test_add_shape_format_fp16_4d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float16, i, [64, 112, 7, 7]] for i in format_list ] self.add_alpha_result(shape_format) - @graph_mode - def test_add_shape_format_fp32_4d(self): + def test_add_shape_format_fp32_4d(self, device="npu"): format_list = [0, 3, 29] shape_format = [ [np.float32, i, [64, 112, 7, 7]] for i in format_list ] self.add_alpha_result(shape_format) - @graph_mode - def test_add_mix_dtype(self): + def test_add_mix_dtype(self, device="npu"): cpu_input1, npu_input1 = create_common_tensor([np.int32, 0, (2, 3)], 1, 100) cpu_input2, npu_input2 = create_common_tensor([np.float32, 0, (2, 3)], 1, 100) cpu_output = torch.add(cpu_input1, cpu_input2) @@ -424,20 +390,6 @@ class TestAdd(TestCase): npu_output = npu_output.to("cpu") self.assertRtolEqual(cpu_output, npu_output) - def test_add_scalar_check_5d_5d_match(self, device="npu"): - ca = torch.randn(4) - cb = ca.view(2, 2).transpose(1, 0) - na = ca.npu() - nb = cb.npu() - caout = torch.add(ca, 1) - cbout = torch.add(cb, 1) - naout = torch.add(na, 1) - nbout = torch.add(nb, 1) - naout = naout.to("cpu") - nbout = nbout.to("cpu") - self.assertRtolEqual(caout, naout) - self.assertRtolEqual(cbout, nbout) - if __name__ == "__main__": run_tests() diff --git a/test/test_network_ops/test_addcdiv.py b/test/test_network_ops/test_addcdiv.py index 14243d767e..d6815ecccc 100644 --- a/test/test_network_ops/test_addcdiv.py +++ b/test/test_network_ops/test_addcdiv.py @@ -14,16 +14,13 @@ # See the License for the specific language governing permissions and # limitations under the License. - import copy import torch import numpy as np from torch_npu.testing.testcase import TestCase, run_tests - class TestAddcdiv(TestCase): - def cpu_op_inp_input3_noncontiguous_exec(self, input1, input2, input3, scalar): input3_strided = input3.as_strided([2, 2], [1, 2], 2) input1.addcdiv_(input2, input3_strided, value=scalar) @@ -43,7 +40,7 @@ class TestAddcdiv(TestCase): def non_zero_rand(self, size, dtype, device="npu"): if dtype.is_floating_point: a = torch.rand(size=size, dtype=dtype, device="cpu") - a = a.to("npu") + a = a.to("npu") elif dtype == torch.uint8: a = torch.randint(1, 5, size=size, dtype=dtype, device="cpu").to(device) else: @@ -152,17 +149,13 @@ class TestAddcdiv(TestCase): self.assertTrue(torch.allclose(expected.to("cpu"), actual.to("cpu"), equal_nan=True)) self.assertRtolEqual(actual.to("cpu"), torch.addcdiv(a, alpha, b, c).to("cpu")) - def test_addcdiv(self, device="npu"): - """NPU does not support numpy.bool. - - with self.maybeWarnsRegex(UserWarning, "This overload of addcdiv is deprecated"): - self.assertRtolEqual(actual.to("cpu"), torch.addcdiv(a, alpha, b, c).to("cpu")) - - """ - dtype_list = [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, - torch.float64, torch.complex64, torch.complex128] + def test_addcdiv(self, device="npu"): + #由于np版本原因,np.bool不支持 with self.maybeWarnsRegex( + #由于np版本原因,np.bool不支持 UserWarning, "This overload of addcdiv is deprecated"): + #由于np版本原因,np.bool不支持 self.assertRtolEqual(actual.to("cpu"), torch.addcdiv(a, alpha, b, c).to("cpu")) for dtype in torch.testing.get_all_math_dtypes(device): - if dtype in dtype_list: + if dtype in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, + torch.float64, torch.complex64, torch.complex128]: continue self._test_addcdiv( self.non_zero_rand((2, 2), dtype=dtype, device=device), @@ -240,21 +233,6 @@ class TestAddcdiv(TestCase): npu_output = self.npu_op_inp_input3_noncontiguous_exec(npu_input1, npu_input2, npu_input3, scalar) self.assertRtolEqual(cpu_output, npu_output) - def test_addcdiv_float64(self): - cpu_input1, cpu_input2, cpu_input3 = self.generate_data(1, 100, (5, 3), np.float64) - scalar = self.generate_scalar(1, 10) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2, cpu_input3, scalar) - npu_output = self.npu_op_exec(cpu_input1, cpu_input2, cpu_input3, scalar) - self.assertRtolEqual(cpu_output, npu_output) - - def test_addcdiv_float16(self): - cpu_input1, cpu_input2, cpu_input3 = self.generate_data(1, 100, (5, 3), np.float16) - scalar = self.generate_scalar(1, 10) - cpu_output = self.cpu_op_exec(cpu_input1.float(), cpu_input2.float(), cpu_input3.float(), scalar) - npu_output = self.npu_op_exec(cpu_input1, cpu_input2, cpu_input3, scalar) - cpu_output = cpu_output.to(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - if __name__ == "__main__": run_tests() + \ No newline at end of file diff --git a/test/test_network_ops/test_addcmul.py b/test/test_network_ops/test_addcmul.py deleted file mode 100644 index 4de84309c5..0000000000 --- a/test/test_network_ops/test_addcmul.py +++ /dev/null @@ -1,107 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 sys -import torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestAddCMul(TestCase): - def generate_data(self, min_d, max_d, shape, dtype): - input1 = np.random.uniform(min_d, max_d, shape).astype(dtype) - input2 = np.random.uniform(min_d, max_d, shape).astype(dtype) - input3 = np.random.uniform(min_d, max_d, shape).astype(dtype) - npu_input1 = torch.from_numpy(input1) - npu_input2 = torch.from_numpy(input2) - npu_input3 = torch.from_numpy(input3) - - return npu_input1, npu_input2, npu_input3 - - def generate_output_data(self, min_d, max_d, shape, dtype): - output_y = np.random.uniform(min_d, max_d, shape).astype(dtype) - npu_output_y = torch.from_numpy(output_y) - return npu_output_y - - def cpu_op_exec(self, input1, input2, input3, scalar): - output = torch.addcmul(input1, input2, input3, value=scalar) - output = output.numpy() - return output - - def cpu_op_exec_out(self, input1, input2, input3, scalar, output_y): - output = output_y - torch.addcmul(input1, input2, input3, value = scalar, out = output_y) - output = output.numpy() - return output - - def npu_op_exec(self, input1, input2, input3, scalar): - input1 = input1.to("npu") - input2 = input2.to("npu") - input3 = input3.to("npu") - output = torch.addcmul(input1, input2, input3, value=scalar) - output = output.to("cpu") - output = output.numpy() - return output - - def npu_op_exec_out(self, input1, input2, input3, scalar, output_y): - input1 = input1.to("npu") - input2 = input2.to("npu") - input3 = input3.to("npu") - output = output_y.to("npu") - torch.addcmul(input1, input2, input3, value=scalar, out=output) - output = output.to("cpu") - output = output.numpy() - return output - - def test_addcmul_3_3_float32(self, device="npu"): - input1, input2, input3 = self.generate_data(0, 100, (3, 3), np.float32) - cpu_output = self.cpu_op_exec(input1, input2, input3, 0.5) - npu_output = self.npu_op_exec(input1, input2, input3, 0.5) - self.assertRtolEqual(cpu_output, npu_output) - - def test_addcmul_10_10_float32(self, device="npu"): - input1, input2, input3 = self.generate_data(0, 100, (10, 10), np.float32) - cpu_output = self.cpu_op_exec(input1, input2, input3, 0.5) - npu_output = self.npu_op_exec(input1, input2, input3, 0.5) - self.assertRtolEqual(cpu_output, npu_output) - - def test_addcmul_3_3_float16(self, device="npu"): - input1, input2, input3 = self.generate_data(0, 100, (3, 3), np.float16) - input1_cpu = input1.float() - input2_cpu = input2.float() - input3_cpu = input3.float() - cpu_output = self.cpu_op_exec(input1_cpu, input2_cpu, input3_cpu, 0.5).astype(np.float16) - npu_output = self.npu_op_exec(input1, input2, input3, 0.5) - self.assertRtolEqual(cpu_output, npu_output) - - def test_addcmul_10_10_float16(self, device="npu"): - input1, input2, input3 = self.generate_data(0, 100, (10, 10), np.float16) - input1_cpu = input1.float() - input2_cpu = input2.float() - input3_cpu = input3.float() - cpu_output = self.cpu_op_exec(input1_cpu, input2_cpu, input3_cpu, 0.5).astype(np.float16) - npu_output = self.npu_op_exec(input1, input2, input3, 0.5) - self.assertRtolEqual(cpu_output, npu_output) - - def test_addcmul_10_23_float32(self, device="npu"): - input1, input2, input3 = self.generate_data(0, 100, (10, 23), np.float32) - cpu_output = self.cpu_op_exec(input1, input2, input3, 0.5) - npu_output = self.npu_op_exec(input1, input2, input3, 0.5) - self.assertRtolEqual(cpu_output, npu_output) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_all.py b/test/test_network_ops/test_all.py index d9de4a6001..33bcd3d574 100644 --- a/test/test_network_ops/test_all.py +++ b/test/test_network_ops/test_all.py @@ -37,7 +37,7 @@ class TestAll(TestCase): output = output.numpy() return output - def test_all_shape_format(self): + def test_all_shape_format(self, device="npu"): shape_list = [[1024], [32, 1024], [32, 8, 1024], [128, 32, 8, 1024], [2, 0, 2]] for item in shape_list: cpu_input, npu_input = self.create_bool_tensor(item, 0, 1) @@ -71,7 +71,7 @@ class TestAll(TestCase): output1 = output1.to("cpu").numpy() return output0, output1 - def test_alld_shape_format(self): + def test_alld_shape_format(self, device="npu"): shape_list = [[1024], [32, 1024], [32, 8, 1024], [128, 32, 8, 1024]] for item in shape_list: cpu_input, npu_input = self.create_bool_tensor(item, 0, 1) @@ -82,15 +82,6 @@ class TestAll(TestCase): self.assertRtolEqual(cpu_output.astype(np.int32), npu_out0.astype(np.int32)) self.assertRtolEqual(cpu_output.astype(np.int32), npu_out1.astype(np.int32)) - def test_all_tensor_numel_0(self): - ca = torch.rand(1, 2, 0, 3, 4).bool() - na = ca.npu() - cout = ca.all(2) - nout = na.all(2) - cout = cout.numpy() - nout = nout.to("cpu").numpy() - self.assertRtolEqual(cout, nout) - if __name__ == "__main__": run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_amp_foreach_non_finite_check_and_unscale_.py b/test/test_network_ops/test_amp_foreach_non_finite_check_and_unscale_.py deleted file mode 100644 index 090dc73292..0000000000 --- a/test/test_network_ops/test_amp_foreach_non_finite_check_and_unscale_.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 copy -import sys -import torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class Test_AmpForeachNonFiniteCheckAndUnscale_(TestCase): - def generate_data(self, min_d, max_d, shape, dtype, input3): - input1 = np.random.uniform(min_d, max_d, shape).astype(dtype) - input1 = torch.from_numpy(input1) - input2 = np.array([0.0]).astype(dtype) - input2 = torch.from_numpy(input2) - input3 = np.array([input3]).astype(dtype) - input3 = torch.from_numpy(input3) - return input1, input2, input3 - - def cpu_op_exec(self, input1, input2, input3): - input1 = input1.numpy() - input2 = input2.numpy() - input3 = input3.numpy() - res = np.multiply(input1, input3) - return res - - def npu_op_exec(self, input1, input2, input3): - input1 = input1.to("npu") - input2 = input2.to("npu") - input3 = input3.to("npu") - torch._amp_foreach_non_finite_check_and_unscale_((input1,),input2,input3) - input1 = input1.to("cpu") - input1 = input1.numpy() - return input1 - - - def test_AmpForeachNonFiniteCheckAndUnscale_float32_case1(self, device='npu'): - params = [(0, 100, (4, 3), np.float32, 1.5), - (0, 100, (2, 5, 6), np.float32, 3.7), - (0, 100, (5, 7), np.float32, 1.9), - (0, 100, (2, 8, 1), np.float32, 3.2) - ] - for param in params: - input1, input2, input3 = self.generate_data(*param) - cpu_output = self.cpu_op_exec(input1, input2, input3) - npu_output = self.npu_op_exec(input1, input2, input3) - self.assertRtolEqual(cpu_output, npu_output) - - -if __name__ == '__main__': - run_tests() diff --git a/test/test_network_ops/test_batch_norm.py b/test/test_network_ops/test_batch_norm.py index 00751fdab0..092cb4b982 100644 --- a/test/test_network_ops/test_batch_norm.py +++ b/test/test_network_ops/test_batch_norm.py @@ -17,7 +17,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor @@ -41,7 +40,6 @@ class TestBatchNorm(TestCase): output = output.to("cpu").detach().numpy() return output - @graph_mode def test_batchnorm_shape_format(self): format_list = [-1, 3, 0] shape_list = [(10, 32, 35, 45), (256, 100, 7, 7), (256, 100, 14, 14), (10, 56, 28, 28), (10, 56, 56, 56)] @@ -76,7 +74,6 @@ class TestBatchNorm(TestCase): output = output.to("cpu").detach().numpy() return output - @graph_mode def test_batchnorm_shape_format_3d(self): format_list = [-1] shape_list = [[8, 512, 4, 28, 28], [8, 256, 8, 56, 56]] @@ -87,6 +84,8 @@ class TestBatchNorm(TestCase): ] for item in shape_format: + print(item) + print(item[0]) cpu_input1, npu_input1 = create_common_tensor(item[0], 0, 10) cpu_output = self.cpu_op_exec_3d(cpu_input1, item[0][2][1], item[1]) npu_output = self.npu_op_exec_new_3d(npu_input1, item[0][2][1], item[1]) diff --git a/test/test_network_ops/test_batchnorm_backward.py b/test/test_network_ops/test_batchnorm_backward.py index cd91e29ced..2e50be2e1b 100644 --- a/test/test_network_ops/test_batchnorm_backward.py +++ b/test/test_network_ops/test_batchnorm_backward.py @@ -18,7 +18,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor @@ -74,7 +73,6 @@ class TestBatchNorm(TestCase): return output, running_mean, running_var, input_grad, weight_grad, bias_grad - @graph_mode def test_BatchNorm1D_float32(self): np.random.seed(1234) format_list = [-1] @@ -117,7 +115,6 @@ class TestBatchNorm(TestCase): self.assertRtolEqual(cpu_weight_grad, npu_weight_grad, 1e-2) self.assertRtolEqual(cpu_bias_grad, npu_bias_grad) - @graph_mode def test_BatchNorm1D_float16(self): np.random.seed(1234) format_list = [-1] @@ -160,7 +157,6 @@ class TestBatchNorm(TestCase): self.assertRtolEqual(cpu_weight_grad, npu_weight_grad, 1e-2) self.assertRtolEqual(cpu_bias_grad, npu_bias_grad) - @graph_mode def test_BatchNorm2D_float32(self): np.random.seed(1234) format_list = [-1] @@ -203,7 +199,6 @@ class TestBatchNorm(TestCase): self.assertRtolEqual(cpu_weight_grad, npu_weight_grad, 1e-2) self.assertRtolEqual(cpu_bias_grad, npu_bias_grad) - @graph_mode def test_BatchNorm2D_float16(self): np.random.seed(1234) format_list = [-1] @@ -246,7 +241,6 @@ class TestBatchNorm(TestCase): self.assertRtolEqual(cpu_weight_grad, npu_weight_grad, 1e-1) self.assertRtolEqual(cpu_bias_grad, npu_bias_grad) - @graph_mode def test_BatchNorm3D_float32(self): np.random.seed(1234) format_list = [-1] @@ -289,7 +283,6 @@ class TestBatchNorm(TestCase): self.assertRtolEqual(cpu_weight_grad, npu_weight_grad, 1e-2) self.assertRtolEqual(cpu_bias_grad, npu_bias_grad) - @graph_mode def test_BatchNorm3D_float16(self): np.random.seed(1234) format_list = [-1] diff --git a/test/test_network_ops/test_bernoulli.py b/test/test_network_ops/test_bernoulli.py index bd9164c039..4458519caa 100644 --- a/test/test_network_ops/test_bernoulli.py +++ b/test/test_network_ops/test_bernoulli.py @@ -11,49 +11,64 @@ # 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 torch import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests - - -SEED = 666 - +from torch_npu.testing.common_utils import create_common_tensor class TestBernoulli(TestCase): - - def get_common_tensor(self, item, minValue, maxValue): - dtype = item[0] - shape = item[2] - npu_input = torch.randn(shape).uniform_(minValue, maxValue).npu().to(dtype) - return npu_input + def cpu_op_exec(self, input1): + output = torch.bernoulli(input1) + output = output.numpy() + return output def npu_op_exec(self, input1): - torch.manual_seed(SEED) output = torch.bernoulli(input1) output = output.to("cpu") output = output.numpy() return output + def cpu_op_inplace_tensor_exec(self, input1, p): + output = input1.bernoulli_(p) + output = output.numpy() + return output + def npu_op_inplace_tensor_exec(self, input1, p): - torch.manual_seed(SEED) output = input1.bernoulli_(p) output = output.to("cpu") output = output.numpy() return output - def npu_op_inplace_float_exec(self, input1, p): - torch.manual_seed(SEED) - output = input1.bernoulli_(p) + def cpu_op_inplace_float_exec(self, input1): + output = input1.bernoulli_(0.5) + output = output.numpy() + return output + + def npu_op_inplace_float_exec(self, input1): + output = input1.bernoulli_(0.5) output = output.to("cpu") output = output.numpy() return output + def cpu_op_out_exec(self, input1, output1): + torch.bernoulli(input1, out=output1) + output1 = output1.numpy() + return output1 + + def npu_op_out_exec(self, input1, output1): + torch.bernoulli(input1, out=output1) + output1 = output1.to("cpu") + output1 = output1.numpy() + return output1 + + def cpu_op_p_exec(self, input1, p): + input1 = input1.bernoulli_(p) + input1 = input1.numpy() + return input1 + def npu_op_p_exec(self, input1, p): - torch.manual_seed(SEED) input1 = input1.bernoulli_(p) input1 = input1.to("cpu") input1 = input1.numpy() @@ -64,75 +79,95 @@ class TestBernoulli(TestCase): shape_list = [(2, 3, 4)] p_list = [0.2, 0.6] shape_format = [ - [torch.float32, i, j, k] - for i in format_list - for j in shape_list + [np.float32, i, j, k] for i in format_list for j in shape_list for k in p_list ] for item in shape_format: - npu_input = self.get_common_tensor(item, 0, 1) - npu_expect_output = self.npu_op_p_exec(npu_input, item[3]) + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_output = self.cpu_op_p_exec(cpu_input, item[3]) npu_output = self.npu_op_p_exec(npu_input, item[3]) - self.assertEqual(npu_expect_output, npu_output) + print(cpu_output, npu_output) + + + def test_bernoulli_out_float32(self): + format_list = [0, 3] + shape_list = [(2, 3, 4)] + shape_format = [ + [np.float32, i, j] for i in format_list for j in shape_list + ] + for item in shape_format: + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_output1, npu_output1 = create_common_tensor(item, 0, 1) + cpu_output = self.cpu_op_out_exec(cpu_input, cpu_output1) + npu_output = self.npu_op_out_exec(npu_input, npu_output1) + print(cpu_output, npu_output) + + def test_bernoulli_out_float16(self): + format_list = [0, 3] + shape_list = [(2, 3, 4)] + shape_format = [ + [np.float16, i, j] for i in format_list for j in shape_list + ] + for item in shape_format: + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_output1, npu_output1 = create_common_tensor(item, 0, 1) + cpu_input = cpu_input.to(torch.float32) + cpu_output1 = cpu_output1.to(torch.float32) + cpu_output = self.cpu_op_out_exec(cpu_input, cpu_output1) + npu_output = self.npu_op_out_exec(npu_input, npu_output1) + cpu_output = cpu_output.astype(np.float16) + print(cpu_output, npu_output) def test_bernoulli_float32(self): format_list = [0, 3] shape_list = [(2, 3, 4)] shape_format = [ - [torch.float32, i, j] - for i in format_list - for j in shape_list + [np.float32, i, j] for i in format_list for j in shape_list ] for item in shape_format: - npu_input = self.get_common_tensor(item, 0, 1) - npu_expect_output = self.npu_op_exec(npu_input) + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_output = self.cpu_op_exec(cpu_input) npu_output = self.npu_op_exec(npu_input) - self.assertEqual(npu_expect_output, npu_output) + print(cpu_output, npu_output) def test_bernoulli_float16(self): format_list = [0, 3] shape_list = [(2, 3, 4)] shape_format = [ - [torch.float16, i, j] - for i in format_list - for j in shape_list + [np.float16, i, j] for i in format_list for j in shape_list ] for item in shape_format: - npu_input = self.get_common_tensor(item, 0, 1) - npu_expect_output = self.npu_op_exec(npu_input) + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_input = cpu_input.to(torch.float32) + cpu_output = self.cpu_op_exec(cpu_input) npu_output = self.npu_op_exec(npu_input) - self.assertEqual(npu_expect_output, npu_output) + cpu_output = cpu_output.astype(np.float16) + print(cpu_output, npu_output) def test_bernoulli_tensor_p(self): format_list = [0, 3] shape_list = [(2, 3, 4)] shape_format = [ - [torch.float32, i, j] - for i in format_list - for j in shape_list + [np.float32, i, j] for i in format_list for j in shape_list ] for item in shape_format: - npu_input = self.get_common_tensor(item, 0, 1) - npu_input_p = self.get_common_tensor(item, 0, 1) - npu_expect_output = self.npu_op_inplace_tensor_exec(npu_input, npu_input_p) + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_input_p, npu_input_p = create_common_tensor(item, 0, 1) + cpu_output = self.cpu_op_inplace_tensor_exec(cpu_input, cpu_input_p) npu_output = self.npu_op_inplace_tensor_exec(npu_input, npu_input_p) - self.assertEqual(npu_expect_output, npu_output) + print(cpu_output, npu_output) def test_bernoulli_float_p(self): format_list = [0, 3] shape_list = [(2, 3, 4)] - p = 0.5 shape_format = [ - [torch.float32, i, j] - for i in format_list - for j in shape_list + [np.float32, i, j] for i in format_list for j in shape_list ] for item in shape_format: - npu_input = self.get_common_tensor(item, 0, 1) - npu_expect_output = self.npu_op_inplace_float_exec(npu_input, p) - npu_output = self.npu_op_inplace_float_exec(npu_input, p) - self.assertEqual(npu_expect_output, npu_output) - + cpu_input, npu_input = create_common_tensor(item, 0, 1) + cpu_output = self.cpu_op_inplace_float_exec(cpu_input) + npu_output = self.npu_op_inplace_float_exec(npu_input) + print(cpu_output, npu_output) if __name__ == '__main__': - run_tests() + run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_broadcast.py b/test/test_network_ops/test_broadcast.py deleted file mode 100644 index 657ac6d162..0000000000 --- a/test/test_network_ops/test_broadcast.py +++ /dev/null @@ -1,86 +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 torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestBroadCastTensors(TestCase): - def cpu_op_exec(self, input1, input2): - output1, output2 = torch.broadcast_tensors(input1,input2); - return output1.numpy(), output2.numpy() - - def npu_op_exec(self, input1, input2, npu_format=None): - input1 =input1.npu() - input2 =input2.npu() - if npu_format is not None: - input1 = torch.npu_format_cast(input1,npu_format) - input2 = torch.npu_format_cast(input2,npu_format) - output1, output2 = torch.broadcast_tensors(input1,input2); - return output1.cpu().numpy(), output2.cpu().numpy() - - def test_broadcast_tensors_common_shape_format(self, device='npu'): - shape_format = [ - [[1, 3], (2, 1), torch.float32], - [[1, 9], (5, 1), torch.float32], - [[3, 1], (1, 3), torch.float32], - ] - for item in shape_format: - cpu_input1 = torch.randn(item[0], dtype=item[2]) - cpu_input2 = torch.randn(item[1], dtype=item[2]) - cpu_output1, cpu_output2 = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output1, npu_output2 = self.npu_op_exec(cpu_input1, cpu_input2) - self.assertRtolEqual(cpu_output1, npu_output1) - self.assertRtolEqual(cpu_output2, npu_output2) - - def test_broadcast_tensors_discontiguous_shape(self, device='npu'): - shape_format = [ - [[1, 6], (4, 1), torch.float32], - [[1, 18], (10, 1), torch.float32], - ] - for item in shape_format: - cpu_input1 = torch.randn(item[0], dtype=item[2])[:,::2] - cpu_input2 = torch.randn(item[1], dtype=item[2])[::2,:] - cpu_output1, cpu_output2 = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output1, npu_output2 = self.npu_op_exec(cpu_input1, cpu_input2) - self.assertRtolEqual(cpu_output1, npu_output1) - self.assertRtolEqual(cpu_output2, npu_output2) - - def test_broadcast_tensors_format(self, device='npu'): - shape_format = [ - [[2,3,4], (3, 1), torch.float32, 0], - [[2,3,4], (3, 1), torch.float32, 2], - [[2,3,4], (3, 1), torch.float32, 3], - [[2,3,4], (3, 1), torch.float32, 4], - [[2,3,4], (3, 1), torch.float32, 29], - [[2,3,4], (3, 1), torch.float32, 30], - ] - for item in shape_format: - cpu_input1 = torch.randn(item[0], dtype=item[2])[:,::2] - cpu_input2 = torch.randn(item[1], dtype=item[2])[::2,:] - cpu_output1, cpu_output2 = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_format = item[3] - npu_output1, npu_output2 = self.npu_op_exec(cpu_input1, cpu_input2, npu_format) - self.assertRtolEqual(cpu_output1, npu_output1) - self.assertRtolEqual(cpu_output2, npu_output2) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_cast.py b/test/test_network_ops/test_cast.py deleted file mode 100644 index 7c335be307..0000000000 --- a/test/test_network_ops/test_cast.py +++ /dev/null @@ -1,109 +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 torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -def cpu_op_exec(input1, func): - output = func(input1) - output = output.numpy() - return output - - -def npu_op_exec(input1, func): - input1 = input1.to("npu") - if func == torch._cast_Byte: - output = func(input1.int()) - else: - output = func(input1) - output = output.to("cpu") - output = output.numpy() - return output - - -shape_format = [ - [[np.bool, -1, (4, 3, 1)]], - [[np.int64, -1, (4, 3)]], - [[np.int32, -1, (4, 3, 1)]], - [[np.int8, -1, (2, 3)]], - [[np.float32, -1, (4, 3, 1)]], - [[np.float16, -1, (4, 3, 1)]], - [[np.uint8, -1, (4, 3, 1)]] -] - - -class TestCast(TestCase): - def test__cast_Byte_common_shape_format(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Byte) - npu_output = npu_op_exec(npu_input1, torch._cast_Byte) - self.assertEqual(cpu_output, npu_output) - - def test_cast_Char_common_shape_format(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Char) - npu_output = npu_op_exec(npu_input1, torch._cast_Char) - self.assertEqual(cpu_output, npu_output) - - def test_cast_Float_common_shape_format(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Float) - npu_output = npu_op_exec(npu_input1, torch._cast_Float) - self.assertRtolEqual(cpu_output, npu_output) - - def test_cast_Half(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Half) - npu_output = npu_op_exec(npu_input1, torch._cast_Half) - self.assertRtolEqual(cpu_output, npu_output) - - def test_cast_Int(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Int) - npu_output = npu_op_exec(cpu_input1, torch._cast_Int) - self.assertRtolEqual(cpu_output, npu_output) - - def test_cast_Long_common_shape_format(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Long) - npu_output = npu_op_exec(npu_input1, torch._cast_Long) - self.assertRtolEqual(cpu_output, npu_output) - - def test_cast_Short_common_shape_format(self, device='npu'): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = cpu_op_exec(cpu_input1, torch._cast_Short) - npu_output = npu_op_exec(npu_input1, torch._cast_Short) - self.assertRtolEqual(cpu_output, npu_output) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_cat.py b/test/test_network_ops/test_cat.py deleted file mode 100644 index 4f8222e599..0000000000 --- a/test/test_network_ops/test_cat.py +++ /dev/null @@ -1,170 +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 torch -import numpy as np -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode -from torch_npu.testing.common_utils import create_common_tensor - -class TestCat(TestCase): - - def cpu_op_exec(self, input1, input2, n): - output = torch.cat(input1 + input2, n) - if not(output.is_contiguous()): - output = output.contiguous() - output = output.numpy() - return output - - def npu_op_exec(self, input1, input2, n): - output = torch.cat(input1 + input2, n) - if not(output.is_contiguous()): - output = output.contiguous() - output = output.to("cpu") - output = output.numpy() - return output - - @graph_mode - def test_cat_shape_format_fp16_3d(self): - format_list = [0, 3, 29] - shape_list = [(256, 32, 56)] - shape_format = [ - [np.float16, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec([cpu_input1], [cpu_input2], 1) - npu_output = self.npu_op_exec([npu_input1], [npu_input2], 1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_cat_shape_format_fp32_3d(self): - format_list = [0, 3, 29] - shape_list = [(256, 32, 56)] - shape_format = [ - [np.float32, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec([cpu_input1], [cpu_input2], 1) - npu_output = self.npu_op_exec([npu_input1], [npu_input2], 1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_cat_shape_format_fp16_4d(self): - format_list = [0, 3, 29] - shape_list = [(256, 32, 56, 56)] - shape_format = [ - [np.float16, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec([cpu_input1], [cpu_input2], 1) - npu_output = self.npu_op_exec([npu_input1], [npu_input2], 1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_cat_shape_format_fp32_4d(self): - format_list = [0, 3, 29] - shape_list = [(256, 32, 56, 56)] - shape_format = [ - [np.float32, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec([cpu_input1], [cpu_input2], 1) - npu_output = self.npu_op_exec([npu_input1], [npu_input2], 1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_cat_shape_format_fp16_2d(self): - format_list = [0, 3, 29] - shape_list = [(56, 56)] - shape_format = [ - [np.float16, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec([cpu_input1], [cpu_input2], 1) - npu_output = self.npu_op_exec([npu_input1], [npu_input2], 1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_cat_shape_format_fp32_2d(self): - format_list = [0, 3, 29] - shape_list = [(56, 56)] - shape_format = [ - [np.float32, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec([cpu_input1], [cpu_input2], 1) - npu_output = self.npu_op_exec([npu_input1], [npu_input2], 1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_cat_null_tensor(self): - x1 = torch.randn(15, 2, 1, 1) - x2 = torch.randn(0, 2, 1, 1) - x3 = torch.randn(0, 2, 3, 1) - y1_cpu = torch.cat([x1, x2], dim=0) - y2_cpu = torch.cat([x2, x3], dim=2) - y3_cpu = torch.cat([x2, x2, x2], dim=1) - x1 = x1.npu() - x2 = x2.npu() - x3 = x3.npu() - y1_npu = torch.cat([x1, x2], dim=0) - y2_npu = torch.cat([x2, x3], dim=2) - y3_npu = torch.cat([x2, x2, x2], dim=1) - self.assertRtolEqual(y1_cpu, y1_npu.cpu()) - self.assertRtolEqual(y2_cpu, y2_npu.cpu()) - self.assertRtolEqual(y3_cpu, y3_npu.cpu()) - - -if __name__ == "__main__": - run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_ciou_backward.py b/test/test_network_ops/test_ciou_backward.py index 9a8aaa61e0..94a0cd71db 100644 --- a/test/test_network_ops/test_ciou_backward.py +++ b/test/test_network_ops/test_ciou_backward.py @@ -16,9 +16,8 @@ import math import torch -import numpy as np - import torch_npu +import numpy as np from torch_npu.testing.testcase import TestCase, run_tests diff --git a/test/test_network_ops/test_conv2d.py b/test/test_network_ops/test_conv2d.py index 9bd92b81af..8a8fe6a0e6 100644 --- a/test/test_network_ops/test_conv2d.py +++ b/test/test_network_ops/test_conv2d.py @@ -18,7 +18,6 @@ import torch.nn as nn import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor @@ -99,8 +98,7 @@ class TestConv2d(TestCase): self.assertRtolEqual(self.input_grad[0].numpy(), self.input_grad[1].numpy()) self.assertRtolEqual(self.weight_grad[0].numpy(), self.weight_grad[1].numpy()) - @graph_mode - def test_conv2d_backward_shape_format_fp16(self): + def test_conv2d_backward_shape_format_fp16(self, device="npu"): shape_format = [ # input, weight, padding, stride, dilation, bias, groups # shuflenet [[np.float16, 3, [1024, 232, 7, 7]], [np.float16, 4, [232, 232, 1, 1]], 0, 1, 1, None, 1], diff --git a/test/test_network_ops/test_conv2d_backward.py b/test/test_network_ops/test_conv2d_backward.py deleted file mode 100644 index 26690b721f..0000000000 --- a/test/test_network_ops/test_conv2d_backward.py +++ /dev/null @@ -1,102 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 sys -import torch -import torch_npu -import numpy as np -import torch.nn as nn -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestConv2dBackward(TestCase): - weight_grad = [] - input_grad = [] - - def getWeightGrad(self, grad): - self.weight_grad.append(grad.to("cpu")) - - def getInputGrad(self, grad): - self.input_grad.append(grad.to("cpu")) - - def op_exec(self, npu_flag, input1, weight, in_channels, out_channels, kernel_size, padding=0, stride=1, - dilation=1, bias=True, groups=1): - weight1 = weight - input1.requires_grad = True - input1.register_hook(lambda grad: self.getInputGrad(grad)) - - m1 = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias, groups=groups) - m1.weight.data = weight1 - m1.weight.register_hook(lambda grad: self.getWeightGrad(grad)) - if npu_flag: - m1 = m1.to("npu") - output = m1(input1) - tmp = torch.ones_like(output) - output.backward(tmp) - if npu_flag: - output = output.to("cpu") - return output - - def test_conv2d_backward_shape_format_fp16(self, device='npu'): - shape_format = [ # input, weight, padding, stride, dilation, bias, groups - # shuflenet - [[np.float16, 3, [1024, 232, 7, 7]], [np.float16, 4, [232, 232, 1, 1]], 0, 1, 1, None, 1], - [[np.float16, 0, [1024, 116, 14, 14]], [np.float16, 4, [116, 116, 1, 1]], 0, 1, 1, None, 1], - [[np.float16, 0, [4, 8, 300, 40]], [np.float16, 0, [16, 8, 3, 3]], [2,1], 1, 1, None, 1], - [[np.float16, 0, [4, 64, 150, 10]], [np.float16, 0, [32, 64, 1, 1]], 0, 1, 1, None, 1], - [[np.float16, 0, [4, 128, 75, 10]], [np.float16, 0, [64, 128, 1, 1]], 0, 1, 1, None, 1], - [[np.float16, 0, [4, 256, 75, 5]], [np.float16, 0, [128, 256, 3, 3]], [2,1], 1, 1, None, 1], - [[np.float16, 0, [4, 384, 75, 1]], [np.float16, 0, [192, 384, 3, 1]], 0, 1, 1, None, 1], - [[np.float16, 0, [4, 384, 1, 75]], [np.float16, 0, [192, 384, 1, 3]], 0, 1, 1, None, 1], - [[np.float16, 3, [4, 256, 75, 5]], [np.float16, 4, [128, 256, 3, 3]], [2,1], 1, 1, None, 1], - [[np.float16, 3, [4, 384, 75, 1]], [np.float16, 4, [192, 384, 3, 1]], 0, 1, 1, None, 1], - [[np.float16, 3, [4, 384, 1, 75]], [np.float16, 4, [192, 384, 1, 3]], 0, 1, 1, None, 1], - [[np.float16, 0, [4, 256, 75, 5]], [np.float16, 4, [128, 256, 3, 3]], [2,1], 1, 1, None, 1], - [[np.float16, 0, [4, 384, 75, 1]], [np.float16, 4, [192, 384, 3, 1]], 0, 1, 1, None, 1], - [[np.float16, 0, [4, 384, 1, 75]], [np.float16, 4, [192, 384, 1, 3]], 0, 1, 1, None, 1] - ] - for item in shape_format: - self.weight_grad.clear() - self.input_grad.clear() - input_cpu, input_npu = create_common_tensor(item[0], -1, 1) - if input_cpu.dtype == torch.float16: - input_cpu = input_cpu.to(torch.float32) - weight_cpu, weight_npu = create_common_tensor(item[1], -1, 1) - if weight_cpu.dtype == torch.float16: - weight_cpu = weight_cpu.to(torch.float32) - kernel_size = (item[1][2][2], item[1][2][3]) - assert item[0][2][1]/item[6] == item[1][2][1], \ - "ilegal parameters: con2d in_channels//groups must equal to weight.size[1]." - cpu_output = self.op_exec(0, input_cpu, weight_cpu, item[0][2][1], item[1][2][0], kernel_size=kernel_size, - padding=item[2], stride=item[3], dilation=item[4], bias=item[5], - groups=item[6]) - weight_npu = weight_npu.to("cpu") - npu_output = self.op_exec(1, input_npu, weight_npu, item[0][2][1], item[1][2][0], kernel_size=kernel_size, - padding=item[2], stride=item[3], dilation=item[4], bias=item[5], - groups=item[6]) - - npu_output = npu_output.to(torch.float16) - cpu_output = cpu_output.to(torch.float16) - self.input_grad[0] = self.input_grad[0].to(torch.float16) - self.input_grad[1] = self.input_grad[1].to(torch.float16) - - self.weight_grad[0] = self.weight_grad[0].to(self.weight_grad[1].dtype) - - self.assertRtolEqual(cpu_output.detach().numpy(), npu_output.detach().numpy()) - self.assertRtolEqual(self.input_grad[0].numpy(), self.input_grad[1].numpy()) - self.assertRtolEqual(self.weight_grad[0].numpy(), self.weight_grad[1].numpy()) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_conv3d_backward.py b/test/test_network_ops/test_conv3d_backward.py deleted file mode 100644 index 12ef5e05c1..0000000000 --- a/test/test_network_ops/test_conv3d_backward.py +++ /dev/null @@ -1,92 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 sys -import torch -import torch_npu -import numpy as np -import torch.nn as nn -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestConv3dBackward(TestCase): - weight_grad = [] - input_grad = [] - - def getWeightGrad(self, grad): - self.weight_grad.append(grad.to("cpu")) - - def getInputGrad(self, grad): - self.input_grad.append(grad.to("cpu")) - - def op_exec(self, npu_flag, input1, weight, in_channels, out_channels, kernel_size, padding=0, stride=1, dilation=1, - bias=False, groups=1): - weight1 = weight - input1.requires_grad = True - input1.register_hook(lambda grad: self.getInputGrad(grad)) - - m1 = nn.Conv3d(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias, groups=groups) - m1.weight.data = weight1 - m1.weight.register_hook(lambda grad: self.getWeightGrad(grad)) - if npu_flag: - m1 = m1.to("npu") - output = m1(input1) - tmp = torch.ones_like(output) - output.backward(tmp) - if npu_flag: - output = output.to("cpu") - return output - - def test_conv3d_backward_shape_format_fp32(self, device='npu'): - shape_format = [ # input, weight, padding, stride, dilation, bias, groups - [[np.float32, 30, [128, 128, 4, 14, 14]], - [np.float32, 30, [128, 128, 3, 3, 3]], [1,1,1], [1,1,1], 1, None, 1], - [[np.float32, 30, [128, 64, 4, 14, 14]], - [np.float32, 30, [128, 64, 3, 3, 3]], [1,1,1], [2,2,2], 1, None, 1], - [[np.float32, 30, [128, 256, 2, 7, 7]], - [np.float32, 30, [256, 256, 3, 3, 3]], [1,1,1], [1,1,1], 1, None, 1], - [[np.float32, 30, [128, 256, 2, 7, 7]], - [np.float32, 30, [512, 256, 1, 1, 1]], 0, [2,2,2], 1, None, 1] - ] - for item in shape_format: - self.weight_grad.clear() - self.input_grad.clear() - input_cpu, input_npu = create_common_tensor(item[0], 0, 1) - if input_cpu.dtype == torch.float16: - input_cpu = input_cpu.to(torch.float32) - weight_cpu, weight_npu = create_common_tensor(item[1], 0, 1) - if weight_cpu.dtype == torch.float16: - weight_cpu = weight_cpu.to(torch.float32) - kernel_size = (item[1][2][2], item[1][2][3],item[1][2][4]) - cpu_output = self.op_exec(0, input_cpu, weight_cpu, item[0][2][1], item[1][2][0], kernel_size=kernel_size, - padding=item[2], stride=item[3], dilation=item[4], bias=item[5], - groups=item[6]) - weight_npu = weight_npu.to("cpu") - - npu_output = self.op_exec(1, input_npu, weight_npu, item[0][2][1], item[1][2][0], kernel_size=kernel_size, - padding=item[2], stride=item[3], dilation=item[4], bias=item[5], - groups=item[6]) - - npu_output = npu_output.to(torch.float16) - cpu_output = cpu_output.to(torch.float16) - self.input_grad[0] = self.input_grad[0].to(torch.float16) - self.input_grad[1] = self.input_grad[1].to(torch.float16) - self.weight_grad[0] = self.weight_grad[0].to(self.weight_grad[1].dtype) - self.assertRtolEqual(cpu_output.detach().numpy(), npu_output.cpu().detach().numpy()) - self.assertRtolEqual(self.input_grad[0].numpy(), self.input_grad[1].cpu().numpy()) - self.assertRtolEqual(self.weight_grad[0].numpy(), self.weight_grad[1].cpu().numpy()) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_conv_transpose3d_backward.py b/test/test_network_ops/test_conv_transpose3d_backward.py deleted file mode 100644 index ee1ad17368..0000000000 --- a/test/test_network_ops/test_conv_transpose3d_backward.py +++ /dev/null @@ -1,120 +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 copy -import sys -import torch -import numpy as np -import torch.nn as nn -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestConvTranspose3dBackward(TestCase): - weight_grad = [] - input_grad = [] - - def getWeightGrad(self, grad): - self.weight_grad.append(grad.to("cpu")) - - def getInputGrad(self, grad): - self.input_grad.append(grad.to("cpu")) - - def cpu_op_exec(self, input1, weight, bias1): - input1.requires_grad = True - input1.register_hook(lambda grad: self.getInputGrad(grad)) - weight.requires_grad = True - weight.register_hook(lambda grad: self.getWeightGrad(grad)) - bias1.requires_grad = True - - res_forward = nn.functional.conv_transpose3d(input1, weight, padding=1, bias=bias1) - grads = torch.ones_like(res_forward).float() - res_forward.backward(grads, retain_graph=True) - return res_forward - - def npu_op_exec(self, input1, weight, bias1): - input1.requires_grad = True - input1.register_hook(lambda grad: self.getInputGrad(grad)) - weight.requires_grad = True - weight.register_hook(lambda grad: self.getWeightGrad(grad)) - bias1 = bias1.to("npu") - bias1.requires_grad = True - - res_forward = nn.functional.conv_transpose3d(input1, weight, padding=1, bias=bias1) - grads = torch.ones_like(res_forward).float() - grads = grads.to("npu") - res_forward.backward(grads, retain_graph=True) - res_forward = res_forward.to("cpu") - return res_forward - - def test_conv_transpose3d_backward_shape_format_fp16(self, device='npu'): - shape_format = [ - [[np.float16, 30, [12, 12, 4, 14, 14]], [np.float16, 30, [12, 12, 3, 3, 3]],], - [[np.float16, 30, [12, 64, 4, 14, 14]], [np.float16, 30, [64, 64, 3, 3, 3]],], - [[np.float16, 30, [12, 25, 2, 7, 7]], [np.float16, 30, [25, 25, 3, 3, 3]],], - [[np.float16, 30, [12, 51, 1, 4, 4]], [np.float16, 30, [51, 51, 3, 3, 3]],], - [[np.float16, 30, [12, 50, 2, 7, 7]], [np.float16, 30, [50, 50, 3, 3, 3]],], - ] - for item in shape_format: - cpu_bias = torch.randn(item[1][2][1]) - npu_bias = copy.deepcopy(cpu_bias) - self.weight_grad.clear() - self.input_grad.clear() - cpu_input1, npu_input1 = create_common_tensor(item[0], -2, 2) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input2, npu_input2 = create_common_tensor(item[1], -2, 2) - if cpu_input2.dtype == torch.float16: - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2, bias1=cpu_bias) - npu_output = self.npu_op_exec(npu_input1, npu_input2, bias1=npu_bias) - - cpu_output = cpu_output.to(torch.float16) - npu_output = npu_output.to(torch.float16) - self.input_grad[0] = self.input_grad[0].to(torch.float16) - self.input_grad[1] = self.input_grad[1].to(torch.float16) - self.weight_grad[0] = self.weight_grad[0].to(self.weight_grad[1].dtype) - - self.assertRtolEqual(cpu_output.detach().numpy(), npu_output.detach().numpy()) - self.assertRtolEqual(self.input_grad[0].numpy(), self.input_grad[1].numpy()) - self.assertRtolEqual(self.weight_grad[0].numpy(), self.weight_grad[1].numpy()) - - def test_conv_transpose3d_backward_shape_format_fp32(self, device='npu'): - shape_format = [ - [[np.float32, 30, [12, 12, 4, 14, 14]], [np.float32, 30, [12, 12, 3, 3, 3]],], - [[np.float32, 30, [12, 64, 4, 14, 14]], [np.float32, 30, [64, 64, 3, 3, 3]],], - [[np.float32, 30, [12, 25, 2, 7, 7]], [np.float32, 30, [25, 25, 3, 3, 3]],], - [[np.float32, 30, [12, 51, 1, 4, 4]], [np.float32, 30, [51, 51, 3, 3, 3]],], - [[np.float32, 30, [12, 50, 2, 7, 7]], [np.float32, 30, [50, 50, 3, 3, 3]],], - ] - for item in shape_format: - cpu_bias = torch.randn(item[1][2][1]) - npu_bias = copy.deepcopy(cpu_bias) - self.weight_grad.clear() - self.input_grad.clear() - cpu_input1, npu_input1 = create_common_tensor(item[0], -2, 2) - cpu_input2, npu_input2 = create_common_tensor(item[1], -2, 2) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2, bias1=cpu_bias) - npu_output = self.npu_op_exec(npu_input1, npu_input2, bias1=npu_bias) - - self.weight_grad[0] = self.weight_grad[0].to(self.weight_grad[1].dtype) - - self.assertRtolEqual(cpu_output.detach().numpy(), npu_output.detach().numpy(), prec=1.e-1) - self.assertRtolEqual(self.input_grad[0].numpy(), self.input_grad[1].numpy(), prec=1.e-1) - self.assertRtolEqual(self.weight_grad[0].numpy(), self.weight_grad[1].numpy(), prec=1.e-1) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_cummaxmin_backward.py b/test/test_network_ops/test_cummaxmin_backward.py index d2252753ce..a6e12705a5 100644 --- a/test/test_network_ops/test_cummaxmin_backward.py +++ b/test/test_network_ops/test_cummaxmin_backward.py @@ -15,8 +15,8 @@ # limitations under the License. import torch -import numpy as np import torch_npu +import numpy as np from torch_npu.testing.testcase import TestCase, run_tests diff --git a/test/test_network_ops/test_div.py b/test/test_network_ops/test_div.py index 2ddc3d3356..4a0071a669 100644 --- a/test/test_network_ops/test_div.py +++ b/test/test_network_ops/test_div.py @@ -19,7 +19,7 @@ import torch_npu from torch_npu.testing.testcase import TestCase, run_tests from torch_npu.testing.common_utils import create_common_tensor, test_2args_broadcast, create_dtype_tensor -from torch_npu.testing.decorator import Dtypes, instantiate_tests, graph_mode +from torch_npu.testing.decorator import Dtypes, instantiate_tests @instantiate_tests @@ -42,8 +42,7 @@ class TestDiv(TestCase): npu_output = npu_out.to("cpu").numpy() return cpu_output, npu_output - @graph_mode - def test_div_broadcast(self): + def test_div_broadcast(self, device="npu"): for item in test_2args_broadcast(torch.div): self.assertRtolEqual(item[0], item[1]) @@ -55,9 +54,8 @@ class TestDiv(TestCase): cpu_input2, npu_input2 = create_dtype_tensor((2, 3, 4, 5), dtype, no_zero=True) cpu_output, npu_output = self.get_outputs([cpu_input1, cpu_input2], [npu_input1, npu_input2], dtype) self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_div_shape_format_fp16(self): + + def test_div_shape_format_fp16(self, device="npu"): format_list = [0, 3, 29] shape_list = [1, (64, 10), (32, 3, 3), (256, 2048, 7, 7)] shape_format = [ @@ -71,8 +69,7 @@ class TestDiv(TestCase): cpu_output, npu_output = self.get_outputs([cpu_input1, cpu_input2], [npu_input1, npu_input2], torch.half) self.assertRtolEqual(cpu_output, npu_output) - @graph_mode - def test_div_shape_format_fp32(self): + def test_div_shape_format_fp32(self, device="npu"): format_list = [0, 3, 29] shape_list = [1, (64, 10), (32, 3, 3), (256, 2048, 7, 7), (2, 0, 2)] shape_format = [ @@ -84,36 +81,31 @@ class TestDiv(TestCase): cpu_output, npu_output = self.get_outputs([cpu_input1, cpu_input2], [npu_input1, npu_input2], torch.float) self.assertRtolEqual(cpu_output, npu_output) - @graph_mode - def test_div_mix_dtype_1(self): + def test_div_mix_dtype_1(self, device="npu"): npu_input1, npu_input2 = create_common_tensor([np.int32, 0, (2, 3)], 1, 100) npu_input3, npu_input4 = create_common_tensor([np.float32, 0, (2, 3)], 1, 100) cpu_output, npu_output = self.get_outputs([npu_input1, npu_input3], [npu_input2, npu_input4], torch.float) self.assertRtolEqual(cpu_output, npu_output) - @graph_mode - def test_div_mix_dtype_2(self): + def test_div_mix_dtype_2(self, device="npu"): npu_input1, npu_input2 = create_common_tensor([np.float32, 0, (2, 3)], 1, 100) npu_input3 = torch.tensor(3).int() cpu_output, npu_output = self.get_outputs([npu_input1, npu_input3], [npu_input2, npu_input3], torch.float) self.assertRtolEqual(cpu_output, npu_output) - @graph_mode - def test_div_scalar_dtype(self): + def test_div_scalar_dtype(self, device="npu"): cpu_input1, npu_input1 = create_common_tensor([np.int32, 0, (2, 3)], 1, 100) cpu_output = cpu_input1 / 0.5 npu_output = npu_input1 / 0.5 self.assertRtolEqual(cpu_output, npu_output.cpu()) - @graph_mode - def test_div_npuscalar_dtype(self): + def test_div_npuscalar_dtype(self, device="npu"): cpu_input1, npu_input1 = create_common_tensor([np.int32, 0, (2, 3)], 1, 100) cpu_output = cpu_input1 / torch.tensor(0.5) npu_output = npu_input1 / torch.tensor(0.5).npu() self.assertRtolEqual(cpu_output, npu_output.cpu()) - @graph_mode - def test_div_shape_format_fp32_1(self): + def test_div_shape_format_fp32_1(self, device="npu"): format_list = [0, 3, 29] shape_list = [1, (64, 10), (32, 3, 3), (256, 2048, 7, 7)] shape_format = [ @@ -165,7 +157,6 @@ class TestDiv(TestCase): npu_output_inp = self.npu_op_exec_mode_inp(npu_input1, npu_input2, item[3]) self.assertRtolEqual(cpu_output, npu_output_inp) - @graph_mode def test_div_scalar_mode(self): shape_format = [ [[np.float32, 0, (20, 16)], 15.9, 'floor'], diff --git a/test/test_network_ops/test_divide.py b/test/test_network_ops/test_divide.py index 3f5157f2ed..61ad1fb19a 100644 --- a/test/test_network_ops/test_divide.py +++ b/test/test_network_ops/test_divide.py @@ -163,8 +163,6 @@ class TestDivide(TestCase): [[np.float16, 0, (2, 20, 16)], 72.2, 'floor'], [[np.float16, 0, (2, 20, 16)], -5.4, 'trunc'], [[np.float16, 0, (3, 20, 16)], -45.3, 'true'], - [[np.int32, 0, (20, 16)], 15.9, 'floor'], - [[np.int32, 0, (20, 16)], 17.2, 'trunc'], ] for item in shape_format: cpu_input, npu_input = create_common_tensor(item[0], 1, 100) diff --git a/test/test_network_ops/test_eq.py b/test/test_network_ops/test_eq.py index 236ad193fe..d18eca235c 100644 --- a/test/test_network_ops/test_eq.py +++ b/test/test_network_ops/test_eq.py @@ -17,7 +17,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor class TestEqual(TestCase): @@ -39,8 +38,7 @@ class TestEqual(TestCase): output = output.numpy() return output - @graph_mode - def test_equal_shape_format_fp32(self): + def test_equal_shape_format_fp32(self, device="npu"): dtype_list = [np.float32] format_list = [0, 3] shape_list = [[1024], [8, 128], [2, 8, 128], [2, 8, 128, 512]] @@ -53,9 +51,8 @@ class TestEqual(TestCase): cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) npu_output = self.npu_op_exec(npu_input1, npu_input2) self.assertEqual(cpu_output, npu_output) - - @graph_mode - def test_equal_shape_format_fp16(self): + + def test_equal_shape_format_fp16(self, device="npu"): dtype_list = [np.float16] format_list = [0, 3] shape_list = [[1024], [8, 128], [2, 8, 128], [2, 8, 128, 512]] @@ -74,8 +71,7 @@ class TestEqual(TestCase): cpu_output = cpu_output.astype(np.float16) self.assertEqual(cpu_output, npu_output) - @graph_mode - def test_equal_out_shape_format_fp32(self): + def test_equal_out_shape_format_fp32(self, device="npu"): dtype_list = [np.float32] format_list = [0] shape_list = [[1024], [8, 128], [2, 8, 128], [2, 8, 128, 512]] @@ -88,9 +84,8 @@ class TestEqual(TestCase): npu_output_out = self.npu_op_exec_out(npu_input1, npu_input2) npu_output = self.npu_op_exec(npu_input1, npu_input2) self.assertEqual(npu_output_out, npu_output) - - @graph_mode - def test_equal_scalar_out_shape_format_fp32(self): + + def test_equal_scalar_out_shape_format_fp32(self, device="npu"): dtype_list = [np.float32] format_list = [0] shape_list = [[1024], [8, 128], [2, 8, 128], [2, 8, 128, 512]] @@ -103,8 +98,7 @@ class TestEqual(TestCase): npu_output = self.npu_op_exec(npu_input1, 5) self.assertEqual(npu_output_out, npu_output) - @graph_mode - def test_equal_mix_dtype(self): + def test_equal_mix_dtype(self, device="npu"): npu_input1, npu_input2 = create_common_tensor([np.float16, 0, (2, 3)], 1, 100) npu_input3, npu_input4 = create_common_tensor([np.float32, 0, (2, 3)], 1, 100) cpu_output = self.cpu_op_exec(npu_input1, npu_input3) diff --git a/test/test_network_ops/test_exp.py b/test/test_network_ops/test_exp.py index 7734b6ebcf..7917c39ed8 100644 --- a/test/test_network_ops/test_exp.py +++ b/test/test_network_ops/test_exp.py @@ -17,7 +17,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor @@ -33,8 +32,7 @@ class TestExp(TestCase): output = output.numpy() return output - @graph_mode - def test_exp_shape_format_fp16(self): + def test_exp_shape_format_fp16(self, device="npu"): format_list = [0, 3] shape_list = [[5], [2, 4], [2, 2, 4], [2, 3, 3, 4]] shape_format = [ @@ -47,9 +45,8 @@ class TestExp(TestCase): npu_output = self.npu_op_exec(npu_input) cpu_output = cpu_output.astype(npu_output.dtype) self.assertRtolEqual(cpu_output, npu_output) - - @graph_mode - def test_exp_shape_format_fp32(self): + + def test_exp_shape_format_fp32(self, device="npu"): format_list = [0, 3] shape_list = [[5], [2, 4], [2, 2, 4], [2, 3, 3, 4]] shape_format = [ diff --git a/test/test_network_ops/test_fill.py b/test/test_network_ops/test_fill.py deleted file mode 100644 index 9bbcd7dea0..0000000000 --- a/test/test_network_ops/test_fill.py +++ /dev/null @@ -1,76 +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 torch -import torch_npu -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestFill_(TestCase): - def cpu_op_exec(self, input1, input2): - output = torch.fill_(input1, input2) - output = output.numpy() - return output - - def npu_op_exec(self, input1, input2): - output = torch.fill_(input1, input2) - output = output.to("cpu") - output = output.numpy() - return output - - def test_fills_shape_format_fp16(self, device='npu'): - format_list = [0, 3] - shape_list = [[1024], [32, 1024], [32, 8, 1024], [128, 32, 8, 1024]] - value_list = [0.8, 1.25, torch.tensor(0.8), torch.tensor(1.25)] - shape_format = [ - [[np.float16, i, j], v] for i in format_list for j in shape_list for v in value_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], 0, 100) - cpu_output = self.cpu_op_exec(cpu_input1, item[1]) - npu_output = self.npu_op_exec(npu_input1, item[1]) - self.assertRtolEqual(cpu_output, npu_output) - - def test_fill_shape_format_fp32(self, device='npu'): - format_list = [0, 3] - shape_list = [[1024], [32, 1024], [32, 8, 1024], [128, 32, 8, 1024]] - value_list = [0.8, 1.25, torch.tensor(0.8), torch.tensor(1.25)] - shape_format = [ - [[np.float32, i, j], v] for i in format_list for j in shape_list for v in value_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], 0, 100) - cpu_output = self.cpu_op_exec(cpu_input1, item[1]) - npu_output = self.npu_op_exec(npu_input1, item[1]) - self.assertRtolEqual(cpu_output, npu_output) - - def test_fill_zero_dim_shape_format(self, device='npu'): - dtype_list = [torch.float16, torch.float32] - init_list = [3, 73, 1000] - value_list = [0.8, 1.25, torch.tensor(0.8), torch.tensor(1.25)] - shape_format = [ - [i, j, v] for i in dtype_list for j in init_list for v in value_list - ] - for item in shape_format: - cpu_input1 = torch.tensor(item[1], dtype=item[0]) - npu_input1 = cpu_input1.npu() - cpu_output = self.cpu_op_exec(cpu_input1, item[2]) - npu_output = self.npu_op_exec(npu_input1, item[2]) - self.assertRtolEqual(cpu_output, npu_output) - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_floatstatus.py b/test/test_network_ops/test_floatstatus.py deleted file mode 100644 index d7d8e10bf1..0000000000 --- a/test/test_network_ops/test_floatstatus.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests - -class TestFloatStatus(TestCase): - def npu_op_exec(self, input1): - output = torch.npu_alloc_float_status(input1) - output = output.to("cpu") - output = output.numpy() - return output - - def test_floatstatus(self, device='npu'): - input1 = torch.randn([1,2,3]).npu() - exoutput = torch.tensor([0., 0., 0., 0., 0., 0., 0., 0.]) - output = self.npu_op_exec(input1) - self.assertRtolEqual(exoutput.numpy(), output) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_indexing.py b/test/test_network_ops/test_indexing.py deleted file mode 100644 index 7a25f0ff90..0000000000 --- a/test/test_network_ops/test_indexing.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor -from torch_npu.testing.decorator import Dtypes, instantiate_tests - - -@instantiate_tests -class TestIndexing(TestCase): - @Dtypes(torch.float, torch.half, torch.int32, torch.uint8, torch.int8, torch.int16, torch.long) - def test_indexing(self, device, dtype): - input1 = torch.tensor([[1, 2, 3, 4],[5, 6, 7, 8]], dtype=dtype).to("npu") - expect_output = torch.tensor([[1, 2],[5, 6]], dtype=dtype) - output = torch.npu_indexing(input1, [0, 0], [2, 2], [1, 1]) - self.assertRtolEqual(expect_output, output.cpu()) - - -if __name__ == "__main__": - run_tests() - diff --git a/test/test_network_ops/test_log_add_exp2.py b/test/test_network_ops/test_log_add_exp2.py deleted file mode 100644 index 6d8999b2b4..0000000000 --- a/test/test_network_ops/test_log_add_exp2.py +++ /dev/null @@ -1,67 +0,0 @@ -# Copyright (c) 2022, Huawei Technologies.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 torch -import numpy as np -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestLogAddExp2(TestCase): - def cpu_op_exec(self, input1, input2): - output = torch.logaddexp2(input1, input2) - output = output.numpy() - return output - - def npu_op_exec(self, input1, input2): - output = torch.logaddexp2(input1, input2) - output = output.to("cpu") - output = output.numpy() - return output - - def npu_op_exec_out(self, input1, input2, out): - torch.logaddexp2(input1, input2, out = out) - output = out.to("cpu") - output = output.numpy() - return output - - def test_logaddexp2_common_shape_format(self): - shape_format =[ - [[np.float16, 0, [1, 2, 3, 4]], [np.float16, 0, [1, 2, 3, 4]]], - [[np.float16, 0, [2, 4]], [np.float16, 0, [2, 4]]], - [[np.float32, 0, [7, 35, 90]], [np.float32, 0, [7, 35, 90]]], - [[np.float32, 0, [4, 128]], [np.float32, 0, [4, 128]]], - [[np.float16, 2, [32, 64]], [np.float16, 2, [32, 64]]], - [[np.float16, 3, [32, 64, 128]], [np.float16, 3, [32, 64, 128]]], - [[np.float32, 2, [32, 64]], [np.float32, 2, [32, 64]]], - [[np.float32, 3, [32, 64, 128]], [np.float32, 3, [32, 64, 128]]], - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], 9, 10) - cpu_input2, npu_input2 = create_common_tensor(item[0], 9, 10) - cpu_out, npu_out = create_common_tensor(item[1], 9, 10) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - if cpu_input2.dtype == torch.float16: - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output = self.npu_op_exec(npu_input1, npu_input2) - npu_output_out = self.npu_op_exec_out(npu_input1, npu_input2, npu_out) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - self.assertRtolEqual(cpu_output, npu_output_out) - -if __name__ == "__main__": - run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_logaddexp.py b/test/test_network_ops/test_logaddexp.py deleted file mode 100644 index 46951cb7b6..0000000000 --- a/test/test_network_ops/test_logaddexp.py +++ /dev/null @@ -1,65 +0,0 @@ -# Copyright (c) 2022, Huawei Technologies.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 torch -import numpy as np -import torch_npu -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor -class TestLogAddExp(TestCase): - def cpu_op_exec(self, input1, input2): - output = torch.logaddexp(input1, input2) - output = output.numpy() - return output - - def npu_op_exec(self, input1, input2): - output = torch.logaddexp(input1, input2) - output = output.to("cpu") - output = output.numpy() - return output - - def npu_op_exec_out(self, input1, input2, out): - torch.logaddexp(input1, input2, out = out) - output = out.to("cpu") - output = output.numpy() - return output - - def test_logaddexp_common_shape_format(self): - shape_format =[ - [[np.float16, 0, [1, 2, 3, 4]], [np.float16, 0, [1, 2, 3, 4]]], - [[np.float16, 0, [2, 4]], [np.float16, 0, [2, 4]]], - [[np.float32, 0, [7, 35, 90]], [np.float32, 0, [7, 35, 90]]], - [[np.float32, 0, [4, 128]], [np.float32, 0, [4, 128]]], - [[np.float16, 2, [32, 64]], [np.float16, 2, [32, 64]]], - [[np.float16, 3, [32, 64, 128]], [np.float16, 3, [32, 64, 128]]], - [[np.float32, 2, [32, 64]], [np.float32, 2, [32, 64]]], - [[np.float32, 3, [32, 64, 128]], [np.float32, 3, [32, 64, 128]]], - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -1, 1) - cpu_input2, npu_input2 = create_common_tensor(item[0], -1, 1) - cpu_out, npu_out = create_common_tensor(item[1], -1, 1) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - if cpu_input2.dtype == torch.float16: - cpu_input2 = cpu_input2.to(torch.float32) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output = self.npu_op_exec(npu_input1, npu_input2) - npu_output_out = self.npu_op_exec_out(npu_input1, npu_input2, npu_out) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - self.assertRtolEqual(cpu_output, npu_output_out) - -if __name__ == "__main__": - run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_masked_fill.py b/test/test_network_ops/test_masked_fill.py index 473f64b2c6..13ec782ff7 100644 --- a/test/test_network_ops/test_masked_fill.py +++ b/test/test_network_ops/test_masked_fill.py @@ -33,8 +33,6 @@ class TestMaskedFill(TestCase): return output def npu_op_exec(self, input1, mask, value): - if torch.is_tensor(value) and value.device.type != 'npu': - value = value.to("npu") output = torch.masked_fill(input1, mask, value) output = output.to("cpu") output = output.numpy() @@ -46,8 +44,6 @@ class TestMaskedFill(TestCase): return output def npu_inp_op_exec(self, input1, mask, value): - if torch.is_tensor(value) and value.device.type != 'npu': - value = value.to("npu") output = input1.masked_fill_(mask, value) output = output.to("cpu") output = output.numpy() diff --git a/test/test_network_ops/test_max_backward.py b/test/test_network_ops/test_max_backward.py index b2582ecd58..7e3ab30989 100644 --- a/test/test_network_ops/test_max_backward.py +++ b/test/test_network_ops/test_max_backward.py @@ -13,9 +13,8 @@ # limitations under the License. import torch -import numpy as np - import torch_npu +import numpy as np from torch_npu.testing.testcase import TestCase, run_tests from torch_npu.testing.common_utils import create_common_tensor diff --git a/test/test_network_ops/test_min_backward.py b/test/test_network_ops/test_min_backward.py index 12b6ed44e9..dfa4199347 100644 --- a/test/test_network_ops/test_min_backward.py +++ b/test/test_network_ops/test_min_backward.py @@ -13,9 +13,8 @@ # limitations under the License. import torch -import numpy as np - import torch_npu +import numpy as np from torch_npu.testing.testcase import TestCase, run_tests from torch_npu.testing.common_utils import create_common_tensor diff --git a/test/test_network_ops/test_mm.py b/test/test_network_ops/test_mm.py index bbeef10bff..9f858614aa 100644 --- a/test/test_network_ops/test_mm.py +++ b/test/test_network_ops/test_mm.py @@ -16,20 +16,18 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor class TestMM(TestCase): - @graph_mode - def test_mm_mat1_mat2_transpose(self): + def test_mm_mat1_mat2_transpose(self, device="npu"): dtype_list = [np.float16, np.float32] format_list = [2, 29] shape_list = [ - [8, 16], - [8, 15], - [7, 16], - [7, 15] + [16, 32], + [16, 30], + [15, 32], + [15, 30] ] shape_format = [ [i, j, k] for i in dtype_list for j in format_list for k in shape_list @@ -43,15 +41,14 @@ class TestMM(TestCase): cpu_out = torch.mm(cpu_input, cpu_input.t()) self.assertRtolEqual(npu_out.to("cpu").numpy(), cpu_out.to(npu_out.dtype).numpy()) - @graph_mode - def test_mm_mat1_view_mat2_view_transpose(self): + def test_mm_mat1_view_mat2_view_transpose(self, device="npu"): dtype_list = [np.float16, np.float32] format_list = [2, 29] shape_list = [ - [2, 7, 5], - [2, 8, 5], - [2, 8, 8], - [2, 7, 8] + [2, 15, 10], + [2, 16, 10], + [2, 16, 16], + [2, 15, 16] ] shape_format = [ [i, j, k] for i in dtype_list for j in format_list for k in shape_list diff --git a/test/test_network_ops/test_mul.py b/test/test_network_ops/test_muls.py similarity index 100% rename from test/test_network_ops/test_mul.py rename to test/test_network_ops/test_muls.py diff --git a/test/test_network_ops/test_multi_head_attention.py b/test/test_network_ops/test_multi_head_attention.py index ffcce4f009..792ec96975 100644 --- a/test/test_network_ops/test_multi_head_attention.py +++ b/test/test_network_ops/test_multi_head_attention.py @@ -13,11 +13,10 @@ # limitations under the License. import torch +import torch_npu import torch.nn.functional as F import numpy as np -import torch_npu - from torch_npu.testing.testcase import TestCase, run_tests diff --git a/test/test_network_ops/test_mv.py b/test/test_network_ops/test_mv.py deleted file mode 100644 index 493e447c7d..0000000000 --- a/test/test_network_ops/test_mv.py +++ /dev/null @@ -1,80 +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 torch -import torch_npu -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestMv(TestCase): - def cpu_op_exec(self, input1, input2): - cpu_output = torch.mv(input1, input2) - cpu_output = cpu_output.numpy() - return cpu_output - - def npu_op_exec(self, input1, input2): - npu_output = torch.mv(input1, input2) - npu_output = npu_output.cpu() - npu_output = npu_output.numpy() - return npu_output - - def npu_op_exec_out(self, input1, input2, output): - torch.mv(input1, input2, out=output) - output = output.cpu() - output = output.numpy() - return output - - def test_mv_shape_format(self, device='npu'): - shape_format = [ - [[np.float32, -1, (3, 3)], [np.float32, -1, (3)]], - [[np.float32, -1, (5, 8)], [np.float32, -1, (8)]], - [[np.float32, -1, (8, 9)], [np.float32, -1, (9)]], - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_input2, npu_input2 = create_common_tensor(item[1], -100, 100) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output = self.npu_op_exec(npu_input1, npu_input2) - self.assertRtolEqual(cpu_output, npu_output) - - def test_mv_out_shape_format(self, device='npu'): - shape_format = [ - [[np.float32, -1, (3, 3)], [np.float32, -1, (3)], [np.float32, -1, (3)]], - [[np.float32, -1, (5, 8)], [np.float32, -1, (8)], [np.float32, -1, (5)]], - [[np.float32, -1, (8, 9)], [np.float32, -1, (9)], [np.float32, -1, (8)]], - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_input2, npu_input2 = create_common_tensor(item[1], -100, 100) - cpu_input3, npu_input3 = create_common_tensor(item[2], -100, 100) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output = self.npu_op_exec_out(npu_input1, npu_input2, npu_input3) - self.assertRtolEqual(cpu_output, npu_output) - - def test_mv_with_transpose(self, device='npu'): - cpu_mat = torch.rand(1, 256) - npu_mat = cpu_mat.npu() - cpu_vec = torch.tensor([1.]) - npu_vec = cpu_vec.npu() - - cpu_mv = torch.mv(cpu_mat.t(), cpu_vec) - npu_mv = torch.mv(npu_mat.t(), npu_vec) - self.assertRtolEqual(cpu_mv, npu_mv.cpu()) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_ne.py b/test/test_network_ops/test_ne.py index 74913faa81..395f7bca4f 100644 --- a/test/test_network_ops/test_ne.py +++ b/test/test_network_ops/test_ne.py @@ -49,20 +49,6 @@ class TestNe(TestCase): output = input3.to("cpu") output = output.numpy() return output - - def test_ne_shape_format_int32(self): - dtype_list = [np.int32] - format_list = [0, 3] - shape_list = [[1024], [8, 128], [2, 8, 128], [2, 8, 128, 512]] - shape_format = [ - [d, i, j] for d in dtype_list for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 1, 100) - cpu_input2, npu_input2 = create_common_tensor(item, 1, 100) - cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2) - npu_output = self.npu_op_exec(npu_input1, npu_input2) - self.assertEqual(cpu_output, npu_output) def test_ne_shape_format_fp32(self): dtype_list = [np.float32] diff --git a/test/test_network_ops/test_nllloss.py b/test/test_network_ops/test_nllloss.py deleted file mode 100644 index d263d03e90..0000000000 --- a/test/test_network_ops/test_nllloss.py +++ /dev/null @@ -1,83 +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 torch -import torch_npu -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestNllloss(TestCase): - def cpu_op_exec_new(self, input1, target, reduction, ignore_index): - if not ignore_index: - ignore_index = -100 # 默认值 - output = torch.nn.functional.nll_loss(input1, target, reduction=reduction, ignore_index=ignore_index) - output = output.numpy() - return output - - def npu_op_exec_new(self, input1, target, reduction, ignore_index): - if not ignore_index: - ignore_index = -100 # 默认值 - target = target.to(torch.int32) - target = target.to("npu") - output = torch.nn.functional.nll_loss(input1, target, reduction=reduction, ignore_index=ignore_index) - output = output.to("cpu") - output = output.numpy() - return output - - def test_nllloss_shape_format_fp32(self, device='npu'): - # 当前仅支持设置正数, 若np.sum(ignore_index == np_target) == 0,则ignore_index设置任意数值不影响 - ignore_index = 1 - for reduction in ['mean', 'none', 'sum']: - shape_format = [ - [[np.float32, 0, [256, 100]], [np.int32, 0, [256]], reduction, None], - [[np.float32, 3, [256, 100]], [np.int32, 0, [256]], reduction, ignore_index], - [[np.float32, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float32, 3, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float32, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, None], - ] - for item in shape_format: - np_target = np.random.randint(0, item[0][2][1], (item[1][2])).astype(np.long) - target = torch.from_numpy(np_target) - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_output = self.cpu_op_exec_new(cpu_input1, target, item[2], item[3]) - npu_output = self.npu_op_exec_new(npu_input1, target, item[2], item[3]) - self.assertRtolEqual(cpu_output, npu_output) - - def test_nllloss_shape_format_fp16(self, device='npu'): - # 当前仅支持设置正数, 若np.sum(ignore_index == np_target) == 0,则ignore_index设置任意数值不影响 - ignore_index = 1 - for reduction in ['mean', 'none', 'sum']: - shape_format = [ - [[np.float16, 0, [256, 100]], [np.int32, 0, [256]], reduction, ignore_index], - [[np.float16, 3, [256, 100]], [np.int32, 0, [256]], reduction, ignore_index], - [[np.float16, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float16, 3, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float16, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, None], - ] - for item in shape_format: - np_target = np.random.uniform(0, item[0][2][1], (item[1][2])).astype(np.long) - target = torch.from_numpy(np_target) - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output = self.cpu_op_exec_new(cpu_input1, target, item[2], item[3]) - npu_output = self.npu_op_exec_new(npu_input1, target, item[2], item[3]) - cpu_output = cpu_output.astype(np.float16) - self.assertRtolEqual(cpu_output, npu_output) - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_nllloss_backward.py b/test/test_network_ops/test_nllloss_backward.py deleted file mode 100644 index ea4111c4df..0000000000 --- a/test/test_network_ops/test_nllloss_backward.py +++ /dev/null @@ -1,95 +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 torch -import torch_npu -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestNlllossbackward(TestCase): - def cpu_op_exec_new(self, input1, target, reduction, ignore_index): - if not ignore_index: - ignore_index = -100 # 默认值 - input1.requires_grad_(True) - output = torch.nn.functional.nll_loss(input1, target, reduction=reduction, ignore_index=ignore_index) - input_cpu = output.detach().numpy() - output.backward(torch.ones_like(output)) - res = input1.grad - res = res.numpy() - return input_cpu, res - - def npu_op_exec_new(self, input1, target, reduction, ignore_index): - if not ignore_index: - ignore_index = -100 # 默认值 - target = target.to(torch.int32) - target = target.to("npu") - input1.requires_grad_(True) - output = torch.nn.functional.nll_loss(input1, target, reduction=reduction, ignore_index=ignore_index) - output.backward(torch.ones_like(output)) - input_npu = output.to("cpu") - input_npu = input_npu.detach().numpy() - res = input1.grad.to("cpu") - res = res.numpy() - return input_npu, res - - def test_nllloss_shape_format_fp32(self, device='npu'): - # 当前仅支持设置正数, 若np.sum(ignore_index == np_target) == 0,则ignore_index设置任意数值不影响 - ignore_index = 1 - for reduction in ['mean', 'none', 'sum']: - shape_format = [ - [[np.float32, 0, [256, 100]], [np.int32, 0, [256]], reduction, None], - [[np.float32, 3, [256, 100]], [np.int32, 0, [256]], reduction, ignore_index], - [[np.float32, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float32, 3, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float32, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, None], - ] - for item in shape_format: - np_target = np.random.randint(0, item[0][2][1], (item[1][2])).astype(np.long) - target = torch.from_numpy(np_target) - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_input, cpu_output = self.cpu_op_exec_new(cpu_input1, target, item[2], item[3]) - npu_input, npu_output = self.npu_op_exec_new(npu_input1, target, item[2], item[3]) - self.assertRtolEqual(cpu_input, npu_input) - self.assertRtolEqual(cpu_output, npu_output) - - def test_nllloss_shape_format_fp16(self, device='npu'): - # 当前仅支持设置正数, 若np.sum(ignore_index == np_target) == 0,则ignore_index设置任意数值不影响 - ignore_index = 1 - for reduction in ['mean', 'none', 'sum']: - shape_format = [ - [[np.float16, 0, [256, 100]], [np.int32, 0, [256]], reduction, ignore_index], - [[np.float16, 3, [256, 100]], [np.int32, 0, [256]], reduction, ignore_index], - [[np.float16, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float16, 3, [4800, 3003]], [np.int32, 0, [4800]], reduction, ignore_index], - [[np.float16, 0, [4800, 3003]], [np.int32, 0, [4800]], reduction, None], - ] - for item in shape_format: - np_target = np.random.uniform(0, item[0][2][1], (item[1][2])).astype(np.long) - target = torch.from_numpy(np_target) - cpu_input1, npu_input1 = create_common_tensor(item[0], -100, 100) - cpu_input1 = cpu_input1.to(torch.float32) - cpu_input, cpu_output = self.cpu_op_exec_new(cpu_input1, target, item[2], item[3]) - npu_input, npu_output = self.npu_op_exec_new(npu_input1, target, item[2], item[3]) - cpu_input = cpu_input.astype(np.float16) - cpu_output = cpu_output.astype(np.float16) - self.assertRtolEqual(cpu_input, npu_input) - self.assertRtolEqual(cpu_output, npu_output) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_normal.py b/test/test_network_ops/test_normal.py deleted file mode 100644 index cf31a459fc..0000000000 --- a/test/test_network_ops/test_normal.py +++ /dev/null @@ -1,66 +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 sys -import torch -import torch_npu -import numpy as np -import torch.nn as nn -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor -from torch_npu.testing.decorator import Dtypes, instantiate_tests - -@instantiate_tests -class TestNormal(TestCase): - @Dtypes(torch.float) # torch.float16 - def test_normal(self, dtype=torch.float16): - q = torch.empty(100, 100, dtype=dtype, device="cpu").to("npu") - q.normal_() - self.assertEqual(q.mean(), 0, 0.2) - self.assertEqual(q.to("cpu").to(torch.float).std(), 1, 0.2) - - q.normal_(2, 3) - self.assertEqual(q.mean(), 2, 0.3) - self.assertEqual(q.to("cpu").to(torch.float).std(), 3, 0.3) - - mean = torch.empty(100, 100, dtype=dtype, device="cpu").to("npu") - std = torch.empty(100, 100, dtype=dtype, device="cpu").to("npu") - mean.fill_(-2) - std.fill_(3) - - r = torch.normal(mean) - self.assertEqual(r.mean(), -2, 0.2) - self.assertEqual(r.to("cpu").to(torch.float).std(), 1, 0.2) - - r = torch.normal(mean, 3) - self.assertEqual(r.mean(), -2, 0.2) - self.assertEqual(r.to("cpu").to(torch.float).std(), 3, 0.2) - - r = torch.normal(2, std) - self.assertEqual(r.mean(), 2, 0.2) - self.assertEqual(r.to("cpu").to(torch.float).std(), 3, 0.2) - - r = torch.normal(mean, std) - self.assertEqual(r.mean(), -2, 0.2) - self.assertEqual(r.to("cpu").to(torch.float).std(), 3, 0.3) - - r = torch.normal(2, 3, (100, 100)) - self.assertEqual(r.mean(), 2, 0.2) - self.assertEqual(r.to("cpu").to(torch.float).std(), 3, 0.2) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_normalization.py b/test/test_network_ops/test_normalization.py deleted file mode 100644 index 5c1d4a0922..0000000000 --- a/test/test_network_ops/test_normalization.py +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestNormalization(TestCase): - def op_exec(self, npu_flag, input1, dim): - m = torch.nn.BatchNorm2d(dim) - if npu_flag: - m = m.to("npu") - input_new = m(input1) - if npu_flag: - input_new = input_new.to("cpu") - input_new = input_new.detach().numpy() - input1.requires_grad_(True) - w = torch.ones_like(input1) - if npu_flag: - w = w.to("npu") - tmp = m(input1) - tmp.backward(w) - output = input1.grad - if npu_flag: - output = output.to("cpu") - output = output.detach().numpy() - return output, input_new - - def test_batchnorm_shape_format_fp16(self, device='npu'): - format_list = [0] - shape_list = [[256, 672, 7, 7],[1024, 58, 28, 28]] - shape_format = [ - [np.float16, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output, cpu_input = self.op_exec(0, cpu_input1, item[2][1]) - npu_output, npu_input = self.op_exec(1, npu_input1, item[2][1]) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - cpu_input = cpu_input.astype(npu_input.dtype) - self.assertRtolEqual(cpu_input, npu_input) - - def test_batchnorm_shape_format_fp32(self, device='npu'): - format_list = [0] - shape_list = [(256, 32, 112, 112)] - shape_format = [ - [np.float32, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - cpu_output, cpu_input = self.op_exec(0, cpu_input1, item[2][1]) - npu_output, npu_input = self.op_exec(1, npu_input1, item[2][1]) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - cpu_input = cpu_input.astype(npu_input.dtype) - self.assertRtolEqual(cpu_input, npu_input) - - -if __name__ == "__main__": - run_tests() - diff --git a/test/test_network_ops/test_one_hot.py b/test/test_network_ops/test_one_hot.py index 16c427e701..52538e0a8e 100644 --- a/test/test_network_ops/test_one_hot.py +++ b/test/test_network_ops/test_one_hot.py @@ -75,13 +75,6 @@ class TestOneHot(TestCase): npu_output = self.npu_op_exec(input1, 12) self.assertRtolEqual(cpu_output, npu_output) - def test_one_hot_aicpu_bug(self): - input1 = torch.randint(0, 4, size=(4, 64, 64, 64)).npu() - cpu_output = self.cpu_op_exec(input1.cpu(), 4) - npu_output = self.npu_op_exec(input1, 4) - - self.assertRtolEqual(cpu_output, npu_output) - if __name__ == "__main__": run_tests() diff --git a/test/test_network_ops/test_ones_like.py b/test/test_network_ops/test_ones_like.py deleted file mode 100644 index 5da78d6e50..0000000000 --- a/test/test_network_ops/test_ones_like.py +++ /dev/null @@ -1,86 +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 torch -import numpy as np -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode -from torch_npu.testing.common_utils import create_common_tensor - -class TestOnesLike(TestCase): - - def cpu_op_exec(self, input1): - output = torch.ones_like(input1) - output = output.numpy() - return output - - def npu_op_exec(self, input1): - output = torch.ones_like(input1) - output = output.to('cpu') - output = output.numpy() - return output - - @graph_mode - def test_ones_like_shape_format(self): - shape_format = [ - [np.float32, -1, (3, )], - [np.float32, -1, (2, 4)], - [np.float32, -1, (3, 6, 9)], - [np.int8, -1, (3,)], - [np.int8, -1, (2, 4)], - [np.int8, -1, (3, 6, 9)], - [np.int32, -1, (3,)], - [np.int32, -1, (2, 4)], - [np.int32, -1, (3, 6, 9)], - [np.uint8, -1, (3,)], - [np.uint8, -1, (2, 4)], - [np.uint8, -1, (3, 6, 9)] - ] - - for item in shape_format: - cpu_input, npu_input = create_common_tensor(item, 1, 100) - - cpu_output = self.cpu_op_exec(cpu_input) - npu_output = self.npu_op_exec(npu_input) - - self.assertRtolEqual(cpu_output, npu_output) - - - @graph_mode - def test_ones_like_float16_shape_format(self): - shape_format = [ - [np.float16, -1, (3, )], - [np.float16, -1, (2, 4)], - [np.float16, -1, (3, 6, 9)], - [np.float16, -1, (3, 4, 5, 12)] - ] - - for item in shape_format: - cpu_input, npu_input = create_common_tensor(item, 1, 100) - - cpu_input = cpu_input.to(torch.float32) - - cpu_output = self.cpu_op_exec(cpu_input) - npu_output = self.npu_op_exec(npu_input) - - cpu_output = cpu_output.astype(np.float16) - - self.assertRtolEqual(cpu_output, npu_output) - -if __name__ == "__main__": - run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_pooling.py b/test/test_network_ops/test_pooling.py deleted file mode 100644 index 4014bc38c0..0000000000 --- a/test/test_network_ops/test_pooling.py +++ /dev/null @@ -1,51 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests - -class TestPooling(TestCase): - def generate_single_data(self, min_val, max_val, shape, dtype): - input1 = np.random.uniform(min_val, max_val, shape).astype(dtype) - npu_input1 = torch.from_numpy(input1) - return npu_input1 - - def cpu_op_exec(self, input_data): - output = torch.max_pool2d(input_data,2) - return output - - def npu_op_exec(self, input_data): - input_npu = input_data.to('npu') - output = torch.max_pool2d(input_npu, 2) - output = output.to("cpu") - return output - - def test_maxpool_float16(self,device='npu'): - params = [ - [-100, 10, (200, 10, 100, 60), np.float16], - [-100, 50, (20, 10, 5, 10), np.float16] - ] - for para in params: - input_data = self.generate_single_data(*para) - input_data = input_data.to(torch.float32) - cpu_output = self.cpu_op_exec(input_data) - npu_output = self.npu_op_exec(input_data) - self.assertRtolEqual(cpu_output, npu_output) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_reciprocal.py b/test/test_network_ops/test_reciprocal.py deleted file mode 100644 index bf13aff6bb..0000000000 --- a/test/test_network_ops/test_reciprocal.py +++ /dev/null @@ -1,156 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestReciprocal(TestCase): - def cpu_op_exec(self, input1): - output = torch.reciprocal(input1) - output = output.numpy() - return output - - def npu_op_exec(self, input1): - output = torch.reciprocal(input1) - output = output.to("cpu") - output = output.numpy() - return output - - def npu_op_exec_out(self, input1, input2): - output = input2.to("npu") - torch.reciprocal(input1, out=output) - output = output.to("cpu") - output = output.numpy() - return output - - def cpu_inp_op_exec(self, input1): - output = torch.reciprocal_(input1) - output = output.numpy() - return output - - def npu_inp_op_exec(self, input1): - output = torch.reciprocal_(input1) - output = input1.to("cpu") - output = output.numpy() - return output - - def reciprocal_result(self, shape_format): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output = self.cpu_op_exec(cpu_input1) - npu_output = self.npu_op_exec(npu_input1) - cpu_output_inp = self.cpu_inp_op_exec(cpu_input1) - npu_output_inp = self.npu_inp_op_exec(npu_input1) - cpu_output = cpu_output.astype(npu_output.dtype) - cpu_output_inp = cpu_output_inp.astype(npu_output_inp.dtype) - - self.assertRtolEqual(cpu_output, npu_output) - self.assertRtolEqual(cpu_output_inp, npu_output_inp) - - def reciprocal_result_out(self, shape_format): - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item[0], 0, 100) - cpu_input2, npu_input2 = create_common_tensor(item[1], 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output = self.cpu_op_exec(cpu_input1) - npu_output_out = self.npu_op_exec_out(npu_input1, npu_input2) - cpu_output = cpu_output.astype(npu_output_out.dtype) - - self.assertRtolEqual(cpu_output, npu_output_out) - - def test_reciprocal_shape_format_fp16_out(self, device='npu'): - shape_format = [[[np.float16, 0, [18]], [np.float16, 0, [18, 20]]], - [[np.float16, 0, [18, 20, 30]], [np.float16, 0, [18, 20, 30]]], - [[np.float16, 0, [18, 10, 10, 20]], [np.float16, 0, [18, 10, 20]]], - [[np.float16, 3, [18]], [np.float16, 3, [18, 20]]], - [[np.float16, 3, [18, 20, 30]], [np.float16, 3, [18, 20, 30]]], - [[np.float16, 3, [18, 10, 10, 20]], [np.float16, 3, [18, 10, 20]]], - [[np.float16, 4, [18]], [np.float16, 4, [18, 20]]], - [[np.float16, 4, [18, 20, 30]], [np.float16, 4, [18, 20, 30]]], - [[np.float16, 4, [18, 10, 10, 20]], [np.float16, 4, [18, 10, 20]]], - ] - self.reciprocal_result_out(shape_format) - - def test_reciprocal_shape_format_fp32_out(self, device='npu'): - shape_format = [[[np.float32, 0, [18]], [np.float32, 0, [18, 20]]], - [[np.float32, 0, [18, 20, 30]], [np.float32, 0, [18, 20, 30]]], - [[np.float32, 0, [18, 10, 10, 20]], [np.float32, 0, [18, 10, 20]]], - [[np.float32, 3, [18]], [np.float32, 3, [18, 20]]], - [[np.float32, 3, [18, 20, 30]], [np.float32, 3, [18, 20, 30]]], - [[np.float32, 3, [18, 10, 10, 20]], [np.float32, 3, [18, 10, 20]]], - [[np.float32, 4, [18]], [np.float32, 4, [18, 20]]], - [[np.float32, 4, [18, 20, 30]], [np.float32, 4, [18, 20, 30]]], - [[np.float32, 4, [18, 10, 10, 20]], [np.float32, 4, [18, 10, 20]]], - ] - self.reciprocal_result_out(shape_format) - - def test_reciprocal_shape_format_fp16_1d(self, device='npu'): - format_list = [0, 3, 4] - shape_format = [[np.float16, i, [18]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp32_1d(self, device='npu'): - format_list = [0, 3, 4] - shape_format = [[np.float32, i, [256]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp16_2d(self, device='npu'): - format_list = [0, 3, 4, 29] - shape_format = [[np.float16, i, [64, 516]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp32_2d(self, device='npu'): - format_list = [0, 3, 4, 29] - shape_format = [[np.float32, i, [64, 516]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp16_3d(self, device='npu'): - format_list = [0, 3, 4, 29] - shape_format = [[np.float16, i, [64, 124, 516]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp32_3d(self, device='npu'): - format_list = [0, 3, 4, 29] - shape_format = [[np.float32, i, [64, 124, 516]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp16_4d(self, device='npu'): - format_list = [0, 3, 4, 29] - shape_format = [[np.float16, i, [64, 128, 516, 32]] for i in format_list - ] - self.reciprocal_result(shape_format) - - def test_reciprocal_shape_format_fp32_4d(self, device='npu'): - format_list = [0, 3, 4, 29] - shape_format = [[np.float32, i, [64, 128, 516, 32]] for i in format_list - ] - self.reciprocal_result(shape_format) - - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_relu.py b/test/test_network_ops/test_relu.py deleted file mode 100644 index 9669cff23b..0000000000 --- a/test/test_network_ops/test_relu.py +++ /dev/null @@ -1,106 +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 torch -import torch_npu -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestRelu(TestCase): - def cpu_op_back_exec(self, input1): - w = torch.ones_like(input1) - input1.requires_grad_(True) - output = torch.relu(input1) - output.backward(w) - res = input1.grad - res = res.numpy() - return output.detach().numpy(), res - - def npu_op_back_exec(self, input1): - w = torch.ones_like(input1) - input1.requires_grad_(True) - output = torch.relu(input1) - output.backward(w) - output = output.to("cpu") - res = input1.grad.to("cpu") - res = res.numpy() - return output.detach().numpy(), res - - def cpu_inp_op_exec(self, input1): - output = torch.relu_(input1) - output = output.numpy() - return output - - def npu_inp_op_exec(self, input1): - output = torch.relu_(input1) - output = output.to("cpu") - output = output.numpy() - return output - - def test_relu_shape_format_fp32(self, device='npu'): - format_list = [-1] - shape_list = [(1000, 1280), (32, 3, 3), (1024, 464, 7, 7)] - shape_format = [ - [np.float32, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output, cpu_res = self.cpu_op_back_exec(cpu_input1) - npu_output, npu_res = self.npu_op_back_exec(npu_input1) - cpu_output = cpu_output.astype(npu_output.dtype) - cpu_res = cpu_res.astype(npu_res.dtype) - self.assertRtolEqual(cpu_output, npu_output) - self.assertRtolEqual(cpu_res, npu_res) - - def test_relu_shape_format_fp16(self, device='npu'): - format_list = [-1] - shape_list = [(1000, 1280), (32, 3, 3), (1024, 464, 7, 7)] - shape_format = [ - [np.float16, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output, cpu_res = self.cpu_op_back_exec(cpu_input1) - npu_output, npu_res = self.npu_op_back_exec(npu_input1) - cpu_output = cpu_output.astype(npu_output.dtype) - cpu_res = cpu_res.astype(npu_res.dtype) - self.assertRtolEqual(cpu_output, npu_output) - self.assertRtolEqual(cpu_res, npu_res) - - def test_relu_shape_format_fp16_inp(self, device='npu'): - format_list = [-1] - shape_list = [(1000, 1280), (32, 3, 3), (1024, 464, 7, 7)] - shape_format = [ - [np.float16, i, j] for i in format_list for j in shape_list - ] - for item in shape_format: - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - cpu_output = self.cpu_inp_op_exec(cpu_input1) - npu_output = self.npu_inp_op_exec(npu_input1) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_scaled_masked_softmax.py b/test/test_network_ops/test_scaled_masked_softmax.py deleted file mode 100644 index f5899e0444..0000000000 --- a/test/test_network_ops/test_scaled_masked_softmax.py +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (c) 2022, Huawei Technologies.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 random -import torch -import numpy as np -import torch.nn.functional as F -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestScaledMaskedSoftmax(TestCase): - def cpu_op_exec_forward(self, x, mask, scale, fixed_triu_mask): - x = x.float() - if fixed_triu_mask: - mask_tri = torch.triu(torch.ones(mask.shape, device=mask.device), diagonal=1).bool() - output = F.softmax((x * scale).masked_fill(mask_tri, value=-10000), dim=-1).half() - else: - output = F.softmax((x * scale).masked_fill(mask, value=-10000), dim=-1).half() - return output.detach().numpy() - - def npu_op_exec_forward(self, x, mask, scale, fixed_triu_mask): - output = torch_npu.npu_scaled_masked_softmax(x, mask, scale, fixed_triu_mask) - return output.cpu().detach().numpy() - - def cpu_op_exec_backward(self, x, y_grad, mask, scale, fixed_triu_mask): - x.requires_grad_(True) - x_fp32 = x.float() - y_grad = y_grad.float() - if fixed_triu_mask: - mask_tri = torch.triu(torch.ones(mask.shape, device=mask.device), diagonal=1).bool() - output = F.softmax((x_fp32 * scale).masked_fill(mask_tri, value=-10000), dim=-1).half() - output.backward(y_grad) - else: - output = F.softmax((x_fp32 * scale).masked_fill(mask, value=-10000), dim=-1).half() - output.backward(y_grad) - x_grad = x.grad - return x_grad.detach().numpy() - - def npu_op_exec_backward(self, x, y_grad, mask, scale, fixed_triu_mask): - x.requires_grad_(True) - output = torch_npu.npu_scaled_masked_softmax(x, mask, scale, fixed_triu_mask) - output.backward(y_grad) - x_grad = x.grad - return x_grad.half().cpu().detach().numpy() - - def test_scaled_masked_softmax_shape_format(self): - shape_format = [ - [[np.float16, 29, (16, 6, 128, 128)], [np.float16, 29, (16, 6, 128, 128)]], - [[np.float16, 2, (16, 6, 128, 512)], [np.float16, 2, (16, 1, 128, 512)]], - [[np.float16, 0, (16, 6, 512, 512)], [np.float16, 0, (16, 1, 512, 512)]], - [[np.float32, 29, (16, 6, 128, 128)], [np.float32, 29, (16, 6, 128, 128)]], - [[np.float32, 2, (16, 6, 128, 512)], [np.float32, 2, (16, 1, 128, 512)]], - [[np.float32, 0, (16, 6, 512, 512)], [np.float32, 0, (16, 1, 512, 512)]], - ] - - # forward ut test - for item in shape_format: - cpu_input, npu_input = create_common_tensor(item[0], -5, 5) - cpu_mask, npu_mask = create_common_tensor(item[1], -1, 1) - cpu_mask = cpu_mask > 0 - npu_mask = npu_mask > 0 - if cpu_input.dtype == torch.float16: - cpu_input = cpu_input.to(torch.float32) - scale = random.uniform(-1, 1) - fixed_triu_mask = False - cpu_output = self.cpu_op_exec_forward(cpu_input, cpu_mask, - scale, fixed_triu_mask) - npu_output = self.npu_op_exec_forward(npu_input, npu_mask, - scale, fixed_triu_mask) - cpu_output = cpu_output.astype(npu_output.dtype) - self.assertRtolEqual(cpu_output, npu_output) - - # backward ut test - for item in shape_format: - cpu_input, npu_input = create_common_tensor(item[0], -5, 5) - cpu_y_grad, npu_y_grad = create_common_tensor(item[0], -5, 5) - cpu_mask, npu_mask = create_common_tensor(item[1], -1, 1) - cpu_mask = cpu_mask > 0 - npu_mask = npu_mask > 0 - if cpu_input.dtype == torch.float16: - cpu_input = cpu_input.to(torch.float32) - if cpu_y_grad.dtype == torch.float16: - cpu_y_grad = cpu_y_grad.to(torch.float32) - scale = random.uniform(-1, 1) - fixed_triu_mask = False - cpu_x_grad = self.cpu_op_exec_backward(cpu_input, cpu_y_grad, - cpu_mask, scale, fixed_triu_mask) - npu_x_grad = self.npu_op_exec_backward(npu_input, npu_y_grad, - npu_mask, scale, fixed_triu_mask) - cpu_x_grad = cpu_x_grad.astype(npu_x_grad.dtype) - self.assertRtolEqual(cpu_x_grad, npu_x_grad) - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_sign_bits_unpack.py b/test/test_network_ops/test_sign_bits_unpack.py index 50791edf52..3ddf1370c2 100644 --- a/test/test_network_ops/test_sign_bits_unpack.py +++ b/test/test_network_ops/test_sign_bits_unpack.py @@ -13,9 +13,8 @@ # limitations under the License. import torch -import numpy as np - import torch_npu +import numpy as np from torch_npu.testing.testcase import TestCase, run_tests from torch_npu.testing.common_utils import create_common_tensor diff --git a/test/test_network_ops/test_slice.py b/test/test_network_ops/test_slice.py deleted file mode 100644 index 4e5c56a3ef..0000000000 --- a/test/test_network_ops/test_slice.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor -from torch_npu.testing.decorator import Dtypes, instantiate_tests - - -@instantiate_tests -class TestSlice(TestCase): - def npu_op_exec(self, input1, offset, sizes): - output = torch.npu_slice(input1, offset, sizes) - output = output.to("cpu") - output = output.numpy() - return output - - @Dtypes(torch.float, torch.half, torch.int32, torch.uint8, torch.int8, torch.int16, torch.long) - def test_slice(self, device, dtype): - input_data = torch.tensor([[1,2,3,4,5], [6,7,8,9,10]]).npu().to(dtype) - exoutput = torch.tensor([[1,2],[6,7]]).to(dtype) - output = self.npu_op_exec(input_data, [0, 0], [2, 2]) - self.assertRtolEqual(exoutput.numpy(), output) - - -if __name__ == "__main__": - run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_softmax.py b/test/test_network_ops/test_softmax.py deleted file mode 100644 index f4d46d9d2d..0000000000 --- a/test/test_network_ops/test_softmax.py +++ /dev/null @@ -1,127 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu -import torch.nn as nn -import numpy as np -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - - -class TestSoftMax(TestCase): - def cpu_op_exec(self, input1, dim): - output = torch.nn.functional.softmax(input1, dim) - output = output.numpy() - return output - - def npu_op_exec(self, input1, dim): - output = torch.nn.functional.softmax(input1, dim) - output = output.to("cpu") - output = output.numpy() - return output - - def cpu_op_exec_dtype(self, input1, dim, dtype): - output = torch.nn.functional.softmax(input1, dim, dtype=dtype) - output = output.numpy() - return output - - def npu_op_exec_dtype(self, input1, dim, dtype): - output = torch.nn.functional.softmax(input1, dim, dtype=dtype) - output = output.to("cpu") - output = output.numpy() - return output - - def npu_op_exec_half_float(self, input1, dim): - output = torch._softmax(input1, dim, True) - output = output.to("cpu") - output = output.numpy() - return output - - def softmax_result(self, shape_format): - for item in shape_format: - dim = np.random.randint(0, len(item[2])) - cpu_input1, npu_input1 = create_common_tensor(item, 0, 100) - if cpu_input1.dtype == torch.float16: - cpu_input1 = cpu_input1.to(torch.float32) - - cpu_output = self.cpu_op_exec(cpu_input1, dim) - npu_output = self.npu_op_exec(npu_input1, dim) - - if npu_input1.dtype == torch.float16: - npu_output_half = self.npu_op_exec_half_float(npu_input1, dim) - npu_output_half = npu_output_half.astype(np.float16) - - cpu_output_inp = self.cpu_op_exec_dtype(cpu_input1, dim, torch.float32) - npu_output_inp = self.npu_op_exec_dtype(npu_input1, dim, torch.float32) - - cpu_output = cpu_output.astype(npu_output.dtype) - cpu_output_inp = cpu_output_inp.astype(npu_output_inp.dtype) - - self.assertRtolEqual(cpu_output, npu_output) - if npu_input1.dtype == torch.float16: - self.assertRtolEqual(cpu_output, npu_output_half) - self.assertRtolEqual(cpu_output_inp, npu_output_inp) - - def test_softmax_shape_format_fp16_1d(self, device='npu'): - format_list = [0] - shape_format = [[np.float16, i, [18]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp16_2d(self, device='npu'): - format_list = [0, 3, 29] - shape_format = [[np.float16, i, [5, 256]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp16_3d(self, device='npu'): - format_list = [0, 29] - shape_format = [[np.float16, i, [32, 8, 8]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp16_4d(self, device='npu'): - format_list = [0, 29] - shape_format = [[np.float16, i, [64, 112, 7, 7]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp32_1d(self, device='npu'): - format_list = [0] - shape_format = [[np.float32, i, [18]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp32_2d(self, device='npu'): - format_list = [3, 29] - shape_format = [[np.float32, i, [5, 256]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp32_3d(self, device='npu'): - format_list = [0, 29] - shape_format = [[np.float32, i, [32, 3, 3]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_shape_format_fp32_4d(self, device='npu'): - format_list = [3, 29] - shape_format = [[np.float32, i, [64, 112, 7, 7]] for i in format_list] - self.softmax_result(shape_format) - - def test_softmax_dimname_shape_format(self, device='npu'): - cpu_input1 = torch.randn(4, 3, names=('N', 'C')) - npu_input1 = cpu_input1.npu() - cpu_output = self.cpu_op_exec(cpu_input1, 'N') - npu_output = self.npu_op_exec(npu_input1, 'N') - self.assertRtolEqual(cpu_output, npu_output) - - - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_sort.py b/test/test_network_ops/test_sort.py index 2d2d8eea6a..2e154fbf87 100644 --- a/test/test_network_ops/test_sort.py +++ b/test/test_network_ops/test_sort.py @@ -87,6 +87,7 @@ class TestSort(TestCase): cpu_output, cpu_indices = self.cpu_default_op_exec(cpu_input1.to(torch.float32)) npu_output, npu_indices = self.npu_default_op_exec(npu_input1) self.assertRtolEqual(cpu_output.astype(np.float16), npu_output) + self.assertRtolEqual(cpu_indices, npu_indices) if __name__ == "__main__": run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_stack.py b/test/test_network_ops/test_stack.py index 57f0dffbf8..e4ca4e21da 100644 --- a/test/test_network_ops/test_stack.py +++ b/test/test_network_ops/test_stack.py @@ -17,7 +17,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor class TestStack(TestCase): @@ -74,80 +73,67 @@ class TestStack(TestCase): self.assertRtolEqual(cpu_output, npu_output) self.assertRtolEqual(cpu_output, npu_output_out) - @graph_mode - def test_stack_shape_format_fp16_1d(self): + def test_stack_shape_format_fp16_1d(self, device="npu"): format_list = [0, 3] shape_format = [[[np.float16, i, [18]], np.random.randint(0, 1)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp16_2d(self): + def test_stack_shape_format_fp16_2d(self, device="npu"): format_list = [0, 3, 29] shape_format = [[[np.float16, i, [5, 256]], np.random.randint(0, 2)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp16_3d(self): + def test_stack_shape_format_fp16_3d(self, device="npu"): format_list = [0, 3, 29] shape_format = [[[np.float16, i, [32, 3, 3]], np.random.randint(0, 3)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp16_4d(self): + def test_stack_shape_format_fp16_4d(self, device="npu"): format_list = [0, 3, 29] shape_format = [[[np.float16, i, [32, 32, 3, 3]], np.random.randint(0, 4)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp32_1d(self): + def test_stack_shape_format_fp32_1d(self, device="npu"): format_list = [0, 3] shape_format = [[[np.float32, i, [18]], np.random.randint(0, 1)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp32_2d(self): + def test_stack_shape_format_fp32_2d(self, device="npu"): format_list = [0, 3, 29] shape_format = [[[np.float32, i, [5, 256]], np.random.randint(0, 2)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp32_3d(self): + def test_stack_shape_format_fp32_3d(self, device="npu"): format_list = [0, 3, 29] shape_format = [[[np.float32, i, [32, 3, 3]], np.random.randint(0, 3)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_fp32_4d(self): + def test_stack_shape_format_fp32_4d(self, device="npu"): format_list = [0, 3, 29] shape_format = [[[np.float32, i, [32, 32, 3, 3]], np.random.randint(0, 4)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_int32_1d(self): + def test_stack_shape_format_int32_1d(self, device="npu"): format_list = [0] shape_format = [[[np.int32, i, [18]], np.random.randint(0, 1)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_int32_2d(self): + def test_stack_shape_format_int32_2d(self, device="npu"): format_list = [0] shape_format = [[[np.int32, i, [5, 256]], np.random.randint(0, 2)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_int32_3d(self): + def test_stack_shape_format_int32_3d(self, device="npu"): format_list = [0] shape_format = [[[np.int32, i, [32, 3, 3]], np.random.randint(0, 3)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_shape_format_int32_4d(self): + def test_stack_shape_format_int32_4d(self, device="npu"): format_list = [-1] shape_format = [[[np.int32, i, [32, 32, 3, 3]], np.random.randint(0, 4)] for i in format_list] self.stack_result(shape_format) - @graph_mode - def test_stack_size_dim(self): + def test_stack_size_dim(self, device="npu"): def cpu_op_exec(input1): output = torch.stack((input1, input1, input1, input1, input1, input1, input1, input1, input1)) return output.numpy() diff --git a/test/test_network_ops/test_strideadd.py b/test/test_network_ops/test_strideadd.py deleted file mode 100644 index 51bd51b1ab..0000000000 --- a/test/test_network_ops/test_strideadd.py +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) 2020, Huawei Technologies.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 torch -import torch_npu -import numpy as np - -from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.common_utils import create_common_tensor - -class TestStrideAdd(TestCase): - def npu_op_exec(self, input1, input2, offset1, offset2, c1_len): - output = torch.npu_stride_add(input1, input2, offset1, offset2, c1_len) - output = output.to("cpu") - output = output.numpy() - - return output - - def test_StrideAdd(self, device='npu'): - input1 = torch.tensor([[[[[1.]]]]]).npu() - input2 = input1 - exoutput = torch.tensor([[[[[2.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]], - [[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]],[[[0.]]]]]) - output = self.npu_op_exec(input1, input2, 0, 0, 1) - self.assertRtolEqual(exoutput.numpy(), output) - -if __name__ == "__main__": - run_tests() diff --git a/test/test_network_ops/test_sum.py b/test/test_network_ops/test_sum.py index a0788c1f59..f14f6dc884 100644 --- a/test/test_network_ops/test_sum.py +++ b/test/test_network_ops/test_sum.py @@ -143,23 +143,6 @@ class TestSum(TestCase): [np.float32, i, [32, 24, 18, 18]] for i in format_list ] self.sum_result(shape_format) - - def test_sum_shape_format_int32(self, device="npu"): - format_list = [0, 3, 4, 29] - shape_list = [[18], [256, 1000], [32, 48, 64], [32, 24, 18, 18]] - shape_format = [ - [np.int32, i, j] for i in format_list for j in shape_list - ] - self.sum_result(shape_format) - - def test_sum_shape_format_int64(self, device="npu"): - format_list = [0, 2, 30] - shape_list = [[18], [256, 1000], [32, 48, 64], [32, 24, 18, 18]] - shape_format = [ - [np.int64, i, j] for i in format_list for j in shape_list - ] - self.sum_result(shape_format) - # --------sum dim--------------------- @@ -221,24 +204,6 @@ class TestSum(TestCase): ] self.sum_dim_result(shape_format) - def test_sum_dim_shape_format_int32(self, device="npu"): - format_list = [0, 3, 4] - shape_list = [[18], [256, 1000], [32, 48, 64], [32, 24, 18, 18]] - shape_format = [ - [np.int32, i, j] for i in format_list for j in shape_list - ] - self.sum_dim_result(shape_format) - - def test_sum_dim_shape_format_int64(self, device="npu"): - format_list = [0, 2,30] - shape_list = [[18], [256, 1000], [32, 48, 64], [32, 24, 18, 18]] - shape_format = [ - [np.int64, i, j] for i in format_list for j in shape_list - ] - self.sum_dim_result(shape_format) - - - def test_sum_dim_with_zero_shape_format(self, device="npu"): format_list = [0, 3, 4] shape_format = [ diff --git a/test/test_network_ops/test_unique_consecutive.py b/test/test_network_ops/test_unique_consecutive.py deleted file mode 100644 index e1f4e04077..0000000000 --- a/test/test_network_ops/test_unique_consecutive.py +++ /dev/null @@ -1,65 +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 torch -import numpy as np -import torch_npu - -from torch_npu.testing.testcase import TestCase, run_tests - -class TestUniqueConsecutive(TestCase): - def test_unique_consecutive(self, device="npu"): - shape_format = [ - [[torch.int32, (2, 3)], 0], - [[torch.long, (2, 3)], 1], - [[torch.float32, (2, 3)], 0], - [[torch.float16, (2, 3)], 1], - [[torch.int32, (2, 3)], None], - [[torch.long, (2, 3)], None], - [[torch.float32, (2, 3)], None], - [[torch.float16, (2, 3)], None] - ] - - for item in shape_format: - cpu_input = torch.rand(item[0][1]).random_(0, 3).to(item[0][0]) - npu_input = cpu_input.npu() - if item[0][0] == torch.float16: - cpu_input = cpu_input.float() - - cpu_output, cpu_idx, cpu_counts = torch.unique_consecutive(cpu_input, return_inverse=True, - return_counts=True, dim=item[1]) - npu_output, npu_idx, npu_counts = torch.unique_consecutive(npu_input, return_inverse=True, - return_counts=True, dim=item[1]) - - if item[0][0] == torch.float16: - cpu_output = cpu_output.half() - self.assertRtolEqual(cpu_output.numpy(), npu_output.cpu().numpy()) - self.assertRtolEqual(cpu_idx.numpy(), npu_idx.cpu().numpy()) - self.assertRtolEqual(cpu_counts.numpy(), npu_counts.cpu().numpy()) - - def test_unique_consecutive_case_in_dino(self, device="npu"): - input_list = [ - torch.tensor([224, 224, 96, 96, 96, 96, 96, 96, 96, 96]), - torch.tensor([224, 224]) - ] - for i in input_list: - cpu_output, cpu_counts = torch.unique_consecutive(i, return_counts=True) - npu_output, npu_counts = torch.unique_consecutive(i.npu(), return_counts=True) - self.assertRtolEqual(cpu_output.numpy(), npu_output.cpu().numpy()) - self.assertRtolEqual(cpu_counts.numpy(), npu_counts.cpu().numpy()) - -if __name__ == "__main__": - run_tests() \ No newline at end of file diff --git a/test/test_network_ops/test_zeroslike.py b/test/test_network_ops/test_zeroslike.py index 50d0c18b70..86b58704f7 100644 --- a/test/test_network_ops/test_zeroslike.py +++ b/test/test_network_ops/test_zeroslike.py @@ -19,7 +19,6 @@ import numpy as np import torch_npu from torch_npu.testing.testcase import TestCase, run_tests -from torch_npu.testing.decorator import graph_mode from torch_npu.testing.common_utils import create_common_tensor @@ -35,8 +34,7 @@ class TestZerosLike(TestCase): output = output.numpy() return output - @graph_mode - def test_zeroslike_fp32(self): + def test_zeroslike_fp32(self, device="npu"): format_list = [0, 3, 29] shape_list = [1, (1000, 1280), (32, 3, 3), (32, 144, 1, 1)] shape_format = [ @@ -48,8 +46,7 @@ class TestZerosLike(TestCase): npu_output = self.npu_op_exec(npu_input, torch.float32) self.assertRtolEqual(cpu_output, npu_output) - @graph_mode - def test_zeroslike_fp16(self): + def test_zeroslike_fp16(self, device="npu"): format_list = [0, 3, 29] shape_list = [1, (1000, 1280), (32, 3, 3), (32, 144, 1, 1)] shape_format = [ diff --git a/test/test_npu.py b/test/test_npu.py index e06c28ac1c..cecdef7060 100644 --- a/test/test_npu.py +++ b/test/test_npu.py @@ -345,19 +345,6 @@ class TestNpu(TestCase): self.assertEqual(a, b) self.assertEqual(torch_npu.npu.initial_seed(), 2) - def test_get_set_rng_state(self): - with freeze_rng_state(): - torch.manual_seed(3) - cpu_state = torch.get_rng_state() - npu_state = torch_npu.npu.get_rng_state() - self.assertEqual(int(cpu_state[0]), 3) - self.assertEqual(cpu_state[0], npu_state[0]) - torch_npu.npu.manual_seed(2) - cpu_state_new = torch.get_rng_state() - npu_state = torch_npu.npu.get_rng_state() - self.assertEqual(cpu_state, cpu_state_new) - self.assertEqual(int(npu_state[0]), 2) - def test_get_device_index(self): from torch_npu.npu import _get_device_index with self.assertRaisesRegex(RuntimeError, "Invalid device string"): @@ -528,9 +515,9 @@ class TestNpu(TestCase): device1 = torch.device("npu:1") device2 = torch.device("npu") device3 = torch.device("npu", 2) - self.assertEqual(str(device1), f"device(type='{torch_npu.npu.npu_device}', index=1)") - self.assertEqual(str(device2), f"device(type='{torch_npu.npu.npu_device}', index=None)") - self.assertEqual(str(device3), f"device(type='{torch_npu.npu.npu_device}', index=2)") + self.assertEqual(str(device1), f"{torch_npu.npu.native_device}:1") + self.assertEqual(str(device2), torch_npu.npu.native_device) + self.assertEqual(str(device3), f"{torch_npu.npu.native_device}:2") def test_function_tensor_data_npu(self): x = torch.ones(()) diff --git a/test/test_distributed/test_send_recv.py b/test/test_send_recv.py similarity index 94% rename from test/test_distributed/test_send_recv.py rename to test/test_send_recv.py index 1a30339a02..b956893594 100644 --- a/test/test_distributed/test_send_recv.py +++ b/test/test_send_recv.py @@ -12,8 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. +from enum import IntEnum, unique + import os +import unittest import torch +import torch.distributed as c10d import torch.distributed as dist import torch.multiprocessing as mp import torch_npu @@ -27,7 +31,6 @@ class HcclSendRecvDistTest(TestCase): def _init_dist_hccl(cls, rank, world_size): os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '29500' - os.environ['HCCL_WHITELIST_DISABLE'] = '1' torch_npu.npu.set_device(rank) dist.init_process_group(backend='hccl', world_size=world_size, rank=rank) return dist @@ -36,7 +39,6 @@ class HcclSendRecvDistTest(TestCase): def _init_pg_hccl(cls, rank, world_size): os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '29500' - os.environ['HCCL_WHITELIST_DISABLE'] = '1' torch_npu.npu.set_device(rank) dist.init_process_group(backend='hccl', world_size=world_size, rank=rank) return dist.new_group([0, 1]) @@ -57,7 +59,7 @@ class HcclSendRecvDistTest(TestCase): c2p.put((src, res.cpu())) @classmethod - def _test_send_recv_group( + def _test_send_recv_process( cls, rank, shared_tensors, world_size, init_pg, c2p, p2c): pg = init_pg(rank, world_size) tag = 1 @@ -115,9 +117,9 @@ class HcclSendRecvDistTest(TestCase): torch.randn(2, 2), HcclSendRecvDistTest._init_dist_hccl) - def test_send_recv_hccl_group(self): + def test_send_recv_hccl_process(self): self._test_multiprocess( - HcclSendRecvDistTest._test_send_recv_group, + HcclSendRecvDistTest._test_send_recv_process, torch.randn(2, 2), HcclSendRecvDistTest._init_pg_hccl) diff --git a/third_party/acl/inc/acl/acl.h b/third_party/acl/inc/acl/acl.h index 01f7028dff..41db19178b 100644 --- a/third_party/acl/inc/acl/acl.h +++ b/third_party/acl/inc/acl/acl.h @@ -19,9 +19,9 @@ extern "C" { #endif -// Current version is 1.2.0 +// Current version is 1.0.0 #define ACL_MAJOR_VERSION 1 -#define ACL_MINOR_VERSION 2 +#define ACL_MINOR_VERSION 0 #define ACL_PATCH_VERSION 0 /** @@ -31,7 +31,7 @@ extern "C" { * @par Restriction * The aclInit interface can be called only once in a process * @param configPath [IN] the config path,it can be NULL - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclInit(const char *configPath); @@ -43,7 +43,7 @@ ACL_FUNC_VISIBILITY aclError aclInit(const char *configPath); * @par Restriction * Need to call aclFinalize before the process exits. * After calling aclFinalize,the services cannot continue to be used normally. - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclFinalize(); @@ -55,20 +55,11 @@ ACL_FUNC_VISIBILITY aclError aclFinalize(); * @param majorVersion[OUT] ACL interface major version * @param minorVersion[OUT] ACL interface minor version * @param patchVersion[OUT] ACL interface patch version - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtGetVersion(int32_t *majorVersion, int32_t *minorVersion, int32_t *patchVersion); -/** - * @ingroup AscendCL - * @brief get recent error message - * - * @retval null for failed - * @retval OtherValues success -*/ -ACL_FUNC_VISIBILITY const char *aclGetRecentErrMsg(); - #ifdef __cplusplus } #endif diff --git a/third_party/acl/inc/acl/acl_base.h b/third_party/acl/inc/acl/acl_base.h index c04d0ece2b..0af9af058c 100644 --- a/third_party/acl/inc/acl/acl_base.h +++ b/third_party/acl/inc/acl/acl_base.h @@ -13,37 +13,16 @@ #include #include -#include "error_codes/rt_error_codes.h" -#include "error_codes/ge_error_codes.h" #ifdef __cplusplus extern "C" { #endif -#if defined(_MSC_VER) -#ifdef FUNC_VISIBILITY -#define ACL_FUNC_VISIBILITY _declspec(dllexport) -#else -#define ACL_FUNC_VISIBILITY -#endif -#else #ifdef FUNC_VISIBILITY #define ACL_FUNC_VISIBILITY __attribute__((visibility("default"))) #else #define ACL_FUNC_VISIBILITY #endif -#endif - -#ifdef __GNUC__ -#define ACL_DEPRECATED __attribute__((deprecated)) -#define ACL_DEPRECATED_MESSAGE(message) __attribute__((deprecated(message))) -#elif defined(_MSC_VER) -#define ACL_DEPRECATED __declspec(deprecated) -#define ACL_DEPRECATED_MESSAGE(message) __declspec(deprecated(message)) -#else -#define ACL_DEPRECATED -#define ACL_DEPRECATED_MESSAGE(message) -#endif typedef void *aclrtStream; typedef void *aclrtEvent; @@ -52,9 +31,8 @@ typedef int aclError; typedef uint16_t aclFloat16; typedef struct aclDataBuffer aclDataBuffer; typedef struct aclTensorDesc aclTensorDesc; - +typedef struct aclprofStepInfo aclprofStepInfo; static const int ACL_ERROR_NONE = 0; -static const int ACL_SUCCESS = 0; static const int ACL_ERROR_INVALID_PARAM = 100000; static const int ACL_ERROR_UNINITIALIZE = 100001; @@ -102,13 +80,6 @@ static const int ACL_ERROR_PROF_ALREADY_RUN = 100042; static const int ACL_ERROR_PROF_NOT_RUN = 100043; static const int ACL_ERROR_DUMP_ALREADY_RUN = 100044; static const int ACL_ERROR_DUMP_NOT_RUN = 100045; -static const int ACL_ERROR_PROF_REPEAT_SUBSCRIBE = 148046; -static const int ACL_ERROR_PROF_API_CONFLICT = 148047; -static const int ACL_ERROR_INVALID_MAX_OPQUEUE_NUM_CONFIG = 148048; -static const int ACL_ERROR_INVALID_OPP_PATH = 148049; -static const int ACL_ERROR_OP_UNSUPPORTED_DYNAMIC = 148050; -static const int ACL_ERROR_RELATIVE_RESOURCE_NOT_CLEARED = 148051; -static const int ACL_ERROR_UNSUPPORTED_JPEG = 148052; static const int ACL_ERROR_BAD_ALLOC = 200000; static const int ACL_ERROR_API_NOT_SUPPORT = 200001; @@ -119,6 +90,8 @@ static const int ACL_ERROR_INVALID_RESOURCE_HANDLE = 200005; static const int ACL_ERROR_FEATURE_UNSUPPORTED = 200006; static const int ACL_ERROR_PROF_MODULES_UNSUPPORTED = 200007; +static const int ACL_ERROR_RT_MEMORY_ALLOCATION = 207001; + static const int ACL_ERROR_STORAGE_OVER_LIMIT = 300000; static const int ACL_ERROR_INTERNAL_ERROR = 500000; @@ -129,7 +102,6 @@ static const int ACL_ERROR_DRV_FAILURE = 500004; static const int ACL_ERROR_PROFILING_FAILURE = 500005; #define ACL_TENSOR_SHAPE_RANGE_NUM 2 -#define ACL_TENSOR_VALUE_RANGE_NUM 2 #define ACL_UNKNOWN_RANK 0xFFFFFFFFFFFFFFFE typedef enum { @@ -146,10 +118,6 @@ typedef enum { ACL_UINT64 = 10, ACL_DOUBLE = 11, ACL_BOOL = 12, - ACL_STRING = 13, - ACL_COMPLEX64 = 16, - ACL_COMPLEX128 = 17, - ACL_BF16 = 27 } aclDataType; typedef enum { @@ -159,13 +127,11 @@ typedef enum { ACL_FORMAT_ND = 2, ACL_FORMAT_NC1HWC0 = 3, ACL_FORMAT_FRACTAL_Z = 4, - ACL_FORMAT_NC1HWC0_C04 = 12, - ACL_FORMAT_HWCN = 16, - ACL_FORMAT_NDHWC = 27, ACL_FORMAT_FRACTAL_NZ = 29, + ACL_FORMAT_NDHWC = 27, ACL_FORMAT_NCDHW = 30, ACL_FORMAT_NDC1HWC0 = 32, - ACL_FRACTAL_Z_3D = 33 + ACL_FRACTAL_Z_3D = 33, } aclFormat; typedef enum { @@ -178,16 +144,19 @@ typedef enum { typedef enum { ACL_MEMTYPE_DEVICE = 0, ACL_MEMTYPE_HOST = 1, - ACL_MEMTYPE_HOST_COMPILE_INDEPENDENT = 2 + ACL_MEMTYPE_HOST_COMPILE_INDEPENDENT = 2, } aclMemType; +typedef enum { + ACL_STEP_START = 0, + ACL_STEP_END = 1, +} aclprofStepTag; /** * @ingroup AscendCL * @brief Converts data of type aclFloat16 to data of type float * * @param value [IN] Data to be converted - * * @retval Transformed data */ ACL_FUNC_VISIBILITY float aclFloat16ToFloat(aclFloat16 value); @@ -197,7 +166,6 @@ ACL_FUNC_VISIBILITY float aclFloat16ToFloat(aclFloat16 value); * @brief Converts data of type float to data of type aclFloat16 * * @param value [IN] Data to be converted - * * @retval Transformed data */ ACL_FUNC_VISIBILITY aclFloat16 aclFloatToFloat16(float value); @@ -210,9 +178,7 @@ ACL_FUNC_VISIBILITY aclFloat16 aclFloatToFloat16(float value); * @li Need to be managed by the user, * call aclrtMalloc interface to apply for memory, * call aclrtFree interface to release memory - * * @param size [IN] size of data in bytes - * * @retval pointer to created instance. nullptr if run out of memory * * @see aclrtMalloc | aclrtFree @@ -227,45 +193,19 @@ ACL_FUNC_VISIBILITY aclDataBuffer *aclCreateDataBuffer(void *data, size_t size); * Only the aclDataBuffer type data is destroyed here. * The memory of the data passed in when the aclDataDataBuffer interface * is called to create aclDataBuffer type data must be released by the user - * * @param dataBuffer [IN] pointer to the aclDataBuffer - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclCreateDataBuffer */ ACL_FUNC_VISIBILITY aclError aclDestroyDataBuffer(const aclDataBuffer *dataBuffer); -/** - * @ingroup AscendCL - * @brief update new data of aclDataBuffer - * - * @param dataBuffer [OUT] pointer to aclDataBuffer - * @li The old data need to be released by the user, otherwise it may occur memory leak leakage - * call aclGetDataBufferAddr interface to get old data address - * call aclrtFree interface to release memory - * - * @param data [IN] pointer to new data - * @li Need to be managed by the user, - * call aclrtMalloc interface to apply for memory, - * call aclrtFree interface to release memory - * - * @param size [IN] size of data in bytes - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclrtMalloc | aclrtFree | aclGetDataBufferAddr - */ -ACL_FUNC_VISIBILITY aclError aclUpdateDataBuffer(aclDataBuffer *dataBuffer, void *data, size_t size); - /** * @ingroup AscendCL * @brief get data address from aclDataBuffer * * @param dataBuffer [IN] pointer to the data of aclDataBuffer - * * @retval data address */ ACL_FUNC_VISIBILITY void *aclGetDataBufferAddr(const aclDataBuffer *dataBuffer); @@ -275,10 +215,8 @@ ACL_FUNC_VISIBILITY void *aclGetDataBufferAddr(const aclDataBuffer *dataBuffer); * @brief get data size of aclDataBuffer * * @param dataBuffer [IN] pointer to the data of aclDataBuffer - * * @retval data size */ -ACL_DEPRECATED_MESSAGE("aclGetDataBufferSize is deprecated, use aclGetDataBufferSizeV2 instead") ACL_FUNC_VISIBILITY uint32_t aclGetDataBufferSize(const aclDataBuffer *dataBuffer); /** @@ -296,7 +234,6 @@ ACL_FUNC_VISIBILITY size_t aclGetDataBufferSizeV2(const aclDataBuffer *dataBuffe * @brief get size of aclDataType * * @param dataType [IN] aclDataType data the size to get - * * @retval size of the aclDataType */ ACL_FUNC_VISIBILITY size_t aclDataTypeSize(aclDataType dataType); @@ -310,7 +247,6 @@ ACL_FUNC_VISIBILITY size_t aclDataTypeSize(aclDataType dataType); * @param numDims [IN] the number of dimensions of the shape * @param dims [IN] the size of the specified dimension * @param format [IN] tensor format - * * @retval aclTensorDesc pointer. * @retval nullptr if param is invalid or run out of memory */ @@ -331,37 +267,22 @@ ACL_FUNC_VISIBILITY void aclDestroyTensorDesc(const aclTensorDesc *desc); * @ingroup AscendCL * @brief set tensor shape range for aclTensorDesc * - * @param desc [OUT] pointer to the data of aclTensorDesc + * @param desc [IN] pointer to the data of aclTensorDesc * @param dimsCount [IN] the number of dimensions of the shape * @param dimsRange [IN] the range of dimensions of the shape * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclSetTensorShapeRange(aclTensorDesc* desc, size_t dimsCount, int64_t dimsRange[][ACL_TENSOR_SHAPE_RANGE_NUM]); -/** - * @ingroup AscendCL - * @brief set value range for aclTensorDesc - * - * @param desc [OUT] pointer to the data of aclTensorDesc - * @param valueCount [IN] the number of value - * @param valueRange [IN] the range of value - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclSetTensorValueRange(aclTensorDesc* desc, - size_t valueCount, - int64_t valueRange[][ACL_TENSOR_VALUE_RANGE_NUM]); /** * @ingroup AscendCL * @brief get data type specified by the tensor description * * @param desc [IN] pointer to the instance of aclTensorDesc - * * @retval data type specified by the tensor description. * @retval ACL_DT_UNDEFINED if description is null */ @@ -372,7 +293,6 @@ ACL_FUNC_VISIBILITY aclDataType aclGetTensorDescType(const aclTensorDesc *desc); * @brief get data format specified by the tensor description * * @param desc [IN] pointer to the instance of aclTensorDesc - * * @retval data format specified by the tensor description. * @retval ACL_FORMAT_UNDEFINED if description is null */ @@ -383,7 +303,6 @@ ACL_FUNC_VISIBILITY aclFormat aclGetTensorDescFormat(const aclTensorDesc *desc); * @brief get tensor size specified by the tensor description * * @param desc [IN] pointer to the instance of aclTensorDesc - * * @retval data size specified by the tensor description. * @retval 0 if description is null */ @@ -394,7 +313,6 @@ ACL_FUNC_VISIBILITY size_t aclGetTensorDescSize(const aclTensorDesc *desc); * @brief get element count specified by the tensor description * * @param desc [IN] pointer to the instance of aclTensorDesc - * * @retval element count specified by the tensor description. * @retval 0 if description is null */ @@ -405,7 +323,6 @@ ACL_FUNC_VISIBILITY size_t aclGetTensorDescElementCount(const aclTensorDesc *des * @brief get number of dims specified by the tensor description * * @param desc [IN] pointer to the instance of aclTensorDesc - * * @retval number of dims specified by the tensor description. * @retval 0 if description is null * @retval ACL_UNKNOWN_RANK if the tensor dim is -2 @@ -418,11 +335,9 @@ ACL_FUNC_VISIBILITY size_t aclGetTensorDescNumDims(const aclTensorDesc *desc); * * @param desc [IN] pointer to the instance of aclTensorDesc * @param index [IN] index of dims, start from 0. - * * @retval dim specified by the tensor description and index. * @retval -1 if description or index is invalid */ -ACL_DEPRECATED_MESSAGE("aclGetTensorDescDim is deprecated, use aclGetTensorDescDimV2 instead") ACL_FUNC_VISIBILITY int64_t aclGetTensorDescDim(const aclTensorDesc *desc, size_t index); /** @@ -431,9 +346,9 @@ ACL_FUNC_VISIBILITY int64_t aclGetTensorDescDim(const aclTensorDesc *desc, size_ * * @param desc [IN] pointer to the instance of aclTensorDesc * @param index [IN] index of dims, start from 0. - * @param dimSize [OUT] size of the specified dim. + * @param dimSize [OUT] size of the specified dim. * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclGetTensorDescDimV2(const aclTensorDesc *desc, size_t index, int64_t *dimSize); @@ -447,7 +362,7 @@ ACL_FUNC_VISIBILITY aclError aclGetTensorDescDimV2(const aclTensorDesc *desc, si * @param dimRangeNum [IN] number of dimRange. * @param dimRange [OUT] range of the specified dim. * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclGetTensorDescDimRange(const aclTensorDesc *desc, @@ -459,7 +374,7 @@ ACL_FUNC_VISIBILITY aclError aclGetTensorDescDimRange(const aclTensorDesc *desc, * @ingroup AscendCL * @brief set tensor description name * - * @param desc [OUT] pointer to the instance of aclTensorDesc + * @param desc [IN] pointer to the instance of aclTensorDesc * @param name [IN] tensor description name */ ACL_FUNC_VISIBILITY void aclSetTensorDescName(aclTensorDesc *desc, const char *name); @@ -469,7 +384,6 @@ ACL_FUNC_VISIBILITY void aclSetTensorDescName(aclTensorDesc *desc, const char *n * @brief get tensor description name * * @param desc [IN] pointer to the instance of aclTensorDesc - * * @retval tensor description name. * @retval empty string if description is null */ @@ -483,49 +397,21 @@ ACL_FUNC_VISIBILITY const char *aclGetTensorDescName(aclTensorDesc *desc); * * @param srcDesc [IN] pointer to the source tensor desc * @param dstFormat [IN] destination format - * @param dstDesc [OUT] pointer to the pointer to the destination tensor desc - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param dstDesc [OUT] pointer to the pointer to the destination tensor desc + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclTransTensorDescFormat(const aclTensorDesc *srcDesc, aclFormat dstFormat, aclTensorDesc **dstDesc); -/** - * @ingroup AscendCL - * @brief Set the storage format specified by the tensor description - * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param format [IN] the storage format - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_DEPRECATED_MESSAGE("aclSetTensorStorageFormat is deprecated, use aclSetTensorFormat instead") -ACL_FUNC_VISIBILITY aclError aclSetTensorStorageFormat(aclTensorDesc *desc, aclFormat format); - -/** - * @ingroup AscendCL - * @brief Set the storage shape specified by the tensor description - * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param numDims [IN] the number of dimensions of the shape - * @param dims [IN] the size of the specified dimension - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_DEPRECATED_MESSAGE("aclSetTensorStorageShape is deprecated, use aclSetTensorShape instead") -ACL_FUNC_VISIBILITY aclError aclSetTensorStorageShape(aclTensorDesc *desc, int numDims, const int64_t *dims); - /** * @ingroup AscendCL * @brief Set the format specified by the tensor description * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param format [IN] the storage format + * @param desc [IN|OUT] pointer to the instance of aclTensorDesc + * @param format [IN] the storage format * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclSetTensorFormat(aclTensorDesc *desc, aclFormat format); @@ -534,11 +420,11 @@ ACL_FUNC_VISIBILITY aclError aclSetTensorFormat(aclTensorDesc *desc, aclFormat f * @ingroup AscendCL * @brief Set the shape specified by the tensor description * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param numDims [IN] the number of dimensions of the shape - * @param dims [IN] the size of the specified dimension + * @param desc [IN|OUT] pointer to the instance of aclTensorDesc + * @param numDims [IN] the number of dimensions of the shape + * @param dims [IN] the size of the specified dimension * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclSetTensorShape(aclTensorDesc *desc, int numDims, const int64_t *dims); @@ -547,10 +433,10 @@ ACL_FUNC_VISIBILITY aclError aclSetTensorShape(aclTensorDesc *desc, int numDims, * @ingroup AscendCL * @brief Set the original format specified by the tensor description * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param format [IN] the storage format + * @param desc [IN|OUT] pointer to the instance of aclTensorDesc + * @param format [IN] the storage format * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclSetTensorOriginFormat(aclTensorDesc *desc, aclFormat format); @@ -559,11 +445,11 @@ ACL_FUNC_VISIBILITY aclError aclSetTensorOriginFormat(aclTensorDesc *desc, aclFo * @ingroup AscendCL * @brief Set the original shape specified by the tensor description * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param numDims [IN] the number of dimensions of the shape - * @param dims [IN] the size of the specified dimension + * @param desc [IN|OUT] pointer to the instance of aclTensorDesc + * @param numDims [IN] the number of dimensions of the shape + * @param dims [IN] the size of the specified dimension * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclSetTensorOriginShape(aclTensorDesc *desc, int numDims, const int64_t *dims); @@ -595,40 +481,14 @@ ACL_FUNC_VISIBILITY void *aclGetTensorDescAddress(const aclTensorDesc *desc); * @ingroup AscendCL * @brief Set the dynamic input name specified by the tensor description * - * @param desc [OUT] pointer to the instance of aclTensorDesc + * @param desc [IN|OUT] pointer to the instance of aclTensorDesc * @param dynamicInputName [IN] pointer to the dynamic input name * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclSetTensorDynamicInput(aclTensorDesc *desc, const char *dynamicInputName); -/** - * @ingroup AscendCL - * @brief Set const data specified by the tensor description - * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param dataBuffer [IN] pointer to the const databuffer - * @param length [IN] the length of const databuffer - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclSetTensorConst(aclTensorDesc *desc, void *dataBuffer, size_t length); - -/** - * @ingroup AscendCL - * @brief Set tensor memory type specified by the tensor description - * - * @param desc [OUT] pointer to the instance of aclTensorDesc - * @param memType [IN] ACL_MEMTYPE_DEVICE means device, ACL_MEMTYPE_HOST or - * ACL_MEMTYPE_HOST_COMPILE_INDEPENDENT means host - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclSetTensorPlaceMent(aclTensorDesc *desc, aclMemType memType); - /** * @ingroup AscendCL * @brief an interface for users to output APP logs @@ -643,14 +503,8 @@ ACL_FUNC_VISIBILITY aclError aclSetTensorPlaceMent(aclTensorDesc *desc, aclMemTy ACL_FUNC_VISIBILITY void aclAppLog(aclLogLevel logLevel, const char *func, const char *file, uint32_t line, const char *fmt, ...); -/** - * @ingroup AscendCL - * @brief get soc name - * - * @retval null for failed - * @retval OtherValues success -*/ -ACL_FUNC_VISIBILITY const char *aclrtGetSocName(); + +ACL_FUNC_VISIBILITY aclError aclSetTensorPlaceMent(aclTensorDesc *desc, aclMemType type); #define ACL_APP_LOG(level, fmt, ...) \ aclAppLog(level, __FUNCTION__, __FILE__, __LINE__, fmt, ##__VA_ARGS__) diff --git a/third_party/acl/inc/acl/acl_mdl.h b/third_party/acl/inc/acl/acl_mdl.h index fb1112d5f4..4379e4671f 100644 --- a/third_party/acl/inc/acl/acl_mdl.h +++ b/third_party/acl/inc/acl/acl_mdl.h @@ -28,22 +28,13 @@ extern "C" { #define ACL_MAX_SHAPE_COUNT 128 #define ACL_INVALID_NODE_INDEX 0xFFFFFFFF -#define ACL_MDL_LOAD_FROM_FILE 1 -#define ACL_MDL_LOAD_FROM_FILE_WITH_MEM 2 -#define ACL_MDL_LOAD_FROM_MEM 3 -#define ACL_MDL_LOAD_FROM_MEM_WITH_MEM 4 -#define ACL_MDL_LOAD_FROM_FILE_WITH_Q 5 -#define ACL_MDL_LOAD_FROM_MEM_WITH_Q 6 - #define ACL_DYNAMIC_TENSOR_NAME "ascend_mbatch_shape_data" #define ACL_DYNAMIC_AIPP_NAME "ascend_dynamic_aipp_data" -#define ACL_ATTR_NAME_DATA_DUMP_ORIGIN_OP_NAMES "_datadump_original_op_names" typedef struct aclmdlDataset aclmdlDataset; typedef struct aclmdlDesc aclmdlDesc; typedef struct aclmdlAIPP aclmdlAIPP; typedef struct aclAippExtendInfo aclAippExtendInfo; -typedef struct aclmdlConfigHandle aclmdlConfigHandle; typedef enum { ACL_YUV420SP_U8 = 1, @@ -63,22 +54,6 @@ typedef enum { ACL_AIPP_RESERVED = 0xffff, } aclAippInputFormat; -typedef enum { - ACL_MDL_PRIORITY_INT32 = 0, - ACL_MDL_LOAD_TYPE_SIZET, - ACL_MDL_PATH_PTR, /**< pointer to model load path with deep copy */ - ACL_MDL_MEM_ADDR_PTR, /**< pointer to model memory with shallow copy */ - ACL_MDL_MEM_SIZET, - ACL_MDL_WEIGHT_ADDR_PTR, /**< pointer to weight memory of model with shallow copy */ - ACL_MDL_WEIGHT_SIZET, - ACL_MDL_WORKSPACE_ADDR_PTR, /**< pointer to worksapce memory of model with shallow copy */ - ACL_MDL_WORKSPACE_SIZET, - ACL_MDL_INPUTQ_NUM_SIZET, - ACL_MDL_INPUTQ_ADDR_PTR, /**< pointer to inputQ with shallow copy */ - ACL_MDL_OUTPUTQ_NUM_SIZET, - ACL_MDL_OUTPUTQ_ADDR_PTR /**< pointer to outputQ with shallow copy */ -} aclmdlConfigAttr; - typedef enum { ACL_DATA_WITHOUT_AIPP = 0, ACL_DATA_WITH_STATIC_AIPP, @@ -178,8 +153,7 @@ ACL_FUNC_VISIBILITY aclmdlDesc *aclmdlCreateDesc(); * @brief destroy data of type aclmdlDesc * * @param modelDesc [IN] Pointer to almdldlDesc to be destroyed - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlDestroyDesc(aclmdlDesc *modelDesc); @@ -190,8 +164,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlDestroyDesc(aclmdlDesc *modelDesc); * * @param modelDesc [OUT] aclmdlDesc pointer * @param modelId [IN] model id - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetDesc(aclmdlDesc *modelDesc, uint32_t modelId); @@ -202,7 +175,6 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetDesc(aclmdlDesc *modelDesc, uint32_t model * the model according to data of aclmdlDesc * * @param modelDesc [IN] aclmdlDesc pointer - * * @retval input size with aclmdlDesc */ ACL_FUNC_VISIBILITY size_t aclmdlGetNumInputs(aclmdlDesc *modelDesc); @@ -213,7 +185,6 @@ ACL_FUNC_VISIBILITY size_t aclmdlGetNumInputs(aclmdlDesc *modelDesc); * the model according to data of aclmdlDesc * * @param modelDesc [IN] aclmdlDesc pointer - * * @retval output size with aclmdlDesc */ ACL_FUNC_VISIBILITY size_t aclmdlGetNumOutputs(aclmdlDesc *modelDesc); @@ -226,7 +197,6 @@ ACL_FUNC_VISIBILITY size_t aclmdlGetNumOutputs(aclmdlDesc *modelDesc); * @param modelDesc [IN] aclmdlDesc pointer * @param index [IN] the size of the number of inputs to be obtained, * the index value starts from 0 - * * @retval Specify the size of the input */ ACL_FUNC_VISIBILITY size_t aclmdlGetInputSizeByIndex(aclmdlDesc *modelDesc, size_t index); @@ -239,7 +209,6 @@ ACL_FUNC_VISIBILITY size_t aclmdlGetInputSizeByIndex(aclmdlDesc *modelDesc, size * @param modelDesc [IN] aclmdlDesc pointer * @param index [IN] the size of the number of outputs to be obtained, * the index value starts from 0 - * * @retval Specify the size of the output */ ACL_FUNC_VISIBILITY size_t aclmdlGetOutputSizeByIndex(aclmdlDesc *modelDesc, size_t index); @@ -257,8 +226,7 @@ ACL_FUNC_VISIBILITY aclmdlDataset *aclmdlCreateDataset(); * @brief destroy data of type aclmdlDataset * * @param dataset [IN] Pointer to aclmdlDataset to be destroyed - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlDestroyDataset(const aclmdlDataset *dataset); @@ -267,47 +235,19 @@ ACL_FUNC_VISIBILITY aclError aclmdlDestroyDataset(const aclmdlDataset *dataset); * @ingroup AscendCL * @brief Add aclDataBuffer to aclmdlDataset * - * @param dataset [OUT] aclmdlDataset address of aclDataBuffer to be added + * @param dataset [IN|OUT] aclmdlDataset address of aclDataBuffer to be added * @param dataBuffer [IN] aclDataBuffer address to be added - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclmdlAddDatasetBuffer(aclmdlDataset *dataset, aclDataBuffer *dataBuffer); - -/** - * @ingroup AscendCL - * @brief Set aclTensorDesc to aclmdlDataset - * - * @param dataset [OUT] aclmdlDataset address of aclDataBuffer to be added - * @param tensorDesc [IN] aclTensorDesc address to be added - * @param index [IN] index of tensorDesc which to be added - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclmdlSetDatasetTensorDesc(aclmdlDataset *dataset, - aclTensorDesc *tensorDesc, - size_t index); - -/** - * @ingroup AscendCL - * @brief Get aclTensorDesc from aclmdlDataset - * - * @param dataset [IN] aclmdlDataset pointer; - * @param index [IN] index of tensorDesc - * - * @retval Get address of aclTensorDesc when executed successfully. - * @retval Failure return NULL - */ -ACL_FUNC_VISIBILITY aclTensorDesc *aclmdlGetDatasetTensorDesc(const aclmdlDataset *dataset, size_t index); +ACL_FUNC_VISIBILITY aclError aclmdlAddDatasetBuffer(aclmdlDataset *dataset, + aclDataBuffer *dataBuffer); /** * @ingroup AscendCL * @brief Get the number of aclDataBuffer in aclmdlDataset * - * @param dataset [IN] aclmdlDataset pointer - * + * @param dataset [IN] aclmdlDataset poiter * @retval the number of aclDataBuffer */ ACL_FUNC_VISIBILITY size_t aclmdlGetDatasetNumBuffers(const aclmdlDataset *dataset); @@ -316,13 +256,13 @@ ACL_FUNC_VISIBILITY size_t aclmdlGetDatasetNumBuffers(const aclmdlDataset *datas * @ingroup AscendCL * @brief Get the aclDataBuffer in aclmdlDataset by index * - * @param dataset [IN] aclmdlDataset pointer + * @param dataset [IN] aclmdlDataset poiter * @param index [IN] the index of aclDataBuffer - * * @retval Get successfully, return the address of aclDataBuffer * @retval Failure return NULL */ -ACL_FUNC_VISIBILITY aclDataBuffer *aclmdlGetDatasetBuffer(const aclmdlDataset *dataset, size_t index); +ACL_FUNC_VISIBILITY aclDataBuffer *aclmdlGetDatasetBuffer(const aclmdlDataset *dataset, + size_t index); /** * @ingroup AscendCL @@ -332,13 +272,11 @@ ACL_FUNC_VISIBILITY aclDataBuffer *aclmdlGetDatasetBuffer(const aclmdlDataset *d * @par Function * After the system finishes loading the model, * the model ID returned is used as a mark to identify the model - * during subsequent operations - * + * during subsequent operations. * @param modelPath [IN] Storage path for offline model files - * @param modelId [OUT] Model ID generated after + * @param modelId [OUT] Model ID generated after * the system finishes loading the model - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromFile(const char *modelPath, uint32_t *modelId); @@ -352,17 +290,15 @@ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromFile(const char *modelPath, uint32_t * After the system finishes loading the model, * the model ID returned is used as a mark to identify the model * during subsequent operations - * - * @param model [IN] Model data stored in memory + * @param model [IN] Model data stored in memory * @param modelSize [IN] model data size - * @param modelId [OUT] Model ID generated after + * @param modelId [OUT] Model ID generated after * the system finishes loading the model - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromMem(const void *model, size_t modelSize, - uint32_t *modelId); + uint32_t *modelId); /** * @ingroup AscendCL @@ -374,19 +310,18 @@ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromMem(const void *model, size_t modelS * the model ID returned is used as a mark to identify the model * during subsequent operations. * @param modelPath [IN] Storage path for offline model files - * @param modelId [OUT] Model ID generated after finishes loading the model - * @param workPtr [IN] A pointer to the working memory - * required by the model on the Device,can be null - * @param workSize [IN] The amount of working memory required by the model - * @param weightPtr [IN] Pointer to model weight memory on Device + * @param modelId [OUT] Model ID generated after finishes loading the model + * @param workPtr [IN] A pointer to the working memory + * required by the model on the Device,can be null + * @param workSize [IN] The amount of working memory required by the model + * @param weightPtr [IN] Pointer to model weight memory on Device * @param weightSize [IN] The amount of weight memory required by the model - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromFileWithMem(const char *modelPath, - uint32_t *modelId, void *workPtr, size_t workSize, - void *weightPtr, size_t weightSize); + uint32_t *modelId, void *workPtr, size_t workSize, + void *weightPtr, size_t weightSize); /** * @ingroup AscendCL @@ -397,96 +332,90 @@ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromFileWithMem(const char *modelPath, * After the system finishes loading the model, * the model ID returned is used as a mark to identify the model * during subsequent operations - * @param model [IN] Model data stored in memory + * @param model [IN] Model data stored in memory * @param modelSize [IN] model data size - * @param modelId [OUT] Model ID generated after finishes loading the model - * @param workPtr [IN] A pointer to the working memory - * required by the model on the Device,can be null - * @param workSize [IN] work memory size - * @param weightPtr [IN] Pointer to model weight memory on Device,can be null - * @param weightSize [IN] The amount of weight memory required by the model - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param modelId [OUT] Model ID generated after finishes loading the model + * @param workPtr [IN] A pointer to the working memory + * required by the model on the Device,can be null + * @param workSize [IN] work memory size + * @param weightPtr [IN] Pointer to model weight memory on Device,can be null + * @param weightSize [IN] The amount of weight memory required by the model + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromMemWithMem(const void *model, size_t modelSize, - uint32_t *modelId, void *workPtr, size_t workSize, - void *weightPtr, size_t weightSize); + uint32_t *modelId, void *workPtr, size_t workSize, + void *weightPtr, size_t weightSize); /** * @ingroup AscendCL * @brief load model from file with async queue * - * @param modelPath [IN] model path - * @param modelId [OUT] return model id if load success - * @param inputQ [IN] input queue pointer + * @param modelPath [IN] model path + * @param modelId [OUT] return model id if load success + * @param inputQ [IN] input queue pointer * @param inputQNum [IN] input queue num - * @param outputQ [IN] output queue pointer - * @param outputQNum [IN] output queue num - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param outputQ [IN] output queue pointer + * @param outputQNum [IN] output queue num + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromFileWithQ(const char *modelPath, uint32_t *modelId, const uint32_t *inputQ, - size_t inputQNum, const uint32_t *outputQ, size_t outputQNum); + size_t inputQNum, const uint32_t *outputQ, size_t outputQNum); /** * @ingroup AscendCL * @brief load model from memory with async queue * - * @param model [IN] model memory which user manages + * @param model [IN] model memory which user manages * @param modelSize [IN] model size - * @param modelId [OUT] return model id if load success - * @param inputQ [IN] input queue pointer + * @param modelId [OUT] return model id if load success + * @param inputQ [IN] input queue pointer * @param inputQNum [IN] input queue num - * @param outputQ [IN] output queue pointer - * @param outputQNum [IN] output queue num - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param outputQ [IN] output queue pointer + * @param outputQNum [IN] output queue num + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlLoadFromMemWithQ(const void *model, size_t modelSize, uint32_t *modelId, - const uint32_t *inputQ, size_t inputQNum, - const uint32_t *outputQ, size_t outputQNum); + const uint32_t *inputQ, size_t inputQNum, const uint32_t *outputQ, size_t outputQNum); /** * @ingroup AscendCL * @brief Execute model synchronous inference until the inference result is returned * * @param modelId [IN] ID of the model to perform inference - * @param input [IN] Input data for model inference + * @param input [IN] Input data for model inference * @param output [OUT] Output data for model inference - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclmdlExecute(uint32_t modelId, const aclmdlDataset *input, aclmdlDataset *output); +ACL_FUNC_VISIBILITY aclError aclmdlExecute(uint32_t modelId, const aclmdlDataset *input, + aclmdlDataset *output); /** * @ingroup AscendCL * @brief Execute model asynchronous inference until the inference result is returned * * @param modelId [IN] ID of the model to perform inference - * @param input [IN] Input data for model inference + * @param input [IN] Input data for model inference * @param output [OUT] Output data for model inference - * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param stream [IN] stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | * aclmdlLoadFromMemWithMem */ ACL_FUNC_VISIBILITY aclError aclmdlExecuteAsync(uint32_t modelId, const aclmdlDataset *input, - aclmdlDataset *output, aclrtStream stream); + aclmdlDataset *output, aclrtStream stream); /** * @ingroup AscendCL * @brief unload model with model id * * @param modelId [IN] model id to be unloaded - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlUnload(uint32_t modelId); @@ -496,11 +425,10 @@ ACL_FUNC_VISIBILITY aclError aclmdlUnload(uint32_t modelId); * @brief Get the weight memory size and working memory size * required for model execution according to the model file * - * @param fileName [IN] Model path to get memory information - * @param workSize [OUT] The amount of working memory for model executed + * @param fileName [IN] Model path to get memory information + * @param workSize [OUT] The amount of working memory for model executed * @param weightSize [OUT] The amount of weight memory for model executed - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlQuerySize(const char *fileName, size_t *workSize, size_t *weightSize); @@ -513,16 +441,15 @@ ACL_FUNC_VISIBILITY aclError aclmdlQuerySize(const char *fileName, size_t *workS * @par Restriction * The execution and weight memory is Device memory, * and requires user application and release. - * @param model [IN] model memory which user manages + * @param model [IN] model memory which user manages * @param modelSize [IN] model data size * @param workSize [OUT] The amount of working memory for model executed - * @param weightSize [OUT] The amount of weight memory for model executed - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param weightSize [OUT] The amount of weight memory for model executed + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlQuerySizeFromMem(const void *model, size_t modelSize, size_t *workSize, - size_t *weightSize); + size_t *weightSize); /** * @ingroup AscendCL @@ -530,49 +457,46 @@ ACL_FUNC_VISIBILITY aclError aclmdlQuerySizeFromMem(const void *model, size_t mo * it is used to set the number of images processed * at one time during model inference * - * @param modelId [IN] model id - * @param dataset [IN|OUT] data for model inference - * @param index [IN] index of dynamic tensor - * @param batchSize [IN] Number of images processed at a time during model - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param modelId [IN] model id + * @param dataset [IN] data for model inference + * @param index [IN] index of dynamic tensor + * @param batchSize [IN] Number of images processed at a time during model + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | * aclmdlLoadFromMemWithMem | aclmdlGetInputIndexByName */ ACL_FUNC_VISIBILITY aclError aclmdlSetDynamicBatchSize(uint32_t modelId, aclmdlDataset *dataset, size_t index, - uint64_t batchSize); + uint64_t batchSize); /** * @ingroup AscendCL * @brief Sets the H and W of the specified input of the model * - * @param modelId [IN] model id - * @param dataset [IN|OUT] data for model inference - * @param index [IN] index of dynamic tensor - * @param height [IN] model height - * @param width [IN] model width - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param modelId [IN] model id + * @param dataset [IN] data for model inference + * @param index [IN] index of dynamic tensor + * @param height [IN] model height + * @param width [IN] model width + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | * aclmdlLoadFromMemWithMem | aclmdlGetInputIndexByName */ ACL_FUNC_VISIBILITY aclError aclmdlSetDynamicHWSize(uint32_t modelId, aclmdlDataset *dataset, size_t index, - uint64_t height, uint64_t width); + uint64_t height, uint64_t width); /** * @ingroup AscendCL * @brief Sets the dynamic dims of the specified input of the model * - * @param modelId [IN] model id - * @param dataset [IN|OUT] data for model inference - * @param index [IN] index of dynamic dims - * @param dims [IN] value of dynamic dims - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param modelId [IN] model id + * @param dataset [IN] data for model inference + * @param index [IN] index of dynamic dims + * @param dims [IN] value of dynamic dims + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | @@ -588,8 +512,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetInputDynamicDims(uint32_t modelId, aclmdlD * @param modelDesc [IN] model description * @param index [IN] input tensor index * @param dims [OUT] dims info - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlGetInputDimsV2 @@ -601,11 +524,11 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetInputDims(const aclmdlDesc *modelDesc, siz * @brief get input dims info(version 2), especially for static aipp * it is the same with aclmdlGetInputDims while model without static aipp * - * @param modelDesc [IN] model description - * @param index [IN] input tensor index - * @param dims [OUT] dims info + * @param modelDesc [IN] model description + * @param index [IN] input tensor index + * @param dims [OUT] dims info * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlGetInputDims @@ -616,11 +539,10 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetInputDimsV2(const aclmdlDesc *modelDesc, s * @ingroup AscendCL * @brief get output dims info * - * @param modelDesc [IN] model description - * @param index [IN] output tensor index - * @param dims [OUT] dims info - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param modelDesc [IN] model description + * @param index [IN] output tensor index + * @param dims [OUT] dims info + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetOutputDims(const aclmdlDesc *modelDesc, size_t index, aclmdlIODims *dims); @@ -637,34 +559,20 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetOutputDims(const aclmdlDesc *modelDesc, si * dynamic shape info is not set * @li Get actual output shape when model is static * - * @param modelDesc [IN] model description - * @param index [IN] output tensor index - * @param dims [OUT] dims info - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param modelDesc [IN] model description + * @param index [IN] output tensor index + * @param dims [OUT] dims info + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetCurOutputDims(const aclmdlDesc *modelDesc, size_t index, aclmdlIODims *dims); -/** - * @ingroup AscendCL - * @brief get attr value by op name - * - * @param modelDesc [IN] model description - * @param opName [IN] op name - * @param attr [IN] attr name - * - * @retval the attr value - */ -ACL_FUNC_VISIBILITY const char *aclmdlGetOpAttr(aclmdlDesc *modelDesc, const char *opName, const char *attr); - /** * @ingroup AscendCL * @brief get input name by index * * @param modelDesc [IN] model description - * @param index [IN] intput tensor index - * + * @param index [IN] intput tensor index * @retval input tensor name,the same life cycle with modelDesc */ ACL_FUNC_VISIBILITY const char *aclmdlGetInputNameByIndex(const aclmdlDesc *modelDesc, size_t index); @@ -674,8 +582,7 @@ ACL_FUNC_VISIBILITY const char *aclmdlGetInputNameByIndex(const aclmdlDesc *mode * @brief get output name by index * * @param modelDesc [IN] model description - * @param index [IN] output tensor index - * + * @param index [IN] output tensor index * @retval output tensor name,the same life cycle with modelDesc */ ACL_FUNC_VISIBILITY const char *aclmdlGetOutputNameByIndex(const aclmdlDesc *modelDesc, size_t index); @@ -685,8 +592,7 @@ ACL_FUNC_VISIBILITY const char *aclmdlGetOutputNameByIndex(const aclmdlDesc *mod * @brief get input format by index * * @param modelDesc [IN] model description - * @param index [IN] intput tensor index - * + * @param index [IN] intput tensor index * @retval input tensor format */ ACL_FUNC_VISIBILITY aclFormat aclmdlGetInputFormat(const aclmdlDesc *modelDesc, size_t index); @@ -696,8 +602,7 @@ ACL_FUNC_VISIBILITY aclFormat aclmdlGetInputFormat(const aclmdlDesc *modelDesc, * @brief get output format by index * * @param modelDesc [IN] model description - * @param index [IN] output tensor index - * + * @param index [IN] output tensor index * @retval output tensor format */ ACL_FUNC_VISIBILITY aclFormat aclmdlGetOutputFormat(const aclmdlDesc *modelDesc, size_t index); @@ -708,7 +613,6 @@ ACL_FUNC_VISIBILITY aclFormat aclmdlGetOutputFormat(const aclmdlDesc *modelDesc, * * @param modelDesc [IN] model description * @param index [IN] intput tensor index - * * @retval input tensor data type */ ACL_FUNC_VISIBILITY aclDataType aclmdlGetInputDataType(const aclmdlDesc *modelDesc, size_t index); @@ -719,7 +623,6 @@ ACL_FUNC_VISIBILITY aclDataType aclmdlGetInputDataType(const aclmdlDesc *modelDe * * @param modelDesc [IN] model description * @param index [IN] output tensor index - * * @retval output tensor data type */ ACL_FUNC_VISIBILITY aclDataType aclmdlGetOutputDataType(const aclmdlDesc *modelDesc, size_t index); @@ -729,10 +632,9 @@ ACL_FUNC_VISIBILITY aclDataType aclmdlGetOutputDataType(const aclmdlDesc *modelD * @brief get input tensor index by name * * @param modelDesc [IN] model description - * @param name [IN] intput tensor name + * @param name [IN] intput tensor name * @param index [OUT] intput tensor index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetInputIndexByName(const aclmdlDesc *modelDesc, const char *name, size_t *index); @@ -744,8 +646,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetInputIndexByName(const aclmdlDesc *modelDe * @param modelDesc [IN] model description * @param name [IN] output tensor name * @param index [OUT] output tensor index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetOutputIndexByName(const aclmdlDesc *modelDesc, const char *name, size_t *index); @@ -756,8 +657,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetOutputIndexByName(const aclmdlDesc *modelD * * @param modelDesc [IN] model description * @param batch [OUT] dynamic batch info - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetDynamicBatch(const aclmdlDesc *modelDesc, aclmdlBatch *batch); @@ -769,8 +669,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetDynamicBatch(const aclmdlDesc *modelDesc, * @param modelDesc [IN] model description * @param index [IN] input tensor index * @param hw [OUT] dynamic height&width info - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetDynamicHW(const aclmdlDesc *modelDesc, size_t index, aclmdlHW *hw); @@ -782,8 +681,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetDynamicHW(const aclmdlDesc *modelDesc, siz * @param modelDesc [IN] model description * @param index [IN] unused, must be -1 * @param gearCount [OUT] dynamic gear count - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetInputDynamicGearCount(const aclmdlDesc *modelDesc, size_t index, @@ -797,8 +695,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetInputDynamicGearCount(const aclmdlDesc *mo * @param index [IN] unused, must be -1 * @param dims [OUT] value of dynamic dims * @param gearCount [IN] dynamic gear count - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlGetInputDynamicDims(const aclmdlDesc *modelDesc, size_t index, aclmdlIODims *dims, @@ -809,7 +706,6 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetInputDynamicDims(const aclmdlDesc *modelDe * @brief Create data of type aclmdlAIPP * * @param batchSize [IN] batchsizes of model - * * @retval the aclmdlAIPP pointer */ ACL_FUNC_VISIBILITY aclmdlAIPP *aclmdlCreateAIPP(uint64_t batchSize); @@ -819,8 +715,7 @@ ACL_FUNC_VISIBILITY aclmdlAIPP *aclmdlCreateAIPP(uint64_t batchSize); * @brief destroy data of type aclmdlAIPP * * @param aippParmsSet [IN] Pointer for aclmdlAIPP to be destroyed - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlDestroyAIPP(const aclmdlAIPP *aippParmsSet); @@ -829,10 +724,9 @@ ACL_FUNC_VISIBILITY aclError aclmdlDestroyAIPP(const aclmdlAIPP *aippParmsSet); * @ingroup AscendCL * @brief set InputFormat of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param inputFormat [IN] The inputFormat of aipp - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -843,7 +737,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPInputFormat(aclmdlAIPP *aippParmsSet, * @ingroup AscendCL * @brief set cscParms of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param csc_switch [IN] Csc switch * @param cscMatrixR0C0 [IN] Csc_matrix_r0_c0 * @param cscMatrixR0C1 [IN] Csc_matrix_r0_c1 @@ -860,13 +754,12 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPInputFormat(aclmdlAIPP *aippParmsSet, * @param cscInputBiasR0 [IN] Input Bias for YUV to RGB, element of row 0, unsigned number * @param cscInputBiasR1 [IN] Input Bias for YUV to RGB, element of row 1, unsigned number * @param cscInputBiasR2 [IN] Input Bias for YUV to RGB, element of row 2, unsigned number - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP */ -ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPCscParams(aclmdlAIPP *aippParmsSet, int8_t cscSwitch, +ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPCscParams(aclmdlAIPP *aippParmsSet, int8_t csc_switch, int16_t cscMatrixR0C0, int16_t cscMatrixR0C1, int16_t cscMatrixR0C2, int16_t cscMatrixR1C0, int16_t cscMatrixR1C1, int16_t cscMatrixR1C2, int16_t cscMatrixR2C0, int16_t cscMatrixR2C1, int16_t cscMatrixR2C2, @@ -878,10 +771,9 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPCscParams(aclmdlAIPP *aippParmsSet, in * @ingroup AscendCL * @brief set rb/ub swap switch of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param rbuvSwapSwitch [IN] rb/ub swap switch - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -892,10 +784,9 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPRbuvSwapSwitch(aclmdlAIPP *aippParmsSe * @ingroup AscendCL * @brief set RGBA->ARGB, YUVA->AYUV swap switch of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param axSwapSwitch [IN] RGBA->ARGB, YUVA->AYUV swap switch - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -906,31 +797,29 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPAxSwapSwitch(aclmdlAIPP *aippParmsSet, * @ingroup AscendCL * @brief set source image of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param srcImageSizeW [IN] Source image width * @param srcImageSizeH [IN] Source image height - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP */ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPSrcImageSize(aclmdlAIPP *aippParmsSet, int32_t srcImageSizeW, - int32_t srcImageSizeH); + int32_t srcImageSizeH); /** * @ingroup AscendCL * @brief set resize switch of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param scfSwitch [IN] Resize switch * @param scfInputSizeW [IN] Input width of scf * @param scfInputSizeH [IN] Input height of scf * @param scfOutputSizeW [IN] Output width of scf * @param scfOutputSizeH [IN] Output height of scf * @param batchIndex [IN] Batch parameter index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -947,15 +836,14 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPScfParams(aclmdlAIPP *aippParmsSet, * @ingroup AscendCL * @brief set cropParams of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param cropSwitch [IN] Crop switch * @param cropStartPosW [IN] The start horizontal position of cropping * @param cropStartPosH [IN] The start vertical position of cropping * @param cropSizeW [IN] Crop width * @param cropSizeH [IN] Crop height * @param batchIndex [IN] Batch parameter index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -972,15 +860,14 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPCropParams(aclmdlAIPP *aippParmsSet, * @ingroup AscendCL * @brief set paddingParams of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param paddingSwitch [IN] Padding switch * @param paddingSizeTop [IN] Top padding size * @param paddingSizeBottom [IN] Bottom padding size * @param paddingSizeLeft [IN] Left padding size * @param paddingSizeRight [IN] Right padding size * @param batchIndex [IN] Batch parameter index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -994,14 +881,13 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPPaddingParams(aclmdlAIPP *aippParmsSet * @ingroup AscendCL * @brief set DtcPixelMean of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param dtcPixelMeanChn0 [IN] Mean value of channel 0 * @param dtcPixelMeanChn1 [IN] Mean value of channel 1 * @param dtcPixelMeanChn2 [IN] Mean value of channel 2 * @param dtcPixelMeanChn3 [IN] Mean value of channel 3 * @param batchIndex [IN] Batch parameter index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -1017,14 +903,13 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPDtcPixelMean(aclmdlAIPP *aippParmsSet, * @ingroup AscendCL * @brief set DtcPixelMin of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param dtcPixelMinChn0 [IN] Min value of channel 0 * @param dtcPixelMinChn1 [IN] Min value of channel 1 * @param dtcPixelMinChn2 [IN] Min value of channel 2 * @param dtcPixelMinChn3 [IN] Min value of channel 3 * @param batchIndex [IN] Batch parameter index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -1040,14 +925,13 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPDtcPixelMin(aclmdlAIPP *aippParmsSet, * @ingroup AscendCL * @brief set PixelVarReci of type aclmdlAIPP * - * @param aippParmsSet [OUT] Pointer for aclmdlAIPP + * @param aippParmsSet [IN] Pointer for aclmdlAIPP * @param dtcPixelVarReciChn0 [IN] sfr_dtc_pixel_variance_reci_ch0 * @param dtcPixelVarReciChn1 [IN] sfr_dtc_pixel_variance_reci_ch1 * @param dtcPixelVarReciChn2 [IN] sfr_dtc_pixel_variance_reci_ch2 * @param dtcPixelVarReciChn3 [IN] sfr_dtc_pixel_variance_reci_ch3 * @param batchIndex [IN] Batch parameter index - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlCreateAIPP @@ -1067,8 +951,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPPixelVarReci(aclmdlAIPP *aippParmsSet, * @param dataset [IN] Pointer of dataset * @param index [IN] index of input for aipp data(ACL_DYNAMIC_AIPP_NODE) * @param aippParmsSet [IN] Pointer for aclmdlAIPP - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | @@ -1087,8 +970,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetInputAIPP(uint32_t modelId, * @param dataset [IN] Pointer of dataset * @param index [IN] index of input for data which linked dynamic aipp(ACL_DATA_WITH_DYNAMIC_AIPP) * @param aippParmsSet [IN] Pointer for aclmdlAIPP - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | @@ -1108,8 +990,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetAIPPByInputIndex(uint32_t modelId, * @param type [OUT] aipp type for input.refrer to aclmdlInputAippType(enum) * @param dynamicAttachedDataIndex [OUT] index for dynamic attached data(ACL_DYNAMIC_AIPP_NODE) * valid when type is ACL_DATA_WITH_DYNAMIC_AIPP, invalid value is ACL_INVALID_NODE_INDEX - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | @@ -1126,16 +1007,15 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetAippType(uint32_t modelId, * * @param modelId [IN] model id * @param index [IN] index of tensor - * @param aippInfo [OUT] Pointer for static aipp info - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param aippinfo [OUT] Pointer for static aipp info + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval ACL_ERROR_MODEL_AIPP_NOT_EXIST The tensor of index is not configured with aipp * @retval OtherValues Failure * * @see aclmdlLoadFromFile | aclmdlLoadFromMem | aclmdlLoadFromFileWithMem | * aclmdlLoadFromMemWithMem | aclmdlGetInputIndexByName */ -ACL_FUNC_VISIBILITY aclError aclmdlGetFirstAippInfo(uint32_t modelId, size_t index, aclAippInfo *aippInfo); +ACL_FUNC_VISIBILITY aclError aclmdlGetFirstAippInfo(uint32_t modelId, size_t index, aclAippInfo *aippinfo); /** * @ingroup AscendCL @@ -1151,7 +1031,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlGetFirstAippInfo(uint32_t modelId, size_t ind * @param outputDesc [OUT] pointer to output description * @param numOutputs [OUT] the number of output tensor * - * @retval ACL_SUCCESS The function is successfully executed + * @retval ACL_ERROR_NONE The function is successfully executed * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlCreateAndGetOpDesc(uint32_t deviceId, uint32_t streamId, @@ -1162,7 +1042,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlCreateAndGetOpDesc(uint32_t deviceId, uint32_ * @ingroup AscendCL * @brief init dump * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlInitDump(); @@ -1173,7 +1053,7 @@ ACL_FUNC_VISIBILITY aclError aclmdlInitDump(); * * @param dumpCfgPath [IN] the path of dump config * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlSetDump(const char *dumpCfgPath); @@ -1182,73 +1062,11 @@ ACL_FUNC_VISIBILITY aclError aclmdlSetDump(const char *dumpCfgPath); * @ingroup AscendCL * @brief finalize dump. * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclmdlFinalizeDump(); -/** - * @ingroup AscendCL - * @brief load model with config - * - * @param handle [IN] pointer to model config handle - * @param modelId [OUT] pointer to model id - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure -*/ -ACL_FUNC_VISIBILITY aclError aclmdlLoadWithConfig(const aclmdlConfigHandle *handle, uint32_t *modelId); - -/** - * @ingroup AscendCL - * @brief create model config handle of type aclmdlConfigHandle - * - * @retval the aclmdlConfigHandle pointer - * - * @see aclmdlDestroyConfigHandle -*/ -ACL_FUNC_VISIBILITY aclmdlConfigHandle *aclmdlCreateConfigHandle(); - -/** - * @ingroup AscendCL - * @brief destroy data of type aclmdlConfigHandle - * - * @param handle [IN] pointer to model config handle - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclmdlCreateConfigHandle - */ -ACL_FUNC_VISIBILITY aclError aclmdlDestroyConfigHandle(aclmdlConfigHandle *handle); - -/** - * @ingroup AscendCL - * @brief set config for model load - * - * @param handle [OUT] pointer to model config handle - * @param attr [IN] config attr in model config handle to be set - * @param attrValue [IN] pointer to model config value - * @param valueSize [IN] memory size of attrValue - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclmdlSetConfigOpt(aclmdlConfigHandle *handle, aclmdlConfigAttr attr, - const void *attrValue, size_t valueSize); - -/** - * @ingroup AscendCL - * @brief get real tensor name from modelDesc - * - * @param modelDesc [IN] pointer to modelDesc - * @param name [IN] tensor name - * - * @retval the pointer of real tensor name - * @retval Failure return NULL - */ -ACL_FUNC_VISIBILITY const char *aclmdlGetTensorRealName(const aclmdlDesc *modelDesc, const char *name); - #ifdef __cplusplus } #endif diff --git a/third_party/acl/inc/acl/acl_op.h b/third_party/acl/inc/acl/acl_op.h index e5da43ee41..e0b9e9b03d 100644 --- a/third_party/acl/inc/acl/acl_op.h +++ b/third_party/acl/inc/acl/acl_op.h @@ -1,12 +1,12 @@ /** -* @file acl_op.h -* -* Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. All Rights Reserved. -* -* This program 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. -*/ + * @file acl_op.h + * + * Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. All Rights Reserved. + * + * This program 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. + */ #ifndef INC_EXTERNAL_ACL_ACL_OP_H_ #define INC_EXTERNAL_ACL_ACL_OP_H_ @@ -21,14 +21,14 @@ typedef struct aclopHandle aclopHandle; typedef struct aclopAttr aclopAttr; typedef struct aclopKernelDesc aclopKernelDesc; -typedef void (*aclDataDeallocator)(void *data, size_t length); +typedef void (*aclDataDeallocator)(void* data, size_t length); static const int ACL_COMPILE_FLAG_BIN_SELECTOR = 1; typedef enum aclEngineType { - ACL_ENGINE_SYS, - ACL_ENGINE_AICORE, - ACL_ENGINE_VECTOR, + ACL_ENGINE_SYS, + ACL_ENGINE_AICORE, + ACL_ENGINE_VECTOR, } aclopEngineType; /** @@ -38,11 +38,10 @@ typedef enum aclEngineType { * @par Restriction * The aclopSetModelDir interface can be called only once in a process. * @param modelDir [IN] path of the directory - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetModelDir(const char *modelDir); +ACL_FUNC_VISIBILITY aclError aclopSetModelDir(const char* modelDir); /** * @ingroup AscendCL @@ -52,11 +51,10 @@ ACL_FUNC_VISIBILITY aclError aclopSetModelDir(const char *modelDir); * The aclopLoad interface can be called more than one times in a process. * @param model [IN] address of single op models * @param modelSize [IN] size of single op models - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopLoad(const void *model, size_t modelSize); +ACL_FUNC_VISIBILITY aclError aclopLoad(const void* model, size_t modelSize); /** * @ingroup AscendCL @@ -65,7 +63,7 @@ ACL_FUNC_VISIBILITY aclError aclopLoad(const void *model, size_t modelSize); * @retval pointer to created instance. * @retval nullptr if run out of memory */ -ACL_FUNC_VISIBILITY aclopAttr *aclopCreateAttr(); +ACL_FUNC_VISIBILITY aclopAttr* aclopCreateAttr(); /** * @ingroup AscendCL @@ -73,167 +71,150 @@ ACL_FUNC_VISIBILITY aclopAttr *aclopCreateAttr(); * * @param attr [IN] pointer to the instance of aclopAttr */ -ACL_FUNC_VISIBILITY void aclopDestroyAttr(const aclopAttr *attr); +ACL_FUNC_VISIBILITY void aclopDestroyAttr(const aclopAttr* attr); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is bool * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param attrValue [IN] attribute value * false if attrValue is 0, true otherwise. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrBool(aclopAttr *attr, const char *attrName, uint8_t attrValue); +ACL_FUNC_VISIBILITY aclError +aclopSetAttrBool(aclopAttr* attr, const char* attrName, uint8_t attrValue); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is int64_t * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param attrValue [IN] attribute value - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrInt(aclopAttr *attr, const char *attrName, int64_t attrValue); +ACL_FUNC_VISIBILITY aclError +aclopSetAttrInt(aclopAttr* attr, const char* attrName, int64_t attrValue); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is float * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param attrValue [IN] attribute value - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrFloat(aclopAttr *attr, const char *attrName, float attrValue); +ACL_FUNC_VISIBILITY aclError +aclopSetAttrFloat(aclopAttr* attr, const char* attrName, float attrValue); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is string * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param attrValue [IN] attribute value - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrString(aclopAttr *attr, const char *attrName, const char *attrValue); - -/** - * @ingroup AscendCL - * @brief set an attribute. the type of the attribute is aclDataType - * - * @param attr [OUT] pointer to the instance of aclopAttr - * @param attrName [IN] attribute name - * @param attrValue [IN] attribute value - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrDataType(aclopAttr *attr, const char *attrName, aclDataType attrValue); - -/** - * @ingroup AscendCL - * @brief set an attribute. the type of the attribute is list of aclDataType - * - * @param attr [OUT] pointer to the instance of aclopAttr - * @param attrName [IN] attribute name - * @param numValues [IN] number of values. false if attrValue is 0, true otherwise. - * @param values [IN] pointer to values - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrListDataType(aclopAttr *attr, const char *attrName, int numValues, - const aclDataType values[]); +ACL_FUNC_VISIBILITY aclError aclopSetAttrString( + aclopAttr* attr, + const char* attrName, + const char* attrValue); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is list of bools * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name - * @param numValues [IN] number of values. false if attrValue is 0, true otherwise. + * @param numValues [IN] number of values. false if attrValue is 0, true + * otherwise. * @param values [IN] pointer to values - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrListBool(aclopAttr *attr, const char *attrName, int numValues, - const uint8_t *values); +ACL_FUNC_VISIBILITY aclError aclopSetAttrListBool( + aclopAttr* attr, + const char* attrName, + int numValues, + const uint8_t* values); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is list of ints * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param numValues [IN] number of values * @param values [IN] pointer to values - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrListInt(aclopAttr *attr, const char *attrName, int numValues, - const int64_t *values); +ACL_FUNC_VISIBILITY aclError aclopSetAttrListInt( + aclopAttr* attr, + const char* attrName, + int numValues, + const int64_t* values); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is list of floats * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param numValues [IN] number of values * @param values [IN] pointer to values - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrListFloat(aclopAttr *attr, const char *attrName, int numValues, - const float *values); +ACL_FUNC_VISIBILITY aclError aclopSetAttrListFloat( + aclopAttr* attr, + const char* attrName, + int numValues, + const float* values); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is list of strings * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param numValues [IN] number of values * @param values [IN] pointer to values - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrListString(aclopAttr *attr, const char *attrName, int numValues, - const char **values); +ACL_FUNC_VISIBILITY aclError aclopSetAttrListString( + aclopAttr* attr, + const char* attrName, + int numValues, + const char** values); /** * @ingroup AscendCL * @brief set an attribute. the type of the attribute is list of list of ints * - * @param attr [OUT] pointer to the instance of aclopAttr + * @param attr [IN] pointer to the instance of aclopAttr * @param attrName [IN] attribute name * @param numLists [IN] number of lists * @param numValues [IN] pointer to number of values of each list * @param values [IN] pointer to values - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetAttrListListInt(aclopAttr *attr, - const char *attrName, - int numLists, - const int *numValues, - const int64_t *const values[]); +ACL_FUNC_VISIBILITY aclError aclopSetAttrListListInt( + aclopAttr* attr, + const char* attrName, + int numLists, + const int* numValues, + const int64_t* const values[]); /** * @ingroup AscendCL @@ -247,7 +228,6 @@ ACL_FUNC_VISIBILITY aclError aclopSetAttrListListInt(aclopAttr *attr, * the ACL finds the corresponding task according to the optype, * the description of the input tesnsor, * the description of the output tesnsor, and attr, and issues the execution. - * * @param opType [IN] type of op * @param numInputs [IN] number of inputs * @param inputDesc [IN] pointer to array of input tensor descriptions @@ -258,25 +238,25 @@ ACL_FUNC_VISIBILITY aclError aclopSetAttrListListInt(aclopAttr *attr, * @param attr [IN] pointer to instance of aclopAttr. * may pass nullptr if the op has no attribute * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_DEPRECATED_MESSAGE("aclopExecute is deprecated, use aclopExecuteV2 instead") -ACL_FUNC_VISIBILITY aclError aclopExecute(const char *opType, - int numInputs, - const aclTensorDesc *const inputDesc[], - const aclDataBuffer *const inputs[], - int numOutputs, - const aclTensorDesc *const outputDesc[], - aclDataBuffer *const outputs[], - const aclopAttr *attr, - aclrtStream stream); +ACL_FUNC_VISIBILITY aclError aclopExecute( + const char* opType, + int numInputs, + const aclTensorDesc* const inputDesc[], + const aclDataBuffer* const inputs[], + int numOutputs, + const aclTensorDesc* const outputDesc[], + aclDataBuffer* const outputs[], + const aclopAttr* attr, + aclrtStream stream); /** * @ingroup AscendCL * @brief Load and execute the specified operator - * The difference with aclopExecute is that aclopExecuteV2 will refresh outputDesc + * The difference with aclopExecute is that aclopExecuteV2 will refresh + * outputDesc * * @par Restriction * @li The input and output organization of each operator is different, @@ -292,24 +272,25 @@ ACL_FUNC_VISIBILITY aclError aclopExecute(const char *opType, * @param inputDesc [IN] pointer to array of input tensor descriptions * @param inputs [IN] pointer to array of input buffers * @param numOutputs [IN] number of outputs - * @param outputDesc [IN|OUT] pointer to array of output tensor descriptions + * @param outputDesc [IN] pointer to array of output tensor descriptions * @param outputs [OUT] pointer to array of output buffers * @param attr [IN] pointer to instance of aclopAttr. * may pass nullptr if the op has no attribute * @param stream [IN] stream * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopExecuteV2(const char *opType, - int numInputs, - aclTensorDesc *inputDesc[], - aclDataBuffer *inputs[], - int numOutputs, - aclTensorDesc *outputDesc[], - aclDataBuffer *outputs[], - aclopAttr *attr, - aclrtStream stream); +ACL_FUNC_VISIBILITY aclError aclopExecuteV2( + const char* opType, + int numInputs, + aclTensorDesc* inputDesc[], + aclDataBuffer* inputs[], + int numOutputs, + aclTensorDesc* outputDesc[], + aclDataBuffer* outputs[], + aclopAttr* attr, + aclrtStream stream); /** * @ingroup AscendCL @@ -323,17 +304,17 @@ ACL_FUNC_VISIBILITY aclError aclopExecuteV2(const char *opType, * @param opAttr [IN] pointer to instance of aclopAttr. * may pass nullptr if the op has no attribute * @param handle [OUT] pointer to the pointer to the handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopCreateHandle(const char *opType, - int numInputs, - const aclTensorDesc *const inputDesc[], - int numOutputs, - const aclTensorDesc *const outputDesc[], - const aclopAttr *opAttr, - aclopHandle **handle); +ACL_FUNC_VISIBILITY aclError aclopCreateHandle( + const char* opType, + int numInputs, + const aclTensorDesc* const inputDesc[], + int numOutputs, + const aclTensorDesc* const outputDesc[], + const aclopAttr* opAttr, + aclopHandle** handle); /** * @ingroup AscendCL @@ -341,7 +322,7 @@ ACL_FUNC_VISIBILITY aclError aclopCreateHandle(const char *opType, * * @param handle [IN] pointer to the instance of aclopHandle */ -ACL_FUNC_VISIBILITY void aclopDestroyHandle(aclopHandle *handle); +ACL_FUNC_VISIBILITY void aclopDestroyHandle(aclopHandle* handle); /** * @ingroup AscendCL @@ -356,20 +337,20 @@ ACL_FUNC_VISIBILITY void aclopDestroyHandle(aclopHandle *handle); * The aclCreateDataBuffer interface has been called * in advance to create aclDataBuffer type data. * @param numOutputs [IN] number of outputs - * @param outputs [OUT] pointer to array of output buffers + * @param outputs [IN] pointer to array of output buffers * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclopCreateHandle | aclCreateDataBuffer */ -ACL_FUNC_VISIBILITY aclError aclopExecWithHandle(aclopHandle *handle, - int numInputs, - const aclDataBuffer *const inputs[], - int numOutputs, - aclDataBuffer *const outputs[], - aclrtStream stream); +ACL_FUNC_VISIBILITY aclError aclopExecWithHandle( + aclopHandle* handle, + int numInputs, + const aclDataBuffer* const inputs[], + int numOutputs, + aclDataBuffer* const outputs[], + aclrtStream stream); /** * @ingroup AscendCL @@ -381,34 +362,33 @@ ACL_FUNC_VISIBILITY aclError aclopExecWithHandle(aclopHandle *handle, * @param dstBuffer [OUT] destination tensor buffer * @param truncate [IN] do not truncate if value is 0, truncate otherwise * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopCast(const aclTensorDesc *srcDesc, - const aclDataBuffer *srcBuffer, - const aclTensorDesc *dstDesc, - aclDataBuffer *dstBuffer, - uint8_t truncate, - aclrtStream stream); +ACL_FUNC_VISIBILITY aclError aclopCast( + const aclTensorDesc* srcDesc, + const aclDataBuffer* srcBuffer, + const aclTensorDesc* dstDesc, + aclDataBuffer* dstBuffer, + uint8_t truncate, + aclrtStream stream); /** * @ingroup AscendCL * @brief create a handle for casting datatype * - * @param srcDesc [IN] source tensor desc - * @param dstDesc [IN] destination tensor desc - * @param truncate [IN] do not truncate if value is 0, truncate otherwise - * @param handle [OUT] pointer to the pointer to the handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param srcDesc [IN] source tensor desc + * @param dstDesc [IN] destination tensor desc + * @param truncate [IN] do not truncate if value is 0, truncate otherwise + * @param handle [IN] pointer to the pointer to the handle + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopCreateHandleForCast(aclTensorDesc *srcDesc, - aclTensorDesc *dstDesc, - uint8_t truncate, - aclopHandle **handle); - +ACL_FUNC_VISIBILITY aclError aclopCreateHandleForCast( + aclTensorDesc* srcDesc, + aclTensorDesc* dstDesc, + uint8_t truncate, + aclopHandle** handle); /** * @ingroup AscendCL @@ -422,41 +402,42 @@ ACL_FUNC_VISIBILITY aclError aclopCreateHandleForCast(aclTensorDesc *srcDesc, * @param enginetype [IN] enigne type * @param deallocator [IN] callback function for deallocating bin data, * null if bin data to be deallocated by caller - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclopCompile */ -ACL_FUNC_VISIBILITY aclError aclopCreateKernel(const char *opType, - const char *kernelId, - const char *kernelName, - void *binData, - int binSize, - aclopEngineType enginetype, - aclDataDeallocator deallocator); - +ACL_FUNC_VISIBILITY aclError aclopCreateKernel( + const char* opType, + const char* kernelId, + const char* kernelName, + void* binData, + int binSize, + aclopEngineType enginetype, + aclDataDeallocator deallocator); /** * @ingroup AscendCL * @brief create kernel * * @param numInputs [IN] number of inputs - * @param inputDesc [IN] pointer to array of input tensor descriptions + * @param inputDesc [IN] pointer to array of input tensor + * descriptions * @param numOutputs [IN] number of outputs - * @param outputDesc [IN] pointer to array of output tensor descriptions + * @param outputDesc [IN] pointer to array of output tensor + * descriptions * @param opAttr [IN] pointer to instance of aclopAttr * @param aclopKernelDesc [IN] pointer to instance of aclopKernelDesc - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -typedef aclError (*aclopCompileFunc)(int numInputs, - const aclTensorDesc *const inputDesc[], - int numOutputs, - const aclTensorDesc *const outputDesc[], - const aclopAttr *opAttr, - aclopKernelDesc *aclopKernelDesc); +typedef aclError (*aclopCompileFunc)( + int numInputs, + const aclTensorDesc* const inputDesc[], + int numOutputs, + const aclTensorDesc* const outputDesc[], + const aclopAttr* opAttr, + aclopKernelDesc* aclopKernelDesc); /** * @ingroup AscendCL @@ -464,24 +445,23 @@ typedef aclError (*aclopCompileFunc)(int numInputs, * * @param opType [IN] op type * @param func [IN] compile function - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclopUnregisterCompileFunc */ -ACL_FUNC_VISIBILITY aclError aclopRegisterCompileFunc(const char *opType, aclopCompileFunc func); +ACL_FUNC_VISIBILITY aclError +aclopRegisterCompileFunc(const char* opType, aclopCompileFunc func); /** * @ingroup AscendCL * @brief unregister compile function * * @param opType [IN] op type - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopUnregisterCompileFunc(const char *opType); +ACL_FUNC_VISIBILITY aclError aclopUnregisterCompileFunc(const char* opType); /** * @ingroup AscendCL @@ -492,15 +472,15 @@ ACL_FUNC_VISIBILITY aclError aclopUnregisterCompileFunc(const char *opType); * @param blockDim [IN] block dim * @param args [IN] args * @param argSize [IN] size in bytes of args - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetKernelArgs(aclopKernelDesc *kernelDesc, - const char *kernelId, - uint32_t blockDim, - const void *args, - uint32_t argSize); +ACL_FUNC_VISIBILITY aclError aclopSetKernelArgs( + aclopKernelDesc* kernelDesc, + const char* kernelId, + uint32_t blockDim, + const void* args, + uint32_t argSize); /** * @ingroup AscendCL @@ -509,58 +489,62 @@ ACL_FUNC_VISIBILITY aclError aclopSetKernelArgs(aclopKernelDesc *kernelDesc, * @param kernelDesc [IN] pointer to instance of aclopKernelDesc * @param numWorkspaces [IN] number of workspaces * @param workspaceSizes [IN] pointer to array of sizes of workspaces - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetKernelWorkspaceSizes(aclopKernelDesc *kernelDesc, int numWorkspaces, - size_t *workspaceSizes); +ACL_FUNC_VISIBILITY aclError aclopSetKernelWorkspaceSizes( + aclopKernelDesc* kernelDesc, + int numWorkspaces, + size_t* workspaceSizes); /** * @ingroup AscendCL * @brief compile op with dynamic shape * - * @param opType [IN] op type - * @param numInputs [IN] number of inputs - * @param inputDesc [IN] pointer to array of input tensor descriptions - * @param numOutputs [IN] number of outputs - * @param outputDesc [IN] pointer to array of output tensor descriptions - * @param attr [IN] pointer to instance of aclopAttr. - * may pass nullptr if the op has no attribute - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param opType [IN] op type + * @param numInputs [IN] number of inputs + * @param inputDesc [IN] pointer to array of input tensor descriptions + * @param numOutputs [IN] number of outputs + * @param outputDesc [IN] pointer to array of output tensor descriptions + * @param attr [IN] pointer to instance of aclopAttr. + * may pass nullptr if the op has no attribute + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopUpdateParams(const char *opType, - int numInputs, - const aclTensorDesc *const inputDesc[], - int numOutputs, - const aclTensorDesc *const outputDesc[], - const aclopAttr *attr); +ACL_FUNC_VISIBILITY aclError aclopUpdateParams( + const char* opType, + int numInputs, + const aclTensorDesc* const inputDesc[], + int numOutputs, + const aclTensorDesc* const outputDesc[], + const aclopAttr* attr); /** * @ingroup AscendCL * @brief inferShape the specified operator synchronously * - * @param opType [IN] type of op - * @param numInputs [IN] number of inputs - * @param inputDesc [IN] pointer to array of input tensor descriptions - * @param inputs [IN] pointer to array of input buffers - * @param numOutputs [IN] number of outputs - * @param outputDesc [OUT] pointer to array of output tensor descriptions - * @param attr [IN] pointer to instance of aclopAttr. - * may pass nullptr if the op has no attribute - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param opType [IN] type of op + * @param numInputs [IN] number of inputs + * @param inputDesc [IN] pointer to array of input tensor descriptions + * @param inputs [IN] pointer to array of input buffers + * @param numOutputs [IN] number of outputs + * @param outputDesc [IN] pointer to array of output tensor descriptions + * @param attr [IN] pointer to instance of aclopAttr. + * may pass nullptr if the op has no attribute + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopInferShape(const char *opType, - int numInputs, - aclTensorDesc *inputDesc[], - aclDataBuffer *inputs[], - int numOutputs, - aclTensorDesc *outputDesc[], - aclopAttr *attr); +ACL_FUNC_VISIBILITY aclError aclopInferShape( + const char* opType, + int numInputs, + aclTensorDesc* inputDesc[], + aclDataBuffer* inputs[], + int numOutputs, + aclTensorDesc* outputDesc[], + aclopAttr* attr); + +ACL_FUNC_VISIBILITY aclError +aclSetTensorConst(aclTensorDesc* desc, void* dataBuffer, size_t length); #ifdef __cplusplus diff --git a/third_party/acl/inc/acl/acl_op_compiler.h b/third_party/acl/inc/acl/acl_op_compiler.h index 55b4c7ebcc..0807efbd8e 100644 --- a/third_party/acl/inc/acl/acl_op_compiler.h +++ b/third_party/acl/inc/acl/acl_op_compiler.h @@ -35,12 +35,10 @@ typedef enum { ACL_OP_PERFORMANCE_MODE } aclCompileOpt; -typedef enum aclCompileFlag { - ACL_OP_COMPILE_DEFAULT, - ACL_OP_COMPILE_FUZZ -} aclOpCompileFlag; - -typedef struct aclGraphDumpOption aclGraphDumpOption; +typedef enum aclCompileFlag{ + ACL_OP_COMPILE_DEFAULT = 0, + ACL_OP_COMPILE_FUZZ = 1, +}aclOpCompileFlag; /** * @ingroup AscendCL @@ -56,8 +54,7 @@ typedef struct aclGraphDumpOption aclGraphDumpOption; * @param engineType [IN] engine type * @param compileFlag [IN] compile flag * @param opPath [IN] path of op - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclopCompile(const char *opType, @@ -87,8 +84,7 @@ ACL_FUNC_VISIBILITY aclError aclopCompile(const char *opType, * @param compileFlag [IN] compile flag * @param opPath [IN] path of op * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclopCompileAndExecute(const char *opType, @@ -97,34 +93,6 @@ ACL_FUNC_VISIBILITY aclError aclopCompileAndExecute(const char *opType, const aclopAttr *attr, aclopEngineType engineType, aclopCompileType compileFlag, const char *opPath, aclrtStream stream); - -/** - * @ingroup AscendCL - * @brief compile and execute op - * - * @param opType [IN] op type - * @param numInputs [IN] number of inputs - * @param inputDesc [IN] pointer to array of input tensor descriptions - * @param inputs [IN] pointer to array of input buffers - * @param numOutputs [IN] number of outputs - * @param outputDesc [IN|OUT] pointer to array of output tensor descriptions - * @param outputs [IN] pointer to array of outputs buffers - * @param attr [IN] pointer to instance of aclopAttr. - * may pass nullptr if the op has no attribute - * @param engineType [IN] engine type - * @param compileFlag [IN] compile flag - * @param opPath [IN] path of op - * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclopCompileAndExecuteV2(const char *opType, - int numInputs, aclTensorDesc *inputDesc[], aclDataBuffer *inputs[], - int numOutputs, aclTensorDesc *outputDesc[], aclDataBuffer *outputs[], - aclopAttr *attr, aclopEngineType engineType, aclopCompileType compileFlag, - const char *opPath, aclrtStream stream); - /** * @ingroup AscendCL * @brief set compile option @@ -139,19 +107,26 @@ ACL_FUNC_VISIBILITY aclError aclSetCompileopt(aclCompileOpt opt, const char *val /** * @ingroup AscendCL - * @brief set compile flag + * @brief set compile option * - * @param flag [IN] compile flag, ACL_OP_COMPILE_DEFAULT means compile with default mode - * ACL_OP_COMPILE_FUZZ means compile with fuzz mode + * @param aclCompileOpt [IN] compile option + * @param value [IN] pointer for the option value * * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -ACL_FUNC_VISIBILITY aclError aclopSetCompileFlag(aclOpCompileFlag flag); +ACL_FUNC_VISIBILITY aclError aclSetCompileopt(aclCompileOpt opt, const char *value); + +typedef enum { + ACL_GRAPH_STAGE_ORIGIN = 0, // default + ACL_GRAPH_STAGE_FUZZ = 1, +} aclGraphStage; + +typedef struct aclGraphDumpOption aclGraphDumpOption; /** * @ingroup AscendCL - * @brief generate graph and dump + * @brief dump op graph for AOE * * @param opType [IN] op type * @param numInputs [IN] number of inputs @@ -163,41 +138,20 @@ ACL_FUNC_VISIBILITY aclError aclopSetCompileFlag(aclOpCompileFlag flag); * @param attr [IN] pointer to instance of aclopAttr. * may pass nullptr if the op has no attribute * @param engineType [IN] engine type - * @param graphDumpPath [IN] dump path, if the suffix is ".txt", it means file path, else it means directory path - * @param graphDumpOpt [IN] dump option, nullptr is supported - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param graphDumpPath [IN] path to save dump graph of op + * @param aclGraphDumpOption [IN] dump graph option + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclGenGraphAndDumpForOp(const char *opType, int numInputs, const aclTensorDesc *const inputDesc[], const aclDataBuffer *const inputs[], int numOutputs, const aclTensorDesc *const outputDesc[], aclDataBuffer *const outputs[], - const aclopAttr *attr, aclopEngineType engineType, - const char *graphDumpPath, const aclGraphDumpOption *graphDumpOpt); + const aclopAttr *attr, aclopEngineType engineType, const char *graphDumpPath, + aclGraphDumpOption* graphdumpOpt); -/** - * @ingroup AscendCL - * @brief Create the graph dump option - * - * @retval null for failed - * @retval OtherValues success - * - * @see aclDestroyGraphDumpOpt - */ -ACL_FUNC_VISIBILITY aclGraphDumpOption *aclCreateGraphDumpOpt(); +ACL_FUNC_VISIBILITY aclGraphDumpOption* aclCreateGraphDumpOpt(); -/** - * @ingroup AscendCL - * @brief Destroy graph dump option - * - * @param graphDumpOpt [IN] pointer to the graph dump option - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclCreateGraphDumpOpt - */ -ACL_FUNC_VISIBILITY aclError aclDestroyGraphDumpOpt(const aclGraphDumpOption *graphDumpOpt); +ACL_FUNC_VISIBILITY aclError aclDestroyGraphDumpOpt(aclGraphDumpOption* aclGraphDumpOpt); #ifdef __cplusplus } diff --git a/third_party/acl/inc/acl/acl_prof.h b/third_party/acl/inc/acl/acl_prof.h index 4328828647..9849f67367 100644 --- a/third_party/acl/inc/acl/acl_prof.h +++ b/third_party/acl/inc/acl/acl_prof.h @@ -1,7 +1,7 @@ /** * @file acl_prof.h * -* Copyright (C) Huawei Technologies Co., Ltd. 2019-2021. All Rights Reserved. +* Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. All Rights Reserved. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -11,26 +11,16 @@ #ifndef INC_EXTERNAL_ACL_PROF_H_ #define INC_EXTERNAL_ACL_PROF_H_ -#if (defined(_WIN32) || defined(_WIN64) || defined(_MSC_VER)) -#define MSVP_PROF_API __declspec(dllexport) -#else -#define MSVP_PROF_API __attribute__((visibility("default"))) -#endif - #include "acl_base.h" #ifdef __cplusplus extern "C" { #endif -#define ACL_PROF_ACL_API 0x0001ULL -#define ACL_PROF_TASK_TIME 0x0002ULL -#define ACL_PROF_AICORE_METRICS 0x0004ULL -#define ACL_PROF_AICPU 0x0008ULL -#define ACL_PROF_L2CACHE 0x0010ULL -#define ACL_PROF_HCCL_TRACE 0x0020ULL -#define ACL_PROF_TRAINING_TRACE 0x0040ULL -#define ACL_PROF_MSPROFTX 0x0080ULL +#define ACL_PROF_ACL_API 0x0001 +#define ACL_PROF_TASK_TIME 0x0002 +#define ACL_PROF_AICORE_METRICS 0x0004 +#define ACL_PROF_AICPU 0x0008 /** * @deprecated please use aclprofGetOpTypeLen and aclprofGetOpTNameLen instead @@ -44,21 +34,13 @@ typedef enum { ACL_AICORE_MEMORY_BANDWIDTH = 2, ACL_AICORE_L0B_AND_WIDTH = 3, ACL_AICORE_RESOURCE_CONFLICT_RATIO = 4, - ACL_AICORE_MEMORY_UB = 5, ACL_AICORE_NONE = 0xFF } aclprofAicoreMetrics; -typedef enum { - ACL_STEP_START = 0, // step start - ACL_STEP_END = 1 // step end -} aclprofStepTag; - - typedef struct aclprofConfig aclprofConfig; typedef struct aclprofStopConfig aclprofStopConfig; typedef struct aclprofAicoreEvents aclprofAicoreEvents; typedef struct aclprofSubscribeConfig aclprofSubscribeConfig; -typedef struct aclprofStepInfo aclprofStepInfo; /** * @ingroup AscendCL @@ -72,7 +54,7 @@ typedef struct aclprofStepInfo aclprofStepInfo; * * @see aclprofFinalize */ -MSVP_PROF_API aclError aclprofInit(const char *profilerResultPath, size_t length); +ACL_FUNC_VISIBILITY aclError aclprofInit(const char *profilerResultPath, size_t length); /** * @ingroup AscendCL @@ -83,7 +65,7 @@ MSVP_PROF_API aclError aclprofInit(const char *profilerResultPath, size_t length * * @see aclprofInit */ -MSVP_PROF_API aclError aclprofFinalize(); +ACL_FUNC_VISIBILITY aclError aclprofFinalize(); /** * @ingroup AscendCL @@ -96,7 +78,7 @@ MSVP_PROF_API aclError aclprofFinalize(); * * @see aclprofStop */ -MSVP_PROF_API aclError aclprofStart(const aclprofConfig *profilerConfig); +ACL_FUNC_VISIBILITY aclError aclprofStart(const aclprofConfig *profilerConfig); /** * @ingroup AscendCL @@ -112,7 +94,7 @@ MSVP_PROF_API aclError aclprofStart(const aclprofConfig *profilerConfig); * * @see aclprofDestroyConfig */ -MSVP_PROF_API aclprofConfig *aclprofCreateConfig(uint32_t *deviceIdList, uint32_t deviceNums, +ACL_FUNC_VISIBILITY aclprofConfig *aclprofCreateConfig(uint32_t *deviceIdList, uint32_t deviceNums, aclprofAicoreMetrics aicoreMetrics, aclprofAicoreEvents *aicoreEvents, uint64_t dataTypeConfig); /** @@ -126,7 +108,7 @@ MSVP_PROF_API aclprofConfig *aclprofCreateConfig(uint32_t *deviceIdList, uint32_ * * @see aclprofCreateConfig */ -MSVP_PROF_API aclError aclprofDestroyConfig(const aclprofConfig *profilerConfig); +ACL_FUNC_VISIBILITY aclError aclprofDestroyConfig(const aclprofConfig *profilerConfig); /** * @ingroup AscendCL @@ -139,7 +121,7 @@ MSVP_PROF_API aclError aclprofDestroyConfig(const aclprofConfig *profilerConfig) * * @see aclprofStart */ -MSVP_PROF_API aclError aclprofStop(const aclprofConfig *profilerConfig); +ACL_FUNC_VISIBILITY aclError aclprofStop(const aclprofConfig *profilerConfig); /** * @ingroup AscendCL @@ -153,7 +135,7 @@ MSVP_PROF_API aclError aclprofStop(const aclprofConfig *profilerConfig); * * @see aclprofModelUnSubscribe */ -MSVP_PROF_API aclError aclprofModelSubscribe(uint32_t modelId, +ACL_FUNC_VISIBILITY aclError aclprofModelSubscribe(uint32_t modelId, const aclprofSubscribeConfig *profSubscribeConfig); /** @@ -167,7 +149,7 @@ MSVP_PROF_API aclError aclprofModelSubscribe(uint32_t modelId, * * @see aclprofModelSubscribe */ -MSVP_PROF_API aclError aclprofModelUnSubscribe(uint32_t modelId); +ACL_FUNC_VISIBILITY aclError aclprofModelUnSubscribe(uint32_t modelId); /** * @ingroup AscendCL @@ -181,7 +163,7 @@ MSVP_PROF_API aclError aclprofModelUnSubscribe(uint32_t modelId); * * @see aclprofDestroySubscribeConfig */ -MSVP_PROF_API aclprofSubscribeConfig *aclprofCreateSubscribeConfig(int8_t timeInfoSwitch, +ACL_FUNC_VISIBILITY aclprofSubscribeConfig *aclprofCreateSubscribeConfig(int8_t timeInfoSwitch, aclprofAicoreMetrics aicoreMetrics, void *fd); /** @@ -195,7 +177,7 @@ MSVP_PROF_API aclprofSubscribeConfig *aclprofCreateSubscribeConfig(int8_t timeIn * * @see aclprofCreateSubscribeConfig */ -MSVP_PROF_API aclError aclprofDestroySubscribeConfig(const aclprofSubscribeConfig *profSubscribeConfig); +ACL_FUNC_VISIBILITY aclError aclprofDestroySubscribeConfig(const aclprofSubscribeConfig *profSubscribeConfig); /** * @ingroup AscendCL @@ -206,7 +188,7 @@ MSVP_PROF_API aclError aclprofDestroySubscribeConfig(const aclprofSubscribeConfi * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -MSVP_PROF_API aclError aclprofGetOpDescSize(size_t *opDescSize); +ACL_FUNC_VISIBILITY aclError aclprofGetOpDescSize(size_t *opDescSize); /** * @ingroup AscendCL @@ -219,7 +201,7 @@ MSVP_PROF_API aclError aclprofGetOpDescSize(size_t *opDescSize); * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -MSVP_PROF_API aclError aclprofGetOpNum(const void *opInfo, size_t opInfoLen, uint32_t *opNumber); +ACL_FUNC_VISIBILITY aclError aclprofGetOpNum(const void *opInfo, size_t opInfoLen, uint32_t *opNumber); /** * @ingroup AscendCL @@ -233,7 +215,7 @@ MSVP_PROF_API aclError aclprofGetOpNum(const void *opInfo, size_t opInfoLen, uin * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -MSVP_PROF_API aclError aclprofGetOpTypeLen(const void *opInfo, size_t opInfoLen, uint32_t index, +ACL_FUNC_VISIBILITY aclError aclprofGetOpTypeLen(const void *opInfo, size_t opInfoLen, uint32_t index, size_t *opTypeLen); /** @@ -249,7 +231,7 @@ MSVP_PROF_API aclError aclprofGetOpTypeLen(const void *opInfo, size_t opInfoLen, * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -MSVP_PROF_API aclError aclprofGetOpType(const void *opInfo, size_t opInfoLen, uint32_t index, +ACL_FUNC_VISIBILITY aclError aclprofGetOpType(const void *opInfo, size_t opInfoLen, uint32_t index, char *opType, size_t opTypeLen); /** @@ -264,7 +246,7 @@ MSVP_PROF_API aclError aclprofGetOpType(const void *opInfo, size_t opInfoLen, ui * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -MSVP_PROF_API aclError aclprofGetOpNameLen(const void *opInfo, size_t opInfoLen, uint32_t index, +ACL_FUNC_VISIBILITY aclError aclprofGetOpNameLen(const void *opInfo, size_t opInfoLen, uint32_t index, size_t *opNameLen); /** @@ -280,7 +262,7 @@ MSVP_PROF_API aclError aclprofGetOpNameLen(const void *opInfo, size_t opInfoLen, * @retval ACL_SUCCESS The function is successfully executed. * @retval OtherValues Failure */ -MSVP_PROF_API aclError aclprofGetOpName(const void *opInfo, size_t opInfoLen, uint32_t index, +ACL_FUNC_VISIBILITY aclError aclprofGetOpName(const void *opInfo, size_t opInfoLen, uint32_t index, char *opName, size_t opNameLen); /** @@ -294,7 +276,7 @@ MSVP_PROF_API aclError aclprofGetOpName(const void *opInfo, size_t opInfoLen, ui * @retval start time(us) of specified op with timestamp * @retval 0 for failed */ -MSVP_PROF_API uint64_t aclprofGetOpStart(const void *opInfo, size_t opInfoLen, uint32_t index); +ACL_FUNC_VISIBILITY uint64_t aclprofGetOpStart(const void *opInfo, size_t opInfoLen, uint32_t index); /** * @ingroup AscendCL @@ -307,7 +289,7 @@ MSVP_PROF_API uint64_t aclprofGetOpStart(const void *opInfo, size_t opInfoLen, u * @retval end time(us) of specified op with timestamp * @retval 0 for failed */ -MSVP_PROF_API uint64_t aclprofGetOpEnd(const void *opInfo, size_t opInfoLen, uint32_t index); +ACL_FUNC_VISIBILITY uint64_t aclprofGetOpEnd(const void *opInfo, size_t opInfoLen, uint32_t index); /** * @ingroup AscendCL @@ -320,7 +302,7 @@ MSVP_PROF_API uint64_t aclprofGetOpEnd(const void *opInfo, size_t opInfoLen, uin * @retval execution time(us) of specified op with timestamp * @retval 0 for failed */ -MSVP_PROF_API uint64_t aclprofGetOpDuration(const void *opInfo, size_t opInfoLen, uint32_t index); +ACL_FUNC_VISIBILITY uint64_t aclprofGetOpDuration(const void *opInfo, size_t opInfoLen, uint32_t index); /** * @ingroup AscendCL @@ -332,112 +314,10 @@ MSVP_PROF_API uint64_t aclprofGetOpDuration(const void *opInfo, size_t opInfoLen * @retval model id of subscription data * @retval 0 for failed */ -MSVP_PROF_API size_t aclprofGetModelId(const void *opInfo, size_t opInfoLen, uint32_t index); +ACL_FUNC_VISIBILITY size_t aclprofGetModelId(const void *opInfo, size_t opInfoLen, uint32_t index); -/** - * @ingroup AscendCL - * @brief - * - * @param stepInfo [IN] pointer to stepInfo data - * @param aclprofstepTag [IN] start or end flag - * @param stream [IN] steam info - * - * @retval 0 for failed - */ -MSVP_PROF_API aclError aclprofGetStepTimestamp(aclprofStepInfo* stepInfo, aclprofStepTag tag, aclrtStream stream); - - /** - * @ingroup AscendCL - * @brief create pointer to aclprofStepInfo data - * - * - * @retval aclprofStepInfo pointer - */ -MSVP_PROF_API aclprofStepInfo* aclprofCreateStepInfo(); - - /** - * @ingroup AscendCL - * @brief destroy aclprofStepInfo pointer - * - * - * @retval void - */ -MSVP_PROF_API void aclprofDestroyStepInfo(aclprofStepInfo* stepinfo); - -/** -* @ingroup AscendCL -* @brief create pointer to aclprofstamp -* -* -* @retval aclprofStamp pointer -*/ -MSVP_PROF_API void *aclprofCreateStamp(); - -/** -* @ingroup AscendCL -* @brief destory stamp pointer -* -* -* @retval void -*/ -MSVP_PROF_API void aclprofDestroyStamp(void *stamp); - -/** -* @ingroup AscendCL -* @brief Record push timestamp -* -* @retval ACL_SUCCESS The function is successfully executed. -* @retval OtherValues Failure -*/ -MSVP_PROF_API aclError aclprofPush(void *stamp); - -/** -* @ingroup AscendCL -* @brief Record pop timestamp -* -* -* @retval ACL_SUCCESS The function is successfully executed. -* @retval OtherValues Failure -*/ -MSVP_PROF_API aclError aclprofPop(); - -/** -* @ingroup AscendCL -* @brief Record range start timestamp -* -* @retval ACL_SUCCESS The function is successfully executed. -* @retval OtherValues Failure -*/ -MSVP_PROF_API aclError aclprofRangeStart(void *stamp, uint32_t *rangeId); - -/** -* @ingroup AscendCL -* @brief Record range end timestamp -* -* @retval ACL_SUCCESS The function is successfully executed. -* @retval OtherValues Failure -*/ -MSVP_PROF_API aclError aclprofRangeStop(uint32_t rangeId); - -/** -* @ingroup AscendCL -* @brief set message to stamp -* -* -* @retval void -*/ -MSVP_PROF_API aclError aclprofSetStampTraceMessage(void *stamp, const char *msg, uint32_t msgLen); - -/** -* @ingroup AscendCL -* @brief Record mark timestamp -* -* @retval ACL_SUCCESS The function is successfully executed. -* @retval OtherValues Failure -*/ -MSVP_PROF_API aclError aclprofMark(void *stamp); #ifdef __cplusplus } #endif -#endif // INC_EXTERNAL_ACL_PROF_H_ +#endif // INC_EXTERNAL_ACL_PROF_H_ \ No newline at end of file diff --git a/third_party/acl/inc/acl/acl_rt.h b/third_party/acl/inc/acl/acl_rt.h index 3d389a7d24..9e5b9aa47a 100644 --- a/third_party/acl/inc/acl/acl_rt.h +++ b/third_party/acl/inc/acl/acl_rt.h @@ -38,17 +38,6 @@ typedef enum aclrtEventStatus { ACL_EVENT_STATUS_RESERVED = 2, } aclrtEventStatus; -typedef enum aclrtEventRecordedStatus { - ACL_EVENT_RECORDED_STATUS_NOT_READY = 0, - ACL_EVENT_RECORDED_STATUS_COMPLETE = 1, -} aclrtEventRecordedStatus; - -typedef enum aclrtEventWaitStatus { - ACL_EVENT_WAIT_STATUS_COMPLETE = 0, - ACL_EVENT_WAIT_STATUS_NOT_READY = 1, - ACL_EVENT_WAIT_STATUS_RESERVED = 0xffff, -} aclrtEventWaitStatus; - typedef enum aclrtCallbackBlockType { ACL_CALLBACK_NO_BLOCK, ACL_CALLBACK_BLOCK, @@ -88,8 +77,7 @@ typedef enum aclrtGroupAttr { ACL_GROUP_AIV_INT, ACL_GROUP_AIC_INT, ACL_GROUP_SDMANUM_INT, - ACL_GROUP_ASQNUM_INT, - ACL_GROUP_GROUPID_INT + ACL_GROUP_ASQNUM_INT } aclrtGroupAttr; typedef struct tagRtGroupInfo aclrtGroupInfo; @@ -105,8 +93,7 @@ typedef void (*aclrtExceptionInfoCallback)(aclrtExceptionInfo *exceptionInfo); * @brief Set a callback function to handle exception information * * @param callback [IN] callback function to handle exception information - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtSetExceptionInfoCallback(aclrtExceptionInfoCallback callback); @@ -116,7 +103,6 @@ ACL_FUNC_VISIBILITY aclError aclrtSetExceptionInfoCallback(aclrtExceptionInfoCal * @brief Get task id from exception information * * @param info [IN] pointer of exception information - * * @retval The task id from exception information * @retval 0xFFFFFFFF if info is null */ @@ -127,7 +113,6 @@ ACL_FUNC_VISIBILITY uint32_t aclrtGetTaskIdFromExceptionInfo(const aclrtExceptio * @brief Get stream id from exception information * * @param info [IN] pointer of exception information - * * @retval The stream id from exception information * @retval 0xFFFFFFFF if info is null */ @@ -138,7 +123,6 @@ ACL_FUNC_VISIBILITY uint32_t aclrtGetStreamIdFromExceptionInfo(const aclrtExcept * @brief Get thread id from exception information * * @param info [IN] pointer of exception information - * * @retval The thread id of fail task * @retval 0xFFFFFFFF if info is null */ @@ -155,25 +139,13 @@ ACL_FUNC_VISIBILITY uint32_t aclrtGetThreadIdFromExceptionInfo(const aclrtExcept */ ACL_FUNC_VISIBILITY uint32_t aclrtGetDeviceIdFromExceptionInfo(const aclrtExceptionInfo *info); -/** - * @ingroup AscendCL - * @brief Get error code from exception information - * - * @param info [IN] pointer of exception information - * - * @retval The error code from exception information - * @retval 0xFFFFFFFF if info is null - */ -ACL_FUNC_VISIBILITY uint32_t aclrtGetErrorCodeFromExceptionInfo(const aclrtExceptionInfo *info); - /** * @ingroup AscendCL * @brief The thread that handles the callback function on the Stream * - * @param threadId [IN] thread ID + * @param threadId [IN] thread ID * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtSubscribeReport(uint64_t threadId, aclrtStream stream); @@ -187,14 +159,13 @@ ACL_FUNC_VISIBILITY aclError aclrtSubscribeReport(uint64_t threadId, aclrtStream * The function prototype of the callback function is: * typedef void (*aclrtCallback)(void *userData); * @param userData [IN] User data to be passed to the callback function - * @param blockType [IN] callback block type - * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param blockType [IN] callback block type + * @param stream [IN] stream handle + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtLaunchCallback(aclrtCallback fn, void *userData, aclrtCallbackBlockType blockType, - aclrtStream stream); + aclrtStream stream); /** * @ingroup AscendCL @@ -203,10 +174,8 @@ ACL_FUNC_VISIBILITY aclError aclrtLaunchCallback(aclrtCallback fn, void *userDat * @par Function * The thread processing callback specified by * the aclrtSubscribeReport interface - * * @param timeout [IN] timeout value - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtSubscribeReport @@ -220,9 +189,8 @@ ACL_FUNC_VISIBILITY aclError aclrtProcessReport(int32_t timeout); * is no longer processed by the specified thread * * @param threadId [IN] thread ID - * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param stream [IN] stream handle + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtUnSubscribeReport(uint64_t threadId, aclrtStream stream); @@ -243,11 +211,9 @@ ACL_FUNC_VISIBILITY aclError aclrtUnSubscribeReport(uint64_t threadId, aclrtStre * It is recommended to explicitly specify the context of the current thread * through the aclrtSetCurrentContext interface to increase. * the maintainability of the program. - * - * @param context [OUT] point to the created context + * @param context [OUT] point to the created context * @param deviceId [IN] device to create context on - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtSetDevice | aclrtSetCurrentContext @@ -260,10 +226,8 @@ ACL_FUNC_VISIBILITY aclError aclrtCreateContext(aclrtContext *context, int32_t d * * @par Function * Can only destroy context created through aclrtCreateContext interface - * * @param context [IN] the context to destroy - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtCreateContext @@ -296,10 +260,8 @@ ACL_FUNC_VISIBILITY aclError aclrtDestroyContext(aclrtContext context); * and the context is used in thread B, * the user must guarantee the execution order of tasks in the same stream * under the same context in two threads. - * * @param context [IN] the current context of the thread - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtCreateContext | aclrtDestroyContext @@ -314,10 +276,8 @@ ACL_FUNC_VISIBILITY aclError aclrtSetCurrentContext(aclrtContext context); * If the user calls the aclrtSetCurrentContext interface * multiple times to set the context of the current thread, * then the last set context is obtained - * * @param context [OUT] the current context of the thread - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtSetCurrentContext @@ -342,10 +302,8 @@ ACL_FUNC_VISIBILITY aclError aclrtGetCurrentContext(aclrtContext *context); * create a Context (aclrtCreateContext interface). * @li In multi-device scenarios, you can switch to other devices * through the aclrtSetDevice interface in the process. - * * @param deviceId [IN] the device id - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtResetDevice |aclrtCreateContext @@ -371,10 +329,8 @@ ACL_FUNC_VISIBILITY aclError aclrtSetDevice(int32_t deviceId); * call aclrtDestroyStream interface to release explicitly created Stream-> * call aclrtDestroyContext to release explicitly created Context-> * call aclrtResetDevice interface - * * @param deviceId [IN] the device id - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtResetDevice(int32_t deviceId); @@ -384,8 +340,7 @@ ACL_FUNC_VISIBILITY aclError aclrtResetDevice(int32_t deviceId); * @brief get target device of current thread * * @param deviceId [OUT] the device id - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtGetDevice(int32_t *deviceId); @@ -395,8 +350,7 @@ ACL_FUNC_VISIBILITY aclError aclrtGetDevice(int32_t *deviceId); * @brief get target side * * @param runMode [OUT] the run mode - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtGetRunMode(aclrtRunMode *runMode); @@ -405,7 +359,7 @@ ACL_FUNC_VISIBILITY aclError aclrtGetRunMode(aclrtRunMode *runMode); * @ingroup AscendCL * @brief Wait for compute device to finish * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtSynchronizeDevice(void); @@ -415,8 +369,7 @@ ACL_FUNC_VISIBILITY aclError aclrtSynchronizeDevice(void); * @brief Set Scheduling TS * * @param tsId [IN] the ts id - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtSetTsDevice(aclrtTsId tsId); @@ -425,9 +378,8 @@ ACL_FUNC_VISIBILITY aclError aclrtSetTsDevice(aclrtTsId tsId); * @ingroup AscendCL * @brief get total device number. * - * @param count [OUT] the device number - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param count [IN|OUT] the device number + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtGetDeviceCount(uint32_t *count); @@ -437,24 +389,11 @@ ACL_FUNC_VISIBILITY aclError aclrtGetDeviceCount(uint32_t *count); * @brief create event instance * * @param event [OUT] created event - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtCreateEvent(aclrtEvent *event); -/** - * @ingroup AscendCL - * @brief create event instance with flag - * - * @param event [OUT] created event - * @param flag [IN] event flag - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclrtCreateEventWithFlag(aclrtEvent *event, uint32_t flag); - /** * @ingroup AscendCL * @brief destroy event instance @@ -465,10 +404,8 @@ ACL_FUNC_VISIBILITY aclError aclrtCreateEventWithFlag(aclrtEvent *event, uint32_ * the user must ensure that the tasks involved in the aclrtSynchronizeEvent * interface or the aclrtStreamWaitEvent interface are completed before * they are destroyed. - * * @param event [IN] event to destroy - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtCreateEvent | aclrtSynchronizeEvent | aclrtStreamWaitEvent @@ -479,10 +416,9 @@ ACL_FUNC_VISIBILITY aclError aclrtDestroyEvent(aclrtEvent event); * @ingroup AscendCL * @brief Record an Event in the Stream * - * @param event [IN] event to record + * @param event [IN] event to record * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtRecordEvent(aclrtEvent event, aclrtStream stream); @@ -494,11 +430,9 @@ ACL_FUNC_VISIBILITY aclError aclrtRecordEvent(aclrtEvent event, aclrtStream stre * @par Function * Users need to make sure to wait for the tasks in the Stream * to complete before resetting the Event - * - * @param event [IN] event to reset + * @param event [IN] event to reset * @param stream [IN] stream handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtResetEvent(aclrtEvent event, aclrtStream stream); @@ -507,46 +441,19 @@ ACL_FUNC_VISIBILITY aclError aclrtResetEvent(aclrtEvent event, aclrtStream strea * @ingroup AscendCL * @brief Queries an event's status * - * @param event [IN] event to query + * @param event [IN] event to query * @param status [OUT] event status - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ -ACL_DEPRECATED_MESSAGE("aclrtQueryEvent is deprecated, use aclrtQueryEventStatus instead") ACL_FUNC_VISIBILITY aclError aclrtQueryEvent(aclrtEvent event, aclrtEventStatus *status); -/** - * @ingroup AscendCL - * @brief Queries an event's status - * - * @param event [IN] event to query - * @param status [OUT] event recorded status - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclrtQueryEventStatus(aclrtEvent event, aclrtEventRecordedStatus *status); - -/** -* @ingroup AscendCL -* @brief Queries an event's wait-status -* -* @param event [IN] event to query -* @param status [OUT] event wait-status -* -* @retval ACL_SUCCESS The function is successfully executed. -* @retval OtherValues Failure -*/ -ACL_FUNC_VISIBILITY aclError aclrtQueryEventWaitStatus(aclrtEvent event, aclrtEventWaitStatus *status); - /** * @ingroup AscendCL * @brief Block Host Running, wait event to be complete * * @param event [IN] event to wait - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtSynchronizeEvent(aclrtEvent event); @@ -555,16 +462,15 @@ ACL_FUNC_VISIBILITY aclError aclrtSynchronizeEvent(aclrtEvent event); * @ingroup AscendCL * @brief computes the elapsed time between events. * - * @param ms [OUT] time between start and end in ms - * @param start [IN] starting event + * @param ms [OUT] time between start and end in ms + * @param start [IN] starting event * @param end [IN] ending event - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtCreateEvent | aclrtRecordEvent | aclrtSynchronizeStream */ -ACL_FUNC_VISIBILITY aclError aclrtEventElapsedTime(float *ms, aclrtEvent startEvent, aclrtEvent endEvent); +ACL_FUNC_VISIBILITY aclError aclrtEventElapsedTime(float *ms, aclrtEvent start, aclrtEvent end); /** * @ingroup AscendCL @@ -580,12 +486,10 @@ ACL_FUNC_VISIBILITY aclError aclrtEventElapsedTime(float *ms, aclrtEvent startEv * @li Before calling the media data processing interface, * if you need to apply memory on the device to store input or output data, * you need to call acldvppMalloc to apply for memory. - * - * @param devPtr [OUT] pointer to pointer to allocated memory on device - * @param size [IN] alloc memory size + * @param devPtr [IN|OUT] pointer to pointer to allocated memory on device + * @param size [IN] alloc memory size * @param policy [IN] memory alloc policy - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtFree | acldvppMalloc | aclrtMallocCached @@ -606,11 +510,11 @@ ACL_FUNC_VISIBILITY aclError aclrtMalloc(void **devPtr, * @li The memory requested by the aclrtMallocCached interface needs to be released * through the aclrtFree interface. * - * @param devPtr [OUT] pointer to pointer to allocated memory on device - * @param size [IN] alloc memory size + * @param devPtr [IN|OUT] pointer to pointer to allocated memory on device + * @param size [IN] alloc memory size * @param policy [IN] memory alloc policy * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtFree | aclrtMalloc @@ -624,9 +528,9 @@ ACL_FUNC_VISIBILITY aclError aclrtMallocCached(void **devPtr, * @brief flush cache data to ddr * * @param devPtr [IN] the pointer that flush data to ddr - * @param size [IN] flush size + * @param size [IN] flush size * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtMemFlush(void *devPtr, size_t size); @@ -638,7 +542,7 @@ ACL_FUNC_VISIBILITY aclError aclrtMemFlush(void *devPtr, size_t size); * @param devPtr [IN] pointer to invalidate cache data * @param size [IN] invalidate size * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtMemInvalidate(void *devPtr, size_t size); @@ -649,10 +553,8 @@ ACL_FUNC_VISIBILITY aclError aclrtMemInvalidate(void *devPtr, size_t size); * * @par Function * can only free memory allocated through the aclrtMalloc interface - * * @param devPtr [IN] Pointer to memory to be freed - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtMalloc @@ -668,11 +570,9 @@ ACL_FUNC_VISIBILITY aclError aclrtFree(void *devPtr); * and needs to be explicitly copied to the Device. * @li The memory requested by the aclrtMallocHost interface * needs to be released through the aclrtFreeHost interface. - * - * @param hostPtr [OUT] pointer to pointer to allocated memory on the host - * @param size [IN] alloc memory size - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param hostPtr [IN|OUT] pointer to pointer to allocated memory on the host + * @param size [IN] alloc memory size + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtFreeHost @@ -685,10 +585,8 @@ ACL_FUNC_VISIBILITY aclError aclrtMallocHost(void **hostPtr, size_t size); * * @par Function * can only free memory allocated through the aclrtMallocHost interface - * * @param hostPtr [IN] free memory pointer - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtMallocHost @@ -699,13 +597,12 @@ ACL_FUNC_VISIBILITY aclError aclrtFreeHost(void *hostPtr); * @ingroup AscendCL * @brief synchronous memory replication between host and device * - * @param dst [IN] destination address pointer + * @param dst [IN] destination address pointer * @param destMax [IN] Max length of the destination address memory - * @param src [IN] source address pointer - * @param count [IN] the length of byte to copy - * @param kind [IN] memcpy type - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param src [IN] source address pointer + * @param count [IN] the length of byte to copy + * @param kind [IN] memcpy type + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtMemcpy(void *dst, @@ -722,13 +619,11 @@ ACL_FUNC_VISIBILITY aclError aclrtMemcpy(void *dst, * The memory to be initialized is on the Host or device side, * and the system determines whether * it is host or device according to the address - * * @param devPtr [IN] Starting address of memory * @param maxCount [IN] Max length of destination address memory * @param value [IN] Set value * @param count [IN] The length of memory - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtMemset(void *devPtr, size_t maxCount, int32_t value, size_t count); @@ -745,15 +640,13 @@ ACL_FUNC_VISIBILITY aclError aclrtMemset(void *devPtr, size_t maxCount, int32_t * @par Restriction * @li For on-chip Device-to-Device memory copy, * both the source and destination addresses must be 64-byte aligned - * * @param dst [IN] destination address pointer * @param destMax [IN] Max length of destination address memory * @param src [IN] source address pointer * @param count [IN] the number of byte to copy * @param kind [IN] memcpy type - * @param stream [IN] asynchronized task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param stream [IN] asynchronized task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtSynchronizeStream @@ -765,54 +658,6 @@ ACL_FUNC_VISIBILITY aclError aclrtMemcpyAsync(void *dst, aclrtMemcpyKind kind, aclrtStream stream); -/** - * @ingroup AscendCL - * @brief synchronous memory replication of two-dimensional matrix between host and device - * - * @param dst [IN] destination address pointer - * @param dpitch [IN] pitch of destination memory - * @param src [IN] source address pointer - * @param spitch [IN] pitch of source memory - * @param width [IN] width of matrix transfer - * @param height [IN] height of matrix transfer - * @param kind [IN] memcpy type - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclrtMemcpy2d(void *dst, - size_t dpitch, - const void *src, - size_t spitch, - size_t width, - size_t height, - aclrtMemcpyKind kind); - -/** - * @ingroup AscendCL - * @brief asynchronous memory replication of two-dimensional matrix between host and device - * - * @param dst [IN] destination address pointer - * @param dpitch [IN] pitch of destination memory - * @param src [IN] source address pointer - * @param spitch [IN] pitch of source memory - * @param width [IN] width of matrix transfer - * @param height [IN] height of matrix transfer - * @param kind [IN] memcpy type - * @param stream [IN] asynchronized task stream - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclrtMemcpy2dAsync(void *dst, - size_t dpitch, - const void *src, - size_t spitch, - size_t width, - size_t height, - aclrtMemcpyKind kind, - aclrtStream stream); - /** * @ingroup AscendCL * @brief Asynchronous initialize memory @@ -822,14 +667,12 @@ ACL_FUNC_VISIBILITY aclError aclrtMemcpy2dAsync(void *dst, * The memory to be initialized is on the Host or device side, * and the system determines whether * it is host or device according to the address - * * @param devPtr [IN] destination address pointer * @param maxCount [IN] Max length of destination address memory -* @param value [IN] set value -* @param count [IN] the number of byte to set -* @param stream [IN] asynchronized task stream -* -* @retval ACL_SUCCESS The function is successfully executed. +* @param value [IN] set value +* @param count [IN] the number of byte to set +* @param stream [IN] asynchronized task stream +* @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtSynchronizeStream @@ -845,8 +688,7 @@ ACL_FUNC_VISIBILITY aclError aclrtMemsetAsync(void *devPtr, * @brief create stream instance * * @param stream [OUT] the created stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtCreateStream(aclrtStream *stream); @@ -862,10 +704,8 @@ ACL_FUNC_VISIBILITY aclError aclrtCreateStream(aclrtStream *stream); * Before calling the aclrtDestroyStream interface to destroy * the specified Stream, you need to call the aclrtSynchronizeStream interface * to ensure that the tasks in the Stream have been completed. - * * @param stream [IN] the stream to destroy - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtCreateStream | aclrtSynchronizeStream @@ -878,8 +718,7 @@ ACL_FUNC_VISIBILITY aclError aclrtDestroyStream(aclrtStream stream); * in the specified stream have completed * * @param stream [IN] the stream to wait - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtSynchronizeStream(aclrtStream stream); @@ -892,8 +731,7 @@ ACL_FUNC_VISIBILITY aclError aclrtSynchronizeStream(aclrtStream stream); * * @param stream [IN] the wait stream If using thedefault Stream, set NULL * @param event [IN] the event to wait - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtStreamWaitEvent(aclrtStream stream, aclrtEvent event); @@ -907,7 +745,7 @@ ACL_FUNC_VISIBILITY aclError aclrtStreamWaitEvent(aclrtStream stream, aclrtEvent * * @param groupId [IN] group id * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtGetGroupCount | aclrtGetAllGroupInfo | aclrtGetGroupInfoDetail @@ -922,9 +760,9 @@ ACL_FUNC_VISIBILITY aclError aclrtSetGroup(int32_t groupId); * get the number of group. if the number of group is zero, * it means that group is not supported or group is not created. * - * @param count [OUT] the number of group + * @param count [IN|OUT] the number of group * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * */ @@ -947,7 +785,7 @@ ACL_FUNC_VISIBILITY aclrtGroupInfo *aclrtCreateGroupInfo(); * * @param groupInfo [IN] pointer to group information * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtCreateGroupInfo @@ -958,9 +796,9 @@ ACL_FUNC_VISIBILITY aclError aclrtDestroyGroupInfo(aclrtGroupInfo *groupInfo); * @ingroup AscendCL * @brief get all group information * - * @param groupInfo [OUT] pointer to group information + * @param groupInfo [IN|OUT] pointer to group information * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtGetGroupCount @@ -971,20 +809,20 @@ ACL_FUNC_VISIBILITY aclError aclrtGetAllGroupInfo(aclrtGroupInfo *groupInfo); * @ingroup AscendCL * @brief get detail information of group * - * @param groupInfo [IN] pointer to group information - * @param groupIndex [IN] group index value - * @param attr [IN] group attribute - * @param attrValue [OUT] pointer to attribute value - * @param valueLen [IN] length of attribute value - * @param paramRetSize [OUT] pointer to real length of attribute value + * @param groupInfo [IN] pointer to group information + * @param groupId [IN] group index value + * @param attr [IN] group attribute + * @param attrValue [IN|OUT] pointer to attribute value + * @param valueLen [IN] length of attribute value + * @param paramRetSize [IN|OUT] pointer to real length of attribute value * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtGetGroupCount | aclrtGetAllGroupInfo */ ACL_FUNC_VISIBILITY aclError aclrtGetGroupInfoDetail(const aclrtGroupInfo *groupInfo, - int32_t groupIndex, + int32_t groupId, aclrtGroupAttr attr, void *attrValue, size_t valueLen, @@ -994,11 +832,11 @@ ACL_FUNC_VISIBILITY aclError aclrtGetGroupInfoDetail(const aclrtGroupInfo *group * @ingroup AscendCL * @brief checking whether current device and peer device support the p2p feature * - * @param canAccessPeer [OUT] pointer to save the checking result - * @param deviceId [IN] current device id - * @param peerDeviceId [IN] peer device id + * @param canAccessPeer [IN|OUT] pointer to save the checking result + * @param deviceId [IN] current device id + * @param peerDeviceId [IN] peer device id * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtDeviceEnablePeerAccess | aclrtDeviceDisablePeerAccess @@ -1012,7 +850,7 @@ ACL_FUNC_VISIBILITY aclError aclrtDeviceCanAccessPeer(int32_t *canAccessPeer, in * @param peerDeviceId [IN] the peer device id * @param flags [IN] reserved field, now it must be zero * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtDeviceCanAccessPeer | aclrtDeviceDisablePeerAccess @@ -1025,7 +863,7 @@ ACL_FUNC_VISIBILITY aclError aclrtDeviceEnablePeerAccess(int32_t peerDeviceId, u * * @param peerDeviceId [IN] the peer device id * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclrtDeviceCanAccessPeer | aclrtDeviceEnablePeerAccess @@ -1037,26 +875,15 @@ ACL_FUNC_VISIBILITY aclError aclrtDeviceDisablePeerAccess(int32_t peerDeviceId); * @brief Obtain the free memory and total memory of specified attribute. * the specified memory include normal memory and huge memory. * - * @param attr [IN] the memory attribute of specified device + * @param attr [IN] the memory attribute of specified device * @param free [OUT] the free memory of specified device - * @param total [OUT] the total memory of specified device. + * @param total [OUT] the total memory of specified device. * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclrtGetMemInfo(aclrtMemAttr attr, size_t *free, size_t *total); -/** - * @ingroup AscendCL - * @brief Set the timeout interval for waitting of op - * - * @param timeout [IN] op wait timeout - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclrtSetOpWaitTimeout(uint32_t timeout); - #ifdef __cplusplus } #endif diff --git a/third_party/acl/inc/acl/acl_tdt.h b/third_party/acl/inc/acl/acl_tdt.h deleted file mode 100644 index 5ea3128f96..0000000000 --- a/third_party/acl/inc/acl/acl_tdt.h +++ /dev/null @@ -1,318 +0,0 @@ -/** -* @file acl_tdt.h -* -* Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. All Rights Reserved. -* -* This program 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. -*/ - -#ifndef INC_EXTERNAL_ACL_ACL_TDT_H_ -#define INC_EXTERNAL_ACL_ACL_TDT_H_ - -#include "acl/acl_base.h" - -#ifdef __cplusplus -extern "C" { -#endif - -enum acltdtTensorType { - ACL_TENSOR_DATA_UNDEFINED = -1, - ACL_TENSOR_DATA_TENSOR, - ACL_TENSOR_DATA_END_OF_SEQUENCE, - ACL_TENSOR_DATA_ABNORMAL -}; - -typedef struct acltdtDataItem acltdtDataItem; -typedef struct acltdtDataset acltdtDataset; -typedef struct acltdtChannelHandle acltdtChannelHandle; - -/** - * @ingroup AscendCL - * @brief Get tensor type from item - * - * @param dataItem [IN] pointer to the data item - * - * @retval Tensor type. - * @retval ACL_DT_UNDEFINED if dataItem is null - */ -ACL_FUNC_VISIBILITY acltdtTensorType acltdtGetTensorTypeFromItem(const acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Get data type from item - * - * @param dataItem [IN] pointer to the data item - * - * @retval Data type. - * @retval ACL_DT_UNDEFINED if dataItem is null - */ -ACL_FUNC_VISIBILITY aclDataType acltdtGetDataTypeFromItem(const acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Get data address from item - * - * @param dataItem [IN] pointer to data item - * - * @retval null for failed - * @retval OtherValues success -*/ -ACL_FUNC_VISIBILITY void *acltdtGetDataAddrFromItem(const acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Get data size from item - * - * @param dataItem [IN] pointer to data item - * - * @retval 0 for failed - * @retval OtherValues success -*/ -ACL_FUNC_VISIBILITY size_t acltdtGetDataSizeFromItem(const acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Get dim's number from item - * - * @param dataItem [IN] pointer to data item - * - * @retval 0 for failed - * @retval OtherValues success -*/ -ACL_FUNC_VISIBILITY size_t acltdtGetDimNumFromItem(const acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Get dims from item - * - * @param dataItem [IN] the struct of data item - * @param dims [IN|OUT] pointer to the dims of dataTtem - * @param dimNum [IN] the size of the dims - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError acltdtGetDimsFromItem(const acltdtDataItem *dataItem, int64_t *dims, size_t dimNum); - -/** - * @ingroup AscendCL - * @brief Create the struct of data item - * - * @param tdtType [IN] Tdt tensor type - * @param dims [IN] pointer of tdtDataItem's dims - * @param dimNum [IN] Dim number - * @param dataType [IN] Data type - * @param data [IN] Data pointer - * @param size [IN] Data size - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyDataItem - */ -ACL_FUNC_VISIBILITY acltdtDataItem *acltdtCreateDataItem(acltdtTensorType tdtType, - const int64_t *dims, - size_t dimNum, - aclDataType dataType, - void *data, - size_t size); - -/** - * @ingroup AscendCL - * @brief Destroy the struct of data item - * - * @param dataItem [IN] pointer to the data item - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateDataItem - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyDataItem(acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Create the tdt dataset - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyDataset - */ -ACL_FUNC_VISIBILITY acltdtDataset *acltdtCreateDataset(); - -/** - * @ingroup AscendCL - * @brief Destroy the tdt dataset - * - * @param dataset [IN] pointer to the dataset - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateDataset - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyDataset(acltdtDataset *dataset); - -/** - * @ingroup AscendCL - * @brief Get the data item - * - * @param dataset [IN] pointer to the dataset - * @param index [IN] index of the dataset - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtAddDataItem - */ -ACL_FUNC_VISIBILITY acltdtDataItem *acltdtGetDataItem(const acltdtDataset *dataset, size_t index); - -/** - * @ingroup AscendCL - * @brief Get the data item - * - * @param dataset [OUT] pointer to the dataset - * @param dataItem [IN] pointer to the data item - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtGetDataItem - */ -ACL_FUNC_VISIBILITY aclError acltdtAddDataItem(acltdtDataset *dataset, acltdtDataItem *dataItem); - -/** - * @ingroup AscendCL - * @brief Get the size of dataset - * - * @param dataset [IN] pointer to the dataset - * - * @retval 0 for failed - * @retval OtherValues success - */ -ACL_FUNC_VISIBILITY size_t acltdtGetDatasetSize(const acltdtDataset *dataset); - -/** - * @ingroup AscendCL - * @brief Get the name of dataset - * - * @param dataset [IN] pointer to the dataset - * - * @retval null for failed - * @retval OtherValues success - */ -ACL_FUNC_VISIBILITY const char *acltdtGetDatasetName(const acltdtDataset *dataset); - -/** - * @ingroup AscendCL - * @brief Stop the channel - * - * @param handle [IN] pointer to the channel handle - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateChannel | acltdtDestroyChannel - */ -ACL_FUNC_VISIBILITY aclError acltdtStopChannel(acltdtChannelHandle *handle); - -/** - * @ingroup AscendCL - * @brief Create the channel - * - * @param deviceId [IN] the device id - * @param name [IN] the name of channel - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtStopChannel | acltdtDestroyChannel - */ -ACL_FUNC_VISIBILITY acltdtChannelHandle *acltdtCreateChannel(uint32_t deviceId, const char *name); - -/** - * @ingroup AscendCL - * @brief Create the channel with max size - * - * @param deviceId [IN] the device id - * @param name [IN] the name of channel - * @param capacity [IN] the capacity of channel - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyChannel - */ -ACL_FUNC_VISIBILITY acltdtChannelHandle *acltdtCreateChannelWithCapacity(uint32_t deviceId, - const char *name, - size_t capacity); - -/** - * @ingroup AscendCL - * @brief Destroy the channel - * - * @param handle [IN] pointer to the channel handle - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateChannel | acltdtStopChannel - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyChannel(acltdtChannelHandle *handle); - -/** - * @ingroup AscendCL - * @brief Send tensor to device - * - * @param handle [IN] pointer to the channel handle - * @param dataset [IN] pointer to the dataset - * @param timeout [IN] to be reserved, now it must be -1 - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtReceiveTensor - */ -ACL_FUNC_VISIBILITY aclError acltdtSendTensor(const acltdtChannelHandle *handle, - const acltdtDataset *dataset, - int32_t timeout); - -/** - * @ingroup AscendCL - * @brief Receive tensor from device - * - * @param handle [IN] pointer to the channel handle - * @param dataset [OUT] pointer to the dataset - * @param timeout [IN] to be reserved, now it must be -1 - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtSendTensor - */ -ACL_FUNC_VISIBILITY aclError acltdtReceiveTensor(const acltdtChannelHandle *handle, - acltdtDataset *dataset, - int32_t timeout); - -/** - * @ingroup AscendCL - * @brief query the size of the channel - * - * @param handle [IN] pointer to the channel handle - * @param size [OUT] current size of this channel - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - */ -ACL_FUNC_VISIBILITY aclError acltdtQueryChannelSize(const acltdtChannelHandle *handle, size_t *size); - -#ifdef __cplusplus -} -#endif - -#endif //INC_EXTERNAL_ACL_ACL_TDT_H_ - diff --git a/third_party/acl/inc/acl/acl_tdt_queue.h b/third_party/acl/inc/acl/acl_tdt_queue.h deleted file mode 100644 index 5c254cfd30..0000000000 --- a/third_party/acl/inc/acl/acl_tdt_queue.h +++ /dev/null @@ -1,484 +0,0 @@ -/** -* @file acl_tdt_queue.h -* -* Copyright (C) Huawei Technologies Co., Ltd. 2020-2021. All Rights Reserved. -* -* This program 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. -*/ - -#ifndef INC_EXTERNAL_ACL_ACL_TDT_QUEUE_H_ -#define INC_EXTERNAL_ACL_ACL_TDT_QUEUE_H_ - -#include "acl/acl_base.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ACL_TDT_QUEUE_PERMISSION_MANAGE 1 -#define ACL_TDT_QUEUE_PERMISSION_DEQUEUE 2 -#define ACL_TDT_QUEUE_PERMISSION_ENQUEUE 4 - -typedef void *acltdtBuf; -typedef struct tagMemQueueAttr acltdtQueueAttr; -typedef struct acltdtQueueRouteList acltdtQueueRouteList; -typedef struct acltdtQueueRouteQueryInfo acltdtQueueRouteQueryInfo; -typedef struct acltdtQueueRoute acltdtQueueRoute; - -typedef enum { - ACL_TDT_QUEUE_NAME_PTR = 0, - ACL_TDT_QUEUE_DEPTH_UINT32 -} acltdtQueueAttrType; - -typedef enum { - ACL_TDT_QUEUE_ROUTE_SRC_UINT32 = 0, - ACL_TDT_QUEUE_ROUTE_DST_UINT32, - ACL_TDT_QUEUE_ROUTE_STATUS_INT32 -} acltdtQueueRouteParamType; - -typedef enum { - ACL_TDT_QUEUE_ROUTE_QUERY_SRC = 0, - ACL_TDT_QUEUE_ROUTE_QUERY_DST, - ACL_TDT_QUEUE_ROUTE_QUERY_SRC_AND_DST -} acltdtQueueRouteQueryMode; - -typedef enum { - ACL_TDT_QUEUE_ROUTE_QUERY_MODE_ENUM = 0, - ACL_TDT_QUEUE_ROUTE_QUERY_SRC_ID_UINT32, - ACL_TDT_QUEUE_ROUTE_QUERY_DST_ID_UINT32 -} acltdtQueueRouteQueryInfoParamType; - -/** - * @ingroup AscendCL - * @brief create queue - * - * @param attr [IN] pointer to the queue attr - * @param qid [OUT] pointer to the qid - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtDestroyQueue - */ -ACL_FUNC_VISIBILITY aclError acltdtCreateQueue(const acltdtQueueAttr *attr, uint32_t *qid); - -/** - * @ingroup AscendCL - * @brief destroy queue - * - * @param qid [IN] qid which to be destroyed - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueue - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyQueue(uint32_t qid); - -/** - * @ingroup AscendCL - * @brief enqueue function - * - * @param qid [IN] qid - * @param buf [IN] acltdtBuf - * @param timeout [IN] timeout, -1 means blocking - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtDequeue - */ -ACL_FUNC_VISIBILITY aclError acltdtEnqueue(uint32_t qid, acltdtBuf buf, int32_t timeout); - -/** - * @ingroup AscendCL - * @brief dequeue function - * - * @param qid [IN] qid - * @param buf [OUT] pointer to the acltdtBuf - * @param timeout [IN] timeout, -1 means blocking - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtEnqueue - */ -ACL_FUNC_VISIBILITY aclError acltdtDequeue(uint32_t qid, acltdtBuf *buf, int32_t timeout); - -/** - * @ingroup AscendCL - * @brief enqueue function - * - * @param qid [IN] qid - * @param data [IN] the pointer to data buf - * @param dataSize [IN] the size of data buf - * @param userData [IN] the pointer to user data buf - * @param userDataSize [IN] the size of user data buf - * @param timeout [IN] timeout, -1 means blocking - * @param rsv [IN] reserved param - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtDequeueData - */ -ACL_FUNC_VISIBILITY aclError acltdtEnqueueData(uint32_t qid, const void *data, size_t dataSize, - const void *userData, size_t userDataSize, int32_t timeout, uint32_t rsv); - -/** - * @ingroup AscendCL - * @brief dequeue function - * - * @param qid [IN] qid - * @param data [IN|OUT] the pointer to data buf - * @param dataSize [IN] the size of data buf - * @param retDataSize [OUT] the return size of data buf - * @param userData [IN|OUT] the pointer to user data buf - * @param userDataSize [IN] the size of user data buf - * @param timeout [IN] timeout, -1 means blocking - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtEnqueueData - */ -ACL_FUNC_VISIBILITY aclError acltdtDequeueData(uint32_t qid, void *data, size_t dataSize, size_t *retDataSize, - void *userData, size_t userDataSize, int32_t timeout); - -/** - * @ingroup AscendCL - * @brief grant queue to other process - * - * @param qid [IN] qid - * @param pid [IN] pid of dst process - * @param permission [IN] permission of queue - * @param timeout [IN] timeout, -1 means blocking - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see ACL_TDT_QUEUE_PERMISSION_MANAGE | ACL_TDT_QUEUE_PERMISSION_DEQUEUE | ACL_TDT_QUEUE_PERMISSION_ENQUEUE - */ -ACL_FUNC_VISIBILITY aclError acltdtGrantQueue(uint32_t qid, int32_t pid, uint32_t permission, int32_t timeout); - -/** - * @ingroup AscendCL - * @brief attach queue in current process - * - * @param qid [IN] qid - * @param timeout [IN] timeout, -1 means blocking - * @param permission [OUT] permission of queue - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtGrantQueue - */ -ACL_FUNC_VISIBILITY aclError acltdtAttachQueue(uint32_t qid, int32_t timeout, uint32_t *permission); - -/** - * @ingroup AscendCL - * @brief bind queue routes - * - * @param qRouteList [IN|OUT] pointer to the route list - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError acltdtBindQueueRoutes(acltdtQueueRouteList *qRouteList); - -/** - * @ingroup AscendCL - * @brief unbind queue routes - * - * @param qRouteList [IN|OUT] pointer to the route list - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError acltdtUnbindQueueRoutes(acltdtQueueRouteList *qRouteList); - -/** - * @ingroup AscendCL - * @brief query queue routes according to query mode - * - * @param queryInfo [IN] pointer to the queue route query info - * @param qRouteList [IN|OUT] pointer to the route list - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError acltdtQueryQueueRoutes(const acltdtQueueRouteQueryInfo *queryInfo, - acltdtQueueRouteList *qRouteList); - -/** - * @ingroup AscendCL - * @brief alloc acltdtBuf - * - * @param size [IN] alloc buf size - * @param type [IN] reserved parameters, need to set zero currently - * @param buf [OUT] pointer to the acltdtBuf - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtFreeBuf - */ -ACL_FUNC_VISIBILITY aclError acltdtAllocBuf(size_t size, uint32_t type, acltdtBuf *buf); - -/** - * @ingroup AscendCL - * @brief free acltdtBuf - * - * @param buf [IN] pointer to the acltdtBuf - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtAllocBuf - */ -ACL_FUNC_VISIBILITY aclError acltdtFreeBuf(acltdtBuf buf); - -/** - * @ingroup AscendCL - * @brief get data buf address - * - * @param buf [IN] acltdtBuf - * @param dataPtr [OUT] pointer to the data ptr which is acquired from acltdtBuf - * @param size [OUT] pointer to the size - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtAllocBuf - */ -ACL_FUNC_VISIBILITY aclError acltdtGetBufData(const acltdtBuf buf, void **dataPtr, size_t *size); - -/** - * @ingroup AscendCL - * @brief Create the queue attr - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyQueueAttr - */ -ACL_FUNC_VISIBILITY acltdtQueueAttr *acltdtCreateQueueAttr(); - -/** - * @ingroup AscendCL - * @brief Destroy the queue attr - * - * @param attr [IN] pointer to the queue attr - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueueAttr - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyQueueAttr(const acltdtQueueAttr *attr); - -/** - * @ingroup AscendCL - * @brief Set parameter for queue attr - * - * @param attr [IN|OUT] pointer to the queue attr - * @param type [IN] parameter type - * @param len [IN] parameter length - * @param param [IN] pointer to parameter value - * - * @retval ACL_SUCCESS for success, other for failure - * - * @see acltdtCreateQueueAttr - */ -ACL_FUNC_VISIBILITY aclError acltdtSetQueueAttr(acltdtQueueAttr *attr, - acltdtQueueAttrType type, - size_t len, - const void *param); - -/** - * @ingroup AscendCL - * - * @brief Get parameter for queue attr. - * - * @param attr [IN] pointer to the queue attr - * @param type [IN] parameter type - * @param len [IN] parameter length - * @param paramRetSize [OUT] pointer to parameter real length - * @param param [OUT] pointer to parameter value - * - * @retval ACL_SUCCESS for success, other for failure - * - * @see acltdtCreateQueueAttr - */ -ACL_FUNC_VISIBILITY aclError acltdtGetQueueAttr(const acltdtQueueAttr *attr, - acltdtQueueAttrType type, - size_t len, - size_t *paramRetSize, - void *param); - -/** - * @ingroup AscendCL - * @brief Create the queue route - * - * @param srcId [IN] src id of queue route - * @param dstId [IN] dst id of queue route - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyQueueRoute - */ -ACL_FUNC_VISIBILITY acltdtQueueRoute* acltdtCreateQueueRoute(uint32_t srcId, uint32_t dstId); - -/** - * @ingroup AscendCL - * @brief Destroy the queue attr - * - * @param route [IN] pointer to the queue route - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueueRoute - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyQueueRoute(const acltdtQueueRoute *route); - -/** - * @ingroup AscendCL - * - * @brief Get parameter for queue route. - * - * @param route [IN] pointer to the queue route - * @param type [IN] parameter type - * @param len [IN] parameter length - * @param paramRetSize [OUT] pointer to parameter real length - * @param param [OUT] pointer to parameter value - * - * @retval ACL_SUCCESS for success, other for failure - * - * @see acltdtCreateQueueRoute - */ -ACL_FUNC_VISIBILITY aclError acltdtGetQueueRouteParam(const acltdtQueueRoute *route, - acltdtQueueRouteParamType type, - size_t len, - size_t *paramRetSize, - void *param); - -/** - * @ingroup AscendCL - * @brief Create the queue route list - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyQueueRouteList - */ -ACL_FUNC_VISIBILITY acltdtQueueRouteList* acltdtCreateQueueRouteList(); - -/** - * @ingroup AscendCL - * @brief Destroy the queue route list - * - * @param routeList [IN] pointer to the queue route list - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueueRouteList - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyQueueRouteList(const acltdtQueueRouteList *routeList); - -/** - * @ingroup AscendCL - * @brief add queue route to the route list - * - * @param routeList [IN|OUT] pointer to the queue route list - * @param route [IN] pointer to the queue route - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueueRouteList | acltdtCreateQueueRoute - * - */ -ACL_FUNC_VISIBILITY aclError acltdtAddQueueRoute(acltdtQueueRouteList *routeList, const acltdtQueueRoute *route); - -/** - * @ingroup AscendCL - * @brief get queue route from route list - * - * @param routeList [IN] pointer to the queue route list - * @param index [IN] index of queue route in route list - * @param route [IN|OUT] pointer to the queue route - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueueRouteList | acltdtCreateQueueRoute - * - */ -ACL_FUNC_VISIBILITY aclError acltdtGetQueueRoute(const acltdtQueueRouteList *routeList, - size_t index, - acltdtQueueRoute *route); - -/** - * @ingroup AscendCL - * @brief get queue route num from route list - * - * @param routeList [IN] pointer to the queue route list - * - * @retval the number of queue route - * - */ -ACL_FUNC_VISIBILITY size_t acltdtGetQueueRouteNum(const acltdtQueueRouteList *routeList); - -/** - * @ingroup AscendCL - * @brief Create the queue route query info - * - * @retval null for failed - * @retval OtherValues success - * - * @see acltdtDestroyQueueRouteQueryInfo - */ -ACL_FUNC_VISIBILITY acltdtQueueRouteQueryInfo* acltdtCreateQueueRouteQueryInfo(); - -/** - * @ingroup AscendCL - * @brief Destroy the queue route query info - * - * @param info [IN] pointer to the queue route info - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acltdtCreateQueueRouteQueryInfo - * - */ -ACL_FUNC_VISIBILITY aclError acltdtDestroyQueueRouteQueryInfo(const acltdtQueueRouteQueryInfo *info); - -/** - * @ingroup AscendCL - * @brief Set parameter for queue route info - * - * @param attr [IN|OUT] pointer to the queue route info - * @param type [IN] parameter type - * @param len [IN] parameter length - * @param param [IN] pointer to parameter value - * - * @retval ACL_SUCCESS for success, other for failure - * - * @see acltdtCreateQueueRouteQueryInfo - */ -ACL_FUNC_VISIBILITY aclError acltdtSetQueueRouteQueryInfo(acltdtQueueRouteQueryInfo *param, - acltdtQueueRouteQueryInfoParamType type, - size_t len, - const void *value); - - -#ifdef __cplusplus -} -#endif - -#endif //INC_EXTERNAL_ACL_ACL_TDT_QUEUE_H_ \ No newline at end of file diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp.h b/third_party/acl/inc/acl/dvpp/hi_dvpp.h deleted file mode 100644 index 491863d3b2..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_DVPP_H_ -#define HI_DVPP_H_ - -#include "hi_dvpp_sys.h" -#include "hi_dvpp_vb.h" -#include "hi_dvpp_vdec.h" -#include "hi_dvpp_venc.h" -#include "hi_dvpp_vpc.h" -#include "hi_dvpp_pngd.h" - -#endif // #ifndef HI_DVPP_H_ diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_common.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_common.h deleted file mode 100644 index 43609a981b..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_common.h +++ /dev/null @@ -1,634 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_DVPP_COMMON_H_ -#define HI_DVPP_COMMON_H_ - -#include "hi_dvpp_type.h" -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#define ALIGN_NUM 8 -#define DEFAULT_ALIGN 32U -#define ATTRIBUTE __attribute__((aligned(ALIGN_NUM))) - -#define ALIGN_UP(x, a) ((((x) + ((a) - 1U)) / (a)) * (a)) - -#define HI_MAX_COLOR_COMPONENT 3 -#define HI_MAX_USER_DATA_NUM 2 - -#define HI_ERR_APP_ID (0x80000000U + 0x20000000U) - -#define HI_DEFINE_ERR(mod, level, err_id) \ - ((hi_s32)((HI_ERR_APP_ID) | ((hi_u32)(mod) << 16) | ((hi_u32)(level) << 13) | ((hi_u32)(err_id)))) - -typedef enum { - HI_ERR_INVALID_DEV_ID = 1, // invlalid device ID - HI_ERR_INVALID_CHN_ID = 2, // invlalid channel ID - HI_ERR_ILLEGAL_PARAM = 3, // at lease one parameter is illagal - // eg, an illegal enumeration value - HI_ERR_EXIST = 4, // resource exists - HI_ERR_UNEXIST = 5, // resource unexists - - HI_ERR_NULL_PTR = 6, // using a NULL point - - HI_ERR_NOT_CFG = 7, // try to enable or initialize system, device - // or channel, before configing attribute - - HI_ERR_NOT_SUPPORT = 8, // operation or type is not supported by NOW - HI_ERR_NOT_PERM = 9, // operation is not permitted - // eg, try to change static attribute - HI_ERR_INVALID_PIPE_ID = 10, // invlalid pipe ID - HI_ERR_INVALID_GRP_ID = 11, // invlalid stitch group ID - - HI_ERR_NO_MEM = 12, // failure caused by malloc memory - HI_ERR_NO_BUF = 13, // failure caused by malloc buffer - - HI_ERR_BUF_EMPTY = 14, // no data in buffer - HI_ERR_BUF_FULL = 15, // no buffer for new data - - HI_ERR_NOT_READY = 16, // System is not ready,maybe not initialed or - // loaded. Returning the error code when opening - // a device file failed. - - HI_ERR_BAD_ADDR = 17, // bad address, - // eg. used for copy_from_user & copy_to_user - - HI_ERR_BUSY = 18, // resource is busy, - // eg. destroy a venc chn without unregister it - HI_ERR_SIZE_NOT_ENOUGH = 19, // buffer size is smaller than the actual size required - HI_ERR_TIMEOUT = 20, // hardware or software timeout - HI_ERR_SYS_ERROR = 21, // Internal system error - - HI_ERR_BUTT = 63, // maxium code, private error code of all modules - // must be greater than it -} hi_errno; - -typedef enum { - HI_ERR_LEVEL_DEBUG = 0, // debug-level - HI_ERR_LEVEL_INFO, // informational - HI_ERR_LEVEL_NOTICE, // normal but significant condition - HI_ERR_LEVEL_WARNING, // warning conditions - HI_ERR_LEVEL_ERROR, // error conditions - HI_ERR_LEVEL_CRIT, // critical conditions - HI_ERR_LEVEL_ALERT, // action must be taken immediately - HI_ERR_LEVEL_FATAL, // just for compatibility with previous version - HI_ERR_LEVEL_BUTT -} hi_err_level; - -typedef enum { - HI_ID_CMPI = 0, - HI_ID_VB = 1, - HI_ID_SYS = 2, - HI_ID_RGN = 3, - HI_ID_CHNL = 4, - HI_ID_VDEC = 5, - HI_ID_AVS = 6, - HI_ID_VPC = 7, - HI_ID_VENC = 8, - HI_ID_SVP = 9, - HI_ID_H264E = 10, - HI_ID_JPEGE = 11, - HI_ID_MPEG4E = 12, - HI_ID_H265E = 13, - HI_ID_JPEGD = 14, - HI_ID_VO = 15, - HI_ID_VI = 16, - HI_ID_DIS = 17, - HI_ID_VALG = 18, - HI_ID_RC = 19, - HI_ID_AIO = 20, - HI_ID_AI = 21, - HI_ID_AO = 22, - HI_ID_AENC = 23, - HI_ID_ADEC = 24, - HI_ID_VPU = 25, - HI_ID_PCIV = 26, - HI_ID_PCIVFMW = 27, - HI_ID_ISP = 28, - HI_ID_IVE = 29, - HI_ID_USER = 30, - HI_ID_DCCM = 31, - HI_ID_DCCS = 32, - HI_ID_PROC = 33, - HI_ID_LOG = 34, - HI_ID_VFMW = 35, - HI_ID_H264D = 36, - HI_ID_GDC = 37, - HI_ID_PHOTO = 38, - HI_ID_FB = 39, - HI_ID_HDMI = 40, - HI_ID_VOIE = 41, - HI_ID_TDE = 42, - HI_ID_HDR = 43, - HI_ID_PRORES = 44, - HI_ID_VGS = 45, - - HI_ID_FD = 47, - HI_ID_ODT = 48, // Object detection trace - HI_ID_VQA = 49, // Video quality analysis - HI_ID_LPR = 50, // Object detection trace - HI_ID_SVP_NNIE = 51, - HI_ID_SVP_DSP = 52, - HI_ID_DPU_RECT = 53, - HI_ID_DPU_MATCH = 54, - - HI_ID_MOTIONSENSOR = 55, - HI_ID_MOTIONFUSION = 56, - - HI_ID_GYRODIS = 57, - HI_ID_PM = 58, - HI_ID_SVP_ALG = 59, - HI_ID_IVP = 60, - HI_ID_MCF = 61, - HI_ID_VPSS = 62, - HI_ID_DRV_VPC = 63, - HI_ID_PNGD = 64, - - HI_ID_VDEC_ADAPT = 65, - HI_ID_DCC = 66, - HI_ID_VDEC_SERVER = 67, - - HI_ID_BUTT = 0x100, -} hi_mod_id; - -// We just coyp this value of payload type from RTP/RTSP definition -typedef enum { - HI_PT_PCMU = 0, - HI_PT_1016 = 1, - HI_PT_G721 = 2, - HI_PT_GSM = 3, - HI_PT_G723 = 4, - HI_PT_DVI4_8K = 5, - HI_PT_DVI4_16K = 6, - HI_PT_LPC = 7, - HI_PT_PCMA = 8, - HI_PT_G722 = 9, - HI_PT_S16BE_STEREO = 10, - HI_PT_S16BE_MONO = 11, - HI_PT_QCELP = 12, - HI_PT_CN = 13, - HI_PT_MPEGAUDIO = 14, - HI_PT_G728 = 15, - HI_PT_DVI4_3 = 16, - HI_PT_DVI4_4 = 17, - HI_PT_G729 = 18, - HI_PT_G711A = 19, - HI_PT_G711U = 20, - HI_PT_G726 = 21, - HI_PT_G729A = 22, - HI_PT_LPCM = 23, - HI_PT_CelB = 25, - HI_PT_JPEG = 26, - HI_PT_CUSM = 27, - HI_PT_NV = 28, - HI_PT_PICW = 29, - HI_PT_CPV = 30, - HI_PT_H261 = 31, - HI_PT_MPEGVIDEO = 32, - HI_PT_MPEG2TS = 33, - HI_PT_H263 = 34, - HI_PT_SPEG = 35, - HI_PT_MPEG2VIDEO = 36, - HI_PT_AAC = 37, - HI_PT_WMA9STD = 38, - HI_PT_HEAAC = 39, - HI_PT_PCM_VOICE = 40, - HI_PT_PCM_AUDIO = 41, - HI_PT_MP3 = 43, - HI_PT_ADPCMA = 49, - HI_PT_AEC = 50, - HI_PT_X_LD = 95, - HI_PT_H264 = 96, - HI_PT_D_GSM_HR = 200, - HI_PT_D_GSM_EFR = 201, - HI_PT_D_L8 = 202, - HI_PT_D_RED = 203, - HI_PT_D_VDVI = 204, - HI_PT_D_BT656 = 220, - HI_PT_D_H263_1998 = 221, - HI_PT_D_MP1S = 222, - HI_PT_D_MP2P = 223, - HI_PT_D_BMPEG = 224, - HI_PT_MP4VIDEO = 230, - HI_PT_MP4AUDIO = 237, - HI_PT_VC1 = 238, - HI_PT_JVC_ASF = 255, - HI_PT_D_AVI = 256, - HI_PT_DIVX3 = 257, - HI_PT_AVS = 258, - HI_PT_REAL8 = 259, - HI_PT_REAL9 = 260, - HI_PT_VP6 = 261, - HI_PT_VP6F = 262, - HI_PT_VP6A = 263, - HI_PT_SORENSON = 264, - HI_PT_H265 = 265, - HI_PT_VP8 = 266, - HI_PT_MVC = 267, - HI_PT_PNG = 268, - // add by hisilicon - HI_PT_AMR = 1001, - HI_PT_MJPEG = 1002, - HI_PT_AMRWB = 1003, - HI_PT_PRORES = 1006, - HI_PT_OPUS = 1007, - HI_PT_VPC = 2000, - HI_PT_BUTT -} hi_payload_type; - -typedef enum { - HI_DATA_BIT_WIDTH_8 = 0, - HI_DATA_BIT_WIDTH_10, - HI_DATA_BIT_WIDTH_12, - HI_DATA_BIT_WIDTH_14, - HI_DATA_BIT_WIDTH_16, - HI_DATA_BIT_WIDTH_BUTT -} hi_data_bit_width; - -// we ONLY define picture format used, all unused will be deleted! -typedef enum { - HI_PIXEL_FORMAT_YUV_400 = 0, - HI_PIXEL_FORMAT_YUV_SEMIPLANAR_420 = 1, - HI_PIXEL_FORMAT_YVU_SEMIPLANAR_420 = 2, - HI_PIXEL_FORMAT_YUV_SEMIPLANAR_422 = 3, - HI_PIXEL_FORMAT_YVU_SEMIPLANAR_422 = 4, - HI_PIXEL_FORMAT_YUV_SEMIPLANAR_444 = 5, - HI_PIXEL_FORMAT_YVU_SEMIPLANAR_444 = 6, - HI_PIXEL_FORMAT_YUYV_PACKED_422 = 7, - HI_PIXEL_FORMAT_UYVY_PACKED_422 = 8, - HI_PIXEL_FORMAT_YVYU_PACKED_422 = 9, - HI_PIXEL_FORMAT_VYUY_PACKED_422 = 10, - HI_PIXEL_FORMAT_YUV_PACKED_444 = 11, - HI_PIXEL_FORMAT_RGB_888 = 12, - HI_PIXEL_FORMAT_BGR_888 = 13, - HI_PIXEL_FORMAT_ARGB_8888 = 14, - HI_PIXEL_FORMAT_ABGR_8888 = 15, - HI_PIXEL_FORMAT_RGBA_8888 = 16, - HI_PIXEL_FORMAT_BGRA_8888 = 17, - HI_PIXEL_FORMAT_YUV_SEMI_PLANNER_420_10BIT = 18, - HI_PIXEL_FORMAT_YVU_SEMI_PLANNER_420_10BIT = 19, - HI_PIXEL_FORMAT_YVU_PLANAR_420 = 20, - HI_PIXEL_FORMAT_YVU_PLANAR_422 = 21, - HI_PIXEL_FORMAT_YVU_PLANAR_444 = 22, - HI_PIXEL_FORMAT_RGB_444 = 23, - HI_PIXEL_FORMAT_BGR_444 = 24, - HI_PIXEL_FORMAT_ARGB_4444 = 25, - HI_PIXEL_FORMAT_ABGR_4444 = 26, - HI_PIXEL_FORMAT_RGBA_4444 = 27, - HI_PIXEL_FORMAT_BGRA_4444 = 28, - HI_PIXEL_FORMAT_RGB_555 = 29, - HI_PIXEL_FORMAT_BGR_555 = 30, - HI_PIXEL_FORMAT_RGB_565 = 31, - HI_PIXEL_FORMAT_BGR_565 = 32, - HI_PIXEL_FORMAT_ARGB_1555 = 33, - HI_PIXEL_FORMAT_ABGR_1555 = 34, - HI_PIXEL_FORMAT_RGBA_1555 = 35, - HI_PIXEL_FORMAT_BGRA_1555 = 36, - HI_PIXEL_FORMAT_ARGB_8565 = 37, - HI_PIXEL_FORMAT_ABGR_8565 = 38, - HI_PIXEL_FORMAT_RGBA_8565 = 39, - HI_PIXEL_FORMAT_BGRA_8565 = 40, - HI_PIXEL_FORMAT_ARGB_CLUT2 = 41, - HI_PIXEL_FORMAT_ARGB_CLUT4 = 42, - - HI_PIXEL_FORMAT_RGB_BAYER_8BPP = 50, - HI_PIXEL_FORMAT_RGB_BAYER_10BPP = 51, - HI_PIXEL_FORMAT_RGB_BAYER_12BPP = 52, - HI_PIXEL_FORMAT_RGB_BAYER_14BPP = 53, - HI_PIXEL_FORMAT_RGB_BAYER_16BPP = 54, - HI_PIXEL_FORMAT_YUV_PLANAR_420 = 55, - HI_PIXEL_FORMAT_YUV_PLANAR_422 = 56, - HI_PIXEL_FORMAT_YUV_PLANAR_444 = 57, - HI_PIXEL_FORMAT_YVU_PACKED_444 = 58, - HI_PIXEL_FORMAT_XYUV_PACKED_444 = 59, - HI_PIXEL_FORMAT_XYVU_PACKED_444 = 60, - HI_PIXEL_FORMAT_YUV_SEMIPLANAR_411 = 61, - HI_PIXEL_FORMAT_YVU_SEMIPLANAR_411 = 62, - HI_PIXEL_FORMAT_YUV_PLANAR_411 = 63, - HI_PIXEL_FORMAT_YVU_PLANAR_411 = 64, - HI_PIXEL_FORMAT_YUV_PLANAR_440 = 65, - HI_PIXEL_FORMAT_YVU_PLANAR_440 = 66, - - HI_PIXEL_FORMAT_RGB_888_PLANAR = 69, - HI_PIXEL_FORMAT_BGR_888_PLANAR = 70, - HI_PIXEL_FORMAT_HSV_888_PACKAGE = 71, - HI_PIXEL_FORMAT_HSV_888_PLANAR = 72, - HI_PIXEL_FORMAT_LAB_888_PACKAGE = 73, - HI_PIXEL_FORMAT_LAB_888_PLANAR = 74, - HI_PIXEL_FORMAT_S8C1 = 75, - HI_PIXEL_FORMAT_S8C2_PACKAGE = 76, - HI_PIXEL_FORMAT_S8C2_PLANAR = 77, - HI_PIXEL_FORMAT_S16C1 = 78, - HI_PIXEL_FORMAT_U8C1 = 79, - HI_PIXEL_FORMAT_U16C1 = 80, - HI_PIXEL_FORMAT_S32C1 = 81, - HI_PIXEL_FORMAT_U32C1 = 82, - HI_PIXEL_FORMAT_U64C1 = 83, - HI_PIXEL_FORMAT_S64C1 = 84, - - HI_PIXEL_FORMAT_RGB_888_INT8 = 110, - HI_PIXEL_FORMAT_BGR_888_INT8 = 111, - HI_PIXEL_FORMAT_RGB_888_INT16 = 112, - HI_PIXEL_FORMAT_BGR_888_INT16 = 113, - HI_PIXEL_FORMAT_RGB_888_INT32 = 114, - HI_PIXEL_FORMAT_BGR_888_INT32 = 115, - HI_PIXEL_FORMAT_RGB_888_UINT16 = 116, - HI_PIXEL_FORMAT_BGR_888_UINT16 = 117, - HI_PIXEL_FORMAT_RGB_888_UINT32 = 118, - HI_PIXEL_FORMAT_BGR_888_UINT32 = 119, - HI_PIXEL_FORMAT_RGB_888_PLANAR_INT8 = 120, - HI_PIXEL_FORMAT_BGR_888_PLANAR_INT8 = 121, - HI_PIXEL_FORMAT_RGB_888_PLANAR_INT16 = 122, - HI_PIXEL_FORMAT_BGR_888_PLANAR_INT16 = 123, - HI_PIXEL_FORMAT_RGB_888_PLANAR_INT32 = 124, - HI_PIXEL_FORMAT_BGR_888_PLANAR_INT32 = 125, - HI_PIXEL_FORMAT_RGB_888_PLANAR_UINT16 = 126, - HI_PIXEL_FORMAT_BGR_888_PLANAR_UINT16 = 127, - HI_PIXEL_FORMAT_RGB_888_PLANAR_UINT32 = 128, - HI_PIXEL_FORMAT_BGR_888_PLANAR_UINT32 = 129, - HI_PIXEL_FORMAT_YUV400_UINT16 = 130, - HI_PIXEL_FORMAT_YUV400_UINT32 = 131, - HI_PIXEL_FORMAT_YUV400_UINT64 = 132, - HI_PIXEL_FORMAT_YUV400_INT8 = 133, - HI_PIXEL_FORMAT_YUV400_INT16 = 134, - HI_PIXEL_FORMAT_YUV400_INT32 = 135, - HI_PIXEL_FORMAT_YUV400_INT64 = 136, - HI_PIXEL_FORMAT_YUV400_FP16 = 137, - HI_PIXEL_FORMAT_YUV400_FP32 = 138, - HI_PIXEL_FORMAT_YUV400_FP64 = 139, - HI_PIXEL_FORMAT_YUV400_BF16 = 140, - - HI_PIXEL_FORMAT_YUV_SEMIPLANAR_440 = 1000, - HI_PIXEL_FORMAT_YVU_SEMIPLANAR_440 = 1001, - HI_PIXEL_FORMAT_FLOAT32 = 1002, - HI_PIXEL_FORMAT_BUTT = 1003, - - HI_PIXEL_FORMAT_RGB_888_PLANAR_FP16 = 1004, - HI_PIXEL_FORMAT_BGR_888_PLANAR_FP16 = 1005, - HI_PIXEL_FORMAT_RGB_888_PLANAR_FP32 = 1006, - HI_PIXEL_FORMAT_BGR_888_PLANAR_FP32 = 1007, - HI_PIXEL_FORMAT_RGB_888_PLANAR_BF16 = 1008, - HI_PIXEL_FORMAT_BGR_888_PLANAR_BF16 = 1009, - HI_PIXEL_FORMAT_RGB_888_FP16 = 1010, - HI_PIXEL_FORMAT_BGR_888_FP16 = 1011, - HI_PIXEL_FORMAT_RGB_888_FP32 = 1012, - HI_PIXEL_FORMAT_BGR_888_FP32 = 1013, - HI_PIXEL_FORMAT_RGB_888_BF16 = 1014, - HI_PIXEL_FORMAT_BGR_888_BF16 = 1015, - - HI_PIXEL_FORMAT_UNKNOWN = 10000 -} hi_pixel_format; - -typedef enum { - HI_VIDEO_FORMAT_LINEAR = 0, // nature video line - HI_VIDEO_FORMAT_TILE_64x16, // tile cell: 64pixel x 16line - HI_VIDEO_FORMAT_BUTT -} hi_video_format; - -typedef enum { - HI_COMPRESS_MODE_NONE = 0, // no compress - HI_COMPRESS_MODE_SEG, // compress unit is 256x1 bytes as a segment - HI_COMPRESS_MODE_TILE, // compress unit is a tile - HI_COMPRESS_MODE_HFBC, - HI_COMPRESS_MODE_BUTT -} hi_compress_mode; - -typedef enum { - HI_COLOR_GAMUT_BT601 = 0, - HI_COLOR_GAMUT_BT709, - HI_COLOR_GAMUT_BT2020, - HI_COLOR_GAMUT_USER, - HI_COLOR_GAMUT_BUTT -} hi_color_gamut; - -typedef enum { - HI_DYNAMIC_RANGE_SDR8 = 0, - HI_DYNAMIC_RANGE_SDR10, - HI_DYNAMIC_RANGE_HDR10, - HI_DYNAMIC_RANGE_HLG, - HI_DYNAMIC_RANGE_SLF, - HI_DYNAMIC_RANGE_XDR, - HI_DYNAMIC_RANGE_BUTT -} hi_dynamic_range; - -typedef enum { - HI_VIDEO_FIELD_TOP = 0x1, // even field - HI_VIDEO_FIELD_BOTTOM = 0x2, // odd field - HI_VIDEO_FIELD_INTERLACED = 0x3, // two interlaced fields - HI_VIDEO_FIELD_FRAME = 0x4, // frame - - HI_VIDEO_FIELD_BUTT -} hi_video_field; - -typedef enum { - HI_VIDEO_OUT_ORDER_DISPLAY = 0, - HI_VIDEO_OUT_ORDER_DEC, - HI_VIDEO_OUT_ORDER_BUTT -} hi_video_out_order; - -typedef enum { - HI_JPEG_RAW_FORMAT_YUV444 = 0, - HI_JPEG_RAW_FORMAT_YUV422 = 1, - HI_JPEG_RAW_FORMAT_YUV420 = 2, - HI_JPEG_RAW_FORMAT_YUV440 = 3, - HI_JPEG_RAW_FORMAT_YUV400 = 4, - HI_JPEG_RAW_FORMAT_YUV411 = 5, - HI_JPEG_RAW_FORMAT_MAX = 100 -} hi_jpeg_raw_format; - -typedef enum { - HI_PNG_COLOR_FORMAT_GRAY = 0x0, // gray bitmap - HI_PNG_COLOR_FORMAT_RGB = 0x2, // RGB bitmap - HI_PNG_COLOR_FORMAT_CLUT = 0x3, // clut - HI_PNG_COLOR_FORMAT_AGRAY = 0x4, // gray bitmap with alpha - HI_PNG_COLOR_FORMAT_ARGB = 0x6, // RGB bitmap with alpha - HI_PNG_COLOR_FORMAT_BUTT = 0x100 -} hi_png_color_format; - -typedef enum { - HI_CSC_MATRIX_BT601_WIDE = 0, - HI_CSC_MATRIX_BT601_NARROW, - HI_CSC_MATRIX_BT709_WIDE, - HI_CSC_MATRIX_BT709_NARROW, - HI_CSC_MATRIX_BT2020_WIDE, - HI_CSC_MATRIX_BT2020_NARROW, - HI_CSC_MATRIX_USER = 100, - HI_CSC_MATRIX_BUTT -} hi_csc_matrix; - -typedef struct { - hi_double csc_matrix_r0_c0; - hi_double csc_matrix_r0_c1; - hi_double csc_matrix_r0_c2; - hi_double csc_matrix_r1_c0; - hi_double csc_matrix_r1_c1; - hi_double csc_matrix_r1_c2; - hi_double csc_matrix_r2_c0; - hi_double csc_matrix_r2_c1; - hi_double csc_matrix_r2_c2; - hi_double csc_bias_r0; - hi_double csc_bias_r1; - hi_double csc_bias_r2; -} hi_coefficient; - -typedef struct { - hi_coefficient yuv_to_rgb_coefficient; - hi_coefficient rgb_to_yuv_coefficient; -} hi_csc_coefficient; - -typedef struct { - hi_u64 misc_info_phys_addr; // default allocated buffer - hi_u64 jpeg_dcf_phys_addr; - hi_u64 isp_info_phys_addr; - hi_u64 low_delay_phys_addr; - hi_u64 bnr_rnt_phys_addr; - hi_u64 motion_data_phys_addr; - hi_u64 frame_dng_phys_addr; - - hi_void* ATTRIBUTE misc_info_virt_addr; // misc info - hi_void* ATTRIBUTE jpeg_dcf_virt_addr; // jpeg_dcf, used in JPEG DCF - hi_void* ATTRIBUTE isp_info_virt_addr; // isp_frame_info, used in ISP debug, when get raw and send raw - hi_void* ATTRIBUTE low_delay_virt_addr; // used in low delay - hi_void* ATTRIBUTE bnr_mot_virt_addr; // used for 3dnr from bnr mot - hi_void* ATTRIBUTE motion_data_virt_addr; // vpss 3dnr use: gme motion data, filter motion data, gyro data - hi_void* ATTRIBUTE frame_dng_virt_addr; -} hi_video_supplement; - -typedef struct { - hi_u32 width; - hi_u32 height; - hi_video_field field; - hi_pixel_format pixel_format; - hi_video_format video_format; - hi_compress_mode compress_mode; - hi_dynamic_range dynamic_range; - hi_color_gamut color_gamut; - - hi_u32 header_stride[HI_MAX_COLOR_COMPONENT]; - hi_u32 width_stride[HI_MAX_COLOR_COMPONENT]; - hi_u32 height_stride[HI_MAX_COLOR_COMPONENT]; - - hi_u64 header_phys_addr[HI_MAX_COLOR_COMPONENT]; - hi_u64 phys_addr[HI_MAX_COLOR_COMPONENT]; - hi_void* header_virt_addr[HI_MAX_COLOR_COMPONENT]; - hi_void* virt_addr[HI_MAX_COLOR_COMPONENT]; - - hi_u32 time_ref; - hi_u64 pts; - - hi_u64 user_data[HI_MAX_USER_DATA_NUM]; - hi_u32 frame_flag; // frame_flag, can be OR operation. - hi_video_supplement supplement; -} hi_video_frame; - -typedef struct { - hi_video_frame v_frame; - hi_u32 pool_id; - hi_mod_id mod_id; -} hi_video_frame_info; - -typedef struct { - hi_u32 width; - hi_u32 height; -} hi_video_size; - -typedef struct { - hi_u32 width; - hi_u32 height; - hi_u32 width_stride; - hi_u32 height_stride; - hi_u32 img_buf_size; - union { - hi_jpeg_raw_format pixel_format; - hi_png_color_format png_pixel_format; - }; - hi_u32 reserved[4]; -} hi_img_info; - -typedef struct { - hi_u32 width; - hi_u32 height; - hi_u32 align; - hi_data_bit_width bit_width; - hi_pixel_format pixel_format; - hi_compress_mode compress_mode; -} hi_pic_buf_attr; - -typedef struct { - hi_payload_type type; - hi_u8 *ATTRIBUTE addr; // stream address - hi_u32 len; // stream len - hi_u64 pts; // W; time stamp - hi_s32 reserved[2]; -} hi_img_stream; - -typedef struct { - hi_void* picture_address; - hi_u32 picture_buffer_size; - hi_u32 picture_width; - hi_u32 picture_height; - hi_u32 picture_width_stride; - hi_u32 picture_height_stride; - hi_pixel_format picture_format; -} hi_pic_info; - -typedef struct { - hi_s32 x; - hi_s32 y; - hi_u32 width; - hi_u32 height; -} hi_rect; - -/* - * @brief alloc device memory for dvpp - * @param [in] dev_id: the device id, set 0 in 1p device - * @param [in] size: memory size - * @param [out] dev_ptr: memory pointer - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_dvpp_malloc(hi_u32 dev_id, hi_void **dev_ptr, hi_u64 size); - -/* - * @brief free the memory requested through the hi_mpi_dvpp_malloc interface - * @param [in] dev_ptr: memory pointer - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_dvpp_free(hi_void *dev_ptr); - -/** - * @brief query DVPP interface version - * @param [out] major_version: DVPP interface major version - * @param [out] minor_version: DVPP interface minor version - * @param [out] patch_version: DVPP interface patch version - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_dvpp_get_version(hi_s32 *major_version, hi_s32 *minor_version, hi_s32 *patch_version); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif - -#endif // #ifndef HI_DVPP_COMMON_H_ diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_pngd.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_pngd.h deleted file mode 100644 index f14237cba9..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_pngd.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_PNGD_H_ -#define HI_PNGD_H_ - -#include "hi_dvpp_common.h" -#include "hi_dvpp_vb.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif // #ifdef __cplusplus - -#define PNGD_MAX_CHN_NUM 128 - -/*********************************************************************************************/ -/* Invalid channel ID. */ -#define HI_ERR_PNGD_INVALID_CHN_ID 0xA0408002 -/* At least one parameter is illegal ,eg, an illegal enumeration value. */ -#define HI_ERR_PNGD_ILLEGAL_PARAM 0xA0408003 -/* Channel exists. */ -#define HI_ERR_PNGD_EXIST 0xA0408004 -/* The channel does not exist. */ -#define HI_ERR_PNGD_UNEXIST 0xA0408005 -/* Using a NULL pointer. */ -#define HI_ERR_PNGD_NULL_PTR 0xA0408006 -/* Try to enable or initialize system, device or channel, before configure attribute. */ -#define HI_ERR_PNGD_NOT_CFG 0xA0408007 -/* Operation is not supported by NOW. */ -#define HI_ERR_PNGD_NOT_SUPPORT 0xA0408008 -/* Operation is not permitted, eg, try to change static attribute. */ -#define HI_ERR_PNGD_NOT_PERM 0xA0408009 -/* Failure caused by malloc memory. */ -#define HI_ERR_PNGD_NO_MEM 0xA040800C -/* Failure caused by malloc buffer. */ -#define HI_ERR_PNGD_NO_BUF 0xA040800D -/* No data in buffer. */ -#define HI_ERR_PNGD_BUF_EMPTY 0xA040800E -/* No buffer for new data. */ -#define HI_ERR_PNGD_BUF_FULL 0xA040800F -/* System is not ready, had not initialized or loaded. */ -#define HI_ERR_PNGD_SYS_NOT_READY 0xA0408010 -/* Bad address, eg. used for copy_from_user & copy_to_user. */ -#define HI_ERR_PNGD_BAD_ADDR 0xA0408011 -/* System busy */ -#define HI_ERR_PNGD_BUSY 0xA0408012 -/* hardware or software timeout */ -#define HI_ERR_PNGD_TIMEOUT 0xA0408014 -/* Internal system error. */ -#define HI_ERR_PNGD_SYS_ERROR 0xA0408015 - -typedef hi_s32 hi_pngd_chn; - -typedef struct { - hi_u32 stream_que_cnt; // reserved - hi_u64 reserved[4]; -} hi_pngd_chn_attr; - -/* - * @brief create png decoder channel - * @param [in] chn: png decoder channel id [0, PNGD_MAX_CHN_NUM) - * @param [in] attr: pointer of png decoder channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_pngd_create_chn(hi_pngd_chn chn, const hi_pngd_chn_attr *attr); - -/* - * @brief destroy png decoder channel - * @param [in] chn: png decoder channel id [0, PNGD_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_pngd_destroy_chn(hi_pngd_chn chn); - -/* - * @brief send stream and outbuffer to png decoder channel - * @param [in] chn: png decoder channel id [0, PNGD_MAX_CHN_NUM) - * @param [in] stream: pointer of stream struct - * @param [in] png_pic_info: pointer of hi_pic_info struct - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_pngd_send_stream(hi_pngd_chn chn, const hi_img_stream *stream, hi_pic_info *png_pic_info, - hi_s32 milli_sec); - -/* - * @brief get frame from png decoder channel - * @param [in] chn: png decoder channel id [0, PNGD_MAX_CHN_NUM) - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @param [out] png_pic_info: pointer of pic info struct - * @param [out] stream: pointer of stream struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_pngd_get_image_data(hi_pngd_chn chn, hi_pic_info *png_pic_info, hi_img_stream *stream, hi_s32 milli_sec); - -/* - * @brief get input image's information parsed by dvpp - * @param [in] stream: stream info pointer - * @param [out] img_info: parsed image info pointer - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_png_get_image_info(const hi_img_stream *png_stream, hi_img_info *img_info); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif // #ifdef __cplusplus - -#endif // #ifndef HI_PNGD_H_ diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_sys.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_sys.h deleted file mode 100644 index c1050449bb..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_sys.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_DVPP_SYS_H_ -#define HI_DVPP_SYS_H_ - -#include "hi_dvpp_common.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#define HI_ERR_SYS_ILLEGAL_PARAM 0xA0028003 -#define HI_ERR_SYS_EXIST 0xA0028004 -#define HI_ERR_SYS_UNEXIST 0xA0028005 -#define HI_ERR_SYS_NULL_PTR 0xA0028006 -#define HI_ERR_SYS_NOT_SUPPORT 0xA0028008 -#define HI_ERR_SYS_NOT_PERM 0xA0028009 -#define HI_ERR_SYS_NO_MEM 0xA002800C -#define HI_ERR_SYS_NOT_READY 0xA0028010 -#define HI_ERR_SYS_BUSY 0xA0028012 -#define HI_ERR_SYS_ERR 0xA0028015 - -typedef enum { - HI_DVPP_EPOLL_CTL_ADD = 1, - HI_DVPP_EPOLL_CTL_MOD = 2, - HI_DVPP_EPOLL_CTL_DEL = 3, - HI_DVPP_EPOLL_CTL_BUTT -} hi_dvpp_epoll_ctl_op; - -typedef enum { - HI_DVPP_EPOLL_IN = 1u, - HI_DVPP_EPOLL_OUT = 1u << 1u, - HI_DVPP_EPOLL_ET = (hi_u32)1u << 31u -} hi_dvpp_epoll_event_type; - -typedef struct { - hi_u32 events; - hi_void *data; -} hi_dvpp_epoll_event; - -/* - * @brief init mpp system - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_init(hi_void); - -/* - * @brief exit mpp system - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_exit(hi_void); - -/** - * @brief Dvpp Epoll create interface - * @param [in] size: Specify the number of dvpp channel descriptors to monitor, - * currently ignored, and must be positive - * @param [out] epoll_fd: return the descriptor referring to the new dvpp epoll instance - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_create_epoll(hi_s32 size, hi_s32 *epoll_fd); - -/** - * @brief Dvpp Epoll control interface - * @param [in] epoll_fd: descriptor of dvpp epoll instance - * @param [in] operation: operation type for the target dvpp channel descriptor referred by @s32Fd - * @param [in] fd: descriptor of target dvpp channel - * @param [in] event: describes the event type wants to monitor, and also the data go with the channel descriptor - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_ctl_epoll(hi_s32 epoll_fd, hi_s32 operation, hi_s32 fd, hi_dvpp_epoll_event *event); - -/** - * @brief Dvpp Epoll wait interface - * @param [in] epoll_fd: descriptor of dvpp epoll instance - * @param [out] events: return events that happened - * @param [in] max_events: maxinum numer of events can return - * @param [in] timeout: milliseconds the caller can block - * @param [out] event_num: return the numer of events saved in @pEvents - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_wait_epoll(hi_s32 epoll_fd, - hi_dvpp_epoll_event *events, hi_s32 max_events, hi_s32 timeout, hi_s32 *event_num); - -/** - * @brief Dvpp Epoll close interface - * @param [in] epoll_fd: descriptor of dvpp epoll instance - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_close_epoll(hi_s32 epoll_fd); - -/* - * @brief set csc matrix coefficient - * @param [in] mode: dvpp module - * @param [in] chn: chn id - * @param [in] csc_matrix: csc matrix mode - * @param [in] csc_coefficient: csc matrix coefficient when use user mode - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_set_chn_csc_matrix(hi_mod_id mode, - hi_s32 chn, hi_csc_matrix csc_matrix, hi_csc_coefficient *csc_coefficient); - -/* - * @brief get csc matrix coefficient - * @param [in] mode: dvpp module - * @param [in] chn: chn id - * @param [out] csc_matrix: csc matrix mode - * @param [out] csc_coefficient: csc matrix coefficient for all mode - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_sys_get_chn_csc_matrix(hi_mod_id mode, - hi_s32 chn, hi_csc_matrix *csc_matrix, hi_csc_coefficient *csc_coefficient); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif - -#endif // #ifndef HI_DVPP_SYS_H_ diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_type.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_type.h deleted file mode 100644 index 78b0ec56a0..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_type.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_DVPP_TYPE_H_ -#define HI_DVPP_TYPE_H_ - -#include - -typedef unsigned char hi_u8; -typedef signed char hi_s8; -typedef unsigned short hi_u16; -typedef short hi_s16; -typedef unsigned int hi_u32; -typedef int hi_s32; -typedef unsigned long long hi_u64; -typedef long long hi_s64; -typedef char hi_char; -typedef double hi_double; -typedef hi_u32 hi_fr32; -typedef float hi_float; - -#define hi_void void -#define HI_NULL 0L -#define HI_SUCCESS 0 -#define HI_FAILURE (-1) - -typedef enum { - HI_FALSE = 0, - HI_TRUE = 1, -} hi_bool; - -#endif // #ifndef HI_DVPP_TYPE_H_ \ No newline at end of file diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_vb.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_vb.h deleted file mode 100644 index bfacfc9577..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_vb.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_DVPP_VB_H_ -#define HI_DVPP_VB_H_ - -#include "hi_dvpp_common.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -typedef hi_u32 hi_vb_pool; - -typedef enum { - HI_VB_SRC_COMMON = 0, - HI_VB_SRC_MOD = 1, - HI_VB_SRC_PRIVATE = 2, - HI_VB_SRC_USER = 3, - HI_VB_SRC_BUTT -} hi_vb_src; - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif - -#endif // #ifndef HI_DVPP_VB_H_ \ No newline at end of file diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_vdec.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_vdec.h deleted file mode 100644 index b4e150e8ac..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_vdec.h +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_VDEC_H_ -#define HI_VDEC_H_ - -#include "hi_dvpp_common.h" -#include "hi_dvpp_vb.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif // #ifdef __cplusplus - -#define VDEC_MAX_CHN_NUM 256 - -/*********************************************************************************************/ -/* Invalid channel ID. */ -#define HI_ERR_VDEC_INVALID_CHN_ID 0xA0058002 -/* At least one parameter is illegal ,eg, an illegal enumeration value. */ -#define HI_ERR_VDEC_ILLEGAL_PARAM 0xA0058003 -/* Channel exists. */ -#define HI_ERR_VDEC_EXIST 0xA0058004 -/* The channel does not exist. */ -#define HI_ERR_VDEC_UNEXIST 0xA0058005 -/* Using a NULL pointer. */ -#define HI_ERR_VDEC_NULL_PTR 0xA0058006 -/* Try to enable or initialize system, device or channel, before configure attribute. */ -#define HI_ERR_VDEC_NOT_CFG 0xA0058007 -/* Operation is not supported by NOW. */ -#define HI_ERR_VDEC_NOT_SUPPORT 0xA0058008 -/* Operation is not permitted, eg, try to change static attribute. */ -#define HI_ERR_VDEC_NOT_PERM 0xA0058009 -/* Failure caused by malloc memory. */ -#define HI_ERR_VDEC_NO_MEM 0xA005800C -/* Failure caused by malloc buffer. */ -#define HI_ERR_VDEC_NO_BUF 0xA005800D -/* No data in buffer. */ -#define HI_ERR_VDEC_BUF_EMPTY 0xA005800E -/* No buffer for new data. */ -#define HI_ERR_VDEC_BUF_FULL 0xA005800F -/* System is not ready, had not initialized or loaded. */ -#define HI_ERR_VDEC_SYS_NOT_READY 0xA0058010 -/* Bad address, eg. used for copy_from_user & copy_to_user. */ -#define HI_ERR_VDEC_BAD_ADDR 0xA0058011 -/* System busy */ -#define HI_ERR_VDEC_BUSY 0xA0058012 -/* system error */ -#define HI_ERR_VDEC_SYS_ERROR 0xA0058015 - -typedef hi_s32 hi_vdec_chn; - -typedef enum { - HI_VDEC_SEND_MODE_STREAM = 0, // Send by stream. - HI_VDEC_SEND_MODE_FRAME, // Send by frame. - HI_VDEC_SEND_MODE_COMPAT, // One frame supports multiple packets sending. - HI_VDEC_SEND_MODE_BUTT -} hi_vdec_send_mode; - -typedef enum { - HI_VIDEO_DEC_MODE_IPB = 0, - HI_VIDEO_DEC_MODE_IP, - HI_VIDEO_DEC_MODE_I, - HI_VIDEO_DEC_MODE_BUTT -} hi_video_dec_mode; - -typedef enum { - HI_VDEC_FRAME_TYPE_I = 0, - HI_VDEC_FRAME_TYPE_P = 1, - HI_VDEC_FRAME_TYPE_B = 2, - HI_VDEC_FRAME_TYPE_BUTT -} hi_vdec_frame_type; - -typedef enum { - HI_QUICK_MARK_ADAPT = 0, - HI_QUICK_MARK_FORCE, - HI_QUICK_MARK_NONE, - HI_QUICK_MARK_BUTT -} hi_quick_mark_mode; - -typedef struct { - hi_vdec_frame_type frame_type; - hi_u32 err_rate; - hi_u32 poc; -} hi_vdec_video_supplement_info; - -typedef struct { - hi_payload_type type; // RW; Video type to be decoded. - union { - hi_vdec_video_supplement_info video_supplement_info; // Structure with video (h265/h264) - }; -} hi_vdec_supplement_info; - -typedef struct { - hi_s32 set_pic_size_err; // R; Picture width or height is larger than channel width or height. - hi_s32 set_protocol_num_err; // R; Protocol num is not enough. eg: slice, pps, sps. - hi_s32 set_ref_num_err; // R; Reference num is not enough. - hi_s32 set_pic_buf_size_err; // R; The buffer size of picture is not enough. - hi_s32 format_err; // R; Format error. eg: do not support filed. - hi_s32 stream_unsupport; // R; Unsupported the stream specification. - hi_s32 pack_err; // R; Stream package error. - hi_s32 stream_size_over; // R; The stream size is too big and force discard stream. - hi_s32 stream_not_release; // R; The stream not released for too long time. -} hi_vdec_dec_err; - -typedef struct { - hi_payload_type type; // R; Video type to be decoded. - hi_u32 left_stream_bytes; // R; Left stream bytes waiting for decode. - hi_u32 left_stream_frames; // R; Left frames waiting for decode,only valid for HI_VDEC_SEND_MODE_FRAME. - hi_u32 left_decoded_frames; // R; Pics waiting for output. - hi_bool is_started; // R; Had started recv stream? - hi_u32 recv_stream_frames; // R; How many frames of stream has been received. valid when send by frame. - hi_u32 dec_stream_frames; // R; How many frames of stream has been decoded. valid when send by frame. - hi_vdec_dec_err dec_err; // R; Information about decode error. - hi_u32 width; // R; The width of the currently decoded stream. - hi_u32 height; // R; The height of the currently decoded stream. - hi_u64 latest_frame_pts; // R; PTS of the latest decoded frame. -} hi_vdec_chn_status; - -typedef struct { - hi_u32 ref_frame_num; // RW, Range: [0, 16]; reference frame num. - hi_bool temporal_mvp_en; // RW; Specifies whether temporal motion vector predictors. - hi_u32 tmv_buf_size; // RW; The size of tmv buffer (byte). -} hi_vdec_video_attr; - -typedef struct { - hi_payload_type type; // RW; Video type to be decoded. - hi_vdec_send_mode mode; // RW; Send by stream or by frame. - hi_u32 pic_width; // RW; Max width of pic. - hi_u32 pic_height; // RW; Max height of pic. - hi_u32 stream_buf_size; // RW; The size of stream buffer (byte). - hi_u32 frame_buf_size; // RW; The size of frame buffer (byte). - hi_u32 frame_buf_cnt; - union { - hi_vdec_video_attr video_attr; // RW; Structure with video (h264/h265). - }; -} hi_vdec_chn_attr; - -typedef struct { - hi_bool end_of_frame; // W; Is the end of a frame. - hi_bool end_of_stream; // W; Is the end of all stream. - hi_bool need_display; // W; Is the current frame displayed. only valid by HI_VDEC_SEND_MODE_FRAME. - hi_u64 pts; // W; Time stamp. - hi_u64 private_data; // W; Private data, only valid by HI_VDEC_SEND_MODE_FRAME or HI_VDEC_SEND_MODE_COMPAT. - hi_u32 len; // W; The len of stream. - hi_u8 *ATTRIBUTE addr; // W; The address of stream. -} hi_vdec_stream; - -typedef struct { - // RW; HI_FALSE: output base layer; HI_TRUE: output enhance layer; default: HI_FALSE - hi_bool composite_dec_en; - // RW; HI_FALSE: don't support slice low latency; HI_TRUE: support slice low latency; default: HI_FALSE - hi_bool slice_input_en; - // RW, Range: [0, 100]; threshold for stream error process, - // 0: discard with any error, 100 : keep data with any error. - hi_s32 err_threshold; - // RW; Decode mode , 0: decode IPB frames, - // 1: only decode I frame & P frame , 2: only decode I frame. - hi_video_dec_mode dec_mode; - // RW; Frames output order , - // 0: the same with display order , 1: the same width decoder order. - hi_video_out_order out_order; - hi_compress_mode compress_mode; // RW; Compress mode. - hi_video_format video_format; // RW; Video format. - hi_quick_mark_mode quick_mark_mode; -} hi_vdec_video_param; - -typedef struct { - hi_pixel_format pixel_format; // RW; Out put pixel format. - // RW, range: [0, 255]; Value 0 is transparent. - // [0 ,127] is deemed to transparent when pixel_format is ARGB1555 or ABGR1555 - // [128 ,256] is deemed to non-transparent when pixel_format is ARGB1555 or ABGR1555. - hi_u32 alpha; -} hi_vdec_pic_param; - -typedef struct { - hi_payload_type type; // RW; video type to be decoded - hi_u32 display_frame_num; // RW, Range: [0, 16]; display frame num - union { - hi_vdec_video_param video_param; // structure with video ( h265/h264) - hi_vdec_pic_param pic_param; // structure with picture (jpeg/mjpeg) - }; -} hi_vdec_chn_param; - -typedef struct { - hi_u32 width; - hi_u32 height; - hi_u32 width_stride; - hi_u32 height_stride; - hi_pixel_format pixel_format; // JPEGD/VDEC OutPut Format - hi_u64 vir_addr; - hi_u32 buffer_size; - hi_s16 offset_top; // For JPEGD Region Decoding - hi_s16 offset_bottom; // For JPEGD Region Decoding - hi_s16 offset_left; // For JPEGD Region Decoding - hi_s16 offset_right; // For JPEGD Region Decoding -} hi_vdec_pic_info; - -typedef struct { - hi_s32 max_slice_num; // RW; max slice num support - hi_s32 max_sps_num; // RW; max sps num support - hi_s32 max_pps_num; // RW; max pps num support -} hi_h264_protocol_param; - -typedef struct { - hi_s32 max_slice_segment_num; // RW; max slice segmnet num support - hi_s32 max_vps_num; // RW; max vps num support - hi_s32 max_sps_num; // RW; max sps num support - hi_s32 max_pps_num; // RW; max pps num support -} hi_h265_protocol_param; - -typedef struct { - hi_payload_type type; // RW; video type to be decoded, only h264 and h265 supported - union { - hi_h264_protocol_param h264_param; // protocol param structure for h264 - hi_h265_protocol_param h265_param; // protocol param structure for h265 - }; -} hi_vdec_protocol_param; - -typedef enum { - YUVOUT_ALIGN_DOWN = 0, - YUVOUT_ALIGN_UP = 1, - YUVOUT_ALIGN_DOWN_COMPAT = 2, -} hi_jpegd_precision_mode; - -/* - * @brief get video decoder picture buffer size - * @param [in] type: video type [PT_H264/PT_H265] - * @param [in] buf_attr: pointer of picture buffer attribute - * @return : video decoder picture buffer size - */ -hi_u32 hi_vdec_get_pic_buf_size(hi_payload_type type, hi_pic_buf_attr *buf_attr); - -/* - * @brief get video decoder tmv buffer size - * @param [in] type: video type [PT_H264/PT_H265] - * @param [in] width: video width - * @param [in] height: video height - * @return : video decoder tmv buffer size - */ -hi_u32 hi_vdec_get_tmv_buf_size(hi_payload_type type, hi_u32 width, hi_u32 height); - -/* - * @brief create video decoder channel - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] attr: pointer of video decoder channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_create_chn(hi_vdec_chn chn, const hi_vdec_chn_attr *attr); - -/* - * @brief destroy video decoder channel - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_destroy_chn(hi_vdec_chn chn); - -/* - * @brief set video decoder channel attribute - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] attr: pointer of video decoder channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_set_chn_attr(hi_vdec_chn chn, const hi_vdec_chn_attr *attr); - -/* - * @brief get video decoder channel attribute - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [out] attr: pointer of video decoder channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_get_chn_attr(hi_vdec_chn chn, hi_vdec_chn_attr *attr); - -/* - * @brief set video decoder channel protocol param - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] protocol_param: pointer of video decoder protocol param - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_set_protocol_param(hi_vdec_chn chn, const hi_vdec_protocol_param *protocol_param); - -/* - * @brief get video decoder channel protocol param - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [out] protocol_param: pointer of video decoder protocol param - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_get_protocol_param(hi_vdec_chn chn, hi_vdec_protocol_param *protocol_param); - -/* - * @brief video decoder channel start receive stream - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_start_recv_stream(hi_vdec_chn chn); - -/* - * @brief video decoder channel stop receive stream - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_stop_recv_stream(hi_vdec_chn chn); - -/* - * @brief query video decoder channel status - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [out] status: pointer of video decoder channel status struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_query_status(hi_vdec_chn chn, hi_vdec_chn_status *status); - -/* - * @brief reset video decoder channel status - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_reset_chn(hi_vdec_chn chn); - -/* - * @brief set video decoder channel parameter - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] chn_param: pointer of video decoder channel parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_set_chn_param(hi_vdec_chn chn, const hi_vdec_chn_param *chn_param); - -/* - * @brief get video decoder channel parameter - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [out] chn_param: pointer of video decoder channel parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_get_chn_param(hi_vdec_chn chn, hi_vdec_chn_param *chn_param); - -/* - * @brief send stream and outbuffer to video decoder channel - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] stream: pointer of stream struct - * @param [in] vdec_pic_info: pointer of vdec_pic_info struct - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_send_stream(hi_vdec_chn chn, const hi_vdec_stream *stream, hi_vdec_pic_info *vdec_pic_info, - hi_s32 milli_sec); - -/* - * @brief get frame from video decoder channel - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @param [out] frame_info: pointer of frame info struct - * @param [out] supplement: pointer of supplement info struct - * @param [out] stream: pointer of stream struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_get_frame(hi_vdec_chn chn, hi_video_frame_info *frame_info, hi_vdec_supplement_info *supplement, - hi_vdec_stream *stream, hi_s32 milli_sec); - -/* - * @brief release frame from video decoder channel - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] frame_info: pointer of frame info struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_release_frame(hi_vdec_chn chn, const hi_video_frame_info *frame_info); - -/* - * @brief get video decoder channel fd - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @return success: return fd - * fail: return negative number - */ -hi_s32 hi_mpi_vdec_get_fd(hi_vdec_chn chn); - -/* - * @brief close video decoder channel fd - * @param [in] chn: video decoder channel id [0, VDEC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return -1 - */ -hi_s32 hi_mpi_vdec_close_fd(hi_vdec_chn chn); - -/* - * @brief get input image's information parsed by dvpp - * @param [in] img_type: payload type of input image - * @param [in] stream: stream info pointer - * @param [out] img_info: parsed image info pointer - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_dvpp_get_image_info(hi_payload_type img_type, const hi_vdec_stream *stream, hi_img_info *img_info); - -/* - * @brief set jpegd decoder channel precision mode - * @param [in] chn: jpegd decoder channel id [0, VDEC_MAX_CHN_NUM) - * @param [in] mode: jpegd decoder channel precision mode struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vdec_set_jpegd_precision_mode(hi_vdec_chn chn, const hi_jpegd_precision_mode mode); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif // #ifdef __cplusplus - -#endif // #ifndef HI_VDEC_H_ diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_venc.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_venc.h deleted file mode 100644 index 5094e20622..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_venc.h +++ /dev/null @@ -1,1236 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_VENC_H_ -#define HI_VENC_H_ - -#include "hi_dvpp_common.h" -#include "hi_dvpp_vb.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#define HI_VENC_MAX_PACK_INFO_NUM 8 -#define HI_VENC_MAX_MPF_NUM 2 -#define HI_VENC_PRORES_MAX_ID_CHAR_NUM 4 -#define HI_VENC_JPEG_QT_COEF_NUM 64 -#define HI_VENC_QP_HIST_NUM 52 -#define HI_VENC_MAX_SSE_NUM 8 -#define HI_VENC_TEXTURE_THRESHOLD_SIZE 16 // The number of thresholds that define the complexity of RC macroblocks - -/* invlalid channel ID */ -#define HI_ERR_VENC_INVALID_CHN_ID 0xA0088002 -/* at least one parameter is illagal ,eg, an illegal enumeration value */ -#define HI_ERR_VENC_ILLEGAL_PARAM 0xA0088003 -/* channel exists */ -#define HI_ERR_VENC_EXIST 0xA0088004 -/* channel exists */ -#define HI_ERR_VENC_UNEXIST 0xA0088005 -/* using a NULL pointer */ -#define HI_ERR_VENC_NULL_PTR 0xA0088006 -/* try to enable or initialize system,device or channel, before configing attribute */ -#define HI_ERR_VENC_NOT_CFG 0xA0088007 -/* operation is not supported by NOW */ -#define HI_ERR_VENC_NOT_SUPPORT 0xA0088008 -/* operation is not permitted ,eg, try to change statuses attribute */ -#define HI_ERR_VENC_NOT_PERM 0xA0088009 -/* failure caused by malloc memory */ -#define HI_ERR_VENC_NO_MEM 0xA008800C -/* failure caused by malloc buffer */ -#define HI_ERR_VENC_NO_BUF 0xA008800D -/* no data in buffer */ -#define HI_ERR_VENC_BUF_EMPTY 0xA008800E -/* no buffer for new data */ -#define HI_ERR_VENC_BUF_FULL 0xA008800F -/* system is not ready,had not initialed or loaded */ -#define HI_ERR_VENC_SYS_NOT_READY 0xA0088010 -/* bad address, eg, used for copy_from_user & copy_to_user */ -#define HI_ERR_VENC_BAD_ADDR 0xA0088011 -/* system is busy */ -#define HI_ERR_VENC_BUSY 0xA0088012 -/* system err */ -#define HI_ERR_VENC_SYS_ERROR 0xA0088015 - -typedef hi_s32 hi_venc_chn; - -// the sse info -typedef struct { - hi_bool enable; // RW; Range:[0,1]; Region SSE enable - hi_u64 sse_val; // R; Region SSE value -} hi_venc_sse_info; - -// the nalu type of H264E -typedef enum { - HI_VENC_H264_NALU_B_SLICE = 0, // B SLICE types - HI_VENC_H264_NALU_P_SLICE = 1, // P SLICE types - HI_VENC_H264_NALU_I_SLICE = 2, // I SLICE types - HI_VENC_H264_NALU_IDR_SLICE = 5, // IDR SLICE types - HI_VENC_H264_NALU_SEI = 6, // SEI types - HI_VENC_H264_NALU_SPS = 7, // SPS types - HI_VENC_H264_NALU_PPS = 8, // PPS types - HI_VENC_H264_NALU_BUTT -} hi_venc_h264_nalu_type; - -// the nalu type of H265E -typedef enum { - HI_VENC_H265_NALU_B_SLICE = 0, // B SLICE types - HI_VENC_H265_NALU_P_SLICE = 1, // P SLICE types - HI_VENC_H265_NALU_I_SLICE = 2, // I SLICE types - HI_VENC_H265_NALU_IDR_SLICE = 19, // IDR SLICE types - HI_VENC_H265_NALU_VPS = 32, // VPS types - HI_VENC_H265_NALU_SPS = 33, // SPS types - HI_VENC_H265_NALU_PPS = 34, // PPS types - HI_VENC_H265_NALU_SEI = 39, // SEI types - HI_VENC_H265_NALU_ENHANCE = 64, // ENHANCE types - HI_VENC_H265_NALU_BUTT -} hi_venc_h265_nalu_type; - -// the reference type of H264E slice -typedef enum { - HI_VENC_H264_REF_SLICE_FOR_1X = 1, // Reference slice for H264E_REF_MODE_1X - HI_VENC_H264_REF_SLICE_FOR_2X = 2, // Reference slice for H264E_REF_MODE_2X - HI_VENC_H264_REF_SLICE_FOR_4X = 5, // Reference slice for H264E_REF_MODE_4X - HI_VENC_H264_REF_SLICE_FOR_BUTT // slice not for reference -} hi_venc_h264_ref_slice_type; - -// the pack type of JPEGE -typedef enum { - HI_VENC_JPEG_PACK_ECS = 5, // ECS types - HI_VENC_JPEG_PACK_APP = 6, // APP types - HI_VENC_JPEG_PACK_VDO = 7, // VDO types - HI_VENC_JPEG_PACK_PIC = 8, // PIC types - HI_VENC_JPEG_PACK_DCF = 9, // DCF types - HI_VENC_JPEG_PACK_DCF_PIC = 10, // DCF PIC types - HI_VENC_JPEG_PACK_BUTT -} hi_venc_jpege_pack_type; - -// the pack type of PRORES -typedef enum { - HI_VENC_PRORES_PACK_PIC = 1, // PIC types - HI_VENC_PRORES_PACK_BUTT -} hi_venc_prores_pack_type; - -// the data type of VENC -typedef union { - hi_venc_h264_nalu_type h264_type; // R; H264E NALU types - hi_venc_jpege_pack_type jpeg_type; // R; JPEGE pack types - hi_venc_h265_nalu_type h265_type; // R; H264E NALU types - hi_venc_prores_pack_type prores_type; -} hi_venc_data_type; - -// the pack info of VENC -typedef struct { - hi_venc_data_type pack_type; // R; the pack type - hi_u32 pack_offset; - hi_u32 pack_len; -} hi_venc_pack_info; - -// Defines a stream packet -typedef struct { - union { - hi_u64 phys_addr; // R; the physics address of stream - hi_u64 input_addr; // R; the address of input frame - }; - hi_u8 ATTRIBUTE *addr; // R; the virtual address of stream - hi_u32 ATTRIBUTE len; // R; the length of stream - - hi_u64 pts; // R; PTS - hi_bool is_frame_end; // R; frame end - - hi_venc_data_type data_type; // R; the type of stream - hi_u32 offset; // R; the offset between the Valid data and the start address - hi_u32 data_num; // R; the stream packets num - hi_venc_pack_info pack_info[HI_VENC_MAX_PACK_INFO_NUM]; // R; the stream packet Information -} hi_venc_pack; - -// Defines the frame type and reference attributes of the H.264 frame skipping reference streams -typedef enum { - HI_VENC_BASE_IDR_SLICE = 0, // the Idr frame at Base layer - HI_VENC_BASE_P_SLICE_REF_TO_IDR, // the P frame at Base layer, referenced by other frames at Base layer and reference to Idr frame - HI_VENC_BASE_P_SLICE_REF_BY_BASE, // the P frame at Base layer, referenced by other frames at Base layer - HI_VENC_BASE_P_SLICE_REF_BY_ENHANCE, // the P frame at Base layer, referenced by other frames at Enhance layer - HI_VENC_ENHANCE_P_SLICE_REF_BY_ENHANCE, // the P frame at Enhance layer, referenced by other frames at Enhance layer - HI_VENC_ENHANCE_P_SLICE_NOT_FOR_REF, // the P frame at Enhance layer ,not referenced - HI_VENC_P_SLICE_BUTT -} hi_venc_ref_type; - -// Defines the features of an H.264 stream -typedef struct { - hi_u32 pic_bytes; // R; the coded picture stream byte number - hi_u32 inter16x16_mb_num; // R; the inter16x16 macroblock num - hi_u32 inter8x8_mb_num; // R; the inter8x8 macroblock num - hi_u32 intra16_mb_num; // R; the intra16x16 macroblock num - hi_u32 intra8_mb_num; // R; the intra8x8 macroblock num - hi_u32 intra4_mb_num; // R; the inter4x4 macroblock num - - hi_venc_ref_type ref_type; // R; Type of encoded frames in advanced frame skipping reference mode - hi_u32 update_attr_cnt; // R; Number of times that channel attributes or - // parameters(including RC parameters) are set - hi_u32 start_qp; // R; the start Qp of encoded frames - hi_u32 mean_qp; // R; the mean Qp of encoded frames - hi_bool is_p_skip; -} hi_venc_h264_stream_info; - -// Defines the features of an H.265 stream -typedef struct { - hi_u32 pic_bytes; // R; the coded picture stream byte number - hi_u32 inter64x64_cu_num; // R; the inter64x64 cu num - hi_u32 inter32x32_cu_num; // R; the inter32x32 cu num - hi_u32 inter16x16_cu_num; // R; the inter16x16 cu num - hi_u32 inter8x8_cu_num; // R; the inter8x8 cu num - hi_u32 intra32x32_cu_num; // R; the Intra32x32 cu num - hi_u32 intra16x16_cu_num; // R; the Intra16x16 cu num - hi_u32 intra8x8_cu_num; // R; the Intra8x8 cu num - hi_u32 intra4x4_cu_num; // R; the Intra4x4 cu num - - hi_venc_ref_type ref_type; // R; Type of encoded frames in advanced frame skipping reference mode - hi_u32 update_attr_cnt; // R; Number of times that channel attributes or - // parameters (including RC parameters) are set - hi_u32 start_qp; // R; the start Qp of encoded frames - hi_u32 mean_qp; // R; the mean Qp of encoded frames - hi_bool is_p_skip; -} hi_venc_h265_stream_info; - -// Defines the features of an jpege stream -typedef struct { - hi_u32 pic_bytes; // R; the coded picture stream byte number - hi_u32 update_attr_cnt; // R; Number of times that channel attributes or parameters(including RC parameters) are set - hi_u32 qfactor; // R; image quality -} hi_venc_jpeg_stream_info; - -// Defines the features of an jpege stream -typedef struct { - hi_u32 pic_bytes; - hi_u32 update_attr_cnt; -} hi_venc_prores_stream_info; - -// the advance information of the h264e -typedef struct { - hi_u32 residual_bits; // R; the residual num - hi_u32 head_bits; // R; the head bit num - hi_u32 madi_val; // R; the madi value - hi_u32 madp_val; // R; the madp value - hi_double psnr_val; // R; the PSNR value - hi_u32 sse_lcu_cnt; // R; the lcu cnt of the sse - hi_u64 sse_sum; // R; the sum of the sse - hi_venc_sse_info sse_info[HI_VENC_MAX_SSE_NUM]; // R; the information of the sse - hi_u32 qp_hist[HI_VENC_QP_HIST_NUM]; // R; the Qp histogram value - hi_u32 move_scene16x16_num; // R; the 16x16 cu num of the move scene - hi_u32 move_scene_bits; // R; the stream bit num of the move scene -} hi_venc_h264_adv_stream_info; - -// the advance information of the h265e -typedef struct { - hi_u32 residual_bits; // R; the residual num - hi_u32 head_bits; // R; the head bit num - hi_u32 madi_val; // R; the madi value - hi_u32 madp_val; // R; the madp value - hi_double psnr_val; // R; the PSNR value - hi_u32 sse_lcu_cnt; // R; the lcu cnt of the sse - hi_u64 sse_sum; // R; the sum of the sse - hi_venc_sse_info sse_info[HI_VENC_MAX_SSE_NUM]; // R; the information of the sse - hi_u32 qp_hist[HI_VENC_QP_HIST_NUM]; // R; the Qp histogram value - hi_u32 move_scene32x32_num; // R; the 32x32 cu num of the move scene - hi_u32 move_scene_bits; // R; the stream bit num of the move scene -} hi_venc_h265_adv_stream_info; - -// Defines the features of an stream -typedef struct { - hi_venc_pack ATTRIBUTE *pack; // R; stream pack attribute - hi_u32 ATTRIBUTE pack_cnt; // R; the pack number of one frame stream - hi_u32 seq; // R; the list number of stream - - union { - hi_venc_h264_stream_info h264_info; // R; the stream info of h264 - hi_venc_jpeg_stream_info jpeg_info; // R; the stream info of jpeg - hi_venc_h265_stream_info h265_info; // R; the stream info of h265 - hi_venc_prores_stream_info prores_info; // R; the stream info of prores - }; - - union { - hi_venc_h264_adv_stream_info h264_adv_info; // R; the stream info of h264 - hi_venc_h265_adv_stream_info h265_adv_info; // R; the stream info of h265 - }; -} hi_venc_stream; - -typedef struct { - hi_venc_ref_type ref_type; // R;Type of encoded frames in advanced frame skipping reference mode - - hi_u32 pic_bytes; // R;the coded picture stream byte number - hi_u32 pic_cnt; // R;When channel attributes 'is_by_frame == 1', it means count of frames. - // When channel attributes 'is_by_frame == 0', it means count of packets - hi_u32 start_qp; // R;the start Qp of encoded frames - hi_u32 mean_qp; // R;the mean Qp of encoded frames - hi_bool is_p_skip; - - hi_u32 residual_bits; // R;residual - hi_u32 head_bits; // R;head information - hi_u32 madi_val; // R;madi - hi_u32 madp_val; // R;madp - hi_u64 sse_sum; // R;Sum of SSE value - hi_u32 sse_lcu_cnt; // R;Sum of LCU number - hi_double psnr_val; // R;PSNR -} hi_venc_stream_info; - -// the status of the venc chnl -typedef struct { - hi_u32 left_pics; // R; left picture number - hi_u32 left_stream_bytes; // R; left stream bytes - hi_u32 left_stream_frames; // R; left stream frames - hi_u32 cur_packs; // R; pack number of current frame - hi_u32 left_recv_pics; // R; Number of frames to be received. - hi_u32 left_enc_pics; // R; Number of frames to be encoded. - hi_bool is_jpeg_snap_end; // R; the end of Snap. - hi_u64 release_pic_pts; - hi_venc_stream_info stream_info; -} hi_venc_chn_status; - -// the attribute of h264e -typedef struct { - hi_bool rcn_ref_share_buf_en; // RW; Range:[0, 1]; Whether to enable the Share Buf of Rcn and Ref - hi_u32 frame_buf_ratio; -} hi_venc_h264_attr; - -// the attribute of h265e -typedef struct { - hi_bool rcn_ref_share_buf_en; // RW; Range:[0, 1]; Whether to enable the Share Buf of Rcn and Ref - hi_u32 frame_buf_ratio; -} hi_venc_h265_attr; - -// the size of array is 2,that is the maximum -typedef struct { - hi_u8 large_thumbnail_num; // RW; Range:[0, 2]; the large thumbnail pic num of the MPF - hi_video_size large_thumbnail_size[HI_VENC_MAX_MPF_NUM]; // RW; The resolution of large ThumbNail -} hi_venc_mpf_cfg; - -typedef enum { - HI_VENC_PIC_RECV_SINGLE = 0, - HI_VENC_PIC_RECV_MULTI, - - HI_VENC_PIC_RECV_BUTT -} hi_venc_pic_recv_mode; - -// the attribute of jpege -typedef struct { - hi_bool dcf_en; // RW; Range:[0, 1]; support dcf - hi_venc_mpf_cfg mpf_cfg; // RW; Range:[0, 1]; config of Mpf - hi_venc_pic_recv_mode recv_mode; // RW; Config the receive mode; -} hi_venc_jpeg_attr; - -// the frame rate of PRORES -typedef enum { - HI_VENC_PRORES_FRAME_RATE_UNKNOWN = 0, - HI_VENC_PRORES_FRAME_RATE_23_976, - HI_VENC_PRORES_FRAME_RATE_24, - HI_VENC_PRORES_FRAME_RATE_25, - HI_VENC_PRORES_FRAME_RATE_29_97, - HI_VENC_PRORES_FRAME_RATE_30, - HI_VENC_PRORES_FRAME_RATE_50, - HI_VENC_PRORES_FRAME_RATE_59_94, - HI_VENC_PRORES_FRAME_RATE_60, - HI_VENC_PRORES_FRAME_RATE_100, - HI_VENC_PRORES_FRAME_RATE_119_88, - HI_VENC_PRORES_FRAME_RATE_120, - HI_VENC_PRORES_FRAME_RATE_BUTT -} hi_venc_prores_frame_rate; - -// the aspect ratio of PRORES -typedef enum { - HI_VENC_PRORES_ASPECT_RATIO_UNKNOWN = 0, - HI_VENC_PRORES_ASPECT_RATIO_SQUARE, - HI_VENC_PRORES_ASPECT_RATIO_4_3, - HI_VENC_PRORES_ASPECT_RATIO_16_9, - HI_VENC_PRORES_ASPECT_RATIO_BUTT -} hi_venc_prores_aspect_ratio; - -// the attribute of PRORES -typedef struct { - hi_char identifier[HI_VENC_PRORES_MAX_ID_CHAR_NUM]; - hi_venc_prores_frame_rate frame_rate_code; - hi_venc_prores_aspect_ratio aspect_ratio; -} hi_venc_prores_attr; - -// the attribute of the Venc -typedef struct { - hi_payload_type type; // RW; the type of payload - - hi_u32 max_pic_width; // RW; maximum width of a picture to be encoded, in pixel - hi_u32 max_pic_height; // RW; maximum height of a picture to be encoded, in pixel - - hi_u32 buf_size; // RW; stream buffer size - hi_u32 profile; // RW; Range:[0, 3] - // H.264: 0: baseline, 1:MP, 2:HP, 3: SVC-T [0, 3] - // H.265: 0: MP, 1:Main 10 [0 1] - // Jpege/MJpege: 0:Baseline - // prores: 0:ProRes Proxy; 1:ProRes 422(LT); 2:ProRes 422; 3:ProRes 422(HQ) - hi_bool is_by_frame; // RW; Range:[0, 1]; get stream mode is slice mode or frame mode - hi_u32 pic_width; // RW; width of a picture to be encoded, in pixel - hi_u32 pic_height; // RW; height of a picture to be encoded, in pixel - union { - hi_venc_h264_attr h264_attr; // attributes of H264e - hi_venc_h265_attr h265_attr; // attributes of H265e - hi_venc_jpeg_attr jpeg_attr; // attributes of jpeg - hi_venc_prores_attr prores_attr; // attributes of prores - }; -} hi_venc_attr; - -// rc mode -typedef enum { - HI_VENC_RC_MODE_H264_CBR = 1, - HI_VENC_RC_MODE_H264_VBR, - HI_VENC_RC_MODE_H264_AVBR, - HI_VENC_RC_MODE_H264_QVBR, - HI_VENC_RC_MODE_H264_CVBR, - HI_VENC_RC_MODE_H264_FIXQP, - HI_VENC_RC_MODE_H264_QPMAP, - HI_VENC_RC_MODE_MJPEG_CBR, - HI_VENC_RC_MODE_MJPEG_VBR, - HI_VENC_RC_MODE_MJPEG_FIXQP, - HI_VENC_RC_MODE_H265_CBR, - HI_VENC_RC_MODE_H265_VBR, - HI_VENC_RC_MODE_H265_AVBR, - HI_VENC_RC_MODE_H265_QVBR, - HI_VENC_RC_MODE_H265_CVBR, - HI_VENC_RC_MODE_H265_FIXQP, - HI_VENC_RC_MODE_H265_QPMAP, - HI_VENC_RC_MODE_BUTT, -} hi_venc_rc_mode; - -// the attribute of h264e cbr -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of I Frame. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 bit_rate; // RW; Range:[2, 614400]; average bitrate -} hi_venc_h264_cbr; - -// the attribute of h264e vbr -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of ISLICE. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 max_bit_rate; // RW; Range:[2, 614400];the max bitrate -} hi_venc_h264_vbr; - -// the attribute of h264e cvbr -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of ISLICE. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 max_bit_rate; // RW; Range:[2, 614400];the max bitrate - - hi_u32 short_term_stats_time; // RW; Range:[1, 120]; the long-term rate statistic time, - // the unit is second (s) - hi_u32 long_term_stats_time; // RW; Range:[1, 1440]; the long-term rate statistic time, - // the unit is long_term_stat_time_unit - hi_u32 long_term_max_bit_rate; // RW; Range:[2, 614400];the long-term target max bitrate, - // can not be larger than max_bit_rate,the unit is kbps - hi_u32 long_term_min_bit_rate; // RW; Range:[0, 614400];the long-term target min bitrate, - // can not be larger than long_term_max_bitrate,the unit is kbps -} hi_venc_h264_cvbr; - -// the attribute of h264e avbr -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of ISLICE. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 max_bit_rate; // RW; Range:[2, 614400];the max bitrate -} hi_venc_h264_avbr; - -// the attribute of h264e qpmap -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of ISLICE. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate -} hi_venc_h264_qpmap; - -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536];the interval of ISLICE. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 target_bit_rate; // RW; Range:[2, 614400]; the target bitrate -} hi_venc_h264_qvbr; - -// qpmap mode -typedef enum { - HI_VENC_RC_QPMAP_MODE_MEAN_QP = 0, - HI_VENC_RC_QPMAP_MODE_MIN_QP, - HI_VENC_RC_QPMAP_MODE_MAX_QP, - - HI_VENC_RC_QPMAP_MODE_BUTT, -} hi_venc_rc_qpmap_mode; - -// the attribute of h265e qpmap -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of ISLICE. - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_venc_rc_qpmap_mode qpmap_mode; // RW; the QpMap Mode. -} hi_venc_h265_qpmap; - -// the attribute of mjpege fixqp -typedef struct { - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 qfactor; // RW; Range:[1,99];image quality. -} hi_venc_mjpeg_fixqp; - -// the attribute of mjpege cbr -typedef struct { - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 bit_rate; // RW; Range:[2, 614400]; average bitrate -} hi_venc_mjpeg_cbr; - -// the attribute of mjpege vbr -typedef struct { - hi_u32 stats_time; // RW; Range:[1, 60]; the rate statistic time, the unit is senconds(s) - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 max_bit_rate; // RW; Range:[2, 614400];the max bitrate -} hi_venc_mjpeg_vbr; - -// the attribute of h264e fixqp -typedef struct { - hi_u32 gop; // RW; Range:[1, 65536]; the interval of ISLICE. - hi_u32 src_frame_rate; // RW; Range:[1, 240]; the input frame rate of the venc chnnel - hi_u32 dst_frame_rate; // RW; Range:[1, 240]; the target frame rate of the venc chnnel, - // can not be larger than src_frame_rate - hi_u32 i_qp; // RW; Range:[0, 51]; qp of the i frame - hi_u32 p_qp; // RW; Range:[0, 51]; qp of the p frame - hi_u32 b_qp; // RW; Range:[0, 51]; qp of the b frame -} hi_venc_h264_fixqp; - -typedef hi_venc_h264_cbr hi_venc_h265_cbr; -typedef hi_venc_h264_vbr hi_venc_h265_vbr; -typedef hi_venc_h264_avbr hi_venc_h265_avbr; -typedef hi_venc_h264_fixqp hi_venc_h265_fixqp; -typedef hi_venc_h264_qvbr hi_venc_h265_qvbr; -typedef hi_venc_h264_cvbr hi_venc_h265_cvbr; - -// the attribute of rc -typedef struct { - hi_venc_rc_mode rc_mode; // RW; the type of rc - union { - hi_venc_h264_cbr h264_cbr; - hi_venc_h264_vbr h264_vbr; - hi_venc_h264_avbr h264_avbr; - hi_venc_h264_qvbr h264_qvbr; - hi_venc_h264_cvbr h264_cvbr; - hi_venc_h264_fixqp h264_fixqp; - hi_venc_h264_qpmap h264_qpmap; - - hi_venc_mjpeg_cbr mjpeg_cbr; - hi_venc_mjpeg_vbr mjpeg_vbr; - hi_venc_mjpeg_fixqp mjpeg_fixqp; - - hi_venc_h265_cbr h265_cbr; - hi_venc_h265_vbr h265_vbr; - hi_venc_h265_avbr h265_avbr; - hi_venc_h265_qvbr h265_qvbr; - hi_venc_h265_cvbr h265_cvbr; - hi_venc_h265_fixqp h265_fixqp; - hi_venc_h265_qpmap h265_qpmap; - }; -} hi_venc_rc_attr; - -// the gop mode -typedef enum { - HI_VENC_GOP_MODE_NORMAL_P = 0, // NORMALP - HI_VENC_GOP_MODE_DUAL_P = 1, // DUALP - HI_VENC_GOP_MODE_SMART_P = 2, // SMARTP - HI_VENC_GOP_MODE_ADV_SMART_P = 3, // ADVSMARTP - HI_VENC_GOP_MODE_BIPRED_B = 4, // BIPREDB - HI_VENC_GOP_MODE_LOW_DELAY_B = 5, // LOWDELAYB - - HI_VENC_GOP_MODE_BUTT, -} hi_venc_gop_mode; - -// the attribute of the normalp -typedef struct { - hi_s32 ip_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and I frame -} hi_venc_gop_normal_p; - -// the attribute of the dualp -typedef struct { - hi_u32 sp_interval; // RW; Range:[0, 65536]; Interval of the special P frames, - // 1 is not supported and should be less than Gop - hi_s32 sp_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and special P frame - hi_s32 ip_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and I frame -} hi_venc_gop_dual_p; - -// the attribute of the smartp -typedef struct { - hi_u32 bg_interval; // RW; Interval of the long-term reference frame, can not be less than gop - hi_s32 bg_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and Bg frame - hi_s32 vi_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and virtual I frame -} hi_venc_gop_smart_p; - -// the attribute of the advsmartp -typedef struct { - hi_u32 bg_interval; // RW; Interval of the long-term reference frame, can not be less than gop - hi_s32 bg_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and Bg frame - hi_s32 vi_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and virtual I frame -} hi_venc_gop_adv_smart_p; - -// the attribute of the bipredb -typedef struct { - hi_u32 b_frame_num; // RW; Range:[1, 3]; Number of B frames - hi_s32 b_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and B frame - hi_s32 ip_qp_delta; // RW; Range:[-10, 30]; QP variance between P frame and I frame -} hi_venc_gop_bipred_b; - -// the attribute of the gop -typedef struct { - hi_venc_gop_mode gop_mode; // RW; Encoding GOP type - union { - hi_venc_gop_normal_p normal_p; // attributes of normal P - hi_venc_gop_dual_p dual_p; // attributes of dual P - hi_venc_gop_smart_p smart_p; // attributes of Smart P - hi_venc_gop_adv_smart_p adv_smart_p; // attributes of AdvSmart P - hi_venc_gop_bipred_b bipred_b; // attributes of b - }; - -} hi_venc_gop_attr; - -// the attribute of the venc chnl -typedef struct { - hi_venc_attr venc_attr; // the attribute of video encoder - hi_venc_rc_attr rc_attr; // the attribute of rate ctrl - hi_venc_gop_attr gop_attr; // the attribute of gop -} hi_venc_chn_attr; - -// the param of receive picture -typedef struct { - hi_s32 recv_pic_num; // RW; Range:[-1, 2147483647]; Number of frames received and - // encoded by the encoding channel,0 is not supported -} hi_venc_start_param; - -// venc mode type -typedef enum { - HI_VENC_MOD_VENC = 1, - HI_VENC_MOD_H264, - HI_VENC_MOD_H265, - HI_VENC_MOD_JPEG, - HI_VENC_MOD_RC, - HI_VENC_MOD_BUTT -} hi_venc_mod_type; - -// the param of the h264e mod -typedef struct { - hi_u32 one_stream_buf; // RW; Range:[0, 1]; one stream buffer - hi_u32 mini_buf_mode; // RW; Range:[0, 1]; H264e MiniBufMode - hi_u32 low_power_mode; // RW; Range:[0, 1]; H264e PowerSaveEn - hi_vb_src vb_src; // RW; H264e VBSource - hi_bool qp_hist_en; // RW; Range:[0, 1] - hi_u32 max_user_data_len; // RW; Range:[0, 65536]; one user data buffer len -} hi_venc_h264_mod_param; - -// the param of the h265e mod -typedef struct { - hi_u32 one_stream_buf; // RW; Range:[0, 1]; one stream buffer - hi_u32 mini_buf_mode; // RW; Range:[0, 1]; H265e MiniBufMode - hi_u32 low_power_mode; // RW; Range:[0, 2]; H265e PowerSaveEn - hi_vb_src vb_src; // RW; H265e VBSource - hi_bool qp_hist_en; // RW; Range:[0, 1] - hi_u32 max_user_data_len; // RW; Range:[0, 65536]; one user data buffer len -} hi_venc_h265_mod_param; - -// the param of the jpege mod -typedef struct { - hi_u32 one_stream_buf; // RW; Range:[0, 1]; one stream buffer - hi_u32 mini_buf_mode; // RW; Range:[0, 1]; Jpege MiniBufMode - hi_u32 clear_stream_buf; // RW; Range:[0, 1]; JpegClearStreamBuf - hi_u32 dering_mode; // RW; Range:[0, 1]; Jpege Dering Mode -} hi_venc_jpeg_mod_param; - -// the param of the venc mod -typedef struct { - hi_u32 buf_cache; // RW; Range:[0, 1]; VencBufferCache - hi_u32 frame_buf_recycle; // RW; Range:[0, 1]; FrameBufRecycle -} hi_venc_venc_mod_param; - -// the param of the mod -typedef struct { - hi_venc_mod_type mod_type; // RW; VencModType - union { - hi_venc_venc_mod_param venc_mod_param; - hi_venc_h264_mod_param h264_mod_param; - hi_venc_h265_mod_param h265_mod_param; - hi_venc_jpeg_mod_param jpeg_mod_param; - }; -} hi_venc_mod_param; - -// the param of the jpege -typedef struct { - hi_u32 qfactor; // RW; Range:{0xFFFFFFFF, [1, 100]}; Qfactor value - hi_u8 y_qt[HI_VENC_JPEG_QT_COEF_NUM]; // Reserved - hi_u8 cb_qt[HI_VENC_JPEG_QT_COEF_NUM]; // Reserved - hi_u8 cr_qt[HI_VENC_JPEG_QT_COEF_NUM]; // Reserved - hi_u32 mcu_per_ecs; // Reserved - hi_bool ecs_output_en; -} hi_venc_jpeg_param; - -typedef struct { - hi_u8 dc_bits[16]; - hi_u8 dc_value[12]; -} hi_venc_huffman_dc_table; - -typedef struct { - hi_u8 ac_bits[16]; - hi_u8 ac_value[162]; -} hi_venc_huffman_ac_table; - -// the huffman param of the jpege -typedef struct { - hi_venc_huffman_dc_table dc_tables[3]; // y, Cb, Cr - hi_venc_huffman_ac_table ac_tables[3]; // y, Cb, Cr - hi_u32 reserved[2]; -} hi_venc_jpeg_huffman_param; - -// the param of the crop -typedef struct { - hi_bool enable; // RW; Range:[0, 1]; Crop region enable - hi_rect rect; // RW; Crop region, note: s32X must be multi of 16 -} hi_crop_info; - -// the param of the venc frame rate -typedef struct { - hi_s32 src_frame_rate; // RW; Range:[0, 240]; Input frame rate of a channel - hi_s32 dst_frame_rate; // RW; Range:[0, 240]; Output frame rate of a channel -} hi_frame_rate_ctrl; - -// the param of the venc encode chnl -typedef struct { - hi_bool color_to_grey_en; // RW; Range:[0, 1]; Whether to enable Color2Grey - hi_u32 priority; // RW; Range:[0, 1]; The priority of the coding chnl - hi_u32 max_stream_cnt; // RW: Range:[0, 4294967295]; Maximum number of frames in a stream buffer - hi_u32 poll_wake_up_frame_cnt; // RW: Range:(0, 4294967295]; the frame num needed to wake up obtaining streams - hi_crop_info crop_info; - hi_frame_rate_ctrl frame_rate; -} hi_venc_chn_param; - -// the scene mode of the venc encode chnl -typedef enum { - HI_VENC_SCENE_0 = 0, // RW; A scene in which the camera does not move or periodically moves continuously - HI_VENC_SCENE_1 = 1, // RW; Motion scene at high bit rate - HI_VENC_SCENE_2 = 2, // RW; It has regular continuous motion at medium bit rate and - // the encoding pressure is relatively large - HI_VENC_SCENE_BUTT -} hi_venc_scene_mode; - -// The param of H264e cbr -typedef struct { - hi_u32 max_i_proportion; // RW; Range:[1, 100]; the max ratio of i frame and p frame */ - // can not be smaller than min_i_proportion */ - hi_u32 min_i_proportion; // RW; Range:[1, 100]; the min ratio of i frame and p frame, - hi_u32 max_qp; // RW; Range:[0, 51];the max QP value */ - hi_u32 min_qp; // RW; Range:[0, 51]; the min QP value,can not be larger than max_qp */ - hi_u32 max_i_qp; // RW; Range:[0, 51]; max qp for i frame */ - hi_u32 min_i_qp; // RW; Range:[0, 51]; min qp for i frame,can not be larger than max_i_qp */ - hi_s32 max_reencode_times; // RW; Range:[0, 3]; Range:max number of re-encode times */ - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap */ -} hi_venc_h264_cbr_param; - -// The param of H264e vbr -typedef struct { - hi_s32 chg_pos; // RW; Range:[50, 100]; Indicates the ratio of the current bit rate to - // the maximum bit rate when the QP value starts to be adjusted - hi_u32 max_i_proportion; // RW; Range:[1, 100] ; the max ratio of i frame and p frame - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; Range:[1, 100] ; the min ratio of i frame and p frame, - hi_s32 max_reencode_times; // RW; Range:[0, 3]; max number of re-encode times - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp ,can not be larger than max_i_qp -} hi_venc_h264_vbr_param; - -// The param of H264e avbr -typedef struct { - hi_s32 chg_pos; // RW; Range:[50, 100]; Indicates the ratio of the current bit rate to - // the maximum bit rate when the QP value starts to be adjusted - hi_u32 max_i_proportion; // RW; Range:[1, 100] ; the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; Range:[1, 100] ; the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; Range:[0, 3]; max number of re-encode times - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - - hi_s32 min_still_percent; // RW; Range:[5, 100]; the min percent of target bitrate for still scene - hi_u32 max_still_qp; // RW; Range:[0, 51]; the max QP value of I frame for still scene,can not be - // smaller than min_i_qp and can not be larger than max_i_qp - hi_u32 min_still_psnr; // RW; reserved,Invalid member currently - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp,can not be larger than max_i_qp - hi_u32 min_qp_delta; // RW; Range:[0, 4];Difference between FrameLevelMinQp and min_qp, - // FrameLevelMinQp = MinQp(or MinIQp) + MinQpDelta - hi_u32 motion_sensitivity; // RW; Range:[0, 100]; Motion Sensitivity - hi_bool save_bitrate_en; -} hi_venc_h264_avbr_param; - -// The param of H264e qvbr -typedef struct { - hi_u32 max_i_proportion; // RW; Range:[1, 100]; the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; Range:[1, 100] ;the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; Range:[0, 3];max number of re-encode times [0, 3] - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp,can not be larger than max_i_qp - - hi_s32 max_bit_percent; // RW; Range:[30, 180]; Indicate the ratio of bitrate upper limit - hi_s32 min_bit_percent; // RW; Range:[30, 180]; Indicate the ratio of bitrate lower limit, - // can not be larger than bit_percent_ul - hi_s32 max_psnr_fluctuate; // RW; Range:[18, 40]; Reduce the target bitrate - // when the value of psnr approch the upper limit - hi_s32 min_psnr_fluctuate; // RW; Range:[18, 40]; Increase the target bitrate when the value of psnr - // approch the lower limit, can not be larger than psnr_fluctuate_ul -} hi_venc_h264_qvbr_param; - -// The param of H264e cvbr -typedef struct { - hi_u32 max_i_proportion; // RW; Range:[1, 100] ; the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; Range:[1, 100] ; the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; Range:[0, 3]; max number of re-encode times - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp,can not be larger than max_i_qp - - hi_u32 min_qp_delta; // RW; Range:[0, 4];Difference between FrameLevelMinQp and min_qp, - // FrameLevelMinQp = MinQp(or MinIQp) + MinQpDelta - hi_u32 max_qp_delta; // RW; Range:[0, 4];Difference between FrameLevelMaxQp and max_qp, - // FrameLevelMaxQp = MaxQp(or MaxIQp) - MaxQpDelta - - hi_u32 extra_bit_percent; // RW; Range:[0, 1000];the extra bits that can be allocated - // when the actual bitrate goes above the target bitrate - hi_u32 long_term_stats_time_unit; // RW; Range:[1, 1800]; the time unit of long_term_stat_time, - // the unit is senconds(s) - hi_bool save_bitrate_en; -} hi_venc_h264_cvbr_param; - -typedef struct { - hi_u32 max_qfactor; - hi_u32 min_qfactor; -} hi_venc_mjpeg_cbr_param; - -typedef struct { - hi_s32 chg_pos; - hi_u32 max_qfactor; - hi_u32 min_qfactor; -} hi_venc_mjpeg_vbr_param; -// The param of h265e cbr -typedef struct { - hi_u32 max_i_proportion; // RW; Range:[1, 100]; the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; Range:[1, 100];the min ratio of i frame and p frame - hi_u32 max_qp; // RW; Range:[0, 51];the max QP value - hi_u32 min_qp; // RW; Range:[0, 51];the min QP value ,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51];max qp for i frame - hi_u32 min_i_qp; // RW; Range:[0, 51];min qp for i frame,can not be larger than max_i_qp - hi_s32 max_reencode_times; // RW; Range:[0, 3]; Range:max number of re-encode times - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - hi_venc_rc_qpmap_mode qpmap_mode; // RW; Qpmap Mode -} hi_venc_h265_cbr_param; - -// The param of h265e vbr -typedef struct { - hi_s32 chg_pos; // RW; Range:[50, 100];Indicates the ratio of the current bit rate - // to the maximum bit rate when the QP value starts to be adjusted - hi_u32 max_i_proportion; // RW; [1, 100]the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; [1, 100]the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; Range:[0, 3]; Range:max number of re-encode times - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp ,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp,can not be larger than max_i_qp - - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - hi_venc_rc_qpmap_mode qpmap_mode; // RW; Qpmap Mode -} hi_venc_h265_vbr_param; - -// The param of h265e avbr -typedef struct { - hi_s32 chg_pos; // RW; Range:[50, 100];Indicates the ratio of the current bit rate to - // the maximum bit rate when the QP value starts to be adjusted - hi_u32 max_i_proportion; // RW; [1, 100]the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; [1, 100]the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; Range:[0, 3]; Range:max number of re-encode times - - hi_s32 min_still_percent; // RW; Range:[5, 100]; the min percent of target bitrate for still scene - hi_u32 max_still_qp; // RW; Range:[0, 51]; the max QP value of I frame for still scene,can not be - // smaller than u32MinIQp and can not be larger than max_iprop - hi_u32 min_still_psnr; // RW; reserved - - hi_u32 max_qp; // RW; Range:[0, 51];the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51];the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51];the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51];the min I qp,can not be larger than max_i_qp - - hi_u32 min_qp_delta; // RW; Range:[0, 4];Difference between FrameLevelMinQp and min_qp, - // FrameLevelMinQp = MinQp(or MinIQp) + MinQpDelta - hi_u32 motion_sensitivity; // RW; Range:[0, 100]; Motion Sensitivity - - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - hi_venc_rc_qpmap_mode qpmap_mode; // RW; Qpmap Mode -} hi_venc_h265_avbr_param; - -// The param of h265e qvbr -typedef struct { - hi_u32 max_i_proportion; // RW; [1, 100];the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; [1, 100];the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; [0, 3]; max number of re-encode times [0, 3] - - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - hi_venc_rc_qpmap_mode qpmap_mode; // RW; Qpmap Mode - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp,can not be larger than max_i_qp - - hi_s32 max_bit_percent; // RW; Range:[30, 180]; Indicate the ratio of bitrate upper limit - hi_s32 min_bit_percent; // RW; Range:[30, 180]; Indicate the ratio of bitrate lower limit, - // can not be larger than bit_percent_ul - hi_s32 max_psnr_fluctuate; // RW; Range:[18, 40]; Reduce the target bitrate - // when the value of psnr approch the upper limit - hi_s32 min_psnr_fluctuate; // RW; Range:[18, 40]; Increase the target bitrate when the value of psnr - // approch the lower limit,can not be larger than psnr_fluctuate_ul -} hi_venc_h265_qvbr_param; - -// The param of h265e cvbr -typedef struct { - hi_u32 max_i_proportion; // RW; Range:[1, 100] ; the max ratio of i frame and p frame, - // can not be smaller than min_i_proportion - hi_u32 min_i_proportion; // RW; Range:[1, 100] ; the min ratio of i frame and p frame - hi_s32 max_reencode_times; // RW; Range:[0, 3]; max number of re-encode times - hi_bool qpmap_en; // RW; Range:[0, 1]; enable qpmap - hi_venc_rc_qpmap_mode qpmap_mode; // RW; Qpmap Mode - - hi_u32 max_qp; // RW; Range:[0, 51]; the max P B qp - hi_u32 min_qp; // RW; Range:[0, 51]; the min P B qp,can not be larger than max_qp - hi_u32 max_i_qp; // RW; Range:[0, 51]; the max I qp - hi_u32 min_i_qp; // RW; Range:[0, 51]; the min I qp,can not be larger than max_i_qp - - hi_u32 min_qp_delta; // RW; Range:[0, 4];Difference between FrameLevelMinQp and min_qp, - // FrameLevelMinQp = MinQp(or MinIQp) + MinQpDelta - hi_u32 max_qp_delta; // RW; Range:[0, 4];Difference between FrameLevelMaxQp and max_qp, - // FrameLevelMaxQp = MaxQp(or MaxIQp) - MaxQpDelta - - hi_u32 extra_bit_percent; // RW; Range:[0, 1000];the extra ratio of bitrate that can be allocated - // when the actual bitrate goes above the long-term target bitrate - hi_u32 long_term_stats_time_unit; // RW; Range:[1, 1800]; the time unit of LongTermStatTime, - // the unit is senconds(s) -} hi_venc_h265_cvbr_param; - -// The param of scene change detect -typedef struct { - hi_bool detect_scene_chg_en; // RW; Range:[0, 1]; enable detect scene change. - hi_bool adapt_insert_idr_frame_en; // RW; Range:[0, 1]; enable a daptive insertIDR frame. -} hi_venc_scene_chg_detect; - -// The param of rc -typedef struct { - hi_u32 threshold_i[HI_VENC_TEXTURE_THRESHOLD_SIZE]; // RW; Range:[0, 255]; Mad threshold for controlling - // the macroblock-level bit rate of I frames - hi_u32 threshold_p[HI_VENC_TEXTURE_THRESHOLD_SIZE]; // RW; Range:[0, 255]; Mad threshold for controlling - // the macroblock-level bit rate of P frames - hi_u32 threshold_b[HI_VENC_TEXTURE_THRESHOLD_SIZE]; // RW; Range:[0, 255]; Mad threshold for controlling - // the macroblock-level bit rate of B frames - hi_u32 direction; // RW; Range:[0, 16]; The direction for controlling - // the macroblock-level bit rate - hi_u32 row_qp_delta; // RW; Range:[0, 10];the start QP value of each macroblock row - // relative to the start QP value - hi_s32 first_frame_start_qp; // RW; Range:[-1, 51];Start QP value of the first frame - hi_venc_scene_chg_detect scene_chg_detect; - union { - hi_venc_h264_cbr_param h264_cbr_param; - hi_venc_h264_vbr_param h264_vbr_param; - hi_venc_h264_avbr_param h264_avbr_param; - hi_venc_h264_qvbr_param h264_qvbr_param; - hi_venc_h264_cvbr_param h264_cvbr_param; - hi_venc_h265_cbr_param h265_cbr_param; - hi_venc_h265_vbr_param h265_vbr_param; - hi_venc_h265_avbr_param h265_avbr_param; - hi_venc_h265_qvbr_param h265_qvbr_param; - hi_venc_h265_cvbr_param h265_cvbr_param; - hi_venc_mjpeg_cbr_param mjpeg_cbr_param; - hi_venc_mjpeg_vbr_param mjpeg_vbr_param; - }; -} hi_venc_rc_param; - -/* - * @brief create video encoder channel - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] attr: pointer of video encoder channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_create_chn(hi_venc_chn chn, const hi_venc_chn_attr *attr); - -/* - * @brief destroy video encoder channel - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_destroy_chn(hi_venc_chn chn); - -/* - * @brief video encoder channel start receive frame - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] recv_param: pointer of receive picture parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_start_chn(hi_venc_chn chn, const hi_venc_start_param *recv_param); - -/* - * @brief video encoder channel stop receive frame - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_stop_chn(hi_venc_chn chn); - -/* - * @brief query video encoder channel status - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [out] status: pointer of video encoder channel status struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_query_status(hi_venc_chn chn, hi_venc_chn_status *status); - -/* - * @brief get stream from video encoder channel - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @param [out] stream: pointer of stream info struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_get_stream(hi_venc_chn chn, hi_venc_stream *stream, hi_s32 milli_sec); - -/* - * @brief release frame from video encoder channel - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] stream: pointer of stream info struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_release_stream(hi_venc_chn chn, hi_venc_stream *stream); - -/* - * @brief send frame to video encoder channel - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] frame: pointer of frame struct - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_send_frame(hi_venc_chn chn, const hi_video_frame_info *frame, hi_s32 milli_sec); - -/* - * @brief send jpege frame to video encoder channel when the output address of stream is assigned - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] frame: pointer of frame struct - * @param [in] jpege_stream: pointer of img stream to assign the output address of stream - * @param [in] milli_sec: -1 is block,0 is no block,other positive number is timeout - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_send_jpege_frame(hi_venc_chn chn, const hi_video_frame_info *frame, - const hi_img_stream* jpege_stream, hi_s32 milli_sec); - -/* - * @brief send jpege frame to video encoder channel when the output address of stream is assigned - * @param [in] frame: pointer of frame struct - * @param [in] jpeg_param: pointer of jpeg encoder quality parameter struct - * @param [out] size: the predicted size of output buffer of img stream - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_get_jpege_predicted_size(const hi_video_frame_info* frame, const hi_venc_jpeg_param* jpeg_param, - hi_u32 *size); - -/* - * @brief get video encoder channel's device file handle - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @return success: return positive number - * fail: return negative number - */ -hi_s32 hi_mpi_venc_get_fd(hi_venc_chn chn); - -/* - * @brief close video encoder channel's device file handle - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_close_fd(hi_venc_chn chn); - -/* - * @brief set channel's parameters - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] chn_param: pointer of video encoder channel patameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_set_chn_param(hi_venc_chn chn, const hi_venc_chn_param *chn_param); - -/* - * @brief set video encoder module parameter - * @param [in] mod_param: pointer of video encoder module parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_set_mod_param(const hi_venc_mod_param *mod_param); - -/* - * @brief get video encoder module parameter - * @param [out] mod_param: pointer of video encoder module parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_get_mod_param(hi_venc_mod_param *mod_param); - -/* - * @brief set jpeg image quality - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] jpeg_param: pointer of jpeg encoder quality parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_set_jpeg_param(hi_venc_chn chn, const hi_venc_jpeg_param *jpeg_param); - -/* - * @brief get jpeg image quality - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [out] jpeg_param: pointer of jpeg encoder quality parameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_get_jpeg_param(hi_venc_chn chn, hi_venc_jpeg_param *jpeg_param); - -/* - * @brief set jpege huffman parameters - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] jpeg_huffman_param: pointer of jpeg encoder huffman table - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_set_jpeg_huffman_param(hi_venc_chn chn, const hi_venc_jpeg_huffman_param *jpeg_huffman_param); - -/* - * @brief get jpege huffman parameter - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [out] jpeg_huffman_data: pointer of jpeg encoder huffman table - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_get_jpeg_huffman_param(hi_venc_chn chn, hi_venc_jpeg_huffman_param *jpeg_huffman_data); - -/* - * @brief compact huffman and qt tables - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] table_type: compact table type only support 0 - * @param [in] enable: enable compact or not [HI_FALSE, HI_TRUE] - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_compact_jpeg_tables(hi_venc_chn chn, hi_u32 table_type, hi_bool enable); - -/* - * @brief request video encoder channel to encode IDR frame - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] instant: whether to encode IDR frame immediately - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_request_idr(hi_venc_chn chn, hi_bool instant); - -/* - * @brief set encoding scene mode - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] scene_mode: scene mode - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_set_scene_mode(hi_venc_chn chn, const hi_venc_scene_mode scene_mode); - -/* - * @brief set rc parameter - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] rc_param: pointer of video encoder channel patameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_set_rc_param(hi_venc_chn chn, const hi_venc_rc_param *rc_param); - -/* - * @brief get rc parameter - * @param [in] chn: video encoder channel id [0, VENC_MAX_CHN_NUM) - * @param [in] rc_param: pointer of video encoder channel patameter struct - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_venc_get_rc_param(hi_venc_chn chn, hi_venc_rc_param *rc_param); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif - -#endif // #ifndef HI_VENC_H_ diff --git a/third_party/acl/inc/acl/dvpp/hi_dvpp_vpc.h b/third_party/acl/inc/acl/dvpp/hi_dvpp_vpc.h deleted file mode 100644 index 71e1442524..0000000000 --- a/third_party/acl/inc/acl/dvpp/hi_dvpp_vpc.h +++ /dev/null @@ -1,814 +0,0 @@ -/* - * Copyright (c) Huawei Technologies Co., Ltd. 2020-2022. All rights reserved. - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2 and - * only version 2 as published by the Free Software Foundation. - * - * This program 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 General Public License for more details. - * - * Description: - * Author: huawei - * Create: 2020-4-1 - */ - -#ifndef HI_VPC_H_ -#define HI_VPC_H_ - -#include "hi_dvpp_common.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif // #ifdef __cplusplus - -#define VPC_MAX_CHN_NUM 512 - -/*********************************************************************************************/ -/* invlalid channel ID */ -#define HI_ERR_VPC_INVALID_CHN_ID 0xA0078002 -/* at lease one parameter is illagal ,eg, an illegal enumeration value */ -#define HI_ERR_VPC_ILLEGAL_PARAM 0xA0078003 -/* channel exists */ -#define HI_ERR_VPC_EXIST 0xA0078004 -/* the channel is not existed */ -#define HI_ERR_VPC_UNEXIST 0xA0078005 -/* using a NULL point */ -#define HI_ERR_VPC_NULL_PTR 0xA0078006 -/* try to enable or initialize system,device or channel, before configuring attribute */ -#define HI_ERR_VPC_NOT_CFG 0xA0078007 -/* operation is not supported by NOW */ -#define HI_ERR_VPC_NOT_SUPPORT 0xA0078008 -/* operation is not permitted ,eg, try to change stati attribute */ -#define HI_ERR_VPC_NOT_PERM 0xA0078009 -/* failure caused by malloc memory */ -#define HI_ERR_VPC_NO_MEM 0xA007800C -/* failure caused by malloc buffer */ -#define HI_ERR_VPC_NO_BUF 0xA007800D -/* no data in buffer */ -#define HI_ERR_VPC_BUF_EMPTY 0xA007800E -/* no buffer for new data */ -#define HI_ERR_VPC_BUF_FULL 0xA007800F -/* system is not ready,had not initialized or loaded */ -#define HI_ERR_VPC_SYS_NOT_READY 0xA0078010 -/* bad address, eg. used for copy_from_user & copy_to_user */ -#define HI_ERR_VPC_BAD_ADDR 0xA0078011 -/* system busy */ -#define HI_ERR_VPC_BUSY 0xA0078012 -/* system err */ -#define HI_ERR_VPC_SYS_ERROR 0xA0078015 - -typedef hi_s32 hi_vpc_chn; - -typedef enum { - HI_BORDER_CONSTANT = 0, - HI_BORDER_REPLICATE, - HI_BORDER_REFLECT, - HI_BORDER_REFLECT_101, - HI_BORDER_WRAP -} hi_vpc_bord_type; - -typedef struct { - hi_double val[4]; -} hi_vpc_scalar; - -typedef struct { - hi_u32 top; - hi_u32 bottom; - hi_u32 left; - hi_u32 right; - hi_vpc_bord_type border_type; - hi_vpc_scalar scalar_value; -} hi_vpc_make_border_info; - -typedef struct { - hi_void* picture_address; - hi_u32 picture_buffer_size; - hi_u32 picture_width; - hi_u32 picture_height; - hi_u32 picture_width_stride; - hi_u32 picture_height_stride; - hi_pixel_format picture_format; -} hi_vpc_pic_info; - -typedef struct { - hi_u32 top_offset; - hi_u32 left_offset; - hi_u32 crop_width; - hi_u32 crop_height; -} hi_vpc_crop_region; - -typedef struct { - hi_vpc_pic_info dest_pic_info; - hi_vpc_crop_region crop_region; -} hi_vpc_crop_region_info; - -typedef struct { - hi_u32 resize_width; - hi_u32 resize_height; - hi_u32 interpolation; -} hi_vpc_resize_info; - -typedef struct { - hi_vpc_pic_info dest_pic_info; - hi_vpc_crop_region crop_region; - hi_vpc_resize_info resize_info; -} hi_vpc_crop_resize_region; - -typedef struct { - hi_vpc_pic_info dest_pic_info; - hi_vpc_crop_region crop_region; - hi_vpc_resize_info resize_info; - hi_u32 dest_top_offset; - hi_u32 dest_left_offset; -} hi_vpc_crop_resize_paste_region; - -typedef struct { - hi_vpc_pic_info dest_pic_info; - hi_vpc_crop_region crop_region; - hi_vpc_resize_info resize_info; - hi_u32 dest_top_offset; - hi_u32 dest_left_offset; - hi_vpc_bord_type border_type; - hi_vpc_scalar scalar_value; -} hi_vpc_crop_resize_border_region; - -typedef struct { - hi_vpc_pic_info dest_pic_info; - hi_vpc_crop_region crop_region; - hi_vpc_resize_info resize_info1; // First bilinear core resize info - hi_vpc_resize_info resize_info2; // Second bilinear core resize info - hi_u32 dest_top_offset; - hi_u32 dest_left_offset; - hi_u32 reserved[2]; // RW; reserved init 0 -} hi_vpc_crop_resize_resize_paste_region; - -typedef struct { - hi_s32 attr; // RW; reserved - hi_u32 pic_width; // RW; max pic width - hi_u32 pic_height; // RW; max pic height -} hi_vpc_chn_attr; - -typedef struct { - hi_u32 histogram_y_or_r[256]; // 256 level statistics of Y or R component - hi_u32 histogram_u_or_g[256]; // 256 level statistics of U or G component - hi_u32 histogram_v_or_b[256]; // 256 level statistics of V or B component -} hi_vpc_histogram_config; - -typedef struct { - hi_u8 map_value_y_or_r[256]; // remap value of Y or R component - hi_u8 map_value_u_or_g[256]; // remap value of U or G component - hi_u8 map_value_v_or_b[256]; // remap value of V or B component -} hi_vpc_lut_remap; - -typedef struct { - hi_u32 alpha; // Alpha indicates how opaque each pixel is - hi_u32 attr[4]; // RW; reserved -} hi_csc_conf; - -typedef struct { - hi_u32 kernel_size; -} hi_median_blur_config; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_median_blur_config median_blur_cfg; -} hi_median_blur_param; - -typedef struct { - hi_s32 x; - hi_s32 y; -} hi_point; - -typedef enum { - MORPH_RECT = 0, // 矩形 - MORPH_CROSS = 1, // 交叉形 暂不支持 - MORPH_ELLIPSE = 2, // 椭圆形 暂不支持 - MORPH_MAX = 100 // 暂不支持 -} hi_morph_shapes; - -typedef struct { - hi_u32 width; - hi_u32 height; -} hi_size; - -typedef struct { - hi_size kernel_size; - hi_morph_shapes morph_shapes; - hi_point anchor; // reserved, 需要设置成(-1,-1) - hi_u32 iterations; // 迭代次数 blur只支持设置成1,erode/dilate 最大支持100 - hi_vpc_bord_type border_type; - hi_vpc_scalar scalar_value; -} hi_blur_config; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_blur_config blur_cfg; -} hi_blur_param; - -typedef struct { - hi_size kernel_size; - hi_double sigma_x; - hi_double sigma_y; - hi_vpc_bord_type border_type; - hi_vpc_scalar scalar_value; - hi_u32 reserved[2]; -} hi_gaussian_blur_config; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_gaussian_blur_config gaussian_blur_cfg; -} hi_gaussian_blur_param; - -typedef struct { - hi_double filter[5][5]; // convolution kernel - hi_size kernel_size; // kernel size - hi_point anchor; // reserved, 需要设置成(-1,-1) - hi_double delta; // optional value `delta` added to the filtered pixels before storing them in dst - hi_vpc_bord_type border_type; - hi_vpc_scalar scalar_value; - hi_u32 reserved[2]; -} hi_filter_2d_config; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_filter_2d_config filter_2d_cfg; -} hi_filter_2d_param; - -typedef struct { - hi_u32 pic1_index; - hi_u32 pic2_index; - hi_float weight1; - hi_float weight2; - hi_float offset1_x; - hi_float offset1_y; - hi_float offset2_x; - hi_float offset2_y; -} hi_stiching_ipm_table; - -typedef struct { - hi_u32 src_pic_width; - hi_u32 src_pic_height; - hi_u32 dest_pic_width; - hi_u32 dest_pic_height; - hi_u32 ipm_table_len; - hi_stiching_ipm_table* ipm_table_address; -} hi_stiching_ipm_param; - -typedef enum { - OVERLAP_HISTOGRAM = 0, - GLOBAL_HISTOGRAM, -} hi_stitching_histogram_type; - -typedef enum { - GAIN_NONE = 0, - GAIN_LUT, -} hi_stitching_gain_type; - -typedef struct { - hi_stitching_histogram_type hist_type; - hi_stitching_gain_type gain_type; - hi_void *user_data; - hi_s32 (*calulate_gain_callback)( - hi_void *user_data, - hi_void *hist_config, - hi_u32 hist_count, - hi_void *gain, - hi_u32 gain_size); -} hi_stitching_gain_param; - -typedef struct { - hi_stiching_ipm_param imp_conf; - hi_stitching_gain_param gain_conf; - hi_u32 reserved[8]; -} hi_roundview_stitching_param; - -typedef struct { - hi_vpc_pic_info *dest_pic; - hi_u32 count; - hi_vpc_pic_info *source_pic[]; -} hi_roundview_stitching_pic_param; - -typedef struct { - hi_u32 pic_index; - hi_u32 overlap_pic_index; - hi_vpc_histogram_config histogram_info; -} hi_stitching_histogram_param; - -typedef enum { - HI_ROTATION_90 = 0, - HI_ROTATION_180 = 1, - HI_ROTATION_270 = 2, -} hi_rotation; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_rotation angle; -} hi_rotate_param; - -typedef enum { - HI_BLK_SIZE_4 = 0, /* block size 4*4 */ - HI_BLK_SIZE_8, /* block size 8*8 */ - HI_BLK_SIZE_16, /* block size 16*16 */ - HI_BLK_SIZE_32, /* block size 32*32 */ - HI_BLK_SIZE_64, /* block size 64*64 */ - HI_BLK_SIZE_128, /* block size 128*128 */ -} hi_blk_size; - -typedef struct { - hi_blk_size blk_size; - hi_rect rect; -} hi_mosaic; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_u32 count; - hi_mosaic *mosaic; -} hi_mosaic_param; - -typedef enum { - HI_COVER_RECT = 0, - HI_COVER_QUAD, -} hi_cover_type; - -typedef struct { - hi_bool is_solid; - hi_u32 thick; - hi_point point[4]; // 四边形 -} hi_quad_cover; - -typedef struct { - hi_cover_type type; - union { - hi_rect rect; - hi_quad_cover quad; - }; - hi_u32 color; -} hi_cover; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_u32 count; - hi_cover *cover; -} hi_cover_param; - -typedef struct { - hi_point start_point; - hi_point end_point; - hi_u32 thick; - hi_u32 color; -} hi_line; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_u32 count; - hi_line *line; -} hi_line_param; - -typedef enum { - HI_OSD_INVERTED_COLOR_NONE = 0, /* Not invert. */ - HI_OSD_INVERTED_COLOR_RGB, /* Invert rgb. */ - HI_OSD_INVERTED_COLOR_ALPHA, /* Invert alpha. */ - HI_OSD_INVERTED_COLOR_ALL, /* Invert rgb and alpha. */ -} hi_osd_inverted_color; - -typedef struct { - hi_rect rect; - hi_pixel_format pixel_format; - hi_void* picture_address; - hi_u32 stride; - hi_u32 bg_alpha; - hi_u32 fg_alpha; - hi_osd_inverted_color osd_inverted_color; -} hi_osd; - -typedef struct { - hi_vpc_pic_info src; - hi_vpc_pic_info dst; - hi_u32 count; - hi_osd *osd; - hi_u32 clut[16]; -} hi_osd_param; - -/* - * @brief median filter - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] median_blur_param: pointer of median blur param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_median_blur(hi_vpc_chn chn, const hi_median_blur_param* median_blur_param, hi_u32* task_id, - hi_s32 milli_sec); - -/* - * @brief erode filter - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] erode_param: pointer of erode blur param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_erode(hi_vpc_chn chn, const hi_blur_param* erode_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief dilate filter - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] dilate_param: pointer of dilate blur param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_dilate(hi_vpc_chn chn, const hi_blur_param* dilate_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief blur filter - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] blur_param: pointer of blur param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_blur(hi_vpc_chn chn, const hi_blur_param* blur_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief gaussian filter - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] gaussian_blur_param: pointer of gaussian blur param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_gaussian_blur(hi_vpc_chn chn, const hi_gaussian_blur_param* gaussian_blur_param, hi_u32* task_id, - hi_s32 milli_sec); - -/* - * @brief median filter - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] filter_2d_param: pointer of filter 2D param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_filter2d(hi_vpc_chn chn, const hi_filter_2d_param* filter_2d_param, hi_u32* task_id, - hi_s32 milli_sec); - -/* - * @brief imgae rotate - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] rotate_param: pointer of rotate param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_rotate(hi_vpc_chn chn, const hi_rotate_param* rotate_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief draw mosaic - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] mosaic_param: pointer of mosaic param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_draw_mosaic(hi_vpc_chn chn, const hi_mosaic_param* mosaic_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief draw cover - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] cover_param: pointer of cover param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_draw_cover(hi_vpc_chn chn, const hi_cover_param* cover_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief draw line - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] line_param: pointer of line param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_draw_line(hi_vpc_chn chn, const hi_line_param* line_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief draw osd - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] osd_param: pointer of osd param - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_draw_osd(hi_vpc_chn chn, hi_osd_param* osd_param, hi_u32* task_id, hi_s32 milli_sec); - -/* - * @brief create vpc channel - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] attr: pointer of vpc channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_create_chn(hi_vpc_chn chn, const hi_vpc_chn_attr *attr); - -/* - * @brief create system vpc channel for single channel multi-core acceleration - * @param [out] chnl: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] attr: pointer of vpc channel attribute - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_sys_create_chn(hi_vpc_chn *chnl, const hi_vpc_chn_attr *attr); - -/* - * @brief destroy vpc channel - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_destroy_chn(hi_vpc_chn chn); - -/* - * @brief crop - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] crop_info: array of vpc crop region info - * @param [in] count: array length of crop_info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_crop(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_crop_region_info crop_info[], - hi_u32 count, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief resize - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic: pointer of vpc dest picture info - * @param [in] fx: width resize info - * @param [in] fy: height resize info - * @param [in] interpolation: resize mode, support bilinear/nearest neighbor - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_resize(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_pic_info *dest_pic, - hi_double fx, hi_double fy, hi_u32 interpolation, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief crop and resize - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] crop_resize_info: array of vpc crop_resize region info - * @param [in] count: array length of crop_resize_info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_crop_resize(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, - hi_vpc_crop_resize_region crop_resize_info[], hi_u32 count, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief crop and resize and paste - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] crop_resize_paste_info: array of vpc crop_resize_paste region info - * @param [in] count: array length of crop_resize_paste_info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_crop_resize_paste(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, - hi_vpc_crop_resize_paste_region crop_resize_paste_info[], hi_u32 count, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief crop and resize and paste interface for batch pictures batch regions - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: array of pointer of vpc source picture info - * @param [in] crop_resize_paste_info: array of vpc crop_resize_paste region info - * @param [in] count: the num of regions correspond to source_pic - * @param [in] pic_num: number os pictures - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_batch_crop_resize_paste(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic[], hi_u32 pic_num, - hi_vpc_crop_resize_paste_region crop_resize_paste_info[], hi_u32 count[], hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief crop and resize and make border - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] crop_resize_make_border_info: array of vpc crop_resize_make_border region info - * @param [in] count: array length of crop_resize_make_border - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_crop_resize_make_border(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, - hi_vpc_crop_resize_border_region crop_resize_make_border_info[], hi_u32 count, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief crop and resize and make border for batch pictures and batch regions - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: arrary of pointer of vpc source picture info - * @param [in] crop_resize_make_border_info: array of vpc crop_resize_make_border region info - * @param [in] count: the num of regions correspond to source_pic - * @param [in] pic_num: number os pictures - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_batch_crop_resize_make_border(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic[], hi_u32 pic_num, - hi_vpc_crop_resize_border_region crop_resize_make_border_info[], hi_u32 count[], hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief convert color - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic: pointer of vpc dest picture info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_convert_color(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_pic_info *dest_pic, - hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief crop and resize and resize and paste - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] crop_resize_resize_paste_info: array of vpc crop_resize_resize_paste region info - * @param [in] count: array length of crop_resize_resize_paste_info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: task id of crop_resize_resize_paste interface - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_crop_resize_resize_paste(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, - hi_vpc_crop_resize_resize_paste_region crop_resize_resize_paste_info[], - hi_u32 count, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief convert color to yuv420sp - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic: pointer of vpc dest picture info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_convert_color_to_yuv420(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_pic_info *dest_pic, - hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief convert color with specified alpha channel - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic: pointer of vpc dest picture info - * @param [in] conf: pointer of csc config, support user config alpha channel - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_convert_color_v2(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_pic_info *dest_pic, - hi_csc_conf *conf, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief border padding - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic: pointer of vpc dest picture info - * @param [in] make_border_info: boundary fill information - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_copy_make_border(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_pic_info *dest_pic, - hi_vpc_make_border_info make_border_info, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief multi-level pyramid down - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic[]: pointer array of vpc dest picture info - * @param [in] filterLevel: pyramid level [1, 4] - * @param [in] gaussian_filter: convolution kernel of 5x5 - * @param [in] make_border_info: boundary padding algorithm and boundary pixel value info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_pyrdown(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, - hi_vpc_pic_info dest_pic[], hi_u32 filter_level, hi_s8 gaussian_filter[][5], - hi_u16 divisor, hi_vpc_make_border_info make_border_info, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief calculate histogram - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] hist_config: histogram result - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_calc_hist(hi_vpc_chn chn, const hi_vpc_pic_info *source_pic, hi_vpc_histogram_config *hist_config, - hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief equalization image - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] source_pic: pointer of vpc source picture info - * @param [in] dest_pic: pointer of vpc dest picture info - * @param [in] lut_remap: remap value of YUV or RGB component - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @param [out] task_id: pointer of the task ID, used to distinguish tasks. - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_equalize_hist(hi_vpc_chn chn, const hi_vpc_pic_info* source_pic, hi_vpc_pic_info *dest_pic, - const hi_vpc_lut_remap *lut_remap, hi_u32 *task_id, hi_s32 milli_sec); - -/* - * @brief query whether the task has been completed, base on task_id - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] task_id: task id generated by calling image processing interface - * @param [in] milli_sec: -1 is block, 0 is no block, other positive number is timeout - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_get_process_result(hi_vpc_chn chn, hi_u32 task_id, hi_s32 milli_sec); - -/* - * @brief : set roundview stitching parameters - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] stitch_param: pointer of the HI_ROUNDVIEW_STITCH_PARA structure - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_set_roundview_stitching_param(hi_vpc_chn chn, const hi_roundview_stitching_param *stitch_param); - -/* - * @brief : get roundview stitching parameters - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [out] stitch_param: pointer of the HI_ROUNDVIEW_STITCH_PARA structure that you want to get - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_get_roundview_stitching_param(hi_vpc_chn chn, hi_roundview_stitching_param *stitch_param); - -/* - * @brief : deliver a roundview stitching task - * @param [in] chn: vpc channel id [0, VPC_MAX_CHN_NUM) - * @param [in] roundview_stitching_pic_param: pointer of structure that contains input and output pictures - * @return success: return 0 - * fail: return error number - */ -hi_s32 hi_mpi_vpc_roundview_stitching(hi_vpc_chn chn, hi_roundview_stitching_pic_param *roundview_stitching_pic_param, - hi_u32 *task_id, hi_s32 milli_sec); - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif // #ifdef __cplusplus - -#endif // #ifndef HI_VPC_H_ diff --git a/third_party/acl/inc/acl/error_codes/ge_error_codes.h b/third_party/acl/inc/acl/error_codes/ge_error_codes.h deleted file mode 100644 index 963403ea5b..0000000000 --- a/third_party/acl/inc/acl/error_codes/ge_error_codes.h +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2019-2020 Huawei Technologies Co., Ltd - * - * 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. - */ - -#ifndef INC_EXTERNAL_GE_GE_ERROR_CODES_H_ -#define INC_EXTERNAL_GE_GE_ERROR_CODES_H_ - -#if defined(_MSC_VER) -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY _declspec(dllexport) -#else -#define GE_FUNC_VISIBILITY -#endif -#else -#ifdef FUNC_VISIBILITY -#define GE_FUNC_VISIBILITY __attribute__((visibility("default"))) -#else -#define GE_FUNC_VISIBILITY -#endif -#endif - -#include - -#ifdef __cplusplus -extern "C" { -#endif -static const uint32_t ACL_ERROR_GE_PARAM_INVALID = 145000U; -static const uint32_t ACL_ERROR_GE_EXEC_NOT_INIT = 145001U; -static const uint32_t ACL_ERROR_GE_EXEC_MODEL_PATH_INVALID = 145002U; -static const uint32_t ACL_ERROR_GE_EXEC_MODEL_ID_INVALID = 145003U; -static const uint32_t ACL_ERROR_GE_EXEC_MODEL_DATA_SIZE_INVALID = 145006U; -static const uint32_t ACL_ERROR_GE_EXEC_MODEL_ADDR_INVALID = 145007U; -static const uint32_t ACL_ERROR_GE_EXEC_MODEL_QUEUE_ID_INVALID = 145008U; -static const uint32_t ACL_ERROR_GE_EXEC_LOAD_MODEL_REPEATED = 145009U; -static const uint32_t ACL_ERROR_GE_DYNAMIC_INPUT_ADDR_INVALID = 145011U; -static const uint32_t ACL_ERROR_GE_DYNAMIC_INPUT_LENGTH_INVALID = 145012U; -static const uint32_t ACL_ERROR_GE_DYNAMIC_BATCH_SIZE_INVALID = 145013U; -static const uint32_t ACL_ERROR_GE_AIPP_BATCH_EMPTY = 145014U; -static const uint32_t ACL_ERROR_GE_AIPP_NOT_EXIST = 145015U; -static const uint32_t ACL_ERROR_GE_AIPP_MODE_INVALID = 145016U; -static const uint32_t ACL_ERROR_GE_OP_TASK_TYPE_INVALID = 145017U; -static const uint32_t ACL_ERROR_GE_OP_KERNEL_TYPE_INVALID = 145018U; -static const uint32_t ACL_ERROR_GE_PLGMGR_PATH_INVALID = 145019U; -static const uint32_t ACL_ERROR_GE_FORMAT_INVALID = 145020U; -static const uint32_t ACL_ERROR_GE_SHAPE_INVALID = 145021U; -static const uint32_t ACL_ERROR_GE_DATATYPE_INVALID = 145022U; -static const uint32_t ACL_ERROR_GE_MEMORY_ALLOCATION = 245000U; -static const uint32_t ACL_ERROR_GE_MEMORY_OPERATE_FAILED = 245001U; -static const uint32_t ACL_ERROR_GE_INTERNAL_ERROR = 545000U; -static const uint32_t ACL_ERROR_GE_LOAD_MODEL = 545001U; -static const uint32_t ACL_ERROR_GE_EXEC_LOAD_MODEL_PARTITION_FAILED = 545002U; -static const uint32_t ACL_ERROR_GE_EXEC_LOAD_WEIGHT_PARTITION_FAILED = 545003U; -static const uint32_t ACL_ERROR_GE_EXEC_LOAD_TASK_PARTITION_FAILED = 545004U; -static const uint32_t ACL_ERROR_GE_EXEC_LOAD_KERNEL_PARTITION_FAILED = 545005U; -static const uint32_t ACL_ERROR_GE_EXEC_RELEASE_MODEL_DATA = 545006U; -static const uint32_t ACL_ERROR_GE_COMMAND_HANDLE = 545007U; -static const uint32_t ACL_ERROR_GE_GET_TENSOR_INFO = 545008U; -static const uint32_t ACL_ERROR_GE_UNLOAD_MODEL = 545009U; - -#ifdef __cplusplus -} // namespace ge -#endif -#endif // INC_EXTERNAL_GE_GE_ERROR_CODES_H_ diff --git a/third_party/acl/inc/acl/error_codes/rt_error_codes.h b/third_party/acl/inc/acl/error_codes/rt_error_codes.h deleted file mode 100644 index 8cb1a1964d..0000000000 --- a/third_party/acl/inc/acl/error_codes/rt_error_codes.h +++ /dev/null @@ -1,105 +0,0 @@ -/** -* @file rt_error_codes.h -* -* Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. All Rights Reserved. -* -* This program 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. -*/ - -#ifndef __INC_EXTERNEL_RT_ERROR_CODES_H__ -#define __INC_EXTERNEL_RT_ERROR_CODES_H__ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -static const int32_t ACL_RT_SUCCESS = 0; // success - -static const int32_t ACL_ERROR_RT_PARAM_INVALID = 107000; // param invalid -static const int32_t ACL_ERROR_RT_INVALID_DEVICEID = 107001; // invalid device id -static const int32_t ACL_ERROR_RT_CONTEXT_NULL = 107002; // current context null -static const int32_t ACL_ERROR_RT_STREAM_CONTEXT = 107003; // stream not in current context -static const int32_t ACL_ERROR_RT_MODEL_CONTEXT = 107004; // model not in current context -static const int32_t ACL_ERROR_RT_STREAM_MODEL = 107005; // stream not in model -static const int32_t ACL_ERROR_RT_EVENT_TIMESTAMP_INVALID = 107006; // event timestamp invalid -static const int32_t ACL_ERROR_RT_EVENT_TIMESTAMP_REVERSAL = 107007; // event timestamp reversal -static const int32_t ACL_ERROR_RT_ADDR_UNALIGNED = 107008; // memory address unaligned -static const int32_t ACL_ERROR_RT_FILE_OPEN = 107009; // open file failed -static const int32_t ACL_ERROR_RT_FILE_WRITE = 107010; // write file failed -static const int32_t ACL_ERROR_RT_STREAM_SUBSCRIBE = 107011; // error subscribe stream -static const int32_t ACL_ERROR_RT_THREAD_SUBSCRIBE = 107012; // error subscribe thread -static const int32_t ACL_ERROR_RT_GROUP_NOT_SET = 107013; // group not set -static const int32_t ACL_ERROR_RT_GROUP_NOT_CREATE = 107014; // group not create -static const int32_t ACL_ERROR_RT_STREAM_NO_CB_REG = 107015; // callback not register to stream -static const int32_t ACL_ERROR_RT_INVALID_MEMORY_TYPE = 107016; // invalid memory type -static const int32_t ACL_ERROR_RT_INVALID_HANDLE = 107017; // invalid handle -static const int32_t ACL_ERROR_RT_INVALID_MALLOC_TYPE = 107018; // invalid malloc type - -static const int32_t ACL_ERROR_RT_FEATURE_NOT_SUPPORT = 207000; // feature not support -static const int32_t ACL_ERROR_RT_MEMORY_ALLOCATION = 207001; // memory allocation error -static const int32_t ACL_ERROR_RT_MEMORY_FREE = 207002; // memory free error -static const int32_t ACL_ERROR_RT_AICORE_OVER_FLOW = 207003; // aicore over flow -static const int32_t ACL_ERROR_RT_NO_DEVICE = 207004; // no device -static const int32_t ACL_ERROR_RT_RESOURCE_ALLOC_FAIL = 207005; // resource alloc fail -static const int32_t ACL_ERROR_RT_NO_PERMISSION = 207006; // no permission -static const int32_t ACL_ERROR_RT_NO_EVENT_RESOURCE = 207007; // no event resource -static const int32_t ACL_ERROR_RT_NO_STREAM_RESOURCE = 207008; // no stream resource -static const int32_t ACL_ERROR_RT_NO_NOTIFY_RESOURCE = 207009; // no notify resource -static const int32_t ACL_ERROR_RT_NO_MODEL_RESOURCE = 207010; // no model resource -static const int32_t ACL_ERROR_RT_NO_CDQ_RESOURCE = 207011; // no cdq resource -static const int32_t ACL_ERROR_RT_OVER_LIMIT = 207012; // over limit -static const int32_t ACL_ERROR_RT_QUEUE_EMPTY = 207013; // queue is empty -static const int32_t ACL_ERROR_RT_QUEUE_FULL = 207014; // queue is full -static const int32_t ACL_ERROR_RT_REPEATED_INIT = 207015; // repeated init - -static const int32_t ACL_ERROR_RT_INTERNAL_ERROR = 507000; // runtime internal error -static const int32_t ACL_ERROR_RT_TS_ERROR = 507001; // ts internel error -static const int32_t ACL_ERROR_RT_STREAM_TASK_FULL = 507002; // task full in stream -static const int32_t ACL_ERROR_RT_STREAM_TASK_EMPTY = 507003; // task empty in stream -static const int32_t ACL_ERROR_RT_STREAM_NOT_COMPLETE = 507004; // stream not complete -static const int32_t ACL_ERROR_RT_END_OF_SEQUENCE = 507005; // end of sequence -static const int32_t ACL_ERROR_RT_EVENT_NOT_COMPLETE = 507006; // event not complete -static const int32_t ACL_ERROR_RT_CONTEXT_RELEASE_ERROR = 507007; // context release error -static const int32_t ACL_ERROR_RT_SOC_VERSION = 507008; // soc version error -static const int32_t ACL_ERROR_RT_TASK_TYPE_NOT_SUPPORT = 507009; // task type not support -static const int32_t ACL_ERROR_RT_LOST_HEARTBEAT = 507010; // ts lost heartbeat -static const int32_t ACL_ERROR_RT_MODEL_EXECUTE = 507011; // model execute failed -static const int32_t ACL_ERROR_RT_REPORT_TIMEOUT = 507012; // report timeout -static const int32_t ACL_ERROR_RT_SYS_DMA = 507013; // sys dma error -static const int32_t ACL_ERROR_RT_AICORE_TIMEOUT = 507014; // aicore timeout -static const int32_t ACL_ERROR_RT_AICORE_EXCEPTION = 507015; // aicore exception -static const int32_t ACL_ERROR_RT_AICORE_TRAP_EXCEPTION = 507016; // aicore trap exception -static const int32_t ACL_ERROR_RT_AICPU_TIMEOUT = 507017; // aicpu timeout -static const int32_t ACL_ERROR_RT_AICPU_EXCEPTION = 507018; // aicpu exception -static const int32_t ACL_ERROR_RT_AICPU_DATADUMP_RSP_ERR = 507019; // aicpu datadump response error -static const int32_t ACL_ERROR_RT_AICPU_MODEL_RSP_ERR = 507020; // aicpu model operate response error -static const int32_t ACL_ERROR_RT_PROFILING_ERROR = 507021; // profiling error -static const int32_t ACL_ERROR_RT_IPC_ERROR = 507022; // ipc error -static const int32_t ACL_ERROR_RT_MODEL_ABORT_NORMAL = 507023; // model abort normal -static const int32_t ACL_ERROR_RT_KERNEL_UNREGISTERING = 507024; // kernel unregistering -static const int32_t ACL_ERROR_RT_RINGBUFFER_NOT_INIT = 507025; // ringbuffer not init -static const int32_t ACL_ERROR_RT_RINGBUFFER_NO_DATA = 507026; // ringbuffer no data -static const int32_t ACL_ERROR_RT_KERNEL_LOOKUP = 507027; // kernel lookup error -static const int32_t ACL_ERROR_RT_KERNEL_DUPLICATE = 507028; // kernel register duplicate -static const int32_t ACL_ERROR_RT_DEBUG_REGISTER_FAIL = 507029; // debug register failed -static const int32_t ACL_ERROR_RT_DEBUG_UNREGISTER_FAIL = 507030; // debug unregister failed -static const int32_t ACL_ERROR_RT_LABEL_CONTEXT = 507031; // label not in current context -static const int32_t ACL_ERROR_RT_PROGRAM_USE_OUT = 507032; // program register num use out -static const int32_t ACL_ERROR_RT_DEV_SETUP_ERROR = 507033; // device setup error -static const int32_t ACL_ERROR_RT_VECTOR_CORE_TIMEOUT = 507034; // vector core timeout -static const int32_t ACL_ERROR_RT_VECTOR_CORE_EXCEPTION = 507035; // vector core exception -static const int32_t ACL_ERROR_RT_VECTOR_CORE_TRAP_EXCEPTION = 507036; // vector core trap exception - -static const int32_t ACL_ERROR_RT_DRV_INTERNAL_ERROR = 507899; // drv internal error -static const int32_t ACL_ERROR_RT_AICPU_INTERNAL_ERROR = 507900; // aicpu internal error -static const int32_t ACL_ERROR_RT_SOCKET_CLOSE = 507901; // hdc disconnect - -#ifdef __cplusplus -} -#endif - -#endif // __INC_EXTERNEL_RT_ERROR_CODES_H__ diff --git a/third_party/acl/inc/acl/ops/acl_cblas.h b/third_party/acl/inc/acl/ops/acl_cblas.h index 63bdcebd09..5fe91e198f 100644 --- a/third_party/acl/inc/acl/ops/acl_cblas.h +++ b/third_party/acl/inc/acl/ops/acl_cblas.h @@ -51,8 +51,7 @@ typedef enum aclComputeType { * @param dataTypeY [IN] datatype of vector y * @param type [IN] computation type * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasGemvEx(aclTransType transA, int m, int n, @@ -73,8 +72,7 @@ ACL_FUNC_VISIBILITY aclError aclblasGemvEx(aclTransType transA, int m, int n, * @param dataTypeY [IN] datatype of vector y * @param type [IN] computation type * @param handle [OUT] pointer to the pointer to the handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForGemvEx(aclTransType transA, @@ -105,7 +103,7 @@ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForGemvEx(aclTransType transA, * @param incy [IN] stride between consecutive elements of vector y * @param type [IN] computation type * @param stream [IN] stream - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasHgemv(aclTransType transA, @@ -131,8 +129,7 @@ ACL_FUNC_VISIBILITY aclError aclblasHgemv(aclTransType transA, * @param n [IN] number of columns of matrix A * @param type [IN] computation type * @param handle [OUT] pointer to the pointer to the handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForHgemv(aclTransType transA, @@ -160,8 +157,7 @@ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForHgemv(aclTransType transA, * @param incy [IN] stride between consecutive elements of vector y * @param type [IN] computation type * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasS8gemv(aclTransType transA, @@ -187,8 +183,7 @@ ACL_FUNC_VISIBILITY aclError aclblasS8gemv(aclTransType transA, * @param n [IN] number of columns of matrix A * @param handle [OUT] pointer to the pointer to the handle * @param type [IN] computation type - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForS8gemv(aclTransType transA, @@ -222,8 +217,7 @@ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForS8gemv(aclTransType transA, * @param dataTypeC [IN] datatype of matrix C * @param type [IN] computation type * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasGemmEx(aclTransType transA, @@ -263,8 +257,7 @@ ACL_FUNC_VISIBILITY aclError aclblasGemmEx(aclTransType transA, * @param type [IN] computation type * @param handle [OUT] pointer to the pointer to the handle * @param type [IN] computation type - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForGemmEx(aclTransType transA, @@ -302,8 +295,7 @@ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForGemmEx(aclTransType transA, * @param ldc [IN] leading dimension used to store the matrix C * @param type [IN] computation type * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasHgemm(aclTransType transA, @@ -335,8 +327,7 @@ ACL_FUNC_VISIBILITY aclError aclblasHgemm(aclTransType transA, * @param k [IN] number of columns of matrix A and rows of matrix B * @param type [IN] computation type * @param handle [OUT] pointer to the pointer to the handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForHgemm(aclTransType transA, @@ -370,8 +361,7 @@ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForHgemm(aclTransType transA, * @param ldc [IN] leading dimension used to store the matrix C * @param type [IN] computation type * @param stream [IN] stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasS8gemm(aclTransType transA, @@ -404,8 +394,7 @@ ACL_FUNC_VISIBILITY aclError aclblasS8gemm(aclTransType transA, * @param k [IN] number of columns of matrix A and rows of matrix B * @param type [IN] computation type * @param handle [OUT] pointer to the pointer to the handle - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclblasCreateHandleForS8gemm(aclTransType transA, diff --git a/third_party/acl/inc/acl/ops/acl_dvpp.h b/third_party/acl/inc/acl/ops/acl_dvpp.h index 9f67b2818d..7a1afa3bcf 100644 --- a/third_party/acl/inc/acl/ops/acl_dvpp.h +++ b/third_party/acl/inc/acl/ops/acl_dvpp.h @@ -127,8 +127,7 @@ enum acldvppStreamFormat { enum acldvppChannelMode { DVPP_CHNMODE_VPC = 1, DVPP_CHNMODE_JPEGD = 2, - DVPP_CHNMODE_JPEGE = 4, - DVPP_CHNMODE_PNGD = 8 + DVPP_CHNMODE_JPEGE = 4 }; // Supported Border Type @@ -139,66 +138,6 @@ enum acldvppBorderType { BORDER_REFLECT_101 }; -// Venc parameter type -enum aclvencChannelDescParamType { - ACL_VENC_THREAD_ID_UINT64 = 0, - ACL_VENC_CALLBACK_PTR, - ACL_VENC_PIXEL_FORMAT_UINT32, - ACL_VENC_ENCODE_TYPE_UINT32, - ACL_VENC_PIC_WIDTH_UINT32, - ACL_VENC_PIC_HEIGHT_UINT32, - ACL_VENC_KEY_FRAME_INTERVAL_UINT32, - ACL_VENC_BUF_ADDR_PTR, - ACL_VENC_BUF_SIZE_UINT32, - ACL_VENC_RC_MODE_UINT32, - ACL_VENC_SRC_RATE_UINT32, - ACL_VENC_MAX_BITRATE_UINT32, - ACL_VENC_MAX_IP_PROP_UINT32 -}; - -// Jpeg picture format -enum acldvppJpegFormat { - ACL_JPEG_CSS_444 = 0, - ACL_JPEG_CSS_422, - ACL_JPEG_CSS_420, - ACL_JPEG_CSS_GRAY, - ACL_JPEG_CSS_440, - ACL_JPEG_CSS_411, - ACL_JPEG_CSS_UNKNOWN = 1000 -}; - -enum acldvppChannelDescParamType { - ACL_DVPP_CSC_MATRIX_UINT32 = 0, - ACL_DVPP_MODE_UINT32, - ACL_DVPP_CHANNEL_ID_UINT64, - ACL_DVPP_CHANNEL_HEIGHT_UINT32, - ACL_DVPP_CHANNEL_WIDTH_UINT32 -}; - -enum aclvdecChannelDescParamType { - ACL_VDEC_CSC_MATRIX_UINT32 = 0, - ACL_VDEC_OUT_MODE_UINT32, - ACL_VDEC_THREAD_ID_UINT64, - ACL_VDEC_CALLBACK_PTR, - ACL_VDEC_CHANNEL_ID_UINT32, - ACL_VDEC_ENCODE_TYPE_UINT32, - ACL_VDEC_OUT_PIC_FORMAT_UINT32, - ACL_VDEC_OUT_PIC_WIDTH_UINT32, - ACL_VDEC_OUT_PIC_HEIGHT_UINT32, - ACL_VDEC_REF_FRAME_NUM_UINT32, - ACL_VDEC_BIT_DEPTH_UINT32 -}; - -// Csc Matrix can be used both for acldvppChannelDescParamType and aclvdecChannelDescParamType -enum acldvppCscMatrix { - ACL_DVPP_CSC_MATRIX_BT601_WIDE = 0, - ACL_DVPP_CSC_MATRIX_BT601_NARROW, - ACL_DVPP_CSC_MATRIX_BT709_WIDE, - ACL_DVPP_CSC_MATRIX_BT709_NARROW, - ACL_DVPP_CSC_MATRIX_BT2020_WIDE, - ACL_DVPP_CSC_MATRIX_BT2020_NARROW -}; - /** * @ingroup AscendCL * @brief alloc device memory for dvpp. @@ -218,11 +157,9 @@ enum acldvppCscMatrix { * when applying for memory, the user needs to align up to 32 integer * times + 32 bytes (ALIGN_UP [len] +32 words) according to * the actual data size of each picture Section) to manage memory. - * - * @param devPtr [OUT] memory pointer. + * @param devPtr [IN] memory pointer. * @param size [IN] memory size. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppFree @@ -236,8 +173,7 @@ ACL_FUNC_VISIBILITY aclError acldvppMalloc(void **devPtr, size_t size); * @par Function * Free the memory requested through the acldvppMalloc interface * @param devPtr [IN] memory pointer to free. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppMalloc @@ -252,7 +188,6 @@ ACL_FUNC_VISIBILITY aclError acldvppFree(void *devPtr); * Create a channel for image data processing. * The same channel can be reused * and is no longer available after destruction - * * @retval null for failed. * @retval OtherValues success. */ @@ -265,8 +200,7 @@ ACL_FUNC_VISIBILITY acldvppChannelDesc *acldvppCreateChannelDesc(); * @par Function * Can only destroy channels created by the acldvppCreateChannel interface * @param channelDesc [IN] the channel description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannelDesc | acldvppDestroyChannel @@ -281,9 +215,7 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyChannelDesc(acldvppChannelDesc *chann * Interface calling sequence: * acldvppCreateChannelDesc --> acldvppCreateChannel --> * acldvppGetChannelDescChannelId - * * @param channelDesc [IN] the channel description. - * * @retval channel id. * * @see acldvppCreateChannelDesc | acldvppCreateChannel @@ -307,8 +239,7 @@ ACL_FUNC_VISIBILITY acldvppPicDesc *acldvppCreatePicDesc(); * Can only destroy picture description information created * through acldvppCreatePicDesc interface. * @param picDesc [IN] dvpp picture description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreatePicDesc @@ -319,11 +250,10 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyPicDesc(acldvppPicDesc *picDesc); * @ingroup AscendCL * @brief Set dvpp picture description's data. * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param dataDev [IN] dvpp picture dataDev.Must be the memory * requested using the acldvppMalloc interface. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppMalloc @@ -334,10 +264,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescData(acldvppPicDesc *picDesc, void * @ingroup AscendCL * @brief Set dvpp picture description's size. * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param size dvpp [IN] picture size. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescSize(acldvppPicDesc *picDesc, uint32_t size); @@ -346,10 +275,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescSize(acldvppPicDesc *picDesc, uint * @ingroup AscendCL * @brief Set dvpp picture description's format. * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param format [IN] dvpp picture format. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescFormat(acldvppPicDesc *picDesc, acldvppPixelFormat format); @@ -358,10 +286,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescFormat(acldvppPicDesc *picDesc, ac * @ingroup AscendCL * @brief Set dvpp picture description's width. * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param width [IN] dvpp picture width. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescWidth(acldvppPicDesc *picDesc, uint32_t width); @@ -370,10 +297,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescWidth(acldvppPicDesc *picDesc, uin * @ingroup AscendCL * @brief Set dvpp picture description's height. * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param height [IN] dvpp picture height. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescHeight(acldvppPicDesc *picDesc, uint32_t height); @@ -394,11 +320,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescHeight(acldvppPicDesc *picDesc, ui * @li yuv444packed, rgb888: input image width alignment * 3, alignment to 16 * @li xrgb8888: input image width * 4, align to 16 * @li HFBC:input image width - * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param widthStride [IN] dvpp picture widthStride. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescWidthStride(acldvppPicDesc *picDesc, uint32_t widthStride); @@ -411,11 +335,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescWidthStride(acldvppPicDesc *picDes * Height alignment requirements: * @li The height of the input image is aligned to 2. * High stride minimum 6 and maximum 4096. - * - * @param picDesc [OUT] dvpp picture description. + * @param picDesc [IN] dvpp picture description. * @param heightStride [IN] dvpp picture heightStride. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescHeightStride(acldvppPicDesc *picDesc, uint32_t heightStride); @@ -424,10 +346,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescHeightStride(acldvppPicDesc *picDe * @ingroup AscendCL * @brief Set dvpp picture description's retcode. * - * @param picDesc [OUT] dvpp picture description. - * @param retCode [IN] dvpp picture retcode. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param picDesc [IN] dvpp picture description. + * @param retCode [IN] dvpp picture retcode. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescRetCode(acldvppPicDesc *picDesc, uint32_t retCode); @@ -437,7 +358,6 @@ ACL_FUNC_VISIBILITY aclError acldvppSetPicDescRetCode(acldvppPicDesc *picDesc, u * @brief Get picture data. * * @param picDesc [IN] dvpp picture description. - * * @retval picture data addr. * @retval default nullptr. */ @@ -448,7 +368,6 @@ ACL_FUNC_VISIBILITY void *acldvppGetPicDescData(const acldvppPicDesc *picDesc); * @brief Get picture data size. * * @param picDesc [IN] dvpp picture description. - * * @retval picture data size. * @retval default 0. */ @@ -459,7 +378,6 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetPicDescSize(const acldvppPicDesc *picDesc * @brief Get dvpp picture desc's format. * * @param picDesc [IN] dvpp picture description. - * * @retval format * @retval default PIXEL_FORMAT_YUV_400. */ @@ -470,7 +388,6 @@ ACL_FUNC_VISIBILITY acldvppPixelFormat acldvppGetPicDescFormat(const acldvppPicD * @brief Get dvpp picture desc's width. * * @param picDesc [IN] dvpp picture description. - * * @retval width. * @retval default 0. */ @@ -481,7 +398,6 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetPicDescWidth(const acldvppPicDesc *picDes * @brief Get dvpp picture desc's height. * * @param picDesc [IN] dvpp picture description. - * * @retval height. * @retval default 0. */ @@ -503,9 +419,7 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetPicDescHeight(const acldvppPicDesc *picDe * @li yuv444packed, rgb888: input image width alignment * 3, alignment to 16 * @li xrgb8888: input image width * 4, align to 16 * @li HFBC:input image width - * * @param picDesc [IN] dvpp picture description. - * * @retval stride width. * @retval default 0. */ @@ -519,9 +433,7 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetPicDescWidthStride(const acldvppPicDesc * * Height alignment requirements: * @li The height of the input image is aligned to 2. * High stride minimum 6 and maximum 4096. - * * @param picDesc [IN] dvpp picture description. - * * @retval stride height. * @retval default 0. */ @@ -532,7 +444,6 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetPicDescHeightStride(const acldvppPicDesc * @brief Get dvpp picture desc's retcode. * * @param picDesc [IN] dvpp picture description. - * * @retval ret code. * @retval default 0. */ @@ -543,10 +454,9 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetPicDescRetCode(const acldvppPicDesc *picD * @brief Create dvpp roi config. * * @param left [IN] the left offset, must be even - * @param right [IN] the right offset, must be odd - * @param top [IN] the top offset, must be even - * @param bottom [IN] the bottom offset, must be odd - * + * @param right [IN] the right offset, must be odd + * @param top [IN] the top offset, must be even + * @param bottom [IN] the bottom offset, must be odd * @retval null for failed. * @retval other success */ @@ -562,8 +472,7 @@ ACL_FUNC_VISIBILITY acldvppRoiConfig *acldvppCreateRoiConfig(uint32_t left, * @par Function * Destroys data created through the acldvppCreateRoiConfig interface * @param roiConfig [IN] dvpp roi config. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateRoiConfig @@ -574,10 +483,9 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyRoiConfig(acldvppRoiConfig *roiConfig * @ingroup AscendCL * @brief Set left of RoiConfig. * - * @param config [OUT] RoiConfig - * @param left [IN] left offset - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param config [IN] RoiConfig + * @param left [IN] left offset + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigLeft(acldvppRoiConfig *config, uint32_t left); @@ -586,10 +494,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigLeft(acldvppRoiConfig *config, u * @ingroup AscendCL * @brief Set right of RoiConfig. * - * @param config [OUT] RoiConfig + * @param config [IN] RoiConfig * @param right [IN] right offset - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigRight(acldvppRoiConfig *config, uint32_t right); @@ -598,10 +505,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigRight(acldvppRoiConfig *config, * @ingroup AscendCL * @brief Set top of RoiConfig. * - * @param config [OUT] RoiConfig - * @param top [IN] top offset - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param config [IN] RoiConfig + * @param top [IN] top offset + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigTop(acldvppRoiConfig *config, uint32_t top); @@ -610,10 +516,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigTop(acldvppRoiConfig *config, ui * @ingroup AscendCL * @brief Set bottom of RoiConfig. * - * @param config [OUT] RoiConfig + * @param config [IN] RoiConfig * @param bottom [IN] bottom offset - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigBottom(acldvppRoiConfig *config, uint32_t bottom); @@ -622,13 +527,12 @@ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfigBottom(acldvppRoiConfig *config, * @ingroup AscendCL * @brief Set RoiConfig. * - * @param config [OUT] RoiConfig + * @param config [IN|OUT] RoiConfig * @param left [IN] left offset * @param right [IN] right offset * @param top [IN] top offset * @param bottom [IN] bottom offset - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetRoiConfig(acldvppRoiConfig *config, @@ -655,10 +559,8 @@ ACL_FUNC_VISIBILITY acldvppResizeConfig *acldvppCreateResizeConfig(); * @par Function * Destroys the scaling configuration data created by * the acldvppCreateResizeConfig interface - * * @param resizeConfig [IN] resize config. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateResizeConfig @@ -681,9 +583,8 @@ ACL_FUNC_VISIBILITY acldvppJpegeConfig *acldvppCreateJpegeConfig(); * @par Function * Destroys the encoding configuration data created by * the acldvppCreateJpegeConfig interface - * @param jpegeConfig [IN] config pointer to destroy. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param jpegeConfig config pointer to destroy. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateJpegeConfig @@ -694,14 +595,13 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyJpegeConfig(acldvppJpegeConfig *jpege * @ingroup AscendCL * @brief Set jpege config's level. * - * @param jpegeConfig [OUT] Call the acldvppCreateJpegeConfig - * interface to create acldvppJpegeConfig data + * @param jpegeConfig [IN|OUT] Call the acldvppCreateJpegeConfig + * interface to create acldvppJpegeConfig data * @param level [IN] Encoding quality range [0, 100], * where level 0 encoding quality is similar to level 100, * and the smaller the value in [1, 100], * the worse the quality of the output picture. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetJpegeConfigLevel(acldvppJpegeConfig *jpegeConfig, uint32_t level); @@ -711,7 +611,6 @@ ACL_FUNC_VISIBILITY aclError acldvppSetJpegeConfigLevel(acldvppJpegeConfig *jpeg * @brief Get jpege config's level. * * @param jpegeConfig [IN] jpege config. - * * @retval compression level. * @retval default 0. */ @@ -735,8 +634,7 @@ ACL_FUNC_VISIBILITY aclvdecChannelDesc *aclvdecCreateChannelDesc(); * Can only destroy aclvdecChannelDesc type created * through aclvdecCreateChannelDesc interface * @param channelDesc [IN] channel description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * @see aclvdecCreateChannelDesc @@ -747,10 +645,9 @@ ACL_FUNC_VISIBILITY aclError aclvdecDestroyChannelDesc(aclvdecChannelDesc *chann * @ingroup AscendCL * @brief Set vdec channel description's channel id. * - * @param channelDesc [OUT] vdec channel description. - * @param channelId [IN] decoding channel id: 0~15. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] vdec channel description. + * @param channelId [IN] decoding channel id: 0~15. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescChannelId(aclvdecChannelDesc *channelDesc, uint32_t channelId); @@ -759,10 +656,9 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescChannelId(aclvdecChannelDesc * * @ingroup AscendCL * @brief Set vdec channel description's thread id. * - * @param channelDesc [OUT] vdec channel description. - * @param threadId [IN] thread id. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] vdec channel description. + * @param threadId [IN] thread id. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescThreadId(aclvdecChannelDesc *channelDesc, uint64_t threadId); @@ -771,12 +667,11 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescThreadId(aclvdecChannelDesc *c * @ingroup AscendCL * @brief Set vdec channel description's callback function. * - * @param channelDesc [OUT] vdec channel description. - * @param callback [IN] function callback.Function prototype: + * @param channelDesc [IN] vdec channel description. + * @param callback [IN] function callback.Function prototype: * void (* aclvdecCallback) * (acldvppStreamDesc * input, acldvppPicDesc * output, void* userdata) - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclvdecCallback @@ -787,10 +682,9 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescCallback(aclvdecChannelDesc *c * @ingroup AscendCL * @brief Set vdec channel description's video encoding type. * - * @param channelDesc [OUT] vdec channel description. - * @param enType [IN] video encoding type. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] vdec channel description. + * @param enType [IN] video encoding type. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescEnType(aclvdecChannelDesc *channelDesc, acldvppStreamFormat enType); @@ -799,10 +693,9 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescEnType(aclvdecChannelDesc *cha * @ingroup AscendCL * @brief Set vdec channel description's out picture format. * - * @param channelDesc [OUT] vdec channel description. + * @param channelDesc [IN] vdec channel description. * @param outPicFormat [IN] out picture format (acldvppPixelFormat). - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutPicFormat(aclvdecChannelDesc *channelDesc, @@ -812,10 +705,9 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutPicFormat(aclvdecChannelDes * @ingroup AscendCL * @brief Set vdec channel description's out picture width. * - * @param channelDesc [OUT] vdec channel description. + * @param channelDesc [IN] vdec channel description. * @param outPicWidth [IN] out picture width. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutPicWidth(aclvdecChannelDesc *channelDesc, uint32_t outPicWidth); @@ -824,10 +716,9 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutPicWidth(aclvdecChannelDesc * @ingroup AscendCL * @brief Set vdec channel description's out picture height. * - * @param channelDesc [OUT] vdec channel description. + * @param channelDesc [IN] vdec channel description. * @param outPicHeight [IN] out picture height. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutPicHeight(aclvdecChannelDesc *channelDesc, uint32_t outPicHeight); @@ -836,32 +727,18 @@ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutPicHeight(aclvdecChannelDes * @ingroup AscendCL * @brief Set vdec channel description's reference frame num. * - * @param channelDesc [OUT] vdec channel description. + * @param channelDesc [IN] vdec channel description. * @param refFrameNum [IN] reference frame num. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescRefFrameNum(aclvdecChannelDesc *channelDesc, uint32_t refFrameNum); -/** - * @ingroup AscendCL - * @brief Set vdec channel description's bit depth. - * - * @param channelDesc [OUT] vdec channel description. - * @param bitDepth [IN] bit depth. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescBitDepth(aclvdecChannelDesc *channelDesc, uint32_t bitDepth); - /** * @ingroup AscendCL * @brief Get vdec channel description's channel id. * * @param channelDesc [IN] vdec channel description. - * * @retval decoding channel id: 0~15. * @retval default 0. */ @@ -872,7 +749,6 @@ ACL_FUNC_VISIBILITY uint32_t aclvdecGetChannelDescChannelId(const aclvdecChannel * @brief Get vdec channel description's thread id. * * @param channelDesc [IN] vdec channel description. - * * @retval thread id. * @retval default 0. */ @@ -883,7 +759,6 @@ ACL_FUNC_VISIBILITY uint64_t aclvdecGetChannelDescThreadId(const aclvdecChannelD * @brief Get vdec channel description's callback function. * * @param channelDesc [IN] vdec channel description. - * * @retval function callback.Function prototype: * void (* aclvdecCallback) * (acldvppStreamDesc * input, acldvppPicDesc * output, void* userdata) @@ -898,7 +773,6 @@ ACL_FUNC_VISIBILITY aclvdecCallback aclvdecGetChannelDescCallback(const aclvdecC * @brief Get vdec channel description's video encoding type. * * @param channelDesc [IN] vdec channel description. - * * @retval video encoding type. * @retval default H265_MAIN_LEVEL. */ @@ -909,7 +783,6 @@ ACL_FUNC_VISIBILITY acldvppStreamFormat aclvdecGetChannelDescEnType(const aclvde * @brief Get vdec channel description's out picture format. * * @param channelDesc [IN] vdec channel description. - * * @retval out picture format. * @retval default DVPP_OUTPUT_YUV420SP_UV. */ @@ -920,7 +793,6 @@ ACL_FUNC_VISIBILITY acldvppPixelFormat aclvdecGetChannelDescOutPicFormat(const a * @brief Get vdec channel description's out picture width. * * @param channelDesc [IN] vdec channel description. - * * @retval out picture width. * @retval default 0. */ @@ -931,29 +803,16 @@ ACL_FUNC_VISIBILITY uint32_t aclvdecGetChannelDescOutPicWidth(const aclvdecChann * @brief Get vdec channel description's out picture height. * * @param channelDesc [IN] vdec channel description. - * * @retval out picture height (for vdec malloc memory). * @retval default 0. */ ACL_FUNC_VISIBILITY uint32_t aclvdecGetChannelDescOutPicHeight(const aclvdecChannelDesc *channelDesc); -/** - * @ingroup AscendCL - * @brief Get vdec channel description's bit depth. - * - * @param channelDesc [IN] vdec channel description. - * - * @retval bit depth. - * @retval default 0. - */ -ACL_FUNC_VISIBILITY uint32_t aclvdecGetChannelDescBitDepth(const aclvdecChannelDesc *channelDesc); - /** * @ingroup AscendCL * @brief Get vdec channel description's reference frame num. * * @param channelDesc [IN] vdec channel description. - * * @retval reference frame num. * @retval default 0. */ @@ -962,412 +821,258 @@ ACL_FUNC_VISIBILITY uint32_t aclvdecGetChannelDescRefFrameNum(const aclvdecChann /** * @ingroup AscendCL * @brief create vencChannelDesc. - * - * @retval null for failed, other success + * @return null for failed, other success */ ACL_FUNC_VISIBILITY aclvencChannelDesc *aclvencCreateChannelDesc(); /** * @ingroup AscendCL * @brief destroy vencChannelDesc. - * - * @param channelDesc [IN] channel desc. - * - * @retval ACL_SUCCESS:success, other:failed + * @param channelDesc channel desc. + * @return ACL_ERROR_NONE:success, other:failed */ ACL_FUNC_VISIBILITY aclError aclvencDestroyChannelDesc(aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Set decoding thread id for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param threadId [IN] thread id - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param threadId[IN] thread id + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescThreadId(aclvencChannelDesc *channelDesc, uint64_t threadId); /** * @ingroup AscendCL * @brief Set func callback for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param callback [IN] func callback - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param callback[IN] func callback + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescCallback(aclvencChannelDesc *channelDesc, aclvencCallback callback); /** * @ingroup AscendCL * @brief Set video encoding type for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param enType [IN] video encoding type - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param enType[IN] video encoding type + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescEnType(aclvencChannelDesc *channelDesc, acldvppStreamFormat enType); /** * @ingroup AscendCL * @brief Set pic format for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param picFormat [IN] pic format - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param picFormat[IN] pic format + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescPicFormat(aclvencChannelDesc *channelDesc, - acldvppPixelFormat picFormat); + acldvppPixelFormat picFormat); /** * @ingroup AscendCL * @brief Set out pic width for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param picWidth [IN] pic width - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param picWidth[IN] pic width + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescPicWidth(aclvencChannelDesc *channelDesc, uint32_t picWidth); /** * @ingroup AscendCL * @brief Set pic height for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param picHeight [IN] pic height - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param picHeight[IN] pic height + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescPicHeight(aclvencChannelDesc *channelDesc, uint32_t picHeight); /** * @ingroup AscendCL * @brief Set key frame interval for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param keyFrameInterval [IN] Interval of key frame - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param keyFrameInterval[IN] Interval of key frame + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescKeyFrameInterval(aclvencChannelDesc *channelDesc, - uint32_t keyFrameInterval); + uint32_t keyFrameInterval); /** * @ingroup AscendCL * @brief Set output buffer address for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param bufAddr [IN] output buffer address - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param bufAddr[IN/OUT] output buffer address + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescBufAddr(aclvencChannelDesc *channelDesc, void *bufAddr); /** * @ingroup AscendCL * @brief Set output buffer size for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param bufSize [IN] output buffer size - * - * @retval ACL_SUCCESS for success, other for failure + * @param channelDesc[IN/OUT] venc channel desc + * @param bufSize[IN] output buffer size + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescBufSize(aclvencChannelDesc *channelDesc, uint32_t bufSize); -/** - * @ingroup AscendCL - * @brief Set rc model for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param rcMode [IN] venc rc mode(VBR=1, CBR=2) - * - * @retval ACL_SUCCESS for success, other for failure - */ -ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescRcMode(aclvencChannelDesc *channelDesc, uint32_t rcMode); - -/** - * @ingroup AscendCL - * @brief Set source rate for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param srcRate [IN] source rate - * - * @retval ACL_SUCCESS for success, other for failure - */ -ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescSrcRate(aclvencChannelDesc *channelDesc, uint32_t srcRate); - -/** - * @ingroup AscendCL - * @brief Set max bit rate for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param maxBitRate [IN] max bit rate - * - * @retval ACL_SUCCESS for success, other for failure - */ -ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescMaxBitRate(aclvencChannelDesc *channelDesc, uint32_t maxBitRate); - -/** - * @ingroup AscendCL - * @brief Set venc parameter for venc channel desc. - * - * @param channelDesc [OUT] venc channel desc - * @param paramType [IN] parameter type - * @param length [IN] parameter length - * @param param [IN] pointer to parameter value - * - * @retval ACL_SUCCESS for success, other for failure - */ -ACL_FUNC_VISIBILITY aclError aclvencSetChannelDescParam(aclvencChannelDesc *channelDesc, - aclvencChannelDescParamType paramType, size_t length, const void *param); - /** * @ingroup AscendCL * @brief Get output buffer address for venc channel desc. - * * @param channelDesc[IN] venc channel desc - * - * @retval output buffer address + * @return output buffer address */ ACL_FUNC_VISIBILITY void *aclvencGetChannelDescBufAddr(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get output buffer size for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval output buffer size + * @param channelDesc[IN] venc channel desc + * @return output buffer size */ ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescBufSize(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get decoding channel id for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval decoding channel id: 0~15, default 0 + * @param channelDesc[IN] venc channel desc + * @return decoding channel id: 0~15, default 0 */ ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescChannelId(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get decoding thread id for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval thread id, default 0 + * @param channelDesc[IN] venc channel desc + * @return thread id, default 0 */ ACL_FUNC_VISIBILITY uint64_t aclvencGetChannelDescThreadId(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get func callback for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval func callback, default null + * @param channelDesc[IN] venc channel desc + * @return func callback, default null */ ACL_FUNC_VISIBILITY aclvencCallback aclvencGetChannelDescCallback(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get video encoding type for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval video encoding type, default H265_MAIN_LEVEL + * @param channelDesc[IN] venc channel desc + * @return video encoding type, default H265_MAIN_LEVEL */ ACL_FUNC_VISIBILITY acldvppStreamFormat aclvencGetChannelDescEnType(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get pic format for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval pic format + * @param channelDesc[IN] venc channel desc + * @return pic format */ ACL_FUNC_VISIBILITY acldvppPixelFormat aclvencGetChannelDescPicFormat(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get pic width for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval pic width, default 0 + * @param channelDesc[IN] venc channel desc + * @return pic width, default 0 */ ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescPicWidth(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get pic height for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval pic height, default 0 + * @param channelDesc[IN] venc channel desc + * @return pic height, default 0 */ ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescPicHeight(const aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Get interval of key frame for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval interval of key frame, default 0 + * @param channelDesc[IN] venc channel desc + * @return interval of key frame, default 0 */ ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescKeyFrameInterval(const aclvencChannelDesc *channelDesc); -/** - * @ingroup AscendCL - * - * @brief Get rc mode for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval rc mode, default 0 - */ -ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescRcMode(const aclvencChannelDesc *channelDesc); - -/** - * @ingroup AscendCL - * - * @brief Get source rate for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval source rate, default 0 - */ -ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescSrcRate(const aclvencChannelDesc *channelDesc); - -/** - * @ingroup AscendCL - * - * @brief Get max bit rate for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * - * @retval max bit rate, default 0 - */ -ACL_FUNC_VISIBILITY uint32_t aclvencGetChannelDescMaxBitRate(const aclvencChannelDesc *channelDesc); - -/** - * @ingroup AscendCL - * - * @brief Get venc parameter for venc channel desc. - * - * @param channelDesc [IN] venc channel desc - * @param paramType [IN] parameter type - * @param length [IN] parameter length - * @param paramRetSize [OUT] pointer to parameter real length - * @param param [OUT] pointer to parameter value - * - * @retval ACL_SUCCESS for success, other for failure - */ -ACL_FUNC_VISIBILITY aclError aclvencGetChannelDescParam(const aclvencChannelDesc *channelDesc, - aclvencChannelDescParamType paramType, size_t length, size_t *paramRetSize, void *param); - /** * @ingroup AscendCL * @brief get forced restart of I-frame interval from config - * - * @param config [IN] venc frame config - * - * @retval 0: Not forced; 1: Forced restart of I-frame -1: error + * @param config[IN] venc frame config + * @return 0: Not forced; 1: Forced restart of I-frame -1: error */ ACL_FUNC_VISIBILITY uint8_t aclvencGetFrameConfigForceIFrame(const aclvencFrameConfig *config); /** * @ingroup AscendCL * @brief get forced restart of I-frame interval from config - * - * @param config [IN] venc frame config - * - * @retval Whether it is the end frame: 0: no; 1: end frame + * @param config[IN] venc frame config + * @return Whether it is the end frame: 0: no; 1: end frame */ ACL_FUNC_VISIBILITY uint8_t aclvencGetFrameConfigEos(const aclvencFrameConfig *config); /** * @ingroup AscendCL * @brief set single frame encoding configuration parameters - * - * @param config [OUT] venc frame config - * @param forceFrame [IN] forced restart of I-frame interval: 0: Not forced; 1: Forced restart of I-frame - * - * @retval ACL_SUCCESS for ok, others for fail + * @param config[IN/OUT] venc frame config + * @param forceFrame[IN] forced restart of I-frame interval: 0: Not forced; 1: Forced restart of I-frame + * @return ACL_ERROR_NONE for ok, others for fail */ ACL_FUNC_VISIBILITY aclError aclvencSetFrameConfigForceIFrame(aclvencFrameConfig *config, uint8_t forceIFrame); /** * @ingroup AscendCL * @brief set single frame encoding configuration parameters - * - * @param config [OUT] venc frame config - * @param eos [IN] Whether it is the end frame: 0: no; 1: end frame - * - * @retval ACL_SUCCESS for ok, others for fail + * @param config[IN/OUT] venc frame config + * @param eos[IN] Whether it is the end frame: 0: no; 1: end frame + * @return ACL_ERROR_NONE for ok, others for fail */ ACL_FUNC_VISIBILITY aclError aclvencSetFrameConfigEos(aclvencFrameConfig *config, uint8_t eos); /** * @ingroup AscendCL * @brief dvpp venc destroy frame config - * - * @param config [IN] venc frame config - * - * @retval ACL_SUCCESS for ok, others for fail + * @param config[IN/OUT] venc frame config + * @return ACL_ERROR_NONE for ok, others for fail */ ACL_FUNC_VISIBILITY aclError aclvencDestroyFrameConfig(aclvencFrameConfig *config); /** * @ingroup AscendCL * @brief Create dvpp venc frame config. - * - * @retval null for failed, other aclvencFrameConfig ptr + * @return null for failed, other aclvencFrameConfig ptr */ ACL_FUNC_VISIBILITY aclvencFrameConfig *aclvencCreateFrameConfig(); /** * @ingroup AscendCL * @brief Create dvpp venc channel. - * - * @param channelDesc [IN|OUT] venc channel desc - * - * @retval ACL_SUCCESS for ok, others for fail + * @param channelDesc[IN/OUT] venc channel desc + * @return ACL_ERROR_NONE for ok, others for fail */ ACL_FUNC_VISIBILITY aclError aclvencCreateChannel(aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief Destroy dvpp venc channel. - * - * @param channelDesc [IN] venc channel desc - * - * @retval ACL_SUCCESS for ok, others for fail + * @param channelDesc[IN/OUT] venc channel desc + * @return ACL_ERROR_NONE for ok, others for fail */ ACL_FUNC_VISIBILITY aclError aclvencDestroyChannel(aclvencChannelDesc *channelDesc); /** * @ingroup AscendCL * @brief dvpp venc launch send frame task. - * - * @param channelDesc [IN] venc channel desc - * @param input [IN] input picture desc - * @param reserve [IN] reserve parameter - * @param config [IN] dvpp frame config - * @param userdata [IN] user callback function - * - * @retval ACL_SUCCESS for ok, others for fail + * @param channelDesc[IN/OUT] venc channel desc + * @param input[IN/OUT] input picture desc + * @param reserve[IN/OUT] reserve parameter + * @param config[IN/OUT] dvpp frame config + * @param userdata[IN/OUT] user callback function + * @return ACL_ERROR_NONE for ok, others for fail */ ACL_FUNC_VISIBILITY aclError aclvencSendFrame(aclvencChannelDesc *channelDesc, acldvppPicDesc *input, void *reserve, - aclvencFrameConfig *config, void *userdata); + aclvencFrameConfig *config, void *userdata); /** * @ingroup AscendCL @@ -1385,10 +1090,8 @@ ACL_FUNC_VISIBILITY acldvppStreamDesc *acldvppCreateStreamDesc(); * @par Function * Can only destroy acldvppStreamDesc type created through * acldvppCreateStreamDesc interface. - * * @param streamDesc [IN] dvpp stream description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateStreamDesc @@ -1399,10 +1102,9 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyStreamDesc(acldvppStreamDesc *streamD * @ingroup AscendCL * @brief Set stream description's data addr. * - * @param streamDesc [OUT] dvpp stream description. - * @param dataDev [IN] data addr. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param streamDesc [IN] dvpp stream description. + * @param dataDev [IN] data addr. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescData(acldvppStreamDesc *streamDesc, void *dataDev); @@ -1411,10 +1113,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescData(acldvppStreamDesc *streamD * @ingroup AscendCL * @brief Set stream description's data size. * - * @param streamDesc [OUT] dvpp stream description. - * @param size [IN] data size. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param streamDesc [IN] dvpp stream description. + * @param size [IN] data size. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescSize(acldvppStreamDesc *streamDesc, uint32_t size); @@ -1423,10 +1124,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescSize(acldvppStreamDesc *streamD * @ingroup AscendCL * @brief Set stream description's format. * - * @param streamDesc [OUT] dvpp stream description. - * @param format [IN] stream format. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param streamDesc [IN] dvpp stream description. + * @param format [IN] stream format. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescFormat(acldvppStreamDesc *streamDesc, acldvppStreamFormat format); @@ -1435,10 +1135,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescFormat(acldvppStreamDesc *strea * @ingroup AscendCL * @brief Set stream description's timestamp. * - * @param streamDesc [OUT] dvpp stream description. + * @param streamDesc [IN] dvpp stream description. * @param timestamp [IN] current timestamp. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescTimestamp(acldvppStreamDesc *streamDesc, uint64_t timestamp); @@ -1447,10 +1146,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescTimestamp(acldvppStreamDesc *st * @ingroup AscendCL * @brief Set stream description's ret code. * - * @param streamDesc [OUT] dvpp stream description. - * @param retCode [IN] result code. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param streamDesc [IN] dvpp stream description. + * @param retCode [IN] result code. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescRetCode(acldvppStreamDesc *streamDesc, uint32_t retCode); @@ -1459,10 +1157,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescRetCode(acldvppStreamDesc *stre * @ingroup AscendCL * @brief Set stream description's eos. * - * @param streamDesc [OUT] dvpp stream description. - * @param eos [IN] end flag of sequence. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param streamDesc [IN] dvpp stream description. + * @param eos [IN] end flag of sequence. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescEos(acldvppStreamDesc *streamDesc, uint8_t eos); @@ -1472,7 +1169,6 @@ ACL_FUNC_VISIBILITY aclError acldvppSetStreamDescEos(acldvppStreamDesc *streamDe * @brief Get stream description's data addr. * * @param streamDesc [IN] dvpp stream description. - * * @retval data addr. * @retval deault nullptr. */ @@ -1483,7 +1179,6 @@ ACL_FUNC_VISIBILITY void *acldvppGetStreamDescData(const acldvppStreamDesc *stre * @brief Get stream description's data size. * * @param streamDesc [IN] dvpp stream description. - * * @retval data size. * @retval default 0. */ @@ -1494,7 +1189,6 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetStreamDescSize(const acldvppStreamDesc *s * @brief Get stream description's format. * * @param streamDesc [IN] dvpp stream description. - * * @retval stream format. * @retval default ACL_DVPP_STREAM_H264. */ @@ -1505,7 +1199,6 @@ ACL_FUNC_VISIBILITY acldvppStreamFormat acldvppGetStreamDescFormat(const acldvpp * @brief Get stream description's timestamp. * * @param streamDesc [IN] dvpp stream description. - * * @retval current timestamp. * @retval default 0. */ @@ -1516,7 +1209,6 @@ ACL_FUNC_VISIBILITY uint64_t acldvppGetStreamDescTimestamp(const acldvppStreamDe * @brief Get stream description's retCode. * * @param streamDesc [IN] dvpp stream description. - * * @retval result code. * @retval default 0. */ @@ -1527,7 +1219,6 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetStreamDescRetCode(const acldvppStreamDesc * @brief Get stream description's eos. * * @param streamDesc [IN] dvpp stream description. - * * @retval end flag of sequence. * @retval default 0(false). */ @@ -1549,10 +1240,8 @@ ACL_FUNC_VISIBILITY aclvdecFrameConfig *aclvdecCreateFrameConfig(); * @par Function * Can only destroy aclvdecFrameConfig type created through * aclvdecCreateFrameConfig interface - * * @param vdecFrameConfig [IN] vdec frame config. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclvdecCreateFrameConfig @@ -1568,8 +1257,7 @@ ACL_FUNC_VISIBILITY aclError aclvdecDestroyFrameConfig(aclvdecFrameConfig *vdecF * @param width [OUT] the width of image from image header * @param height [OUT] the height of image from image header * @param components [OUT] the components of image from image header - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppJpegGetImageInfo(const void *data, @@ -1578,27 +1266,6 @@ ACL_FUNC_VISIBILITY aclError acldvppJpegGetImageInfo(const void *data, uint32_t *height, int32_t *components); -/** - * @ingroup AscendCL - * @brief Get image width and height of jpeg. - * - * @param data [IN] image data in host memory - * @param size [IN] the size of image data - * @param width [OUT] the width of image from image header - * @param height [OUT] the height of image from image header - * @param components [OUT] the components of image from image header - * @param format [OUT] the format of image from image header - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError acldvppJpegGetImageInfoV2(const void *data, - uint32_t size, - uint32_t *width, - uint32_t *height, - int32_t *components, - acldvppJpegFormat *format); - /** * @ingroup AscendCL * @brief Predict encode size of jpeg image. @@ -1606,8 +1273,7 @@ ACL_FUNC_VISIBILITY aclError acldvppJpegGetImageInfoV2(const void *data, * @param inputDesc [IN] dvpp image desc * @param config [IN] jpeg encode config * @param size [OUT] the size predicted of image - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppJpegPredictEncSize(const acldvppPicDesc *inputDesc, @@ -1622,14 +1288,13 @@ ACL_FUNC_VISIBILITY aclError acldvppJpegPredictEncSize(const acldvppPicDesc *inp * @param dataSize [IN] the size of origin image data * @param outputPixelFormat [IN] the pixel format jpeg decode * @param decSize [OUT] the size predicted for decode image - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppJpegPredictDecSize(const void *data, - uint32_t dataSize, - acldvppPixelFormat outputPixelFormat, - uint32_t *decSize); + uint32_t dataSize, + acldvppPixelFormat outputPixelFormat, + uint32_t *decSize); /** * @ingroup AscendCL @@ -1641,7 +1306,7 @@ ACL_FUNC_VISIBILITY aclError acldvppJpegPredictDecSize(const void *data, * @param height [OUT] the height of image from image header * @param components [OUT] the components of image from image header * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppPngGetImageInfo(const void *data, @@ -1659,7 +1324,7 @@ ACL_FUNC_VISIBILITY aclError acldvppPngGetImageInfo(const void *data, * @param outputPixelFormat [IN] the pixel format jpeg decode * @param decSize [OUT] the size predicted for decode image * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppPngPredictDecSize(const void *data, @@ -1673,8 +1338,7 @@ ACL_FUNC_VISIBILITY aclError acldvppPngPredictDecSize(const void *data, * and is no longer available after destruction. * * @param channelDesc [IN|OUT] the channel destruction - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannelDesc @@ -1687,10 +1351,8 @@ ACL_FUNC_VISIBILITY aclError acldvppCreateChannel(acldvppChannelDesc *channelDes * * @par Restriction * Can only destroy channel created through the acldvppCreateChannel interface - * * @param channelDesc [IN] the channel destruction - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel @@ -1716,24 +1378,22 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyChannel(acldvppChannelDesc *channelDe * Height alignment requirements: * @li The height of the input image is aligned to 2. * High stride minimum 6 and maximum 4096. - * - * @param channelDesc [IN] the channel destruction - * @param inputDesc [IN] resize input picture destruction - * @param outputDesc [IN|OUT] resize output picture destruction - * @param resizeConfig [IN] resize config - * @param stream [IN] resize task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] the channel destruction + * @param inputDesc [IN] resize input picture destruction + * @param outputDesc [IN|OUT] resize output picture destruction + * @param resizeConfig [IN] resize config + * @param stream [IN] resize task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc * | acldvppCreateResizeConfig */ ACL_FUNC_VISIBILITY aclError acldvppVpcResizeAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - acldvppResizeConfig *resizeConfig, - aclrtStream stream); + acldvppPicDesc *inputDesc, + acldvppPicDesc *outputDesc, + acldvppResizeConfig *resizeConfig, + aclrtStream stream); /** * @ingroup AscendCL @@ -1741,7 +1401,7 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcResizeAsync(acldvppChannelDesc *channelDe * * @par Function * crop the input picture according to the specified area, - * and then store the picture in the output memory as the output picture + * and then store the picture in the output memory as the output picture * * @par Restriction * Width alignment requirements: @@ -1758,63 +1418,19 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcResizeAsync(acldvppChannelDesc *channelDe * Height alignment requirements: * @li The height of the input image is aligned to 2. * High stride minimum 6 and maximum 4096. - * - * @param channelDesc [IN] the channel destruction - * @param inputDesc [IN] crop input picture destruction - * @param outputDesc [IN|OUT] crop output picture destruction - * @param cropArea [IN] crop area config - * @param stream [IN] crop task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] the channel destruction + * @param inputDesc [IN] crop input picture destruction + * @param outputDesc [IN|OUT] crop output picture destruction + * @param cropArea [IN] crop area config + * @param stream [IN] crop task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppVpcCropAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - acldvppRoiConfig *cropArea, - aclrtStream stream); - -/** - * @ingroup AscendCL - * @brief dvpp vpc crop and resize config. - * - * @par Function - * crop the input picture with resize config according to the specified area, - * and then store the picture in the output memory as the output picture - * - * @par Restriction - * Width alignment requirements: - * @li The minimum stride is 32 and the maximum is 4096 * 4 - * (that is, an image in argb format with a width of 4096); - * @li For 8K scaling, widthStride is required to be aligned to 2; - * @li For non 8K scaling, the calculation formula for widthStride - * is different for different image formats: - * @li yuv400sp, yuv420sp, yuv422sp, yuv444sp: input image width aligned to 16 - * @li yuv422packed: input image width * 2 and then align to 16 - * @li yuv444packed, rgb888: input image width alignment * 3, alignment to 16 - * @li xrgb8888: input image width * 4, align to 16 - * @li HFBC:input image width - * Height alignment requirements: - * @li The height of the input image is aligned to 2. - * High stride minimum 6 and maximum 4096. - * - * @param channelDesc [IN] the channel destruction - * @param inputDesc [IN] crop input picture destruction - * @param outputDesc [IN|OUT] crop output picture destruction - * @param cropArea [IN] crop area config - * @param resizeConfig [IN] resize config - * @param stream [IN] crop and resize config task stream - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError acldvppVpcCropResizeAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - acldvppRoiConfig *cropArea, - acldvppResizeConfig *resizeConfig, - aclrtStream stream); - + acldvppPicDesc *inputDesc, + acldvppPicDesc *outputDesc, + acldvppRoiConfig *cropArea, + aclrtStream stream); /** * @ingroup AscendCL @@ -1823,58 +1439,25 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcCropResizeAsync(acldvppChannelDesc *chann * @par Function * crop the input batch picture according to the specified area * as the output batch pictures - * - * @param channelDesc [IN] the channel destruction - * @param srcBatchPicDescs [IN] crop input batch picture destruction + * @param channelDesc [IN] the channel destruction + * @param srcBatchPicDescs [IN|OUT] crop input batch picture destruction * @param roiNums [IN] roi config numbers - * @param size [IN] roiNum size + * @param size [IN] roiNum size * @param dstBatchPicDescs [IN|OUT] crop output batch picture destruction * @param cropAreas [IN] crop area configs - * @param stream [IN] crop batch task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param stream [IN] crop batch task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreateBatchPicDesc | acldvppCreateRoiConfig */ ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropAsync(acldvppChannelDesc *channelDesc, - acldvppBatchPicDesc *srcBatchPicDescs, - uint32_t *roiNums, - uint32_t size, - acldvppBatchPicDesc *dstBatchPicDescs, - acldvppRoiConfig *cropAreas[], - aclrtStream stream); - -/** - * @ingroup AscendCL - * @brief dvpp vpc batch crop and resize config. - * - * @par Function - * crop the input batch picture with resize config according to the specified area - * as the output batch pictures - * - * @param channelDesc [IN] the channel destruction - * @param srcBatchPicDescs [IN] crop input batch picture destruction - * @param roiNums [IN] roi config numbers - * @param size [IN] roiNum size - * @param dstBatchPicDescs [IN|OUT] crop output batch picture destruction - * @param cropAreas [IN] crop area configs - * @param resizeConfig [IN] resize config - * @param stream [IN] crop batch and resize config task stream - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acldvppCreateChannel | acldvppCreateBatchPicDesc | acldvppCreateRoiConfig | acldvppCreateDvppConfig - */ -ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropResizeAsync(acldvppChannelDesc *channelDesc, - acldvppBatchPicDesc *srcBatchPicDescs, - uint32_t *roiNums, - uint32_t size, - acldvppBatchPicDesc *dstBatchPicDescs, - acldvppRoiConfig *cropAreas[], - acldvppResizeConfig *resizeConfig, - aclrtStream stream); + acldvppBatchPicDesc *srcBatchPicDescs, + uint32_t *roiNums, + uint32_t size, + acldvppBatchPicDesc *dstBatchPicDescs, + acldvppRoiConfig *cropAreas[], + aclrtStream stream); /** * @ingroup AscendCL @@ -1884,55 +1467,23 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropResizeAsync(acldvppChannelDesc * * crop the input picture according to the specified area, * and paste the picture to the specified position of the target picture * as the output picture - * - * @param channelDesc [IN] thechannel destruction - * @param inputDesc [IN] crop and paste input picture destruction - * @param outputDesc [IN|OUT] crop and paste output picture destruction - * @param cropArea [IN] crop area config - * @param pasteArea [IN] paste area config - * @param stream [IN] crop and paste task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] thechannel destruction + * @param inputDesc [IN] crop and paste input picture destruction + * @param outputDesc [IN|OUT] crop and paste output picture destruction + * @param cropArea [IN] crop area config + * @param pasteArea [IN] paste area config + * @param stream [IN] crop and paste task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc | acldvppCreateRoiConfig */ ACL_FUNC_VISIBILITY aclError acldvppVpcCropAndPasteAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - acldvppRoiConfig *cropArea, - acldvppRoiConfig *pasteArea, - aclrtStream stream); - -/** - * @ingroup AscendCL - * @brief dvpp vpc crop, resize config and paste. - * - * @par Function - * crop the input picture with resize config according to the specified area, - * and paste the picture to the specified position of the target picture - * as the output picture - * - * @param channelDesc [IN] thechannel destruction - * @param inputDesc [IN] crop and paste input picture destruction - * @param outputDesc [IN|OUT] crop and paste output picture destruction - * @param cropArea [IN] crop area config - * @param pasteArea [IN] paste area config - * @param resizeConfig [IN] resize config - * @param stream [IN] crop, paste and resize task stream - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acldvppCreateChannel | acldvppCreatePicDesc | acldvppCreateRoiConfig | acldvppCreateResizeConfig - */ -ACL_FUNC_VISIBILITY aclError acldvppVpcCropResizePasteAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - acldvppRoiConfig *cropArea, - acldvppRoiConfig *pasteArea, - acldvppResizeConfig *resizeConfig, - aclrtStream stream); + acldvppPicDesc *inputDesc, + acldvppPicDesc *outputDesc, + acldvppRoiConfig *cropArea, + acldvppRoiConfig *pasteArea, + aclrtStream stream); /** * @ingroup AscendCL @@ -1942,64 +1493,27 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcCropResizePasteAsync(acldvppChannelDesc * * crop the input batch picture according to the specified area, * and paste the pictures to the specified position of the target pictures * as the output batch pictures - * - * @param channelDesc [IN] the channel destruction - * @param srcBatchPicDescs [IN] crop input batch picture destruction - * @param roiNums [IN] roi config numbers - * @param size [IN] roiNum size + * @param channelDesc [IN] the channel destruction + * @param srcBatchPicDescs [IN|OUT] crop input batch picture destruction + * @param roiNums [IN] roi config numbers + * @param size [IN] roiNum size * @param dstBatchPicDescs [IN|OUT] crop output batch picture destruction - * @param cropAreas [IN] crop area configs - * @param pasteAreas [IN] paste area configs - * @param stream [IN] crop batch task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param cropAreas [IN] crop area configs + * @param pasteAreas [IN] paste area configs + * @param stream [IN] crop batch task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreateBatchPicDesc | acldvppCreateRoiConfig */ ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropAndPasteAsync(acldvppChannelDesc *channelDesc, - acldvppBatchPicDesc *srcBatchPicDescs, - uint32_t *roiNums, - uint32_t size, - acldvppBatchPicDesc *dstBatchPicDescs, - acldvppRoiConfig *cropAreas[], - acldvppRoiConfig *pasteAreas[], - aclrtStream stream); - -/** - * @ingroup AscendCL - * @brief dvpp vpc batch crop, resize config and paste. - * - * @par Function - * crop the input batch picture with resize config according to the specified area, - * and paste the pictures to the specified position of the target pictures - * as the output batch pictures - * - * @param channelDesc [IN] the channel destruction - * @param srcBatchPicDescs [IN] crop input batch picture destruction - * @param roiNums [IN] roi config numbers - * @param size [IN] roiNum size - * @param dstBatchPicDescs [IN|OUT] crop output batch picture destruction - * @param cropAreas [IN] crop area configs - * @param pasteAreas [IN] paste area configs - * @param resizeConfig [IN] resize config - * @param stream [IN] crop batch and resize config task stream - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acldvppCreateChannel | acldvppCreateBatchPicDesc | acldvppCreateRoiConfig | acldvppCreateResizeConfig - */ -ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropResizePasteAsync(acldvppChannelDesc *channelDesc, - acldvppBatchPicDesc *srcBatchPicDescs, - uint32_t *roiNums, - uint32_t size, - acldvppBatchPicDesc *dstBatchPicDescs, - acldvppRoiConfig *cropAreas[], - acldvppRoiConfig *pasteAreas[], - acldvppResizeConfig *resizeConfig, - aclrtStream stream); - + acldvppBatchPicDesc *srcBatchPicDescs, + uint32_t *roiNums, + uint32_t size, + acldvppBatchPicDesc *dstBatchPicDescs, + acldvppRoiConfig *cropAreas[], + acldvppRoiConfig *pasteAreas[], + aclrtStream stream); /** * @ingroup AscendCL @@ -2015,58 +1529,55 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropResizePasteAsync(acldvppChannelD * @li jpeg(420) -> YUV420SP: * V is front U is back, YUV420SP U is front V is back; * @li jpeg(400) -> YUV420SP:UV data is filled with 0 x 80. - * - * @param channelDesc [IN] the channel destruction - * @param data [IN] decode input picture destruction's data - * @param size [IN] decode input picture destruction's size - * @param outputDesc [IN|OUT] decode output picture destruction - * @param stream [IN] decode task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] the channel destruction + * @param data [IN] decode input picture destruction's data + * @param size [IN] decode input picture destruction's size + * @param outputDesc [IN|OUT] decode output picture destruction + * @param stream [IN] decode task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc */ ACL_FUNC_VISIBILITY aclError acldvppJpegDecodeAsync(acldvppChannelDesc *channelDesc, - const void *data, - uint32_t size, - acldvppPicDesc *outputDesc, - aclrtStream stream); + const void *data, + uint32_t size, + acldvppPicDesc *outputDesc, + aclrtStream stream); /** * @ingroup AscendCL * @brief dvpp vpc jpeg encode. * - * @param channelDesc [IN] the channel destruction + * @param channelDesc [IN] the channel destruction * @param inputDesc [IN] encode input picture destruction - * @param data [OUT] encode output picture destruction's data - * @param size [IN|OUT] encode output picture destruction's size - * @param config [IN] jpeg encode config - * @param stream [IN] encode task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param data [IN] encode output picture destruction's data + * @param size [IN] encode output picture destruction's size + * @param config [IN] jpeg encode config + * @param stream [IN] encode task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreateJpegeConfig */ ACL_FUNC_VISIBILITY aclError acldvppJpegEncodeAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - const void *data, - uint32_t *size, - acldvppJpegeConfig *config, - aclrtStream stream); + acldvppPicDesc *inputDesc, + const void *data, + uint32_t *size, + acldvppJpegeConfig *config, + aclrtStream stream); /** * @ingroup AscendCL * @brief dvpp vpc png decode. * * @param channelDesc [IN] the channel destruction - * @param data [IN] decode input picture destruction's data - * @param size [IN] decode input picture destruction's size + * @param data [IN] decode input picture destruction's data + * @param size [IN] decode input picture destruction's size * @param outputDesc [IN|OUT] decode output picture destruction - * @param stream [IN] decode task stream + * @param stream [IN] decode task stream * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc @@ -2085,10 +1596,8 @@ ACL_FUNC_VISIBILITY aclError acldvppPngDecodeAsync(acldvppChannelDesc *channelDe * Create a channel for video data processing, * the same channel can be reused, * and is no longer available after destruction - * - * @param channelDesc [IN|OUT] the channel destruction - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN] the channel destruction + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclvdecCreateChannelDesc @@ -2101,10 +1610,8 @@ ACL_FUNC_VISIBILITY aclError aclvdecCreateChannel(aclvdecChannelDesc *channelDes * * @par Function * Can only destroy channels created by the aclvdecCreateChannel interface - * * @param channelDesc [IN] the channel destruction - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclvdecCreateChannel @@ -2118,45 +1625,21 @@ ACL_FUNC_VISIBILITY aclError aclvdecDestroyChannel(aclvdecChannelDesc *channelDe * @par Function * Pass the input memory to be decoded * and the decoded output memory to the decoder for decoding - * - * @param channelDesc [IN] vdec channel destruction - * @param input [IN] input stream destruction - * @param output [IN|OUT] output picture destruction - * @param config [IN] vdec frame config + * @param channelDesc [IN] vdec channel destruction + * @param input [IN] input stream destruction + * @param output [IN] output picture destruction + * @param config [IN] vdec frame config * @param userData [IN] user data for callback function - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see aclvdecCreateChannel | acldvppCreateStreamDesc | acldvppCreatePicDesc */ ACL_FUNC_VISIBILITY aclError aclvdecSendFrame(aclvdecChannelDesc *channelDesc, - acldvppStreamDesc *input, - acldvppPicDesc *output, - aclvdecFrameConfig *config, - void *userData); - -/** - * @ingroup AscendCL - * @brief dvpp vdec send skipped frame. - * - * @par Function - * Pass video frame to decoder - * - * @param channelDesc [IN] vdec channel destruction - * @param input [IN] input stream destruction - * @param config [IN] vdec frame config - * @param userData [IN] user data for callback function - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclvdecCreateChannel | acldvppCreateStreamDesc | acldvppCreatePicDesc | aclvdecSendFrame - */ -ACL_FUNC_VISIBILITY aclError aclvdecSendSkippedFrame(aclvdecChannelDesc *channelDesc, - acldvppStreamDesc *input, - aclvdecFrameConfig *config, - void *userData); + acldvppStreamDesc *input, + acldvppPicDesc *output, + aclvdecFrameConfig *config, + void* userData); /** * @ingroup AscendCL @@ -2166,21 +1649,19 @@ ACL_FUNC_VISIBILITY aclError aclvdecSendSkippedFrame(aclvdecChannelDesc *channel * @li outputDesc:Width height stride, No changes are allowed. Just configure 0 * @par Function * Convert color gamut - * - * @param channelDesc [IN] the channel destruction - * @param inputDesc [IN] convert color input picture destruction + * @param channelDesc [IN|OUT] the channel destruction + * @param inputDesc [IN|OUT] convert color input picture destruction * @param outputDesc [IN|OUT] convert color output picture destruction - * @param stream [IN] convert color task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param stream [IN] convert color task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc */ ACL_FUNC_VISIBILITY aclError acldvppVpcConvertColorAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - aclrtStream stream); + acldvppPicDesc *inputDesc, + acldvppPicDesc *outputDesc, + aclrtStream stream); /** * @ingroup AscendCL @@ -2190,56 +1671,50 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcConvertColorAsync(acldvppChannelDesc *cha * @li outputDesc:format only supported YUV400 * @par Function * Image pyramid down - * - * @param channelDesc [IN] the channel destruction - * @param inputDesc [IN] pyr down input picture destruction + * @param channelDesc [IN|OUT] the channel destruction + * @param inputDesc [IN|OUT] pyr down input picture destruction * @param outputDesc [IN|OUT] pyr down output picture destruction - * @param reserve [IN] reserved param , must be nullptr - * @param stream [IN] pyr down task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param reserve [IN|OUT] reserved param , must be nullptr + * @param stream [IN] pyr down task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc */ ACL_FUNC_VISIBILITY aclError acldvppVpcPyrDownAsync(acldvppChannelDesc *channelDesc, - acldvppPicDesc *inputDesc, - acldvppPicDesc *outputDesc, - void *reserve, - aclrtStream stream); + acldvppPicDesc *inputDesc, + acldvppPicDesc *outputDesc, + void *reserve, + aclrtStream stream); /** * @ingroup AscendCL * @brief Set dvpp channel mode. * - * @param channelDesc [OUT] the channel destruction - * @param mode [IN] channel mode - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc [IN|OUT] the channel destruction + * @param mode [IN] channel mode + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetChannelDescMode(acldvppChannelDesc *channelDesc, - uint32_t mode); + uint32_t mode); /** * @ingroup AscendCL * @brief Set resize config interpolation. * - * @param resizeConfig [OUT] the resize config + * @param resizeConfig [IN|OUT] the resize config * @param interpolation [IN] interpolation - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppSetResizeConfigInterpolation(acldvppResizeConfig *resizeConfig, - uint32_t interpolation); + uint32_t interpolation); /** * @ingroup AscendCL * @brief Get resize config interpolation. - * * @param resizeConfig [IN] the resize config - * * @retval Interpolation of resize config. */ ACL_FUNC_VISIBILITY uint32_t acldvppGetResizeConfigInterpolation(const acldvppResizeConfig *resizeConfig); @@ -2248,21 +1723,19 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetResizeConfigInterpolation(const acldvppRe * @ingroup AscendCL * @brief Set vdec channel out mode. * - * @param channelDesc [OUT] the channel destruction + * @param channelDesc [IN|OUT] the channel destruction * @param outMode [IN] channel out mode - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescOutMode(aclvdecChannelDesc *channelDesc, - uint32_t outMode); + uint32_t outMode); /** * @ingroup AscendCL * @brief Get vdec channel out mode. * * @param channelDesc [IN] the channel destruction - * * @retval Out mode of channel destruction * @retval default 0 */ @@ -2273,7 +1746,6 @@ ACL_FUNC_VISIBILITY uint32_t aclvdecGetChannelDescOutMode(const aclvdecChannelDe * @brief Create dvpp batch picture description. * * @param batchSize [IN] batch size - * * @retval null for failed. * @retval OtherValues success. */ @@ -2283,9 +1755,8 @@ ACL_FUNC_VISIBILITY acldvppBatchPicDesc *acldvppCreateBatchPicDesc(uint32_t batc * @ingroup AscendCL * @brief Get dvpp picture description. * - * @param batchPicDesc [IN] dvpp batch picture description. - * @param index [IN] index of batch - * + * @param batchPicDesc [IN] dvpp batch picture description. + * @param index [IN] index of batch * @retval null for failed. * @retval OtherValues Failure * @@ -2300,10 +1771,8 @@ ACL_FUNC_VISIBILITY acldvppPicDesc *acldvppGetPicDesc(acldvppBatchPicDesc *batch * @par Function * Can only destroy batch picture description information created * through acldvppCreateBatchPicDesc interface. - * * @param batchPicDesc [IN] dvpp batch picture description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateBatchPicDesc @@ -2324,8 +1793,7 @@ ACL_FUNC_VISIBILITY acldvppLutMap *acldvppCreateLutMap(); * @brief Destroy lut map. * * @param lutMap [IN] lut map - * - * @retval ACL_SUCCESS for success, other for failure + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppDestroyLutMap(acldvppLutMap *lutMap); @@ -2334,7 +1802,6 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyLutMap(acldvppLutMap *lutMap); * @brief Get lut map dims. * * @param lutMap [IN] lut map - * * @retval 0 for failed. * @retval OtherValues success. */ @@ -2344,12 +1811,11 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetLutMapDims(const acldvppLutMap *lutMap); * @ingroup AscendCL * @brief Get lut map data. * - * @param lutMap [IN] lut map - * @param dim [IN] input dim of map + * @param lutMap [IN] lut map + * @param dim [IN] input dim of map * @param data [OUT] the dim of lut map's data - * @param len [OUT] the dim of lut map's length - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param len [OUT] the dim of lut map's length + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure */ ACL_FUNC_VISIBILITY aclError acldvppGetLutMapData(const acldvppLutMap *lutMap, @@ -2360,13 +1826,12 @@ ACL_FUNC_VISIBILITY aclError acldvppGetLutMapData(const acldvppLutMap *lutMap, * @ingroup AscendCL * @brief Vpc equalize hist. * - * @param channelDesc [IN] channel desc - * @param inputDesc [IN] input desc - * @param outputDesc [IN|OUT] output desc - * @param lutMap [IN] lut map param - * @param stream [IN] runtime stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc[in] channel desc + * @param inputDesc[in] input desc + * @param outputDesc[in|out] output desc + * @param lutMap[in] lut map param + * @param stream[in] runtime stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel|acldvppCreatePicDesc|acldvppCreateLutMap @@ -2390,11 +1855,10 @@ ACL_FUNC_VISIBILITY acldvppBorderConfig *acldvppCreateBorderConfig(); * @ingroup AscendCL * @brief Set value of border config. * - * @param borderConfig [OUT] border config - * @param index [IN] index of value array - * @param value [IN] value - * - * @retval ACL_SUCCESS for success, other for failure + * @param borderConfig[IN/OUT] border config + * @param index[IN] index of value array + * @param value[IN] value + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigValue(acldvppBorderConfig *borderConfig, uint32_t index, @@ -2404,10 +1868,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigValue(acldvppBorderConfig *bo * @ingroup AscendCL * @brief Set border type of border config. * - * @param borderConfig [OUT] border config - * @param borderType [IN] border type - * - * @retval ACL_SUCCESS for success, other for failure + * @param borderConfig[IN/OUT] border config + * @param borderType[IN] border type + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigBorderType(acldvppBorderConfig *borderConfig, acldvppBorderType borderType); @@ -2416,10 +1879,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigBorderType(acldvppBorderConfi * @ingroup AscendCL * @brief Set top of border config. * - * @param borderConfig [OUT] border config - * @param top [IN] top of border - * - * @retval ACL_SUCCESS for success, other for failure + * @param borderConfig[IN/OUT] border config + * @param top[IN] top of border + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigTop(acldvppBorderConfig *borderConfig, uint32_t top); @@ -2427,10 +1889,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigTop(acldvppBorderConfig *bord * @ingroup AscendCL * @brief Set bottom of border config. * - * @param borderConfig [OUT] border config - * @param bottom [IN] bottom of border - * - * @retval ACL_SUCCESS for success, other for failure + * @param borderConfig[IN/OUT] border config + * @param bottom[IN] bottom of border + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigBottom(acldvppBorderConfig *borderConfig, uint32_t bottom); @@ -2438,10 +1899,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigBottom(acldvppBorderConfig *b * @ingroup AscendCL * @brief Set left of border config. * - * @param borderConfig [OUT] border config - * @param left [IN] left of border - * - * @retval ACL_SUCCESS for success, other for failure + * @param borderConfig[IN/OUT] border config + * @param left[IN] left of border + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigLeft(acldvppBorderConfig *borderConfig, uint32_t left); @@ -2449,10 +1909,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigLeft(acldvppBorderConfig *bor * @ingroup AscendCL * @brief Set right of border config. * - * @param borderConfig [OUT] border config - * @param right [IN] right of border - * - * @retval ACL_SUCCESS for success, other for failure + * @param borderConfig[IN/OUT] border config + * @param right[IN] right of border + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigRight(acldvppBorderConfig *borderConfig, uint32_t right); @@ -2460,10 +1919,9 @@ ACL_FUNC_VISIBILITY aclError acldvppSetBorderConfigRight(acldvppBorderConfig *bo * @ingroup AscendCL * @brief Get value of border config. * - * @param borderConfig [IN] border config + * @param borderConfig[IN] border config * @param index[IN] index of value array - * - * @retval invalid value is < 0, normal Value is >= 0 + * @return invalid value is < 0, normal Value is >= 0 */ ACL_FUNC_VISIBILITY double acldvppGetBorderConfigValue(const acldvppBorderConfig *borderConfig, uint32_t index); @@ -2471,8 +1929,8 @@ ACL_FUNC_VISIBILITY double acldvppGetBorderConfigValue(const acldvppBorderConfig * @ingroup AscendCL * @brief Get border type of border config. * - * @param borderConfig [IN] border config - * @retval border type of border config + * @param borderConfig[IN] border config + * @return border type of border config */ ACL_FUNC_VISIBILITY acldvppBorderType acldvppGetBorderConfigBorderType(const acldvppBorderConfig *borderConfig); @@ -2480,9 +1938,8 @@ ACL_FUNC_VISIBILITY acldvppBorderType acldvppGetBorderConfigBorderType(const acl * @ingroup AscendCL * @brief Get right of border config. * - * @param borderConfig [IN] border config - * - * @retval default 0, top value of border config + * @param borderConfig[IN] border config + * @return default 0, top value of border config */ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigTop(const acldvppBorderConfig *borderConfig); @@ -2490,9 +1947,8 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigTop(const acldvppBorderConfig * @ingroup AscendCL * @brief Get Bottom of border config. * - * @param borderConfig [IN] border config - * - * @retval default 0, top value of border config + * @param borderConfig[IN] border config + * @return default 0, top value of border config */ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigBottom(const acldvppBorderConfig *borderConfig); @@ -2500,9 +1956,8 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigBottom(const acldvppBorderCon * @ingroup AscendCL * @brief Get left of border config. * - * @param borderConfig [IN] border config - * - * @retval default 0, top value of border config + * @param borderConfig[IN] border config + * @return default 0, top value of border config */ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigLeft(const acldvppBorderConfig *borderConfig); @@ -2510,9 +1965,8 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigLeft(const acldvppBorderConfi * @ingroup AscendCL * @brief Get right of border config. * - * @param borderConfig [IN] border config - * - * @retval default 0, right value of border config + * @param borderConfig[IN/OUT] border config + * @return default 0, right value of border config */ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigRight(const acldvppBorderConfig *borderConfig); @@ -2521,8 +1975,7 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetBorderConfigRight(const acldvppBorderConf * @brief Destroy border config. * * @param borderConfig [IN] border config - * - * @retval ACL_SUCCESS for success, other for failure + * @return ACL_ERROR_NONE for success, other for failure */ ACL_FUNC_VISIBILITY aclError acldvppDestroyBorderConfig(acldvppBorderConfig *borderConfig); @@ -2530,13 +1983,12 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyBorderConfig(acldvppBorderConfig *bor * @ingroup AscendCL * @brief Vpc make border. * - * @param channelDesc [IN] channel desc - * @param inputDesc [IN] input desc - * @param outputDesc [IN|OUT] output desc - * @param borderConfig [IN] border config param - * @param stream [IN] runtime stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param channelDesc[in] channel desc + * @param inputDesc[in] input desc + * @param outputDesc[in|out] output desc + * @param borderConfig[in] border config param + * @param stream[in] runtime stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel|acldvppCreatePicDesc|acldvppCreateBorderConfig @@ -2552,12 +2004,11 @@ ACL_FUNC_VISIBILITY aclError acldvppVpcMakeBorderAsync(const acldvppChannelDesc * @brief Dvpp vpc calc hist. * * @param channelDesc [IN] the channel destruction - * @param srcPicDesc [IN] pyr down input picture destruction - * @param hist [IN|OUT] pyr down output picture destruction - * @param reserve [IN] reserved param, must be nullptr - * @param stream [IN] task stream - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param srcPicDesc [IN] pyr down input picture destruction + * @param hist [IN|OUT] pyr down output picture destruction + * @param reserve [IN] reserved param, must be nullptr + * @param stream [IN] task stream + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateChannel | acldvppCreatePicDesc | acldvppCreateHist @@ -2584,10 +2035,8 @@ ACL_FUNC_VISIBILITY acldvppHist* acldvppCreateHist(); * @par Function * Can only destroy hist description information created * through acldvppCreateHist interface. - * * @param hist [IN] vpc hist description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateHist @@ -2599,8 +2048,7 @@ ACL_FUNC_VISIBILITY aclError acldvppDestroyHist(acldvppHist *hist); * @brief Get dims of vpc hist description. * * @param hist [IN] vpc hist description. - * - * @retval dims of vpc hist description. + * @return dims of vpc hist description. * * @see acldvppCreateHist | acldvppVpcCalcHistAsync */ @@ -2610,12 +2058,11 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetHistDims(acldvppHist *hist); * @ingroup AscendCL * @brief Get data from vpc hist description by dim. * - * @param hist [IN] vpc hist description. - * @param dim [IN] which dim to get data. + * @param hist [IN] vpc hist description. + * @param dim [IN] which dim to get data. * @param data [OUT] address of output hist data. - * @param len [OUT] len of output hist data. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @param len [OUT] len of output hist data. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateHist | acldvppVpcCalcHistAsync @@ -2627,8 +2074,7 @@ ACL_FUNC_VISIBILITY aclError acldvppGetHistData(acldvppHist *hist, uint32_t dim, * @brief Get dvpp calc hist process return code. * * @param hist [IN] vpc hist description. - * - * @retval Dvpp calc hist process return code. + * @return Dvpp calc hist process return code. * * @see acldvppCreateHist | acldvppVpcCalcHistAsync */ @@ -2641,139 +2087,14 @@ ACL_FUNC_VISIBILITY uint32_t acldvppGetHistRetCode(acldvppHist* hist); * @par Function * Can only clear hist description information created * through acldvppCreateHist interface. - * * @param hist [IN] vpc hist description. - * - * @retval ACL_SUCCESS The function is successfully executed. + * @retval ACL_ERROR_NONE The function is successfully executed. * @retval OtherValues Failure * * @see acldvppCreateHist */ ACL_FUNC_VISIBILITY aclError acldvppClearHist(acldvppHist *hist); - -/** - * @ingroup AscendCL - * @brief dvpp vpc batch crop, resize config and make border. - * - * @par Function - * crop the input batch picture with resize config and border configs according to the specified area - * as the output batch pictures - * - * @param channelDesc [IN] the channel destruction - * @param srcBatchPicDescs [IN] crop input batch picture destruction - * @param roiNums [IN] roi config numbers - * @param size [IN] roiNum size - * @param dstBatchPicDescs [IN|OUT] crop output batch picture destruction - * @param cropAreas [IN] crop area configs - * @param borderCfgs [IN] border configs - * @param resizeConfig [IN] resize config - * @param stream [IN] crop batch, resize config and make border task stream - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acldvppCreateChannel | acldvppCreateBatchPicDesc | acldvppCreateRoiConfig | acldvppCreateResizeConfig - */ -ACL_FUNC_VISIBILITY aclError acldvppVpcBatchCropResizeMakeBorderAsync(acldvppChannelDesc *channelDesc, - acldvppBatchPicDesc *srcBatchPicDescs, - uint32_t *roiNums, - uint32_t size, - acldvppBatchPicDesc *dstBatchPicDescs, - acldvppRoiConfig *cropAreas[], - acldvppBorderConfig *borderCfgs[], - acldvppResizeConfig *resizeConfig, - aclrtStream stream); -/** - * @ingroup AscendCL - * @brief set param for dvpp channel desc - * - * @par Function - * set attribution in dvpp channelDesc for specified type - * - * @param channelDesc [OUT] the channel destruction - * @param paramType [IN] specified param type - * @param length [IN] mem length of param - * @param param [IN] pointer to param - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acldvppGetChannelDescParam | acldvppCreateChannelDesc | acldvppDestroyChannelDesc - */ -ACL_FUNC_VISIBILITY aclError acldvppSetChannelDescParam(acldvppChannelDesc *channelDesc, - acldvppChannelDescParamType paramType, - size_t length, - const void *param); - -/** - * @ingroup AscendCL - * @brief get param of dvpp channel desc - * - * @par Function - * get attribution value in dvpp channelDesc for specified type - * - * @param channelDesc [IN] the channel destruction - * @param paramType [IN] specified param type - * @param length [IN] mem length allocated for output param - * @param paramRetSize [OUT] mem length of output param - * @param param [OUT] pointer to output param - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see acldvppSetChannelDescParam | acldvppCreateChannelDesc | acldvppDestroyChannelDesc - */ -ACL_FUNC_VISIBILITY aclError acldvppGetChannelDescParam(const acldvppChannelDesc *channelDesc, - acldvppChannelDescParamType paramType, - size_t length, - size_t *paramRetSize, - void *param); -/** - * @ingroup AscendCL - * @brief set param for vdec channel desc - * - * @par Function - * set attribution in channelDesc for specified type - * - * @param channelDesc [OUT] the vdec channel destruction - * @param paramType [IN] specified param type - * @param length [IN] mem length of param - * @param param [IN] pointer to param - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclvdecGetChannelDescParam | aclvdecCreateChannelDesc | aclvdecDestroyChannelDesc - */ -ACL_FUNC_VISIBILITY aclError aclvdecSetChannelDescParam(aclvdecChannelDesc *channelDesc, - aclvdecChannelDescParamType paramType, - size_t length, - const void *param); - -/** - * @ingroup AscendCL - * @brief get param of vdec channel desc - * - * @par Function - * get attribution value in channelDesc for specified type - * - * @param channelDesc [IN] the vdec channel destruction - * @param paramType [IN] specified param type - * @param length [IN] mem length allocated for output param - * @param paramRetSize [OUT] mem length of output param - * @param param [OUT] pointer to output param - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclvdecSetChannelDescParam | aclvdecCreateChannelDesc | aclvdecDestroyChannelDesc - */ -ACL_FUNC_VISIBILITY aclError aclvdecGetChannelDescParam(const aclvdecChannelDesc *channelDesc, - aclvdecChannelDescParamType paramType, - size_t length, - size_t *paramRetSize, - void *param); #ifdef __cplusplus } #endif diff --git a/third_party/acl/inc/acl/ops/acl_fv.h b/third_party/acl/inc/acl/ops/acl_fv.h deleted file mode 100644 index c0b46759a7..0000000000 --- a/third_party/acl/inc/acl/ops/acl_fv.h +++ /dev/null @@ -1,339 +0,0 @@ -/* * - * @file acl_fv.h - * - * Copyright (C) Huawei Technologies Co., Ltd. 2019-2020. All Rights Reserved. - * - * This program 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. - */ -#ifndef INC_EXTERNAL_ACL_OPS_ACL_RETR_H_ -#define INC_EXTERNAL_ACL_OPS_ACL_RETR_H_ - -#include "acl/acl.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct aclfvInitPara aclfvInitPara; -typedef struct aclfvFeatureInfo aclfvFeatureInfo; -typedef struct aclfvRepoRange aclfvRepoRange; -typedef struct aclfvQueryTable aclfvQueryTable; -typedef struct aclfvSearchInput aclfvSearchInput; -typedef struct aclfvSearchResult aclfvSearchResult; - -// search operation type -enum aclfvSearchType { - SEARCH_1_N, // 1:N operation type - SEARCH_N_M // N:M operation type -}; - -/** - * @ingroup AscendCL - * @brief Create fv init param. - * - * @param fsNum [IN] The feature num - * - * @retval null for failed. - * @retval OtherValues success. - */ -ACL_FUNC_VISIBILITY aclfvInitPara *aclfvCreateInitPara(uint64_t fsNum); - -/** - * @ingroup AscendCL - * @brief Destroy fv init param. - * - * @par Function - * Can only destroy fv init param information created - * through aclfvCreateInitPara interface. - * - * @param initPara [IN] fv init param. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclfvCreateInitPara - */ -ACL_FUNC_VISIBILITY aclError aclfvDestroyInitPara(aclfvInitPara *initPara); - -/** - * @ingroup AscendCL - * @brief set value for maxTopNumFor1N which in fv init param. - * - * @param initPara [IN|OUT] fv init param. - * @param maxTopNumFor1N [IN] maxTopNumFor1N value for init param. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclfvSet1NTopNum(aclfvInitPara *initPara, uint32_t maxTopNumFor1N); - -/** - * @ingroup AscendCL - * @brief set value for maxTopNumForNM which in fv init param. - * - * @param initPara [IN|OUT] fv init param. - * @param maxTopNumForNM [IN] maxTopNumForNM value for init param. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - */ -ACL_FUNC_VISIBILITY aclError aclfvSetNMTopNum(aclfvInitPara *initPara, uint32_t maxTopNumForNM); - -/** - * @ingroup AscendCL - * @brief Create fv feature info. - * - * @param id0 [IN] The first level library id0 - * @param id1 [IN] Secondary library id1 - * @param offset [IN] The offset of the first feature in the library - * @param featureLen [IN] Single feature length - * @param featureCount [IN] Single feature count - * @param featureData [IN] Feature value list - * @param featureDataLen [IN] Feature value list length - * - * @retval null for failed. - * @retval OtherValues success. - */ -ACL_FUNC_VISIBILITY aclfvFeatureInfo *aclfvCreateFeatureInfo(uint32_t id0, uint32_t id1, uint32_t offset, - uint32_t featureLen, uint32_t featureCount, uint8_t *featureData, uint32_t featureDataLen); - -/** - * @ingroup AscendCL - * @brief Destroy fv feature info. - * - * @par Function - * Can only destroy fv feature info information created - * through aclfvCreateFeatureInfo interface. - * - * @param featureInfo [IN] fv feature info. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclfvCreateFeatureInfo - */ -ACL_FUNC_VISIBILITY aclError aclfvDestroyFeatureInfo(aclfvFeatureInfo *featureInfo); - -/** - * @ingroup AscendCL - * @brief Create fv repo range. - * - * @param id0Min [IN] id0 start value - * @param id0Min [IN] id0 max - * @param id1Min [IN] id0 start value - * @param id1Max [IN] id1 max - * - * @retval null for failed. OtherValues success - */ -ACL_FUNC_VISIBILITY aclfvRepoRange *aclfvCreateRepoRange(uint32_t id0Min, uint32_t id0Max, uint32_t id1Min, - uint32_t id1Max); - -/** - * @ingroup AscendCL - * @brief Destroy fv repo range. - * - * @par Function - * Can only destroy fv repo range information created - * through aclfvCreateRepoRange interface. - * - * @param repoRange [IN] fv repo range. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclfvCreateRepoRange - */ -ACL_FUNC_VISIBILITY aclError aclfvDestroyRepoRange(aclfvRepoRange *repoRange); - -/** - * @ingroup AscendCL - * @brief Create query table. - * - * @param queryCnt [IN] Number of tables, the maximum number is 6 - * @param tableLen [IN] Single table length, table length is 32KB - * @param tableData [IN] Feature value list - * @param tableDataLen [IN] The length of memory requested by the featureData pointer - * - * @retval null for failed. OtherValues success - */ -ACL_FUNC_VISIBILITY aclfvQueryTable *aclfvCreateQueryTable(uint32_t queryCnt, uint32_t tableLen, uint8_t *tableData, - uint32_t tableDataLen); - -/** - * @ingroup AscendCL - * @brief Destroy query table. - * - * @par Function - * Can only destroy query table information created - * through aclfvCreateQueryTable interface. - * - * @param queryTable [IN] query table. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclfvCreateQueryTable - */ -ACL_FUNC_VISIBILITY aclError aclfvDestroyQueryTable(aclfvQueryTable *queryTable); - -/** - * @ingroup AscendCL - * @brief Create search input. - * - * @param queryTable [IN] query table - * @param repoRange [IN] query repo range - * @param topk [IN] query topk - * - * @retval null for failed. OtherValues success - */ -ACL_FUNC_VISIBILITY aclfvSearchInput *aclfvCreateSearchInput(aclfvQueryTable *queryTable, aclfvRepoRange *repoRange, - uint32_t topk); - -/** - * @ingroup AscendCL - * @brief Destroy search input. - * - * @par Function - * Can only destroy search input information created - * through aclfvCreateSearchInput interface. - * - * @param searchInput [IN] search input. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclfvCreateSearchInput - */ -ACL_FUNC_VISIBILITY aclError aclfvDestroySearchInput(aclfvSearchInput *searchInput); - -/** - * @ingroup AscendCL - * @brief Create search result. - * - * @param queryCnt [IN] Retrieve the number of features - * @param resultNum [IN] The number of search results for each feature, the number is queryCnt - * @param resultNumDataLen [IN] resultNum memory length - * @param id0 [IN] Level 1 library id0 - * @param id1 [IN] Secondary library id1 - * @param resultOffset [IN] The offset of the bottom library corresponding - * to each feature retrieval result, total length topK * queryCnt - * @param resultDistance [IN] Distance, total length topK * queryCnt - * @param dataLen [IN] The memory size requested by - * id0\id1\reslutOffset\resultDistance - * - * @retval null for failed. OtherValues success - */ -ACL_FUNC_VISIBILITY aclfvSearchResult *aclfvCreateSearchResult(uint32_t queryCnt, uint32_t *resultNum, - uint32_t resultNumDataLen, uint32_t *id0, uint32_t *id1, uint32_t *resultOffset, float *resultDistance, - uint32_t dataLen); - -/** - * @ingroup AscendCL - * @brief Destroy search result. - * - * @par Function - * Can only destroy search result information created - * through aclfvCreateSearchResult interface. - * - * @param searchResult [IN] search result. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure - * - * @see aclfvCreateSearchResult - */ -ACL_FUNC_VISIBILITY aclError aclfvDestroySearchResult(aclfvSearchResult *searchResult); - -/** - * @ingroup AscendCL - * @brief fv IP initialize. - * - * @param initPara [IN] fv init param. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - */ -ACL_FUNC_VISIBILITY aclError aclfvInit(aclfvInitPara *initPara); - -/** - * @ingroup AscendCL - * @brief release fv resources. - * - * @par Function - * Can only release fv resources created - * through aclfvInit interface. - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - * - * @see aclfvInit - */ -ACL_FUNC_VISIBILITY aclError aclfvRelease(); - -/** - * @ingroup AscendCL - * @brief fv repo add. - * - * @param type [IN] repo add type - * @param featureInfo [IN] add feature information - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - */ -ACL_FUNC_VISIBILITY aclError aclfvRepoAdd(aclfvSearchType type, aclfvFeatureInfo *featureInfo); - -/** - * @ingroup AscendCL - * @brief fv repo del. - * - * @param type [IN] repo delete type - * @param repoRange [IN] repo range information - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - */ -ACL_FUNC_VISIBILITY aclError aclfvRepoDel(aclfvSearchType type, aclfvRepoRange *repoRange); - -/** - * @ingroup AscendCL - * @brief fv accurate del. - * - * @param featureInfo [IN] accurate delete feature information - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - */ -ACL_FUNC_VISIBILITY aclError aclfvDel(aclfvFeatureInfo *featureInfo); - -/** - * @ingroup AscendCL - * @brief fv accurate modify. - * - * @param featureInfo [IN] accurate modify feature information - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - */ -ACL_FUNC_VISIBILITY aclError aclfvModify(aclfvFeatureInfo *featureInfo); - -/** - * @ingroup AscendCL - * @brief fv search. - * - * @param type [IN] search type - * @param searchInput [IN] search input - * @param searchRst [OUT] search result - * - * @retval ACL_SUCCESS The function is successfully executed. - * @retval OtherValues Failure. - */ -ACL_FUNC_VISIBILITY aclError aclfvSearch(aclfvSearchType type, aclfvSearchInput *searchInput, - aclfvSearchResult *searchRst); - -#ifdef __cplusplus -} -#endif - -#endif // INC_EXTERNAL_ACL_OPS_ACL_RETR_H_ diff --git a/third_party/acl/libs/acl.cpp b/third_party/acl/libs/acl.cpp index 149428a431..1570a34134 100644 --- a/third_party/acl/libs/acl.cpp +++ b/third_party/acl/libs/acl.cpp @@ -64,7 +64,6 @@ aclError aclopSetAttrString(aclopAttr *attr, const char *attrName, const char *a aclError aclopSetAttrListInt(aclopAttr *attr, const char *attrName, int numValues, const int64_t *values){return 0;} aclError aclopSetAttrListFloat(aclopAttr *attr, const char *attrName, int numValues, const float *values){return 0;} aclError aclopSetAttrListBool(aclopAttr *attr, const char *attrName, int numValues, const uint8_t *values){return 0;} -aclError aclopSetAttrDataType(aclopAttr *attr, const char *attrName, aclDataType values){return 0;} // Tensor相关 aclTensorDesc *aclCreateTensorDesc(aclDataType dataType, int numDims, const int64_t *dims, aclFormat format){return NULL;} void aclDestroyTensorDesc(const aclTensorDesc *desc){return;} diff --git a/third_party/acl/libs/acl_op_compiler.cpp b/third_party/acl/libs/acl_op_compiler.cpp index aaa4886cd7..ea5feee968 100644 --- a/third_party/acl/libs/acl_op_compiler.cpp +++ b/third_party/acl/libs/acl_op_compiler.cpp @@ -43,22 +43,6 @@ aclError aclopCompileAndExecute( return 0; } -aclError aclopCompileAndExecuteV2( - const char* opType, - int numInputs, - aclTensorDesc *inputDesc[], - aclDataBuffer *inputs[], - int numOutputs, - aclTensorDesc *outputDesc[], - aclDataBuffer *outputs[], - aclopAttr* attr, - aclopEngineType engineType, - aclopCompileType compileFlag, - const char* opPath, - aclrtStream stream) { - return 0; -} - void GeGeneratorFinalize() { return; } diff --git a/third_party/acl/libs/operator.cpp b/third_party/acl/libs/operator.cpp index 06439c28b8..ed48a19239 100644 --- a/third_party/acl/libs/operator.cpp +++ b/third_party/acl/libs/operator.cpp @@ -154,8 +154,4 @@ Operator& Operator::SetAttr(const char* name, const Tensor& attr_value) { return op; } -Operator& Operator::SetAttr(const char* name, const ge::DataType& attr_value){ - return op; -} - } // namespace ge \ No newline at end of file diff --git a/third_party/hccl/inc/hccl/hccl.h b/third_party/hccl/inc/hccl/hccl.h index 3720a60322..e8d903420c 100644 --- a/third_party/hccl/inc/hccl/hccl.h +++ b/third_party/hccl/inc/hccl/hccl.h @@ -133,26 +133,6 @@ extern HcclResult HcclSend(void *sendBuf, uint64_t count, HcclDataType dataType, extern HcclResult HcclRecv(void *recvBuf, uint64_t count, HcclDataType dataType, uint32_t srcRank, HcclComm comm, aclrtStream stream); -/** - * @brief AlltoAllV operator. - * - * @param sendBuff A pointer identifying the input data address of the operator. - * @param sendCounts Integer array, where entry i specifies the number of elements to send to rank i. - * @param sdispls Integer array, where entry i specifies the displacement (offset from sendbuf, in units of sendtype) from which to send data to rank i. - * @param sendType Datatype of send buffer elements, must be one of the following types: int8, int32, int64, uint64, float16, float32. - * @param recvBuf A pointer identifying the output data address of the operator. - * @param recvCounts Integer array, where entry j specifies the number of elements to receive from rank j. - * @param rdispls Integer array, where entry j specifies the displacement (offset from recvbuf, in units of recvtype) to which data from rank j should be written. - * @param recvType Datatype of receive buffer elements, must be one of the following types: int8, int32, int64, uint64, float16, float32. - * @param comm A pointer identifying the communication resource based on. - * @param stream A pointer identifying the stream information. - * @return HcclResult - */ - -extern HcclResult HcclAlltoAllV(const void *sendBuf, const void *sendCounts, const void *sdispls, - HcclDataType sendType, const void *recvBuf, const void *recvCounts, const void *rdispls, - HcclDataType recvType, HcclComm comm, aclrtStream stream); - #ifdef __cplusplus } #endif // __cplusplus diff --git a/torch_npu/__init__.py b/torch_npu/__init__.py index 5ab74cdc29..bc4aa6f447 100644 --- a/torch_npu/__init__.py +++ b/torch_npu/__init__.py @@ -31,7 +31,7 @@ import torch_npu._C from torch_npu.contrib.function import npu_functional from torch_npu.contrib.module import npu_modules from torch_npu.utils import apply_module_patch, add_tensor_methods, add_torch_funcs, \ - serialization_patches, add_storage_methods, add_str_methods, add_dataloader_method + serialization_patches, add_str_methods, add_dataloader_method from .version import __version__ as __version__ @@ -70,11 +70,11 @@ for name in dir(torch_npu._C._VariableFunctions): all_monkey_patches = [ ["npu", torch_npu.npu], ["npu.amp", torch_npu.npu.amp], - ["autograd.profiler", torch_npu.npu.profiler], - ["distributed", torch_npu.distributed], - ["nn.parallel.distributed._get_device_index", torch_npu.npu._get_device_index], - ["distributed.distributed_c10d", torch_npu.distributed.distributed_c10d], - ["nn.parallel.distributed._get_default_group", torch_npu.distributed.distributed_c10d._get_default_group], + # ["autograd.profiler", torch_npu.npu.profiler], + # ["distributed", torch_npu.distributed], + # ["nn.parallel.distributed._get_device_index", torch_npu.npu._get_device_index], + # ["distributed.distributed_c10d", torch_npu.distributed.distributed_c10d], + # ["nn.parallel.distributed._get_default_group", torch_npu.distributed.distributed_c10d._get_default_group], ["nn.functional", npu_functional], ["nn", npu_modules], ["_C.Generator", torch_npu._C.Generator] @@ -119,7 +119,7 @@ def apply_class_patches(): apply_module_patch() add_tensor_methods() add_torch_funcs() - add_storage_methods() + # add_storage_methods() add_str_methods() add_dataloader_method() diff --git a/torch_npu/contrib/__init__.py b/torch_npu/contrib/__init__.py index 7fc18a3214..404f09ac56 100644 --- a/torch_npu/contrib/__init__.py +++ b/torch_npu/contrib/__init__.py @@ -16,7 +16,7 @@ from .function import npu_iou, npu_ptiou, npu_giou, npu_diou, npu_ciou, npu_mult npu_batched_multiclass_nms, npu_single_level_responsible_flags, npu_fast_condition_index_put, \ npu_bbox_coder_encode_yolo, npu_bbox_coder_encode_xyxy2xywh, npu_bbox_coder_decode_xywh2xyxy from .module import ChannelShuffle, Prefetcher, LabelSmoothingCrossEntropy, ROIAlign, DCNv2, \ - ModulatedDeformConv, Mish, BiLSTM, PSROIPool, SiLU, Swish, NpuFairseqDropout, MultiheadAttention, FusedColorJitter + ModulatedDeformConv, Mish, BiLSTM, PSROIPool, SiLU, Swish __all__ = [ # from function diff --git a/torch_npu/contrib/transfer_to_npu.py b/torch_npu/contrib/auto_cast_gpu.py similarity index 93% rename from torch_npu/contrib/transfer_to_npu.py rename to torch_npu/contrib/auto_cast_gpu.py index f74982d00b..dd0e063922 100644 --- a/torch_npu/contrib/transfer_to_npu.py +++ b/torch_npu/contrib/auto_cast_gpu.py @@ -27,7 +27,7 @@ torch_fn_white_list = ['logspace', 'randint', 'hann_window', 'rand', 'full_like' 'eye', '_sparse_csr_tensor_unsafe', 'empty', '_sparse_coo_tensor_unsafe', 'blackman_window', 'zeros_like', 'range', 'sparse_csr_tensor', 'randn_like', 'from_file', '_cudnn_init_dropout_state', '_empty_affine_quantized', 'linspace', 'hamming_window', - 'empty_quantized', '_pin_memory', 'device'] + 'empty_quantized', '_pin_memory'] torch_tensor_fn_white_list = ['new_empty', 'new_empty_strided', 'new_full', 'new_ones', 'new_tensor', 'new_zeros', 'to'] torch_module_fn_white_list = ['to', 'to_empty'] @@ -73,6 +73,17 @@ def wrapper_hccl(fn): return decorated +def wrapper_tensor_type(fn): + @wraps(fn) + def decorated(*args, **kwargs): + output = fn(*args, **kwargs) + if isinstance(output, str): + output = output.replace('torch.npu.', 'torch.cuda.') + return output + + return decorated + + def patch_cuda(): patchs = [['cuda', torch_npu.npu], ['cuda.amp', torch_npu.npu.amp]] torch_npu._apply_patches(patchs) @@ -119,6 +130,7 @@ def init(): device_wrapper(torch.Tensor, torch_tensor_fn_white_list) torch.Tensor.cuda = torch.Tensor.npu torch.cuda.DoubleTensor = torch.npu.FloatTensor + torch.Tensor.type = wrapper_tensor_type(torch.Tensor.type) # torch.nn.Module.* device_wrapper(torch.nn.Module, torch_module_fn_white_list) diff --git a/torch_npu/contrib/function/iou.py b/torch_npu/contrib/function/iou.py index 903279d934..1bd46c3d4c 100644 --- a/torch_npu/contrib/function/iou.py +++ b/torch_npu/contrib/function/iou.py @@ -25,7 +25,7 @@ def npu_iou(boxes1, boxes2, mode="ptiou", is_normalized=False, - normalized_scale=100. + normalized_scale=100., ): """ Applies an NPU based IOU operation. @@ -84,7 +84,7 @@ npu_ptiou = npu_iou def npu_giou(boxes1, boxes2, - is_permuted=True + is_permuted=True, ): """ Applies an NPU based GIOU operation. @@ -144,7 +144,7 @@ def npu_diou(boxes1, boxes2, trans=True, is_cross=False, - mode=0 + mode=0, ): """ Applies an NPU based DIOU operation. @@ -161,8 +161,8 @@ def npu_diou(boxes1, .. note:: - Util now, diou backward only support trans==True, is_cross==False, mode==0('iou') current version if you - need to back propagation, please ensure your parameter is correct! + Util now, diou backward only support trans==True, is_cross==False, mode==0('iou') current version if you + need to back propagation, please ensure your parameter is correct! Examples:: >>> box1 = torch.randn(4, 32) @@ -194,7 +194,7 @@ def npu_ciou(boxes1, boxes2, trans=True, is_cross=False, - mode=0 + mode=0, ): """ Applies an NPU based CIOU operation. @@ -210,9 +210,7 @@ def npu_ciou(boxes1, weight function, v is used to measure the similarity of the aspect ratio. .. note:: - - Util now, ciou backward only support trans==True, is_cross==False, mode==0('iou') current version if you - need to back propagation, please ensure your parameter is correct! + Util now, ciou only support is_cross==False, atan_sub_flag==True. Examples:: >>> box1 = torch.randn(4, 32) diff --git a/torch_npu/contrib/module/__init__.py b/torch_npu/contrib/module/__init__.py index f7a358a5cf..ae5c275bfa 100644 --- a/torch_npu/contrib/module/__init__.py +++ b/torch_npu/contrib/module/__init__.py @@ -22,7 +22,6 @@ from .bidirectional_lstm import BiLSTM from .ps_roi_pooling import PSROIPool from .ensemble_dropout import NpuFairseqDropout from .multihead_attention import MultiheadAttention -from .fusedcolorjitter import FusedColorJitter __all__ = [ "ChannelShuffle", @@ -38,5 +37,4 @@ __all__ = [ "Swish", "NpuFairseqDropout", "MultiheadAttention", - "FusedColorJitter", ] diff --git a/torch_npu/contrib/module/ensemble_dropout.py b/torch_npu/contrib/module/ensemble_dropout.py index f0a59c4cc7..5431a0c1b6 100644 --- a/torch_npu/contrib/module/ensemble_dropout.py +++ b/torch_npu/contrib/module/ensemble_dropout.py @@ -18,11 +18,10 @@ import logging from typing import List, Optional import torch +import torch_npu import torch.nn as nn import torch.nn.functional as F -import torch_npu - logger = logging.getLogger(__name__) diff --git a/torch_npu/contrib/module/fusedcolorjitter.py b/torch_npu/contrib/module/fusedcolorjitter.py deleted file mode 100644 index 5f9525aedb..0000000000 --- a/torch_npu/contrib/module/fusedcolorjitter.py +++ /dev/null @@ -1,182 +0,0 @@ -# Copyright (c) 2022 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. - -import random -from math import sin, cos, pi -import numbers -import numpy as np -from PIL import Image -import torch - - -class FusedColorJitterApply(object): - def __init__(self, - hue=0.0, - saturation=1.0, - contrast=0.0, - brightness=0.0, - is_normalized=False, - force_return_array=False): - self.hue = hue - self.saturation = saturation - self.contrast = contrast - self.brightness = brightness - self.is_normalized = is_normalized - self.force_return_array = force_return_array - self.half_range = 127.5 if not is_normalized else 0.5 - - def hue_saturation_matrix(self, hue, saturation): - """ - Single matrix transform for both hue and saturation change. - Matrix taken from https://beesbuzz.biz/code/16-hsv-color-transforms. - Derived by transforming first to YIQ, then do the modification, and transform back to RGB. - """ - const_mat = np.array([[0.299, 0.299, 0.299], - [0.587, 0.587, 0.587], - [0.114, 0.114, 0.114], - ], dtype=np.float32) - sch_mat = np.array([[0.701, -0.299, -0.300], - [-0.587, 0.413, -0.588], - [-0.114, -0.114, 0.886], - ], dtype=np.float32) - ssh_mat = np.array([[0.168, -0.328, 1.250], - [0.330, 0.035, -1.050], - [-0.497, 0.292, -0.203], - ], dtype=np.float32) - sch = saturation * cos(hue * 255. * pi / 180.0) - ssh = saturation * sin(hue * 255. * pi / 180.0) - m = const_mat + sch * sch_mat + ssh * ssh_mat - return m - - def get_random_transform_matrix(self, hue=0.05, saturation=0.5, contrast=0.5, brightness=0.125): - hue = random.uniform(-hue, hue) - saturation = random.uniform(max(0, 1. - saturation), 1 + saturation) - contrast = random.uniform(max(0, 1. - contrast), 1 + contrast) - brightness = random.uniform(max(0, 1. - brightness), 1 + brightness) - - transform_matrix = self.hue_saturation_matrix(hue, saturation) - transform_matrix = transform_matrix * brightness * contrast - transform_offset = (1. - contrast) * brightness * self.half_range - return transform_matrix, transform_offset - - def apply_image_transform(self, img, transform_matrix, transform_offset): - H, W, C = img.shape - if C != 3: - if C == 4: - img = img[:, :, :3] - elif C == 1: - img = img.repeat(3, axis=-1) - else: - raise ('Unknow format using.. Currnet shape is {}'.format(img.shape)) - H, W, C = img.shape - img = np.matmul(img.reshape(-1, 3), transform_matrix) + transform_offset - return img.reshape(H, W, C) - - def __call__(self, img): - transform_matrix, transform_offset = self.get_random_transform_matrix( - self.hue, self.saturation, self.contrast, self.brightness - ) - - if isinstance(img, Image.Image): - img = np.asarray(img, dtype=np.float32) - return_img = True - self.raw_type = np.uint8 - else: - self.raw_type = img.dtype - return_img = False - img = self.apply_image_transform(img, transform_matrix, transform_offset) - - img = img.clip(0., 1. if self.is_normalized else 255.).astype(self.raw_type) - - if return_img and not self.force_return_array: - return Image.fromarray(img, mode='RGB') - - return img - - -class FusedColorJitter(torch.nn.Module): - """Randomly change the brightness, contrast, saturation and hue of an image. - - Unlike the native torchvision.transforms.ColorJitter, - FusedColorJitter completes the adjustment of the image's brightness, contrast, saturation, and hue, - through a matmul and an add operation, approximately 20% performance acceleration can be achieved. - - Args: - brightness (float or tuple of float (min, max)): How much to jitter brightness. - brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness] - or the given [min, max]. Should be non negative numbers. - contrast (float or tuple of float (min, max)): How much to jitter contrast. - contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast] - or the given [min, max]. Should be non negative numbers. - saturation (float or tuple of float (min, max)): How much to jitter saturation. - saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation] - or the given [min, max]. Should be non negative numbers. - hue (float or tuple of float (min, max)): How much to jitter hue. - hue_factor is chosen uniformly from [-hue, hue] or the given [min, max]. - Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5. - - .. Reference 1: Affine HSV color manipulation - https://beesbuzz.biz/code/16-hsv-color-transforms - .. Reference 2: Affine HSV color manipulation - https://github.com/NVIDIA/DALI/blob/release_v1.15/dali/operators/image/color/color_twist.h#L155 - - """ - - def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): - super().__init__() - self.brightness = self._check_input(brightness, 'brightness') - self.contrast = self._check_input(contrast, 'contrast') - self.saturation = self._check_input(saturation, 'saturation') - self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5), - clip_first_on_zero=False) - - self.transformer = FusedColorJitterApply(brightness, contrast, saturation, hue) - - @torch.jit.unused - def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True): - if isinstance(value, numbers.Number): - if value < 0: - raise ValueError("If {} is a single number, it must be non negative.".format(name)) - value = [center - float(value), center + float(value)] - if clip_first_on_zero: - value[0] = max(value[0], 0.0) - elif isinstance(value, (tuple, list)) and len(value) == 2: - if not bound[0] <= value[0] <= value[1] <= bound[1]: - raise ValueError("{} values should be between {}".format(name, bound)) - else: - raise TypeError("{} should be a single number or a list/tuple with length 2.".format(name)) - - # if value is 0 or (1., 1.) for brightness/contrast/saturation - # or (0., 0.) for hue, do nothing - if value[0] == value[1] == center: - value = None - return value - - def forward(self, img): - return self.transformer(img) - - def __repr__(self): - format_string = self.__class__.__name__ + '(' - format_string += 'brightness={0}'.format(self.brightness) - format_string += ', contrast={0}'.format(self.contrast) - format_string += ', saturation={0}'.format(self.saturation) - format_string += ', hue={0})'.format(self.hue) - return format_string - - -if __name__ == '__main__': - image = Image.fromarray(torch.randint(0, 256, size=(224, 224, 3)).numpy().astype(np.uint8)) - fcj = FusedColorJitter(0.1, 0.1, 0.1, 0.1) - image = fcj(image) diff --git a/torch_npu/contrib/module/multihead_attention.py b/torch_npu/contrib/module/multihead_attention.py index db1209c611..681fe9dbb9 100644 --- a/torch_npu/contrib/module/multihead_attention.py +++ b/torch_npu/contrib/module/multihead_attention.py @@ -188,8 +188,6 @@ class MultiheadAttention(nn.Module): output of the decoder, where the self-attention of the encoder is used as the key and value, and the self-attention of the decoder is used as the query. Default: False. - q_noise(float): amount of Quantization Noise - qn_block_size(int): size of the blocks for subsequent quantization with iPQ """ def __init__( diff --git a/torch_npu/csrc/InitNpuBindings.cpp b/torch_npu/csrc/InitNpuBindings.cpp index 44df05c2f7..65e14c6c41 100644 --- a/torch_npu/csrc/InitNpuBindings.cpp +++ b/torch_npu/csrc/InitNpuBindings.cpp @@ -24,10 +24,9 @@ #include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h" #include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" -#include "torch_npu/csrc/distributed/Init.h" -#include "torch_npu/csrc/profiler/init.h" +// #include "torch_npu/csrc/distributed/Init.h" +// #include "torch_npu/csrc/profiler/init.h" #include "torch_npu/csrc/npu/Generator.h" -#include "torch_npu/csrc/npu/Module.h" #include "torch_npu/csrc/utils/TensorMethods.h" PyObject* module; @@ -94,8 +93,8 @@ PyObject* initModule(){ AddPyMethodDefs(methods, TorchNpuMethods); AddPyMethodDefs(methods, THNPModule_get_methods()); - AddPyMethodDefs(methods, torch_npu::profiler::profiler_functions()); - AddPyMethodDefs(methods, torch_npu::distributed::python_functions()); + // AddPyMethodDefs(methods, torch_npu::profiler::profiler_functions()); + // AddPyMethodDefs(methods, torch_npu::distributed::python_functions()); AddPyMethodDefs(methods, torch_npu::utils::tensor_functions()); static struct PyModuleDef torchnpu_module = { PyModuleDef_HEAD_INIT, @@ -116,8 +115,6 @@ PyObject* initModule(){ torch_npu::autograd::initTorchFunctions(module); - RegisterNPUDeviceProperties(module); - BindGetDeviceProperties(module); return module; } diff --git a/torch_npu/csrc/aten/BinaryOps.cpp b/torch_npu/csrc/aten/BinaryOps.cpp index b79e58d3a4..64d0583e01 100644 --- a/torch_npu/csrc/aten/BinaryOps.cpp +++ b/torch_npu/csrc/aten/BinaryOps.cpp @@ -15,7 +15,7 @@ #include #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { diff --git a/torch_npu/csrc/aten/NPUGeneratorImpl.cpp b/torch_npu/csrc/aten/NPUGeneratorImpl.cpp index eed591bfa0..95a99dc205 100644 --- a/torch_npu/csrc/aten/NPUGeneratorImpl.cpp +++ b/torch_npu/csrc/aten/NPUGeneratorImpl.cpp @@ -1,24 +1,9 @@ -// 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. - #include #include #include "torch_npu/csrc/core/npu/NPUFunctions.h" #include "torch_npu/csrc/aten/NPUGeneratorImpl.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace detail { @@ -164,19 +149,21 @@ c10::intrusive_ptr NPUGeneratorImpl::get_state() const { // It used to be static const size_t states_size = MAX_NUM_BLOCKS * sizeof(curandStateMtgp32); // MAX_NUM_BLOCKS was 200 and sizeof(curandStateMtgp32) is 4120. Hardcoding these numbers here // because this is just host side code and we don't want to worry about linking with npu + static const size_t states_size = 200 * sizeof(4120); static const size_t seed_size = sizeof(uint64_t); static const size_t offset_size = sizeof(int64_t); - static const size_t total_size = seed_size + offset_size; + static const size_t total_size = states_size + seed_size + offset_size; auto state_tensor = at::detail::empty_cpu({(int64_t)total_size}, at::ScalarType::Byte, c10::nullopt, c10::nullopt, c10::nullopt, c10::nullopt); auto rng_state = state_tensor.data_ptr(); // since curandStateMTGP is not used anymore, fill gen_states of THCGenerator with deterministic garbage value of -1 // gen_states in THCGenerator struct was an array of curandStateMtgp32s. + memset(rng_state, -1, states_size); auto current_seed = this->current_seed(); auto offset = static_cast(this->philox_offset_per_thread()); // Note that old THCGeneratorState had offset as std::atomic - memcpy(rng_state, ¤t_seed, seed_size); - memcpy(rng_state + seed_size, &offset, offset_size); + memcpy(rng_state + states_size, ¤t_seed, seed_size); + memcpy(rng_state + states_size + seed_size, &offset, offset_size); return state_tensor.getIntrusivePtr(); } @@ -188,10 +175,10 @@ c10::intrusive_ptr NPUGeneratorImpl::get_state() const { * and size of the internal state. */ void NPUGeneratorImpl::set_state(const c10::TensorImpl& new_state) { - + static const size_t states_size = 200 * sizeof(4120); // this line is just here for BC reason static const size_t seed_size = sizeof(uint64_t); static const size_t offset_size = sizeof(int64_t); - static const size_t total_size = seed_size + offset_size; + static const size_t total_size = states_size + seed_size + offset_size; at::detail::check_rng_state(new_state); @@ -205,11 +192,11 @@ void NPUGeneratorImpl::set_state(const c10::TensorImpl& new_state) { uint64_t input_seed; auto new_rng_state = new_state.data(); - memcpy(&input_seed, new_rng_state, seed_size); + memcpy(&input_seed, new_rng_state + states_size, seed_size); this->set_current_seed(input_seed); int64_t philox_offset = 0; if (!no_philox_seed) { - memcpy(&philox_offset, new_rng_state + seed_size, offset_size); + memcpy(&philox_offset, new_rng_state + states_size + seed_size, offset_size); } this->set_philox_offset_per_thread(static_cast(philox_offset)); } diff --git a/torch_npu/csrc/aten/PinMemory.cpp b/torch_npu/csrc/aten/PinMemory.cpp index 09a6442192..19f987d7d6 100644 --- a/torch_npu/csrc/aten/PinMemory.cpp +++ b/torch_npu/csrc/aten/PinMemory.cpp @@ -5,42 +5,44 @@ #include #include #include "torch_npu/csrc/core/npu/NPUFunctions.h" +#include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" + +#define TORCH_ASSERT_ONLY_METHOD_OPERATORS +#include +#include #include -#include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" +#ifndef AT_PER_OPERATOR_HEADERS +#include +#else +#include +#include + +${ops_headers} +#endif namespace at_npu { namespace native { -at::Tensor pin_memory(const at::Tensor& self) { - if (self.options().backend() != c10::Backend::CPU) { - AT_ERROR("cannot pin '", self.toString(), "' only dense CPU tensors can be pinned"); +bool is_pinned(const at::Tensor& self, c10::optional device) { + // Only CPU tensors can be pinned + if (!self.is_cpu()) { + return false; } - if (self.is_pinned()) { - return self; - } - - at::Allocator* allocator = nullptr; - if (c10_npu::device_count() > 0) { - allocator = getPinnedMemoryAllocator(); - } - - if(allocator == nullptr) { - return self; - } - auto storage = c10::Storage( - c10::Storage::use_byte_size_t(), - at::detail::computeStorageNbytes( - self.sizes(), self.strides(), self.dtype().itemsize()), - allocator, - false); - auto tensor = at::empty({0}, self.options()).set_(storage, 0, self.sizes(), self.strides()); - tensor.copy_(self); - return tensor; + // TODO: fetch scalar type from Tensor? But it doesn't really matter... + c10::DispatchKeySet _dk = c10::DispatchKeySet(c10::computeDispatchKey(c10::nullopt, self.layout(), device.value_or(at_npu::key::NativeDeviceType))); + return at::_ops::is_pinned::redispatch(_dk, self, device); } -TORCH_LIBRARY_IMPL(aten, CPU, m){ - m.impl("pin_memory", TORCH_FN(pin_memory)); +at::Tensor _pin_memory(const at::Tensor& self, c10::optional device) { + TORCH_CHECK(self.device().is_cpu(), "cannot pin '", self.toString(), "' only dense CPU tensors can be pinned"); + c10::DispatchKeySet _dk = c10::DispatchKeySet(c10::computeDispatchKey(c10::nullopt, self.layout(), device.value_or(at_npu::key::NativeDeviceType))); + return at::_ops::_pin_memory::redispatch(_dk, self, device); +} + +TORCH_LIBRARY_IMPL(aten, BackendSelect, m) { + m.impl(TORCH_SELECTIVE_NAME("aten::is_pinned"), TORCH_FN(is_pinned)); + m.impl(TORCH_SELECTIVE_NAME("aten::_pin_memory"), TORCH_FN(_pin_memory)); } } diff --git a/torch_npu/csrc/aten/common/CopyKernel.cpp b/torch_npu/csrc/aten/common/CopyKernel.cpp index 22ed0f1be1..a5b55756d6 100644 --- a/torch_npu/csrc/aten/common/CopyKernel.cpp +++ b/torch_npu/csrc/aten/common/CopyKernel.cpp @@ -26,7 +26,7 @@ #include "torch_npu/csrc/aten/common/FormatCastHelper.h" #include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" #include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/npu/NPURunMode.h" namespace at_npu { @@ -85,7 +85,7 @@ void copy_d2d_dtype_format(at::Tensor& self, const at::Tensor& src, bool non_blo at::Tensor src_4D = FormatCastHelper::ApplyBaseFormatTensorBy(src); at::Tensor dst_4D = FormatCastHelper::ApplyBaseFormatTensorBy(self); copy_d2d_dtype_baseformat(dst_4D, src_4D, non_blocking); - NPUNativeFunctions::npu_format_cast_(self, dst_4D); + XLANativeFunctions::npu_format_cast_(self, dst_4D); return; } copy_d2d_dtype_baseformat(self, src, non_blocking); @@ -93,7 +93,7 @@ void copy_d2d_dtype_format(at::Tensor& self, const at::Tensor& src, bool non_blo void copy_d2d(at::Tensor& self, const at::Tensor& src, bool non_blocking) { if (self.dtype() != src.dtype()) { - NPUNativeFunctions::npu_dtype_cast_(self, src); // npu_dtype_cast_ will call copy function. + XLANativeFunctions::npu_dtype_cast_(self, src); // npu_dtype_cast_ will call copy function. return; } copy_d2d_dtype(self, src, non_blocking); @@ -120,7 +120,6 @@ void copy_between_host_and_device( } else { aclError error = aclrtSynchronizeStream(stream); if (error != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); AT_ERROR("ACL stream synchronize failed, error code:", error); } } @@ -209,7 +208,7 @@ void copy_h2d(at::Tensor& self, const at::Tensor& src, bool non_blocking) { if (!FormatHelper::IsBaseFormatType(self)) { at::Tensor dst = OpPreparation::ApplyTensorWithSizes(self.sizes(), self.options()); copy_h2d_baseformat(dst, src, non_blocking, true); - NPUNativeFunctions::npu_format_cast_(self, dst); + XLANativeFunctions::npu_format_cast_(self, dst); return; } copy_h2d_baseformat(self, src, non_blocking); @@ -260,7 +259,7 @@ void copy_d2d_dtype(at::Tensor& self, const at::Tensor& src, bool non_blocking) } at::Tensor dst_4D = FormatCastHelper::ApplyBaseFormatTensorBy(self); copy_d2d_dtype_baseformat(dst_4D, src_4D, non_blocking); - NPUNativeFunctions::npu_format_cast_(self, dst_4D); + XLANativeFunctions::npu_format_cast_(self, dst_4D); return; } copy_d2d_dtype_format(self, src, non_blocking); @@ -285,18 +284,10 @@ void copy_d2d_dtype_baseformat( return; } else { // General trans-contiguous method - NPUNativeFunctions::npu_stride_copy_out(src, src.sizes(), src.strides(), src.storage_offset(), self); + XLANativeFunctions::npu_stride_copy_out(src, src.sizes(), src.strides(), src.storage_offset(), self); return; } } else { - if (c10_npu::NpuRunMode::IsGraphMode()) { - // In graph mode, in order to identify and call the corresponding npu operators, - // opt is necessary for contiguous tensor, such as reshape/slice/select. - OptimizationCases contiguous_opt_cases = {"reshape", "slice", "select"}; - if (TransContiguous::ContiguousOptimizeWithBaseFormat(self, src, contiguous_opt_cases)) { - return; - } - } // Contiguous source tensor copy to contiguous self tensor int64_t numel = self.numel(); if (numel == src.numel()) { @@ -316,7 +307,7 @@ bool try_to_optimize_copy_with_any_format(at::Tensor& self, const at::Tensor& sr return TransContiguous::ContiguousOptimizeWithAnyFormat(self, src); } -at::Tensor& NPUNativeFunctions::copy_(at::Tensor& self, const at::Tensor& src, bool non_blocking) { +at::Tensor& XLANativeFunctions::copy_(at::Tensor& self, const at::Tensor& src, bool non_blocking) { if (self.numel() == 0) { return self; } diff --git a/torch_npu/csrc/aten/common/CopyKernelNpu.cpp b/torch_npu/csrc/aten/common/CopyKernelNpu.cpp index 17ded5f7c0..7ed60a0863 100644 --- a/torch_npu/csrc/aten/common/CopyKernelNpu.cpp +++ b/torch_npu/csrc/aten/common/CopyKernelNpu.cpp @@ -18,12 +18,8 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/StorageDescHelper.h" #include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" -#include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" -#include "torch_npu/csrc/framework/graph/util/GraphModeGuard.h" -#include "torch_npu/csrc/core/npu/NPURunMode.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" namespace at_npu { namespace native { @@ -53,8 +49,6 @@ void copy_kernel_npu( const at::Tensor& src, bool non_blocking) { RECORD_FUNCTION("d2dCopyWithPTCopy", std::vector({src})); - // In graph mode, PTcopy will be supported in the future - GraphModeGuard mode_guard(c10_npu::ModeKind::SINGLE_OP_MODE); const int64_t HEAD_FLAG = 0x6461656800000000; const int64_t FIXED_LEN = 9; // head, len, version, two tensors' numel, offset and strides lens @@ -103,26 +97,8 @@ void copy_kernel_npu( // so: caller should make sure that the storage size of src and dst are reasonable. void copy_d2d_by_memcpy(at::Tensor& dst, const at::Tensor& src, int64_t exceptSize) { int64_t size = exceptSize; - auto dst_mem_size = StorageDescHelper::GetMemorySize(dst); if (exceptSize == 0) { - size = dst_mem_size; - } - - if (c10_npu::NpuRunMode::IsGraphMode()) { - if (dst_mem_size != size || - dst_mem_size != StorageDescHelper::GetMemorySize(src)) { - // In graph mode, using PTcopy to copy part data of src. - copy_kernel_npu(dst, src, true); - return; - } - - // In graph mode, using identity to copy whole data of src. - OpCommand cmd; - cmd.Name("Identity") - .InputWithoutContiguous(src) - .Output(dst) - .Run(); - return; + size = StorageDescHelper::GetMemorySize(dst); } if(!dst.data_ptr()) { @@ -135,14 +111,16 @@ void copy_d2d_by_memcpy(at::Tensor& dst, const at::Tensor& src, int64_t exceptSi return; } - aclError error = c10_npu::queue::LaunchAsyncCopyTask( + c10_npu::NPUStream copy_stream = c10_npu::getCurrentNPUStream(); + aclError error = aclrtMemcpyAsync( dst.data_ptr(), size * dst.element_size(), src.data_ptr(), size * dst.element_size(), - ACL_MEMCPY_DEVICE_TO_DEVICE); + ACL_MEMCPY_DEVICE_TO_DEVICE, + copy_stream); if (error != ACL_ERROR_NONE) { - AT_ERROR("async copy device to device error."); + AT_ERROR("aclrtMemcpy device to device error."); return; } } diff --git a/torch_npu/csrc/aten/common/CopyMemoryKernel.cpp b/torch_npu/csrc/aten/common/CopyMemoryKernel.cpp index 922c16f0bb..5a5e53543f 100644 --- a/torch_npu/csrc/aten/common/CopyMemoryKernel.cpp +++ b/torch_npu/csrc/aten/common/CopyMemoryKernel.cpp @@ -19,15 +19,14 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/FormatHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" -#include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" #include "third_party/acl/inc/acl/acl.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::copy_memory_(at::Tensor& self, const at::Tensor& src, bool non_blocking) { +at::Tensor& XLANativeFunctions::copy_memory_(at::Tensor& self, const at::Tensor& src, bool non_blocking) { AT_ASSERT(at_npu::key::isDeviceTensor(src), "copy_memory_ only support npu tensor"); AT_ASSERT( src.dtype() == self.dtype(), @@ -46,32 +45,34 @@ at::Tensor& NPUNativeFunctions::copy_memory_(at::Tensor& self, const at::Tensor& if (FormatHelper::IsPadded(&self)) { AT_ASSERT(self.storage_offset() == 0); - dst_size = at::prod_intlist(dst_desc.storage_sizes_); + dst_size = c10::multiply_integers(dst_desc.storage_sizes_); } else { - auto dst_element = at::prod_intlist(self.sizes()); - auto dst_storage = at::prod_intlist(dst_desc.storage_sizes_); + auto dst_element = c10::multiply_integers(self.sizes()); + auto dst_storage = c10::multiply_integers(dst_desc.storage_sizes_); dst_size = (dst_element > dst_storage) ? dst_storage : dst_element; } if (FormatHelper::IsPadded(&src)) { AT_ASSERT(src.storage_offset() == 0); - src_size = at::prod_intlist(src_desc.storage_sizes_); + src_size = c10::multiply_integers(src_desc.storage_sizes_); } else { - auto src_element = at::prod_intlist(src.sizes()); - auto src_storage = at::prod_intlist(src_desc.storage_sizes_); + auto src_element = c10::multiply_integers(src.sizes()); + auto src_storage = c10::multiply_integers(src_desc.storage_sizes_); src_size = (src_element > src_storage) ? src_storage : src_element; } + c10_npu::NPUStream stream = c10_npu::getCurrentNPUStream(); + // Designed for the gather of tensors, ignoring npu_format_ and // copying continuous memory between npu tensors. - C10_NPU_CHECK(c10_npu::queue::LaunchAsyncCopyTask( + C10_NPU_CHECK(aclrtMemcpyAsync( self.data_ptr(), dst_size * self.itemsize(), src.data_ptr(), dst_size * self.itemsize(), - ACL_MEMCPY_DEVICE_TO_DEVICE)); + ACL_MEMCPY_DEVICE_TO_DEVICE, + stream)); if (!non_blocking) { - c10_npu::NPUStream stream = c10_npu::getCurrentNPUStream(); C10_NPU_CHECK(aclrtSynchronizeStream(stream)); } return self; diff --git a/torch_npu/csrc/aten/common/FormatCastHelper.cpp b/torch_npu/csrc/aten/common/FormatCastHelper.cpp index e1059b1977..6c69b7bf4f 100644 --- a/torch_npu/csrc/aten/common/FormatCastHelper.cpp +++ b/torch_npu/csrc/aten/common/FormatCastHelper.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/FormatHelper.h" #include "torch_npu/csrc/aten/common/FormatCastHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/npu/NPURunMode.h" @@ -31,7 +31,7 @@ bool FormatCastHelper::IsSameGroupType(const at::Tensor& src, const at::Tensor& void FormatCastHelper::base_format_cast_nocheck(at::Tensor& dst, const at::Tensor& src) { dst.set_(dst.storage(), src.storage_offset(), src.sizes(), src.strides()); - NPUNativeFunctions::copy_memory_(dst, src, true); + XLANativeFunctions::copy_memory_(dst, src, true); } void FormatCastHelper::format_cast_as_base_format(const at::Tensor& src, aclFormat format) { @@ -90,12 +90,14 @@ bool FormatCastHelper::format_cast_between_group(at::Tensor& dst, const at::Tens at::Tensor FormatCastHelper::ApplyBaseFormatTensorBy(const at::Tensor& src) { auto format = FormatHelper::GetBaseFormat(src); - return NPUNativeFunctions::npu_format_cast(src, format); + return XLANativeFunctions::npu_format_cast(src, format); } -at::Tensor& FormatCastHelper::CovertSelfToBaseFormat(at::Tensor& src) { +at::Tensor& FormatCastHelper::CovertSelfToBaseFormat(const at::Tensor& src) { auto format = FormatHelper::GetBaseFormat(src); - return NPUNativeFunctions::npu_format_cast_(src, format); + at::Tensor result = src; + XLANativeFunctions::npu_format_cast_(result, format); + return result; } } // namespace native diff --git a/torch_npu/csrc/aten/common/FormatCastHelper.h b/torch_npu/csrc/aten/common/FormatCastHelper.h index 1aa33fd8a9..eb137c28ae 100644 --- a/torch_npu/csrc/aten/common/FormatCastHelper.h +++ b/torch_npu/csrc/aten/common/FormatCastHelper.h @@ -30,7 +30,7 @@ public: static bool format_cast_between_group(at::Tensor& dst, const at::Tensor& src, FormatCastFunc format_cast_inside_group); // this interface is similar to CastBackToOriFormat, but CastBackToOriFormat may have overload problem. static at::Tensor ApplyBaseFormatTensorBy(const at::Tensor& src); - static at::Tensor& CovertSelfToBaseFormat(at::Tensor& src); + static at::Tensor& CovertSelfToBaseFormat(const at::Tensor& src); private: // help function of format_cast_between_group static void base_format_cast_nocheck(at::Tensor& dst, const at::Tensor& src); diff --git a/torch_npu/csrc/aten/common/FormatCastKernelNpu.cpp b/torch_npu/csrc/aten/common/FormatCastKernelNpu.cpp index dc12314486..174b84207b 100644 --- a/torch_npu/csrc/aten/common/FormatCastKernelNpu.cpp +++ b/torch_npu/csrc/aten/common/FormatCastKernelNpu.cpp @@ -19,7 +19,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/NpuStorageOffsetGuard.h" #include "torch_npu/csrc/aten/common/FormatCastHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" @@ -52,7 +52,7 @@ at::Tensor format_cast_impl_out_npu(at::Tensor& dst, const at::Tensor& src) { } // convert src from src_format to dst_format, write the result into dst -at::Tensor& NPUNativeFunctions::npu_format_cast_(at::Tensor& dst, const at::Tensor& src) { +at::Tensor& XLANativeFunctions::npu_format_cast_(at::Tensor& dst, const at::Tensor& src) { auto src_desc = torch_npu::NPUBridge::GetNpuStorageImpl(src)->npu_desc_; auto dst_desc = torch_npu::NPUBridge::GetNpuStorageImpl(dst)->npu_desc_; if (src_desc.npu_format_ == dst_desc.npu_format_) { @@ -94,16 +94,16 @@ at::Tensor npu_format_cast_impl( } // conver self to dst'format, write the result into new result tensor -at::Tensor NPUNativeFunctions::npu_format_cast( +at::Tensor XLANativeFunctions::npu_format_cast( const at::Tensor& src, const at::Tensor& dst) { auto dst_desc = torch_npu::NPUBridge::GetNpuStorageImpl(dst)->npu_desc_; int64_t dst_format = dst_desc.npu_format_; - return NPUNativeFunctions::npu_format_cast(src, dst_format); + return XLANativeFunctions::npu_format_cast(src, dst_format); } // conver self to acl_format, write the result into self -at::Tensor& NPUNativeFunctions::npu_format_cast_( +at::Tensor& XLANativeFunctions::npu_format_cast_( at::Tensor& src, int64_t acl_format) { auto src_desc = torch_npu::NPUBridge::GetNpuStorageImpl(src)->npu_desc_; @@ -129,7 +129,7 @@ at::Tensor& NPUNativeFunctions::npu_format_cast_( return src; } -int64_t NPUNativeFunctions::get_npu_format(const at::Tensor& src) { +int64_t XLANativeFunctions::get_npu_format(const at::Tensor& src) { auto src_desc = torch_npu::NPUBridge::GetNpuStorageImpl(src)->npu_desc_; return src_desc.npu_format_; } @@ -153,7 +153,7 @@ public: } }; -at::Tensor NPUNativeFunctions::npu_format_cast(const at::Tensor& self, +at::Tensor XLANativeFunctions::npu_format_cast(const at::Tensor& self, int64_t acl_format) { return NPUFormatCastFunction::apply(self, acl_format); } diff --git a/torch_npu/csrc/aten/common/LocalScalarDenseNpu.cpp b/torch_npu/csrc/aten/common/LocalScalarDenseNpu.cpp index 85a9204da7..efcc0dbbee 100644 --- a/torch_npu/csrc/aten/common/LocalScalarDenseNpu.cpp +++ b/torch_npu/csrc/aten/common/LocalScalarDenseNpu.cpp @@ -20,12 +20,12 @@ #include "torch_npu/csrc/framework/graph/util/GraphModeGuard.h" #include "third_party/acl/inc/acl/acl_base.h" #include "third_party/acl/inc/acl/acl_rt.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -c10::Scalar NPUNativeFunctions::_local_scalar_dense(const at::Tensor& self) { +c10::Scalar XLANativeFunctions::_local_scalar_dense(const at::Tensor& self) { c10::Scalar r; AT_DISPATCH_ALL_TYPES_AND2( at::ScalarType::Half, diff --git a/torch_npu/csrc/aten/common/MatmulByBmmV2KernelNpu.cpp b/torch_npu/csrc/aten/common/MatmulByBmmV2KernelNpu.cpp index 29be794d1b..d63d6f3ea2 100644 --- a/torch_npu/csrc/aten/common/MatmulByBmmV2KernelNpu.cpp +++ b/torch_npu/csrc/aten/common/MatmulByBmmV2KernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -45,9 +45,9 @@ at::Tensor matmul_by_bmmV2(const at::Tensor& tensor1, const at::Tensor& tensor2) at::Tensor output = at::_unsafe_view(t1.mm(t2), output_size); return output; } else if ((dim_tensor1 == 1 || dim_tensor1 == 2) && dim_tensor2 >= 3) { - return NPUNativeFunctions::npu_bmmV2(tensor1, tensor2, {}); + return XLANativeFunctions::npu_bmmV2(tensor1, tensor2, {}); } else if ((dim_tensor1 >= 1 && dim_tensor2 >= 1) && (dim_tensor1 >= 3 || dim_tensor2 >= 3)) { - return NPUNativeFunctions::npu_bmmV2(tensor1, tensor2, {}); + return XLANativeFunctions::npu_bmmV2(tensor1, tensor2, {}); } AT_ERROR("both arguments to matmul need to be at least 1D, but they are ", dim_tensor1, "D and ", dim_tensor2, "D"); diff --git a/torch_npu/csrc/aten/common/NpuFastReshape.cpp b/torch_npu/csrc/aten/common/NpuFastReshape.cpp index e7df99dc6a..2eab56e8f7 100644 --- a/torch_npu/csrc/aten/common/NpuFastReshape.cpp +++ b/torch_npu/csrc/aten/common/NpuFastReshape.cpp @@ -17,7 +17,7 @@ #include "torch_npu/csrc/framework/FormatHelper.h" #include "torch_npu/csrc/framework/InferFormat.h" #include "torch_npu/csrc/framework/StorageDescHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -46,7 +46,7 @@ void npu_fast_reshape_(at::Tensor& tensor) { // refresh matadata to input tensor StorageDescHelper::ReflushDescBySelf(tensor); auto base_format = InferFormat::GuessBaseFormat(tensor.sizes()); - NPUNativeFunctions::npu_format_cast_(tensor, base_format); + XLANativeFunctions::npu_format_cast_(tensor, base_format); } } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/common/PinnedMemoryAllocator.cpp b/torch_npu/csrc/aten/common/PinnedMemoryAllocator.cpp new file mode 100644 index 0000000000..04614ad02d --- /dev/null +++ b/torch_npu/csrc/aten/common/PinnedMemoryAllocator.cpp @@ -0,0 +1,45 @@ +// #include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "torch_npu/csrc/aten/XLANativeFunctions.h" +#include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" + +namespace at_npu { +namespace native { + +bool XLANativeFunctions::is_pinned(const at::Tensor& self, c10::optional device) { + // Only CPU tensors can be pinned + if (!self.is_cpu()) { + return false; + } + + return false; +} + +at::Tensor XLANativeFunctions::_pin_memory(const at::Tensor& self, c10::optional device) { + // TORCH_INTERNAL_ASSERT_DEBUG_ONLY(!device.has_value() || device->is_npu()); + auto allocator = getPinnedMemoryAllocator(); + auto storage = c10::Storage( + c10::Storage::use_byte_size_t(), + at::detail::computeStorageNbytes( + self.sizes(), + self.strides(), + self.dtype().itemsize()), + allocator, + /*resizable=*/false); + auto tensor = at::cpu::empty({0}, self.options()).set_(storage, 0, self.sizes(), self.strides()); + tensor.copy_(self); + return tensor; +} + +} // namespace native +} // namespace namespace at_npu { + diff --git a/torch_npu/csrc/aten/common/ResizeNpu.cpp b/torch_npu/csrc/aten/common/ResizeNpu.cpp index 2caf9cb378..246acd239e 100644 --- a/torch_npu/csrc/aten/common/ResizeNpu.cpp +++ b/torch_npu/csrc/aten/common/ResizeNpu.cpp @@ -19,27 +19,28 @@ #include "torch_npu/csrc/aten/common/ResizeNpu.h" #include "torch_npu/csrc/framework/FormatHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::resize_( - at::Tensor& self, +const at::Tensor& XLANativeFunctions::resize_( + const at::Tensor& self, c10::IntArrayRef size, c10::optional format) { // because of resize _impl_npu_ only support at base format, so // no need to reflush NpuStorageDesc here. - if (!FormatHelper::IsBaseFormatType(self)) { - NPUNativeFunctions::npu_format_cast_(self, FormatHelper::GetBaseFormat(self)); + at::Tensor result = self; + if (!FormatHelper::IsBaseFormatType(result)) { + XLANativeFunctions::npu_format_cast_(result, FormatHelper::GetBaseFormat(self)); } - auto* self_ = self.unsafeGetTensorImpl(); - resize_impl_npu_(self_, size, c10::nullopt); - return self; + auto* self_ = result.unsafeGetTensorImpl(); + resize_impl_npu_(self_, size, /*strides=*/c10::nullopt); + return result; } -at::Tensor& NPUNativeFunctions::resize_as_( - at::Tensor& self, +const at::Tensor& XLANativeFunctions::resize_as_( + const at::Tensor& self, const at::Tensor& the_template, c10::optional format) { TORCH_CHECK( @@ -48,10 +49,12 @@ at::Tensor& NPUNativeFunctions::resize_as_( TORCH_CHECK( !format.has_value(), "NPU does not support specify memory_format."); - at::Tensor& result = self.resize_(the_template.sizes()); + const at::Tensor& result = self.resize_(the_template.sizes()); at::namedinference::propagate_names(result, the_template); - return result; + at::Tensor temp = result; + return temp; } + } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/common/ResizeNpu.h b/torch_npu/csrc/aten/common/ResizeNpu.h index 581810ad9a..ba6a939110 100644 --- a/torch_npu/csrc/aten/common/ResizeNpu.h +++ b/torch_npu/csrc/aten/common/ResizeNpu.h @@ -17,14 +17,11 @@ #pragma once #include -#include #include "torch_npu/csrc/core/npu/NPUStream.h" -#include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/StorageDescHelper.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" -#include "torch_npu/csrc/core/npu/NPURunMode.h" namespace at_npu { namespace native { @@ -54,12 +51,14 @@ static void storage_resize_npu( copy_size = storage.nbytes(); } if (copy_size > 0) { - aclError error = c10_npu::queue::LaunchAsyncCopyTask( + c10_npu::NPUStream copy_stream = c10_npu::getCurrentNPUStream(); + aclError error = aclrtMemcpyAsync( storage.data(), copy_size, old_data.get(), copy_size, - ACL_MEMCPY_DEVICE_TO_DEVICE); + ACL_MEMCPY_DEVICE_TO_DEVICE, + copy_stream); if (error != ACL_ERROR_NONE) { AT_ERROR("ACL_Memcpy device to device error."); return; @@ -72,15 +71,19 @@ static inline void maybe_resize_storage_npu( at::TensorImpl* self, int64_t new_size, c10::IntArrayRef size) { + if (new_size == 0) { + return; + } + if (new_size > 0) { - if (!THTensor_getStoragePtr(self)) { + if (!self->storage().unsafeGetStorageImpl()) { AT_ERROR("Try to resize a tensor with null storage"); } int64_t new_size_bytes = (new_size + self->storage_offset()) * self->dtype().itemsize(); if (new_size_bytes > self->storage().nbytes()) { storage_resize_npu( - *torch_npu::NPUBridge::GetNpuStorageImpl((THTensor_getStoragePtr(self))), + *torch_npu::NPUBridge::GetNpuStorageImpl(self->storage().unsafeGetStorageImpl()), new_size_bytes, size); } @@ -127,70 +130,5 @@ static void resize_nd_npu( } resize_impl_npu_(self, sizes, strides); } - -static inline void checkInBoundsForStorage( - c10::IntArrayRef size, - c10::IntArrayRef stride, - int64_t storage_offset, - const caffe2::TypeMeta data_type, - const c10::Storage& new_storage) { - int64_t storage_size_bytes = - at::detail::computeStorageNbytes(size, stride, data_type.itemsize()); - int64_t storage_offset_bytes = storage_offset * data_type.itemsize(); - if (storage_size_bytes == 0) { - // NB: (a tensor with arbitrary 0 dims)'s storage can have any numel. - return; - } - - int64_t new_storage_size_bytes; - if (c10_npu::NpuRunMode::IsGraphMode()){ - new_storage_size_bytes = at::prod_intlist(size) * data_type.itemsize(); - } else { - new_storage_size_bytes = new_storage.nbytes(); - } - - TORCH_CHECK( - storage_size_bytes + storage_offset_bytes <= new_storage_size_bytes, - "setStorage: sizes ", - size, - ", strides ", - stride, - "," - " storage offset ", - storage_offset, - ", and itemsize ", - data_type.itemsize(), - " requiring a storage size of ", - storage_size_bytes, - " are out of bounds for storage of size ", - new_storage_size_bytes); -} - -inline void setStrided( - const at::Tensor& self, - c10::IntArrayRef size, - c10::IntArrayRef stride, - int64_t storage_offset) { - TORCH_CHECK(size.size() == stride.size(), "mismatch in length of strides and shape"); - auto* self_ = self.unsafeGetTensorImpl(); - checkInBoundsForStorage( - size, stride, storage_offset, self_->dtype(), self_->storage()); - - /* storage offset */ - TORCH_CHECK(storage_offset >= 0, "Tensor: invalid storage offset ", storage_offset); - self_->set_storage_offset(storage_offset); - - /* size and stride */ - if (self_->sizes() == size && self_->strides() == stride) { - return; - } - for (auto val : stride) { - TORCH_CHECK(val >= 0, - "as_strided: Negative strides are not supported at the moment, " - "got strides: ", stride); - } - self_->set_sizes_and_strides(size, stride); -} - } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/common/SetNpu.cpp b/torch_npu/csrc/aten/common/SetNpu.cpp index e5b5563167..11203fd2b4 100644 --- a/torch_npu/csrc/aten/common/SetNpu.cpp +++ b/torch_npu/csrc/aten/common/SetNpu.cpp @@ -17,12 +17,13 @@ // #pragma once #include #include -#include +// #include +#include #include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" #include "torch_npu/csrc/aten/common/ResizeNpu.h" #include "torch_npu/csrc/framework/StorageDescHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" namespace at_npu { @@ -42,36 +43,26 @@ torch_npu::NPUStorageImpl* storage_new_npu(caffe2::TypeMeta data_type) { } void set_storage_nd_npu( - at::TensorImpl* self, - torch_npu::NPUStorageImpl* storage, - ptrdiff_t storageOffset, + at::Tensor& self, + c10::Storage storage, + int64_t storage_offset, int nDimension, - const int64_t* size, - const int64_t* stride) { - if (THTensor_getStoragePtr(self) != storage) { - if (!THTensor_getStoragePtr(self)) { - AT_ERROR("at::Tensor: invalid null storage"); - } - auto data_type = self->dtype(); - if (storage != nullptr) { - c10::raw::intrusive_ptr::incref(storage); - THTensor_stealAndSetStoragePtr(self, static_cast(storage)); - } else { - THTensor_stealAndSetStoragePtr(self, static_cast(storage_new_npu(data_type))); - } - } + c10::IntArrayRef size, + c10::IntArrayRef stride) { - if (storageOffset < 0) { + at::native::checkSetStorage(self, storage, storage_offset, size, stride); + + if (storage_offset < 0) { AT_ERROR("at::Tensor: invalid storage offset"); } - self->set_storage_offset(storageOffset); - resize_nd_npu(self, nDimension, size, stride); + self.unsafeGetTensorImpl()->set_storage_offset(storage_offset); + resize_nd_npu(self.unsafeGetTensorImpl(), nDimension, size.data(), stride.data()); } void set_storage_npu_( - at::TensorImpl* self, - torch_npu::NPUStorageImpl* storage_, - ptrdiff_t storageOffset_, + at::Tensor& self, + c10::Storage storage_, + long storageOffset_, c10::IntArrayRef size_, c10::IntArrayRef stride_) { if (stride_.data()) { @@ -81,15 +72,15 @@ void set_storage_npu_( storage_, storageOffset_, size_.size(), - size_.data(), - stride_.data()); + size_, + stride_); } -at::Tensor& NPUNativeFunctions::set_(at::Tensor& self, c10::Storage src) { +at::Tensor& XLANativeFunctions::set_(at::Tensor& self, c10::Storage src) { int64_t new_size = static_cast(src.nbytes() / self.dtype().itemsize()); set_storage_npu_( - self.unsafeGetTensorImpl(), - torch_npu::NPUBridge::GetNpuStorageImpl(src.unsafeGetStorageImpl()), + self, + src, 0, {new_size}, {}); @@ -97,15 +88,15 @@ at::Tensor& NPUNativeFunctions::set_(at::Tensor& self, c10::Storage src) { return self; } -at::Tensor& NPUNativeFunctions::set_( +at::Tensor& XLANativeFunctions::set_( at::Tensor& self, c10::Storage src, long storage_offset, c10::IntArrayRef size, c10::IntArrayRef stride) { set_storage_npu_( - self.unsafeGetTensorImpl(), - torch_npu::NPUBridge::GetNpuStorageImpl(src.unsafeGetStorageImpl()), + self, + src, storage_offset, size, stride); @@ -121,8 +112,8 @@ at::Tensor& set_format_npu_( c10::IntArrayRef size, c10::IntArrayRef stride) { set_storage_npu_( - self.unsafeGetTensorImpl(), - torch_npu::NPUBridge::GetNpuStorageImpl(src.unsafeGetStorageImpl()), + self, + src, storage_offset, size, stride); @@ -131,23 +122,31 @@ at::Tensor& set_format_npu_( return self; } -at::Tensor& NPUNativeFunctions::set_(at::Tensor& self) { - set_storage_npu_(self.unsafeGetTensorImpl(), NULL, 0, {0}, {}); +at::Tensor& XLANativeFunctions::set_(at::Tensor& self) { + caffe2::TypeMeta dtype = self.dtype(); + c10::Storage storage( + c10::Storage::use_byte_size_t(), + 0, + c10_npu::NPUCachingAllocator::get(), + true); + + set_storage_npu_(self, storage, 0, {0}, {}); StorageDescHelper::SetDesc(self); + TORCH_INTERNAL_ASSERT(dtype == self.dtype()); return self; } -at::Tensor& NPUNativeFunctions::set_(at::Tensor& self, const at::Tensor& src) { +at::Tensor& XLANativeFunctions::set_(at::Tensor& self, const at::Tensor& src) { at::TensorImpl* self_ = self.unsafeGetTensorImpl(); at::TensorImpl* src_ = src.unsafeGetTensorImpl(); if (self_ != src_) { set_storage_nd_npu( - self_, - torch_npu::NPUBridge::GetNpuStorageImpl(THTensor_getStoragePtr(src_)), - src_->storage_offset(), - src_->dim(), - THTensor_getSizePtr(src_), - THTensor_getStridePtr(src_)); + self, + src.storage(), + src.storage_offset(), + src.dim(), + src.sizes(), + src.strides()); } StorageDescHelper::CopyDesc(self, src); return self; diff --git a/torch_npu/csrc/aten/common/StorageSizeNpu.cpp b/torch_npu/csrc/aten/common/StorageSizeNpu.cpp index 37462cf551..1efe150e52 100644 --- a/torch_npu/csrc/aten/common/StorageSizeNpu.cpp +++ b/torch_npu/csrc/aten/common/StorageSizeNpu.cpp @@ -15,13 +15,13 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" namespace at_npu { namespace native { - int64_t NPUNativeFunctions::get_storage_size(const at::Tensor& self) { + int64_t XLANativeFunctions::get_storage_size(const at::Tensor& self) { auto sizes = torch_npu::NPUBridge::GetNpuStorageImpl(self)->npu_desc_.storage_sizes_; int64_t n = 1; for (auto s : sizes) { diff --git a/torch_npu/csrc/aten/common/TensorFactories.cpp b/torch_npu/csrc/aten/common/TensorFactories.cpp index bca78bc3cc..2160ad6e61 100644 --- a/torch_npu/csrc/aten/common/TensorFactories.cpp +++ b/torch_npu/csrc/aten/common/TensorFactories.cpp @@ -39,7 +39,7 @@ #include "torch_npu/csrc/framework/InferFormat.h" #include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUTensorImpl.h" #include "torch_npu/csrc/framework/contiguous/ContiguousOpt.h" #include "torch_npu/csrc/core/NPUBridge.h" @@ -105,7 +105,7 @@ namespace at_npu return; } - int64_t new_storage_size_bytes = at::prod_intlist(size) * data_type.itemsize(); + int64_t new_storage_size_bytes = c10::multiply_integers(size) * data_type.itemsize(); TORCH_CHECK( storage_size_bytes <= new_storage_size_bytes, "setStorage: sizes ", @@ -124,16 +124,16 @@ namespace at_npu } } // namespace - at::Tensor NPUNativeFunctions::scalar_tensor(c10::Scalar s, c10::optional dtype, c10::optional layout, - c10::optional device, c10::optional pin_memory) { - at::tracer::impl::NoTracerDispatchMode tracer_guard; - at::AutoNonVariableTypeMode non_var_type_mode(true); - auto result = at::native::empty_cpu({}, dtype, layout, c10::make_optional(c10::Device(at::kCPU)), pin_memory); - at::native::fill_(result, s); - return result.to(at::device(at_npu::key::NativeDeviceType)); - } + // at::Tensor XLANativeFunctions::scalar_tensor(c10::Scalar s, c10::optional dtype, c10::optional layout, + // c10::optional device, c10::optional pin_memory) { + // at::tracer::impl::NoTracerDispatchMode tracer_guard; + // at::AutoNonVariableTypeMode non_var_type_mode(true); + // auto result = at::native::empty_cpu({}, dtype, layout, c10::make_optional(c10::Device(at::kCPU)), pin_memory); + // at::native::fill_(result, s); + // return result.to(at::device(at_npu::key::NativeDeviceType)); + // } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ empty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - at::Tensor NPUNativeFunctions::empty(c10::IntArrayRef size, + at::Tensor XLANativeFunctions::empty(c10::IntArrayRef size, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -144,7 +144,7 @@ namespace at_npu TORCH_CHECK(!pinned_memory_or_default(pin_memory_opt), "Only dense CPU tensors can be pinned"); check_size_nonnegative(size); c10::Allocator *allocator = c10_npu::NPUCachingAllocator::get(); - int64_t nelements = at::prod_intlist(size); + int64_t nelements = c10::multiply_integers(size); auto dtype = c10::scalarTypeToTypeMeta(dtype_or_default(dtype_opt)); int64_t size_bytes = nelements * dtype.itemsize(); c10::intrusive_ptr storage_impl = c10::make_intrusive( @@ -312,7 +312,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::empty_like( + at::Tensor XLANativeFunctions::empty_like( const at::Tensor &self, c10::optional dtype_opt, c10::optional layout_opt, @@ -329,7 +329,7 @@ namespace at_npu return at_npu::native::empty_like_npu(self, options, optional_memory_format); } - at::Tensor NPUNativeFunctions::empty_with_format(c10::IntArrayRef size, + at::Tensor XLANativeFunctions::empty_with_format(c10::IntArrayRef size, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -419,7 +419,7 @@ namespace at_npu return tensor; } - at::Tensor NPUNativeFunctions::empty_with_format(c10::IntArrayRef size, + at::Tensor XLANativeFunctions::empty_with_format(c10::IntArrayRef size, c10::optional names, c10::optional dtype_opt, c10::optional layout_opt, @@ -468,7 +468,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::empty_strided( + at::Tensor XLANativeFunctions::empty_strided( c10::IntArrayRef size, c10::IntArrayRef stride, c10::optional dtype_opt, @@ -479,7 +479,7 @@ namespace at_npu check_size_nonnegative(size); checkInBoundsForStorage(size, stride, dtype_opt); c10::optional optional_memory_format = c10::nullopt; - auto t = NPUNativeFunctions::empty({0}, + auto t = XLANativeFunctions::empty({0}, dtype_opt, layout_opt, device_opt, @@ -513,7 +513,7 @@ namespace at_npu } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ blackman_window ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - at::Tensor NPUNativeFunctions::blackman_window(int64_t window_length, + at::Tensor XLANativeFunctions::blackman_window(int64_t window_length, bool periodic, c10::optional dtype_opt, c10::optional layout_opt, @@ -544,7 +544,7 @@ namespace at_npu return periodic ? window.narrow(0, 0, window_length - 1) : window; } - at::Tensor NPUNativeFunctions::blackman_window(int64_t window_length, + at::Tensor XLANativeFunctions::blackman_window(int64_t window_length, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -554,7 +554,7 @@ namespace at_npu } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ bartlett_window ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - at::Tensor NPUNativeFunctions::bartlett_window( + at::Tensor XLANativeFunctions::bartlett_window( int64_t window_length, bool periodic, c10::optional dtype_opt, @@ -587,7 +587,7 @@ namespace at_npu return periodic ? window.narrow(0, 0, window_length - 1) : window; } - at::Tensor NPUNativeFunctions::bartlett_window(int64_t window_length, + at::Tensor XLANativeFunctions::bartlett_window(int64_t window_length, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -598,7 +598,7 @@ namespace at_npu } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ hann_window ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - at::Tensor NPUNativeFunctions::hann_window( + at::Tensor XLANativeFunctions::hann_window( int64_t window_length, bool periodic, c10::optional dtype_opt, @@ -616,7 +616,7 @@ namespace at_npu return at::hamming_window(window_length, periodic, 0.5, 0.5, options); } - at::Tensor NPUNativeFunctions::hann_window(int64_t window_length, + at::Tensor XLANativeFunctions::hann_window(int64_t window_length, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -626,7 +626,7 @@ namespace at_npu } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ hamming_window ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - at::Tensor NPUNativeFunctions::hamming_window( + at::Tensor XLANativeFunctions::hamming_window( int64_t window_length, bool periodic, double alpha, @@ -663,7 +663,7 @@ namespace at_npu return periodic ? window.narrow(0, 0, window_length - 1) : window; } - at::Tensor NPUNativeFunctions::hamming_window( + at::Tensor XLANativeFunctions::hamming_window( int64_t window_length, bool periodic, double alpha, @@ -675,7 +675,7 @@ namespace at_npu return hamming_window(window_length, periodic, alpha, 0.46, dtype_opt, layout_opt, device_opt, pin_memory_opt); } - at::Tensor NPUNativeFunctions::hamming_window( + at::Tensor XLANativeFunctions::hamming_window( int64_t window_length, bool periodic, c10::optional dtype_opt, @@ -686,7 +686,7 @@ namespace at_npu return hamming_window(window_length, periodic, 0.54, dtype_opt, layout_opt, device_opt, pin_memory_opt); } - at::Tensor NPUNativeFunctions::hamming_window(int64_t window_length, + at::Tensor XLANativeFunctions::hamming_window(int64_t window_length, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -730,7 +730,7 @@ namespace at_npu #undef TENSOR // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ clone ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - at::Tensor NPUNativeFunctions::clone(const at::Tensor &src, + at::Tensor XLANativeFunctions::clone(const at::Tensor &src, c10::optional format) { OptimizationCases opt_cases{"reshape", "slice"}; @@ -756,25 +756,25 @@ namespace at_npu } } - at::Tensor NPUNativeFunctions::full( - c10::IntArrayRef size, - c10::Scalar fill_value, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) - { - c10::TensorOptions options = c10::TensorOptions().dtype(dtype_opt) - .device(device_opt) - .layout(layout_opt) - .pinned_memory(pin_memory_opt); - TORCH_CHECK( - options.layout() != at::kSparse, - "full(...) is not implemented for sparse layout"); + // at::Tensor XLANativeFunctions::full( + // c10::IntArrayRef size, + // c10::Scalar fill_value, + // c10::optional dtype_opt, + // c10::optional layout_opt, + // c10::optional device_opt, + // c10::optional pin_memory_opt) + // { + // c10::TensorOptions options = c10::TensorOptions().dtype(dtype_opt) + // .device(device_opt) + // .layout(layout_opt) + // .pinned_memory(pin_memory_opt); + // TORCH_CHECK( + // options.layout() != at::kSparse, + // "full(...) is not implemented for sparse layout"); - auto result = OpPreparation::ApplyTensorWithSizes(size, options); - return result.fill_(fill_value); - } + // auto result = OpPreparation::ApplyTensorWithSizes(size, options); + // return result.fill_(fill_value); + // } } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/common/TensorFactories.h b/torch_npu/csrc/aten/common/TensorFactories.h index 3b7e243fa9..c05f660b25 100644 --- a/torch_npu/csrc/aten/common/TensorFactories.h +++ b/torch_npu/csrc/aten/common/TensorFactories.h @@ -21,8 +21,8 @@ namespace at_npu { namespace native { -inline void check_size_nonnegative(c10::IntArrayRef& size) { - for (auto& x : size) { +inline void check_size_nonnegative(c10::IntArrayRef size) { + for (auto x : size) { TORCH_CHECK( x >= 0, "Trying to create tensor with negative dimension ", diff --git a/torch_npu/csrc/aten/common/TensorProperties.cpp b/torch_npu/csrc/aten/common/TensorProperties.cpp index 878a74a6bb..e5f1696f44 100644 --- a/torch_npu/csrc/aten/common/TensorProperties.cpp +++ b/torch_npu/csrc/aten/common/TensorProperties.cpp @@ -16,12 +16,12 @@ #include #include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor NPUNativeFunctions::contiguous(const at::Tensor& self, c10::MemoryFormat memory_format) { +at::Tensor XLANativeFunctions::contiguous(const at::Tensor& self, c10::MemoryFormat memory_format) { if (self.is_contiguous(memory_format)) { return self; } diff --git a/torch_npu/csrc/aten/common/TensorShape.cpp b/torch_npu/csrc/aten/common/TensorShape.cpp index b306c1ef3b..403e9ee594 100644 --- a/torch_npu/csrc/aten/common/TensorShape.cpp +++ b/torch_npu/csrc/aten/common/TensorShape.cpp @@ -32,8 +32,7 @@ #include "torch_npu/csrc/framework/InferFormat.h" #include "torch_npu/csrc/aten/common/FormatCastHelper.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/aten/common/ResizeNpu.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "third_party/acl/inc/acl/acl_base.h" @@ -67,7 +66,7 @@ at::Tensor alias_with_sizes_and_strides_npu( return self_; } -at::Tensor NPUNativeFunctions::view(const at::Tensor& self, c10::IntArrayRef size) { +at::Tensor XLANativeFunctions::view(const at::Tensor& self, c10::IntArrayRef size) { auto inferred_size = at::infer_size(size, self.numel()); auto stride = at::detail::computeStride(self.sizes(), self.strides(), inferred_size); @@ -84,7 +83,7 @@ at::Tensor NPUNativeFunctions::view(const at::Tensor& self, c10::IntArrayRef siz return alias_with_sizes_and_strides_npu(dst, inferred_size, stride_value); } -at::Tensor NPUNativeFunctions::as_strided( +at::Tensor XLANativeFunctions::as_strided( const at::Tensor& self, c10::IntArrayRef size, c10::IntArrayRef stride, @@ -98,21 +97,22 @@ at::Tensor NPUNativeFunctions::as_strided( c10::Storage(dst.storage()), dst.key_set(), dst.dtype()); - setStrided(result, size, stride, storage_offset); + at::native::setStrided(result, size, stride, storage_offset); return result; } -at::Tensor& NPUNativeFunctions::as_strided_( - at::Tensor& self, +const at::Tensor& XLANativeFunctions::as_strided_( + const at::Tensor& self, c10::IntArrayRef size, c10::IntArrayRef stride, c10::optional storage_offset_) { + at::Tensor reuslt = self; if (InferFormat::IsDefiniteTensorWhenMetaDataChanges(self, size)) { - self = FormatCastHelper::CovertSelfToBaseFormat(self); + reuslt = FormatCastHelper::CovertSelfToBaseFormat(self); } - auto storage_offset = storage_offset_.value_or(self.storage_offset()); - at::native::setStrided(self, size, stride, storage_offset); - return self; + auto storage_offset = storage_offset_.value_or(reuslt.storage_offset()); + at::native::setStrided(reuslt, size, stride, storage_offset); + return reuslt; } } // namespace native diff --git a/torch_npu/csrc/aten/common/ToKernelNpu.cpp b/torch_npu/csrc/aten/common/ToKernelNpu.cpp index 07404dd2fe..2aedf52cdf 100644 --- a/torch_npu/csrc/aten/common/ToKernelNpu.cpp +++ b/torch_npu/csrc/aten/common/ToKernelNpu.cpp @@ -20,7 +20,7 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -71,91 +71,91 @@ static inline at::Tensor to_impl_npu( return r; } -at::Tensor NPUNativeFunctions::to( - const at::Tensor& self, - c10::optional dtype, - c10::optional layout, - c10::optional device, - c10::optional pin_memory, - bool non_blocking, - bool copy, - c10::optional optional_memory_format) { - TORCH_CHECK( - !optional_memory_format.has_value(), - "NPU not support specify memory_format."); - c10::TensorOptions options_; - options_ = options_.dtype(dtype) - .layout(layout) - .device(device); - TORCH_CHECK( - !(options_.has_memory_format() && optional_memory_format.has_value()), - "Cannot set memory_format both in c10::TensorOptions and explicit argument; please delete " - "the redundant setter."); - auto options = - options_.merge_in(c10::TensorOptions().memory_format(optional_memory_format)); +// at::Tensor XLANativeFunctions::to( +// const at::Tensor& self, +// c10::optional dtype, +// c10::optional layout, +// c10::optional device, +// c10::optional pin_memory, +// bool non_blocking, +// bool copy, +// c10::optional optional_memory_format) { +// TORCH_CHECK( +// !optional_memory_format.has_value(), +// "NPU not support specify memory_format."); +// c10::TensorOptions options_; +// options_ = options_.dtype(dtype) +// .layout(layout) +// .device(device); +// TORCH_CHECK( +// !(options_.has_memory_format() && optional_memory_format.has_value()), +// "Cannot set memory_format both in c10::TensorOptions and explicit argument; please delete " +// "the redundant setter."); +// auto options = +// options_.merge_in(c10::TensorOptions().memory_format(optional_memory_format)); - TORCH_CHECK( - options.requires_grad_opt() == c10::nullopt, - "to(options) expects unset requires_grad flag, but got " - "options.requires_grad set as ", - options.requires_grad()); +// TORCH_CHECK( +// options.requires_grad_opt() == c10::nullopt, +// "to(options) expects unset requires_grad flag, but got " +// "options.requires_grad set as ", +// options.requires_grad()); - TORCH_CHECK( - !options.has_layout() || self.layout() == options.layout(), - "to(options) doesn't support converting to a different layout, " - "but got self.layout being ", - self.layout(), - " and options.layout set as ", - options.layout()); +// TORCH_CHECK( +// !options.has_layout() || self.layout() == options.layout(), +// "to(options) doesn't support converting to a different layout, " +// "but got self.layout being ", +// self.layout(), +// " and options.layout set as ", +// options.layout()); - if (options.has_device()) { - options = options.device(ensure_has_index(options.device())); - } - auto specified_options = self.options().merge_in(options); - return to_impl_npu(self, specified_options, non_blocking, copy); -} +// if (options.has_device()) { +// options = options.device(ensure_has_index(options.device())); +// } +// auto specified_options = self.options().merge_in(options); +// return to_impl_npu(self, specified_options, non_blocking, copy); +// } -at::Tensor NPUNativeFunctions::to( - const at::Tensor& self, - c10::Device device, - at::ScalarType dtype, - bool non_blocking, - bool copy, - c10::optional optional_memory_format) { - device = ensure_has_index(device); - return to_impl_npu( - self, - self.options().device(device).dtype(dtype).memory_format( - optional_memory_format), - non_blocking, - copy); -} +// at::Tensor XLANativeFunctions::to( +// const at::Tensor& self, +// c10::Device device, +// at::ScalarType dtype, +// bool non_blocking, +// bool copy, +// c10::optional optional_memory_format) { +// device = ensure_has_index(device); +// return to_impl_npu( +// self, +// self.options().device(device).dtype(dtype).memory_format( +// optional_memory_format), +// non_blocking, +// copy); +// } -at::Tensor NPUNativeFunctions::to( - const at::Tensor& self, - at::ScalarType dtype, - bool non_blocking, - bool copy, - c10::optional optional_memory_format) { - if (self.dtype() == dtype) { - return self; - } - if (at::ScalarType::Double == dtype) { - TORCH_WARN_ONCE("Unsupport Double dtype now, replace with float."); - } - dtype = (at::ScalarType::Double == dtype) ? at::ScalarType::Float : dtype; - return NPUNativeFunctions::npu_dtype_cast(self, dtype); -} +// at::Tensor XLANativeFunctions::to( +// const at::Tensor& self, +// at::ScalarType dtype, +// bool non_blocking, +// bool copy, +// c10::optional optional_memory_format) { +// if (self.dtype() == dtype) { +// return self; +// } +// if (at::ScalarType::Double == dtype) { +// TORCH_WARN_ONCE("Unsupport Double dtype now, replace with float."); +// } +// dtype = (at::ScalarType::Double == dtype) ? at::ScalarType::Float : dtype; +// return XLANativeFunctions::npu_dtype_cast(self, dtype); +// } -at::Tensor NPUNativeFunctions::to( - const at::Tensor& self, - const at::Tensor& other, - bool non_blocking, - bool copy, - c10::optional optional_memory_format) { - auto options = other.options(); - return to_impl_npu( - self, options.memory_format(optional_memory_format), non_blocking, copy); -} +// at::Tensor XLANativeFunctions::to( +// const at::Tensor& self, +// const at::Tensor& other, +// bool non_blocking, +// bool copy, +// c10::optional optional_memory_format) { +// auto options = other.options(); +// return to_impl_npu( +// self, options.memory_format(optional_memory_format), non_blocking, copy); +// } } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/npu_native_functions.yaml b/torch_npu/csrc/aten/npu_native_functions.yaml index 3259381754..6d32b40f6a 100644 --- a/torch_npu/csrc/aten/npu_native_functions.yaml +++ b/torch_npu/csrc/aten/npu_native_functions.yaml @@ -26,6 +26,9 @@ supported: - align_to.ellipsis_idx - align_as - align_tensors + - ceil + - ceil_ + - ceil.out - refine_names - _use_cudnn_ctc_loss - _cudnn_ctc_loss @@ -66,18 +69,25 @@ supported: - sgn.out - real - imag - - conj - - conj.out - - _conj - acos - acos_ - acos.out - arccos - arccos_ - arccos.out - - avg_pool1d - adaptive_avg_pool1d - adaptive_max_pool1d + - adaptive_avg_pool2d.out + - native_batch_norm + - native_batch_norm.out + - native_batch_norm_backward + - record_stream + - slow_conv_transpose2d.out + - slow_conv_transpose2d + - slow_conv3d.out + - slow_conv3d + - slow_conv_transpose3d.out + - slow_conv_transpose3d - add.Tensor - add_.Tensor - add.out @@ -89,864 +99,113 @@ supported: - addmv - addmv_ - addmv.out - - _addmv_impl_ - - addr - - addr_ - - addr.out - - affine_grid_generator - - affine_grid_generator_backward - - all.dim - - all.out - - allclose - - any.dim - - any.out - - arange - - arange.start - - arange.start_step - - arange.out - - arange.start_out - - _dim_arange - - argmax - - argmax.out - - argmin - - argmin.out - - acosh - - acosh_ - - acosh.out - - arccosh - - arccosh_ - - arccosh.out - - asinh - - asinh_ - - asinh.out - - arcsinh - - arcsinh_ - - arcsinh.out - - atanh - - atanh_ - - atanh.out - - arctanh - - arctanh_ - - arctanh.out + - set_.source_Storage + - set_.source_Storage_storage_offset + - set_.source_Tensor + - set_ + - _local_scalar_dense + - resize_ - as_strided - as_strided_ - - asin - - asin_ - - asin.out - - arcsin - - arcsin_ - - arcsin.out - - atan - - atan_ - - atan.out - - arctan - - arctan_ - - arctan.out - - atleast_1d - - atleast_1d.Sequence - - atleast_2d - - atleast_2d.Sequence - - atleast_3d - - atleast_3d.Sequence - - baddbmm - - baddbmm_ - - _baddbmm_mkl_ - - baddbmm.out - - bartlett_window - - bartlett_window.periodic - - batch_norm - - quantized_batch_norm - - _batch_norm_impl_index - - _batch_norm_impl_index_backward - - bernoulli - - bernoulli.out - - bernoulli_.Tensor - - bernoulli_.float - - bernoulli.p - - bilinear - - binary_cross_entropy - - binary_cross_entropy.out - - binary_cross_entropy_backward - - binary_cross_entropy_backward.grad_input - - binary_cross_entropy_with_logits - - binary_cross_entropy_with_logits_backward - - bincount - - bitwise_not - - bitwise_not_ - - bitwise_not.out - - copysign.Tensor - - copysign_.Tensor - - copysign.out - - copysign.Scalar - - copysign_.Scalar - - logical_not - - logical_not_ - - logical_not.out - - logical_xor - - logical_xor_ - - logical_xor.out - - logical_and - - logical_and_ - - logical_and.out - - logical_or - - logical_or_ - - logical_or.out - - blackman_window - - blackman_window.periodic - - bmm - - _bmm - - bmm.out - - _bmm.out - - broadcast_tensors - - broadcast_to - cat - cat.out - cat.names - cat.names_out - - block_diag - - ceil - - ceil_ - - ceil.out - - chain_matmul - - unsafe_chunk - - chunk - - tensor_split.sections - - tensor_split.indices - - tensor_split.tensor_indices_or_sections - - clamp - - clamp_ - - clamp.out - - clamp_max - - clamp_max_ - - clamp_max.out - - clamp_min - - clamp_min_ - - clamp_min.out - - clip - - clip_ - - clip.out - - cudnn_is_acceptable - - complex - - complex.out - - polar - - polar.out - - constant_pad_nd + - _cat + - _cat.out + - clone - contiguous - - convolution - convolution_overrideable - convolution_backward_overrideable - - _convolution - - _convolution_nogroup - - _convolution_double_backward - - conv1d - - conv2d - - conv3d - - conv_tbc - - conv_tbc_backward - - conv_transpose1d - - conv_transpose2d.input - - conv_transpose3d.input - copy_ - _copy_from - - cos - - cos_ - - cos.out - - cosh - - cosh_ - - cosh.out - - cosine_embedding_loss - - count_nonzero.dim_IntList - - count_nonzero - - cudnn_affine_grid_generator - - cudnn_affine_grid_generator_backward - - cudnn_batch_norm - - cudnn_batch_norm_backward - - cudnn_convolution.deprecated - - cudnn_convolution.deprecated2 - - cudnn_convolution - - cudnn_convolution_backward_input - - cudnn_convolution_backward - - cudnn_convolution_backward_weight - - cudnn_convolution_transpose.deprecated - - cudnn_convolution_transpose.deprecated2 - - cudnn_convolution_transpose - - cudnn_convolution_transpose_backward - - cudnn_convolution_transpose_backward_input - - cudnn_convolution_transpose_backward_weight - - cudnn_grid_sampler - - cudnn_grid_sampler_backward - - cummax - - cummax.out - - cummax.dimname - - cummax.dimname_out - - _cummax_helper - - cummin - - cummin.out - - cummin.dimname - - cummin.dimname_out - - _cummin_helper - - cummaxmin_backward - - cumprod - - cumprod_ - - cumprod.out - - cumprod.dimname - - cumprod_.dimname - - cumprod.dimname_out - - cumprod_backward - - cumsum - - cumsum_ - - cumsum.out - - cumsum.dimname - - cumsum_.dimname - - cumsum.dimname_out - - ctc_loss.IntList - - ctc_loss.Tensor - - _ctc_loss - - _ctc_loss_backward - - diag_embed - - diagflat - - diagonal - - diagonal.Dimname - - diagonal_backward - - fill_diagonal_ - - diff - - diff.out - div.Tensor - div_.Tensor - div.out - div.Scalar - div_.Scalar - - div.Tensor_mode - - div_.Tensor_mode - - div.out_mode - - div.Scalar_mode - - div_.Scalar_mode - - divide.Tensor - - divide_.Tensor - - divide.out - - divide.Scalar - - divide_.Scalar - - divide.Tensor_mode - - divide_.Tensor_mode - - divide.out_mode - - divide.Scalar_mode - - divide_.Scalar_mode - - true_divide.Tensor - - true_divide_.Tensor - - true_divide.out - - true_divide.Scalar - - true_divide_.Scalar - - dot - - dot.out - - vdot - - vdot.out - - einsum - - embedding - - embedding_backward - - embedding_dense_backward - - embedding_renorm_ - - embedding_sparse_backward - - _embedding_bag_forward_only - - _rowwise_prune - - row_stack - - row_stack.out - - embedding_bag - - _embedding_bag - - _embedding_bag_backward - - _embedding_bag_sparse_backward - - _embedding_bag_dense_backward - - _embedding_bag_per_sample_weights_backward - - empty_meta + - resize_as_ - empty.memory_format - - new_empty - - new_empty_strided - new_full - new_zeros - - _empty_affine_quantized - - _empty_per_channel_affine_quantized - resize_ - - empty_quantized - empty.out - empty_like - empty_strided - - erf - - erf_ - - erf.out - - erfc - - erfc_ - - erfc.out - - exp - - exp_ - - exp.out - - exp2 - - exp2_ - - exp2.out - - expm1 - - expm1_ - - expm1.out - - expand - - expand_as - - eye - - eye.m - - eye.out - - eye.m_out - - flatten.using_ints - - flatten.named_out_dim - - flatten.using_names - - flatten.DimnameList - - unflatten.int - - unflatten.Dimname - fill_.Scalar - fill_.Tensor - - floor - - floor_ - - floor.out - - floor_divide - - floor_divide_.Tensor - - floor_divide.out - - floor_divide.Scalar - - floor_divide_.Scalar - - frac - - frac_ - - frac.out - - full.names - - full - - full.out - - full_like - - from_file - - gcd.out - - gcd - - gcd_ - - lcm.out - - lcm - - lcm_ - - grid_sampler - - grid_sampler_2d - - grid_sampler_2d_backward - - _grid_sampler_2d_cpu_fallback - - _grid_sampler_2d_cpu_fallback_backward - - grid_sampler_3d - - grid_sampler_3d_backward - hann_window - hann_window.periodic - hamming_window - hamming_window.periodic - hamming_window.periodic_alpha - hamming_window.periodic_alpha_beta - - kaiser_window - - kaiser_window.periodic - - kaiser_window.beta - - hinge_embedding_loss - - group_norm - - native_group_norm - - native_group_norm_backward - - _fft_r2c - - _fft_r2c.out - - _fft_c2r - - _fft_c2r.out - - _fft_c2c - - _fft_c2c.out - - _cufft_get_plan_cache_size - - _cufft_get_plan_cache_max_size - - _cufft_set_plan_cache_max_size - - _cufft_clear_plan_cache - - index.Tensor - - index_copy_ - - index_copy - - index_copy_.dimname - - index_copy.dimname - - index_put_ - - index_put - - _index_put_impl_ - - instance_norm - - inverse - - inverse.out - - _inverse_helper - - isclose - - isnan - - is_distributed - - is_floating_point - - is_complex - - isreal - - is_nonzero - - is_same_size - - is_signed - - kl_div - - kl_div_backward - - kron - - kron.out - - kthvalue - - kthvalue.values - - kthvalue.dimname - - kthvalue.dimname_out - - layer_norm - - native_layer_norm - - native_layer_norm_backward - - nan_to_num - - nan_to_num_ - - nan_to_num.out - - linear - - mkldnn_linear - - mkldnn_linear_backward_input - - mkldnn_linear_backward_weights - - mkldnn_linear_backward - - fbgemm_linear_int8_weight_fp32_activation - - fbgemm_linear_int8_weight - - fbgemm_linear_quantize_weight - - fbgemm_pack_gemm_matrix_fp16 - - fbgemm_linear_fp16_weight_fp32_activation - - fbgemm_linear_fp16_weight - - fbgemm_pack_quantized_matrix - - fbgemm_pack_quantized_matrix.KN - - ldexp.Tensor - - ldexp_ - - ldexp.out - - linspace - - linspace.out - - log - - log_ - - log.out - - log10 - - log10_ - - log10.out - - log1p - - log1p_ - - log1p.out - - log2 - - log2_ - - log2.out - - logaddexp.out - - logaddexp - - logaddexp2.out - - logaddexp2 - - xlogy.Tensor - - xlogy.Scalar_Self - - xlogy.Scalar_Other - - xlogy_.Tensor - - xlogy_.Scalar_Other - - xlogy.OutTensor - - xlogy.OutScalar_Self - - xlogy.OutScalar_Other - - logdet - - logspace - - logspace.out + - bartlett_window + - bartlett_window.periodic + - blackman_window - log_softmax.int - log_softmax.Dimname - _log_softmax - _log_softmax_backward_data - - _logcumsumexp - - _logcumsumexp.out - - logcumsumexp - - logcumsumexp.out - - logcumsumexp.dimname - - logcumsumexp.dimname_out - - logsumexp - - logsumexp.out - - logsumexp.names - - logsumexp.names_out - - margin_ranking_loss - - matmul - - matmul.out - - matrix_rank.tol - - matrix_rank - - matrix_power - - matrix_exp - - matrix_exp_backward - - _aminmax - - _aminmax.dim - - _compute_linear_combination - - _compute_linear_combination.out + - amin + - amin.out + - max - max.dim - max.dim_max - max.names_dim - max.names_dim_max - - value_selecting_reduction_backward - amax - amax.out - - max_pool1d_with_indices - - max_pool1d - - max_pool2d - - mkldnn_max_pool2d - - mkldnn_max_pool3d - - quantized_max_pool1d - - quantized_max_pool2d - - max_pool3d - mean - mean.dim - mean.out - mean.names_dim - mean.names_out - - median - - median.dim - - median.dim_values - - median.names_dim - - median.names_dim_values - - nanmedian - - nanmedian.dim - - nanmedian.dim_values - - nanmedian.names_dim - - nanmedian.names_dim_values - min.dim - min.dim_min - min.names_dim - min.names_dim_min - - amin - - amin.out - - mkldnn_convolution - - mkldnn_convolution_backward_input - - mkldnn_convolution_backward_weights - - mkldnn_convolution_backward - - miopen_batch_norm - - miopen_batch_norm_backward - - miopen_convolution - - miopen_convolution_backward_input - - miopen_convolution_backward - - miopen_convolution_backward_bias - - miopen_convolution_backward_weight - - miopen_convolution_transpose - - miopen_convolution_transpose_backward - - miopen_convolution_transpose_backward_input - - miopen_convolution_transpose_backward_weight - - miopen_depthwise_convolution - - miopen_depthwise_convolution_backward_input - - miopen_depthwise_convolution_backward - - miopen_depthwise_convolution_backward_weight - - miopen_rnn - - miopen_rnn_backward - - mm - - mm.out - - _sparse_mm - - _sparse_sparse_matmul - - _sparse_matrix_mask_helper - - mode - - mode.values - - mode.dimname - - mode.dimname_out + - min + - min.out + - minimum + - minimum.out + - blackman_window.periodic - mul.Tensor - mul_.Tensor - mul.out - mul.Scalar - mul_.Scalar - - multiply.Tensor - - multiply_.Tensor - - multiply.out - - multiply.Scalar - - multiply_.Scalar - - mv - - mv.out - - mvlgamma - - mvlgamma_ - - narrow_copy - - narrow_copy.out - - narrow - - narrow.Tensor - - native_batch_norm - - native_batch_norm.out - - batch_norm_stats - - batch_norm_elemt - - batch_norm_elemt.out - - batch_norm_gather_stats - - batch_norm_gather_stats_with_counts - - native_batch_norm_backward - - batch_norm_backward_reduce - - batch_norm_backward_elemt - - batch_norm_update_stats - - is_vulkan_available - - _nnpack_available - - _nnpack_spatial_convolution - - _nnpack_spatial_convolution_backward - - _nnpack_spatial_convolution_backward_input - - _nnpack_spatial_convolution_backward_weight - - ones.names - - ones - - ones.out - - ones_like - - pairwise_distance - - cdist - - _euclidean_dist - - _cdist_forward - - _cdist_backward - - pdist - - _pdist_forward - - _pdist_backward - - cosine_similarity - - permute - - movedim.intlist - - movedim.int - - moveaxis.intlist - - moveaxis.int - - numpy_T - - pixel_shuffle - - pixel_unshuffle - - channel_shuffle - - is_pinned - - pin_memory - - pinverse - - poisson_nll_loss - - rad2deg - - rad2deg_ - - rad2deg.out - - deg2rad - - deg2rad_ - - deg2rad.out - - scalar_tensor - - rand.names - - rand.generator_with_names - - rand - - rand.generator - - rand.out - - rand.generator_out - - rand_like - - randint - - randint.generator - - randint.low - - randint.low_generator - - randint.out - - randint.generator_out - - randint.low_out - - randint.low_generator_out - - randint_like - - randint_like.low_dtype - - randn - - randn.generator - - randn.names - - randn.generator_with_names - - randn.out - - randn.generator_out - - randn_like - - randperm - - randperm.generator - - randperm.out - - randperm.generator_out - - range.step - - range - - range.out - - ravel - - reciprocal - - reciprocal_ - - reciprocal.out - neg - neg_ - neg.out - - negative - - negative_ - - negative.out - - repeat - - repeat_interleave.self_int - - reshape - - _mkldnn_reshape - - reshape_as - - round - - round_ - - round.out - - rrelu - - rrelu_ + - reciprocal + - reciprocal_ + - reciprocal.out + - mse_loss.out + - mse_loss + - mse_loss_backward.grad_input + - mse_loss_backward - relu - relu_ - - prelu - - prelu_backward - - gelu - - gelu_backward - - infinitely_differentiable_gelu_backward - - hardshrink - - hardshrink_backward - - rsqrt - - rsqrt_ - - rsqrt.out - - select.Dimname - - select.int - - select_backward - - selu - - selu_ - - celu - - celu_ - - silu - - silu_ - - silu.out - - silu_backward - - sigmoid - - sigmoid_ - - sigmoid.out - - logit - - logit_ - - logit.out - - sin - - sin_ - - sin.out - - sinc - - sinc_ - - sinc.out - - sinh - - sinh_ - - sinh.out - - detach - - detach_ - - size.int - - size.Dimname - slice.Tensor - slice_backward - - slogdet - - smm - softmax.int - softmax.Dimname - _softmax - _softmax_backward_data - - unsafe_split.Tensor - - split.Tensor - - unsafe_split_with_sizes - - split_with_sizes - - squeeze - - squeeze.dim - - squeeze.dimname - - squeeze_ - - squeeze_.dim - - squeeze_.dimname - - sspaddmm - - sspaddmm.out - - stack - - stack.out - - _stack - - _stack.out - - hstack - - hstack.out - - vstack - - vstack.out - - dstack - - dstack.out - - stft - - istft - - stride.int - - stride.Dimname - sum - sum.dim_IntList - sum.dim_DimnameList - sum.IntList_out - sum.DimnameList_out - - nansum - - nansum.dim_IntList - - nansum.IntList_out - - sum_to_size - sqrt - sqrt_ - sqrt.out - - square - - square_ - - std - - std.dim - - std_mean - - std_mean.dim - - std_mean.names_dim - - std.out - - std.names_dim - - std.names_out - - prod - - prod.dim_int - - prod.int_out - - prod.dim_Dimname - - prod.Dimname_out - - t - - t_ - - tan - - tan_ - - tan.out - - tanh - - tanh_ - - tanh.out - - tensordot - - tensordot.out - threshold - threshold_ - threshold.out - threshold_backward - - tile - - transpose.int - - transpose.Dimname - - _mkldnn_transpose - - transpose_ - - _mkldnn_transpose_ - one_hot - - flip - - fliplr - - flipud - - roll - - rot90 - - trapz.x - - trapz.dx - - _trilinear - - triplet_margin_loss - - trunc - - trunc_ - - trunc.out - - fix - - fix_ - - fix.out - - type_as - - _has_compatible_shallow_copy_type - - _unique - - unique_dim - - unique_consecutive - - unique_dim_consecutive - - _unique2 - - _unsafe_view - - unsqueeze - - unsqueeze_ - - vander - - var - - var.dim - - var.out - - var.names_dim - - var.names_out - - var_mean - - var_mean.dim - - var_mean.names_dim - - view_as - - where.self - - where - - _s_where - - norm_except_dim - - _weight_norm - - _weight_norm_cuda_interface - - _weight_norm_cuda_interface_backward - - _weight_norm_differentiable_backward - - zeros.names - - zeros - - zeros.out - - zeros_like - - _standard_gamma_grad - - _standard_gamma - - _dirichlet_grad - - _sample_dirichlet - - poisson - - binomial - - native_norm - - native_norm.ScalarOpt_dim_dtype - - _sparse_sum - - _sparse_sum.dtype - - _sparse_sum.dim - - _sparse_sum.dim_dtype - - _sparse_sum_backward - - _sparse_softmax.int - - _sparse_softmax.Dimname - - _sparse_softmax - - _sparse_softmax_backward_data - - _sparse_log_softmax.int - - _sparse_log_softmax.Dimname - - _sparse_log_softmax - - _sparse_log_softmax_backward_data - - norm.ScalarOpt_dtype - - norm.Scalar - - norm.ScalarOpt_dim_dtype - - norm.ScalarOpt_dim - - norm.dtype_out - - norm.out - - frobenius_norm - - frobenius_norm.dim - - frobenius_norm.out - - nuclear_norm - - nuclear_norm.out - - nuclear_norm.dim - - nuclear_norm.dim_out - - clone - resize_as_ - zero_ - sub.out @@ -954,441 +213,27 @@ supported: - sub_.Tensor - sub.Scalar - sub_.Scalar - - subtract.out - - subtract.Tensor - - subtract_.Tensor - - subtract.Scalar - - subtract_.Scalar + - addcdiv_ + - addcdiv.out + - addcdiv + - addcmul.out + - addcmul + - addcmul_ - rsub.Tensor - - heaviside.out - - heaviside - - heaviside_ - rsub.Scalar - - _sparse_addmm - addmm.out - addmm - addmm_ - - sparse_coo_tensor.size - - sparse_coo_tensor.indices - - sparse_coo_tensor.indices_size - - _sparse_coo_tensor_unsafe - - _validate_sparse_coo_tensor_args - - _sparse_coo_tensor_with_dims - - _sparse_coo_tensor_with_dims_and_tensors - - sparse_resize_ - - sparse_resize_and_clear_ - - sparse_mask - - to_dense - - to_dense_backward - - sparse_dim - - _dimI - - dense_dim - - _dimV - - _nnz - - coalesce - - is_coalesced - - _indices - - _values - - _coalesced_ - - indices - - values - - hspmm.out - - hspmm - - copy_sparse_to_sparse_ - - unbind.int - - unbind.Dimname - - to_sparse.sparse_dim - - to_sparse - - to_mkldnn - - mkldnn_reorder_conv2d_weight - - mkldnn_reorder_conv3d_weight - - to_mkldnn_backward - - quantize_per_tensor - - quantize_per_channel - - dequantize.self - - dequantize.tensors - - q_scale - - q_zero_point - - q_per_channel_scales - - q_per_channel_zero_points - - q_per_channel_axis - - int_repr - - _make_per_tensor_quantized_tensor - - _make_per_channel_quantized_tensor - - qscheme - - fake_quantize_per_tensor_affine - - fake_quantize_per_tensor_affine_cachemask - - fake_quantize_per_tensor_affine_cachemask_backward - - _fake_quantize_learnable_per_tensor_affine - - _fake_quantize_learnable_per_tensor_affine_backward - - fake_quantize_per_channel_affine - - fake_quantize_per_channel_affine_cachemask - - fake_quantize_per_channel_affine_cachemask_backward - - _fake_quantize_learnable_per_channel_affine - - _fake_quantize_learnable_per_channel_affine_backward - - _choose_qparams_per_tensor - - _saturate_weight_to_fp16 - - choose_qparams_optimized - - to.dtype_layout - - to.device - - to.dtype - - to.other - - meshgrid - - cartesian_prod - - combinations - - item - - result_type.Tensor - - result_type.Scalar - - result_type.Scalar_Tensor - - result_type.Scalar_Scalar - - can_cast - - promote_types - - _local_scalar_dense - - _thnn_fused_lstm_cell - - _thnn_fused_lstm_cell_backward - - _thnn_differentiable_lstm_cell_backward - - _thnn_fused_gru_cell - - _thnn_fused_gru_cell_backward - - _thnn_differentiable_gru_cell_backward - - lstm.input - - lstm.data - - gru.input - - rnn_tanh.input - - rnn_tanh.data - - rnn_relu.input - - rnn_relu.data - - lstm_cell - - gru_cell - - rnn_tanh_cell - - rnn_relu_cell - - quantized_gru_cell - - quantized_rnn_relu_cell - - quantized_rnn_tanh_cell - - _pack_padded_sequence - - _pack_padded_sequence_backward - - _pad_packed_sequence - set_.source_Storage - set_.source_Storage_storage_offset - set_.source_Tensor - set_ - - is_set_to - - masked_fill_.Scalar - - masked_fill.Scalar - - masked_fill_.Tensor - - masked_fill.Tensor - - masked_scatter_ - - masked_scatter - view - - put_ - - index_add_ - - index_add - - index_add.dimname - - index_fill_.int_Scalar - - index_fill.int_Scalar - - index_fill_.int_Tensor - - index_fill.int_Tensor - - scatter_.src - - scatter.src - - scatter_.value - - scatter.value - - scatter.dimname_src - - scatter.dimname_value - - scatter_add_ - - scatter_add - - scatter_add.dimname - - eq_.Scalar - - eq_.Tensor - - bitwise_and.Tensor_out - - bitwise_and.Scalar_out - - bitwise_and.Scalar - - bitwise_and.Tensor - - bitwise_and_.Scalar - - bitwise_and_.Tensor - - __and__.Scalar - - __and__.Tensor - - __iand__.Scalar - - __iand__.Tensor - - bitwise_or.Tensor_out - - bitwise_or.Scalar_out - - bitwise_or.Scalar - - bitwise_or.Tensor - - bitwise_or_.Scalar - - bitwise_or_.Tensor - - __or__.Scalar - - __or__.Tensor - - __ior__.Scalar - - __ior__.Tensor - - bitwise_xor.Tensor_out - - bitwise_xor.Scalar_out - - bitwise_xor.Scalar - - bitwise_xor.Tensor - - bitwise_xor_.Scalar - - bitwise_xor_.Tensor - - __xor__.Scalar - - __xor__.Tensor - - __ixor__.Scalar - - __ixor__.Tensor - - __lshift__.Scalar - - __lshift__.Tensor - - __ilshift__.Scalar - - __ilshift__.Tensor - - __rshift__.Scalar - - __rshift__.Tensor - - __irshift__.Scalar - - __irshift__.Tensor - - atan2_ - - tril_ - - triu_ - - digamma_ - - polygamma_ - - renorm_ - - lerp_.Scalar - - lerp_.Tensor - - fmod_.Scalar - - fmod_.Tensor - - remainder_.Scalar - - remainder_.Tensor - - addbmm_ - - addbmm.out - - addbmm - - addcdiv_ - - random_.from - - random_.to - - random_ - - uniform_ - - cauchy_ - - log_normal_ - - exponential_ - - geometric_ - - diag.out - - diag - - diag_backward - - cross.out - - cross - - triu.out - - triu - - tril.out - - tril - - tril_indices - - triu_indices - - trace - - trace_backward - - ne.Scalar_out - - ne.Scalar - - ne.Tensor_out - - ne.Tensor - - ne_.Scalar - - ne_.Tensor - - not_equal.Scalar_out - - not_equal.Scalar - - not_equal.Tensor_out - - not_equal.Tensor - - not_equal_.Scalar - - not_equal_.Tensor - - eq.Scalar_out - - eq.Scalar - - eq.Tensor_out - - eq.Tensor - - ge.Scalar_out - - ge.Scalar - - ge.Tensor_out - - ge.Tensor - - ge_.Scalar - - ge_.Tensor - - greater_equal.Scalar_out - - greater_equal.Scalar - - greater_equal.Tensor_out - - greater_equal.Tensor - - greater_equal_.Scalar - - greater_equal_.Tensor - - le.Scalar_out - - le.Scalar - - le.Tensor_out - - le.Tensor - - le_.Scalar - - le_.Tensor - - less_equal.Scalar_out - - less_equal.Scalar - - less_equal.Tensor_out - - less_equal.Tensor - - less_equal_.Scalar - - less_equal_.Tensor - - gt.Scalar_out - - gt.Scalar - - gt.Tensor_out - - gt.Tensor - - gt_.Scalar - - gt_.Tensor - - greater.Scalar_out - - greater.Scalar - - greater.Tensor_out - - greater.Tensor - - greater_.Scalar - - greater_.Tensor - - lt.Scalar_out - - lt.Scalar - - lt.Tensor_out - - lt.Tensor - - lt_.Scalar - - lt_.Tensor - - less.Scalar_out - - less.Scalar - - less.Tensor_out - - less.Tensor - - less_.Scalar - - less_.Tensor - - take.out - - take - - take_backward - - index_select.out - - index_select - - index_select.dimname_out - - index_select.dimname - - index_select_backward - - masked_select.out - - masked_select - - masked_select_backward - - nonzero.out - - nonzero - - nonzero_numpy - - gather.out - - gather - - gather_backward - - gather.dimname_out - - gather.dimname - - _gather_sparse_backward - - addcmul.out - - addcmul - - addcmul_ - - addcdiv.out - - addcdiv - - lstsq.X - - lstsq - - triangular_solve.X - - triangular_solve - - _triangular_solve_helper - - symeig.e - - symeig - - _symeig_helper - - eig.e - - eig - - svd.U - - svd - - _svd_helper - - swapaxes - - swapaxes_ - - swapdims - - swapdims_ - - cholesky.out - - cholesky - - _cholesky_helper - - cholesky_solve.out - - cholesky_solve - - _cholesky_solve_helper - - solve - - solve.solution - - _solve_helper - - cholesky_inverse - - cholesky_inverse.out - - qr.Q - - qr - - geqrf.a - - geqrf - - orgqr.out - - orgqr - - ormqr.out - - ormqr - - _lu_with_info - - lu_solve.out - - lu_solve - - _lu_solve_helper - - multinomial.out - - multinomial - - lgamma.out - - lgamma_ - - lgamma - - digamma.out - - digamma - - polygamma.out - - polygamma - - erfinv - - erfinv_ - - erfinv.out - - i0 - - i0_ - - i0.out - - sign - - sign_ - - sign.out - - sgn.out - - signbit - - signbit.out - - dist - - atan2.out - - atan2 - - lerp.Scalar_out - - lerp.Tensor_out - - lerp.Scalar - - lerp.Tensor - - histc.out - - histc - - fmod.Scalar_out - - fmod.Scalar - - fmod.Tensor_out - - fmod.Tensor - - hypot.out - - hypot - - hypot_ - - igamma.out - - igamma - - igamma_ - - igammac.out - - igammac - - igammac_ - - nextafter.out - - nextafter - - nextafter_ - - remainder.Scalar_out - - remainder.Scalar - - remainder.Tensor_out - - remainder.Tensor - - min - - fmin - - fmin.out - - max - - fmax - - fmax.out - - maximum - - maximum.out + - copy_ + - max.other - max.out - - minimum - - minimum.out - - min.out - - quantile.scalar_out - - quantile.scalar - - quantile.out - - quantile - - nanquantile.scalar_out - - nanquantile.scalar - - nanquantile.out - - nanquantile - - sort.values - - sort - - sort.dimname_values - - sort.dimname - - msort.out - - msort - - argsort - - argsort.dimname - topk.values - topk - - all - - any - - renorm.out - - renorm - - unfold - - unfold_backward - - equal - pow.Tensor_Tensor_out - pow.Tensor_Tensor - pow.Scalar_out @@ -1397,14 +242,6 @@ supported: - pow.Tensor_Scalar - pow_.Scalar - pow_.Tensor - - float_power.Tensor_Tensor_out - - float_power.Tensor_Tensor - - float_power.Scalar_out - - float_power.Scalar - - float_power.Tensor_Scalar_out - - float_power.Tensor_Scalar - - float_power_.Scalar - - float_power_.Tensor - normal_ - normal.Tensor_float_out - normal.Tensor_float @@ -1414,135 +251,6 @@ supported: - normal.Tensor_Tensor - normal.float_float - normal.float_float_out - - alias - - _index_copy_ - - _cumsum - - _cumsum.out - - _cumprod - - _cumprod.out - - _var - - _std - - _amp_foreach_non_finite_check_and_unscale_ - - _amp_update_scale - - _cat - - _cat.out - - _foreach_add.Scalar - - _foreach_add_.Scalar - - _foreach_sub.Scalar - - _foreach_sub_.Scalar - - _foreach_mul.Scalar - - _foreach_mul_.Scalar - - _foreach_div.Scalar - - _foreach_div_.Scalar - - _foreach_add.List - - _foreach_add_.List - - _foreach_sub.List - - _foreach_sub_.List - - _foreach_mul.List - - _foreach_mul_.List - - _foreach_div.List - - _foreach_div_.List - - _foreach_add.ScalarList - - _foreach_add_.ScalarList - - _foreach_sub.ScalarList - - _foreach_sub_.ScalarList - - _foreach_div.ScalarList - - _foreach_div_.ScalarList - - _foreach_mul.ScalarList - - _foreach_mul_.ScalarList - - _foreach_exp - - _foreach_zero_ - - _foreach_exp_ - - _foreach_sqrt - - _foreach_sqrt_ - - _foreach_abs - - _foreach_abs_ - - _foreach_acos - - _foreach_acos_ - - _foreach_asin - - _foreach_asin_ - - _foreach_atan - - _foreach_atan_ - - _foreach_ceil - - _foreach_ceil_ - - _foreach_cos - - _foreach_cos_ - - _foreach_cosh - - _foreach_cosh_ - - _foreach_erf - - _foreach_erf_ - - _foreach_erfc - - _foreach_erfc_ - - _foreach_expm1 - - _foreach_expm1_ - - _foreach_floor - - _foreach_floor_ - - _foreach_log - - _foreach_log_ - - _foreach_log10 - - _foreach_log10_ - - _foreach_log1p - - _foreach_log1p_ - - _foreach_log2 - - _foreach_log2_ - - _foreach_neg - - _foreach_neg_ - - _foreach_tan - - _foreach_tan_ - - _foreach_tanh - - _foreach_tanh_ - - _foreach_sin - - _foreach_sin_ - - _foreach_sinh - - _foreach_sinh_ - - _foreach_round - - _foreach_round_ - - _foreach_lgamma - - _foreach_lgamma_ - - _foreach_frac - - _foreach_frac_ - - _foreach_reciprocal - - _foreach_reciprocal_ - - _foreach_sigmoid - - _foreach_sigmoid_ - - _foreach_trunc - - _foreach_trunc_ - - _foreach_addcdiv_.Scalar - - _foreach_addcmul_.Scalar - - _foreach_addcdiv_.ScalarList - - _foreach_addcmul_.ScalarList - - _foreach_addcdiv.Scalar - - _foreach_addcmul.Scalar - - _foreach_addcdiv.ScalarList - - _foreach_addcmul.ScalarList - - _foreach_maximum.List - - _foreach_minimum.List - - _mode - - _mode.values - - bucketize.Tensor - - bucketize.Tensor_out - - bucketize.Scalar - - searchsorted.Tensor - - searchsorted.Tensor_out - - searchsorted.Scalar - - mse_loss.out - - mse_loss - - mse_loss_backward.grad_input - - mse_loss_backward - - l1_loss.out - - l1_loss - - l1_loss_backward.grad_input - - l1_loss_backward - - multi_margin_loss.out - - multi_margin_loss - - multi_margin_loss_backward.grad_input - - multi_margin_loss_backward - - multilabel_margin_loss.out - - multilabel_margin_loss - - multilabel_margin_loss_forward.output - - multilabel_margin_loss_forward - - multilabel_margin_loss_backward.grad_input - - multilabel_margin_loss_backward - nll_loss.out - nll_loss - nll_loss_forward.output @@ -1555,319 +263,131 @@ supported: - nll_loss2d_forward - nll_loss2d_backward.grad_input - nll_loss2d_backward - - smooth_l1_loss.out - - smooth_l1_loss - - smooth_l1_loss_backward.grad_input - - smooth_l1_loss_backward - - soft_margin_loss.out - - soft_margin_loss - - soft_margin_loss_backward.grad_input - - soft_margin_loss_backward - - glu.out - - glu - - glu_backward.grad_input - - glu_backward - - hardsigmoid.out - - hardsigmoid - - hardsigmoid_ - - hardsigmoid_backward - - hardtanh.out - - hardtanh - - hardtanh_backward.grad_input - - hardtanh_backward - - hardtanh_ - - hardswish.out - - hardswish - - hardswish_ - - hardswish_backward - - leaky_relu.out - - leaky_relu - - leaky_relu_backward - - leaky_relu_ - - log_sigmoid.out - - log_sigmoid - - log_sigmoid_forward.output - - log_sigmoid_forward - - log_sigmoid_backward.grad_input - - log_sigmoid_backward - - rrelu_with_noise.out - - rrelu_with_noise - - rrelu_with_noise_backward - - rrelu_with_noise_ - - softplus.out - - softplus - - softplus_backward.grad_input - - softplus_backward - - softshrink.out - - softshrink - - softshrink_backward.grad_input - - softshrink_backward - - adaptive_avg_pool2d.out - - adaptive_avg_pool2d - - mkldnn_adaptive_avg_pool2d + - ones.names + - ones + - ones.out + - ones_like + - zeros_like + - equal + - index.Tensor + - index_copy_ + - index_copy + - index_copy_.dimname + - index_copy.dimname + - index_put_ + - index_put + - _index_put_impl_ + - bitwise_and.Tensor_out + - bitwise_and.Scalar_out + - bitwise_and.Scalar + - bitwise_and.Tensor + - bitwise_and_.Scalar + - bitwise_and_.Tensor + - conv_transpose2d.input + - conv_transpose3d.input + - addcmul + - addcmul.out + - addcmul_ + - avg_pool2d_backward + - avg_pool2d_backward.grad_input + - avg_pool2d + - avg_pool2d.out - _adaptive_avg_pool2d - _adaptive_avg_pool2d_backward - - adaptive_avg_pool3d.out - - adaptive_avg_pool3d - - adaptive_avg_pool3d_backward.grad_input - - adaptive_avg_pool3d_backward - - adaptive_max_pool2d.out - - adaptive_max_pool2d - - adaptive_max_pool2d_backward.grad_input - - adaptive_max_pool2d_backward - - adaptive_max_pool3d.out - - adaptive_max_pool3d - - adaptive_max_pool3d_backward.grad_input - - adaptive_max_pool3d_backward - - avg_pool2d.out - - avg_pool2d - - avg_pool2d_backward.grad_input - - avg_pool2d_backward - - avg_pool3d.out - - avg_pool3d - - avg_pool3d_backward.grad_input - - avg_pool3d_backward - - fractional_max_pool2d.output - - fractional_max_pool2d - - fractional_max_pool2d_backward.grad_input - - fractional_max_pool2d_backward - - fractional_max_pool3d.output - - fractional_max_pool3d - - fractional_max_pool3d_backward.grad_input - - fractional_max_pool3d_backward - max_pool2d_with_indices.out - max_pool2d_with_indices - max_pool2d_with_indices_backward.grad_input - max_pool2d_with_indices_backward - - max_pool3d_with_indices.out - - max_pool3d_with_indices - - max_pool3d_with_indices_backward.grad_input - - max_pool3d_with_indices_backward - - max_unpool2d.out - - max_unpool2d - - max_unpool2d_backward.grad_input - - max_unpool2d_backward - - max_unpool3d.out - - max_unpool3d - - max_unpool3d_backward.grad_input - - max_unpool3d_backward - - reflection_pad1d.out - - reflection_pad1d - - reflection_pad1d_backward.grad_input - - reflection_pad1d_backward - - reflection_pad2d.out - - reflection_pad2d - - reflection_pad2d_backward.grad_input - - reflection_pad2d_backward - - replication_pad1d.out - - replication_pad1d - - replication_pad1d_backward.grad_input - - replication_pad1d_backward - - replication_pad2d.out - - replication_pad2d - - replication_pad2d_backward.grad_input - - replication_pad2d_backward - - replication_pad3d.out - - replication_pad3d - - replication_pad3d_backward.grad_input - - replication_pad3d_backward - - upsample_trilinear3d.vec - - upsample_trilinear3d_backward.vec - - upsample_nearest1d.vec - - upsample_nearest1d_backward.vec - - upsample_nearest2d.vec - - upsample_nearest2d_backward.vec - - upsample_nearest3d.vec - - upsample_nearest3d_backward.vec - - upsample_linear1d.out - - upsample_linear1d - - upsample_linear1d.vec - - upsample_linear1d_backward.grad_input - - upsample_linear1d_backward - - upsample_linear1d_backward.vec - - upsample_bilinear2d.out - - upsample_bilinear2d - - upsample_bilinear2d.vec - - upsample_bilinear2d_backward.grad_input - - upsample_bilinear2d_backward - - upsample_bilinear2d_backward.vec - - upsample_bicubic2d.out - - upsample_bicubic2d - - upsample_bicubic2d.vec - - upsample_bicubic2d_backward.grad_input - - upsample_bicubic2d_backward - - upsample_bicubic2d_backward.vec - - upsample_trilinear3d.out - - upsample_trilinear3d - - upsample_trilinear3d_backward.grad_input - - upsample_trilinear3d_backward - - upsample_nearest1d.out - - upsample_nearest1d - - upsample_nearest1d_backward.grad_input - - upsample_nearest1d_backward - - upsample_nearest2d.out - - upsample_nearest2d - - upsample_nearest2d_backward.grad_input - - upsample_nearest2d_backward - - upsample_nearest3d.out - - upsample_nearest3d - - upsample_nearest3d_backward.grad_input - - upsample_nearest3d_backward - - sigmoid_backward.grad_input - - sigmoid_backward - - logit_backward.grad_input - - logit_backward - - tanh_backward.grad_input - - tanh_backward - - slow_conv_transpose2d.out - - slow_conv_transpose2d - - slow_conv_transpose2d_backward.grad_output - - slow_conv_transpose2d_backward.output_mask - - slow_conv_transpose3d.out - - slow_conv_transpose3d - - slow_conv_transpose3d_backward.grad_output - - slow_conv_transpose3d_backward.output_mask - - thnn_conv2d.out - - thnn_conv2d - - thnn_conv2d_forward.output - - thnn_conv2d_forward - - thnn_conv2d_backward.grad_input - - thnn_conv2d_backward.output_mask - - thnn_conv_depthwise2d.out - - thnn_conv_depthwise2d - - thnn_conv_depthwise2d_forward.out - - thnn_conv_depthwise2d_forward - - thnn_conv_depthwise2d_backward.grad_input - - thnn_conv_depthwise2d_backward.output_mask - - slow_conv3d.out - - slow_conv3d - - slow_conv3d_forward.output - - slow_conv3d_forward - - slow_conv3d_backward.grad_input - - slow_conv3d_backward.output_mask - - slow_conv_dilated2d - - slow_conv_dilated2d_backward - - slow_conv_dilated3d - - slow_conv_dilated3d_backward - - col2im.out - - col2im - - col2im_backward.grad_input - - col2im_backward - - column_stack - - column_stack.out - - im2col.out - - im2col - - im2col_backward.grad_input - - im2col_backward - - isfinite - - isinf - - record_stream - - isposinf - - isposinf.out - - isneginf - - isneginf.out - - _add_batch_dim - - _remove_batch_dim - - fft_fft - - fft_fft.out - - fft_ifft - - fft_ifft.out - - fft_rfft - - fft_rfft.out - - fft_irfft - - fft_irfft.out - - fft_hfft - - fft_hfft.out - - fft_ihfft - - fft_ihfft.out - - fft_fft2 - - fft_fft2.out - - fft_ifft2 - - fft_ifft2.out - - fft_rfft2 - - fft_rfft2.out - - fft_irfft2 - - fft_irfft2.out - - fft_fftn - - fft_fftn.out - - fft_ifftn - - fft_ifftn.out - - fft_rfftn - - fft_rfftn.out - - fft_irfftn - - fft_irfftn.out - - fft_fftfreq - - fft_fftfreq.out - - fft_rfftfreq - - fft_rfftfreq.out - - fft_fftshift - - fft_ifftshift - - linalg_cholesky - - linalg_cholesky.out - - linalg_det - - det - - linalg_slogdet - - linalg_slogdet.out - - _syevd_helper - - linalg_eigh - - linalg_eigh.eigvals - - linalg_eigvalsh - - linalg_eigvalsh.out - - _linalg_inv_out_helper_ - - linalg_inv - - linalg_inv.out - - inner - - inner.out - - outer - - outer.out - - ger - - ger.out - - linalg_norm - - linalg_norm.ord_str - - linalg_norm.out - - linalg_norm.ord_str_out - - linalg_svd.U - - linalg_svd - - linalg_cond - - linalg_cond.out - - linalg_cond.p_str - - linalg_cond.p_str_out - - linalg_pinv - - linalg_pinv.rcond_tensor - - linalg_pinv.out - - linalg_pinv.out_rcond_tensor - - _linalg_solve_out_helper_ - - linalg_solve - - linalg_solve.out - - linalg_tensorinv - - linalg_tensorinv.out - - linalg_tensorsolve - - linalg_tensorsolve.out - - linalg_qr - - linalg_qr.out - - _linalg_qr_helper - - linalg_matrix_rank - - linalg_matrix_rank.out - - _test_serialization_subcmul - - _test_optional_intlist - - _test_optional_filled_intlist - - _test_optional_floatlist - - _test_string_default - - _test_ambiguous_defaults.a - - _test_ambiguous_defaults.b + - _pin_memory + - is_pinned + - _reshape_alias + - eq.Scalar_out + - eq.Scalar + - eq.Tensor_out + - eq.Tensor + - ge.Scalar_out + - ge.Scalar + - ge.Tensor_out + - ge.Tensor + - ge_.Scalar + - ge_.Tensor + - abs + - abs_ + - abs.out + - ne.Scalar_out + - ne.Scalar + - ne.Tensor_out + - ne.Tensor + - ne_.Scalar + - ne_.Tensor + - not_equal.Scalar_out + # - not_equal.Scalar + - not_equal.Tensor_out + # - not_equal.Tensor + - not_equal_.Scalar + - not_equal_.Tensor + - gather.out + - gather + - gather.dimname_out + - gather.dimname + - gelu + - gelu.out + - gelu_backward + - gt.Scalar_out + - gt.Scalar + - gt.Tensor_out + - gt.Tensor + - gt_.Scalar + - gt_.Tensor + - masked_select.out + - masked_select + - masked_select_backward + - _convolution_double_backward + - embedding + - embedding_dense_backward + - erf + - erf_ + - erf.out + - exp + - exp_ + - exp.out + - index_select.out + - index_select + - index_select.dimname_out + - index_select.dimname + - native_layer_norm + - native_layer_norm_backward + - lt.Scalar_out + - lt.Scalar + - lt.Tensor_out + - lt.Tensor + - lt_.Scalar + - lt_.Tensor + - stack + - stack.out + - where.self + - where + - _s_where + - mm.out + - mm + - kl_div + - kl_div_backward + - unsqueeze + - unsqueeze_ -autograd: - - elu.out - - elu - - elu_ + #- full custom: - - func: npu_transpose(Tensor self, int[] perm, bool require_contiguous=True) -> Tensor + - func: npu_transpose_to_contiguous(Tensor self) -> Tensor variants: function, method - - func: npu_transpose.out(Tensor self, int[] perm, bool require_contiguous=True, *, Tensor(a!) out) -> Tensor(a!) + - func: npu_transpose(Tensor self, int[] perm) -> Tensor + variants: function, method + - func: npu_transpose.out(Tensor self, int[] perm, *, Tensor(a!) out) -> Tensor(a!) - func: npu_broadcast(Tensor self, int[] size) -> Tensor variants: function, method - func: npu_broadcast.out(Tensor self, int[] size, *, Tensor(a!) out) -> Tensor(a!) + - func: npu_dtype_cast(Tensor self, ScalarType dtype) -> Tensor + variants: function, method - func: npu_dtype_cast_(Tensor(a!) self, Tensor src) -> Tensor(a!) variants: method - func: npu_alloc_float_status(Tensor self) -> Tensor @@ -1878,12 +398,6 @@ custom: variants: function, method - func: one_(Tensor(a!) self) -> Tensor(a!) variants: method, function - - func: fast_gelu_backward(Tensor grad, Tensor self) -> Tensor - variants: function, method - - func: _amp_foreach_non_finite_check_(Tensor[] scaled_grads) -> bool - - func: npu_sign_bits_pack(Tensor self, int size) -> Tensor - - func: npu_bert_apply_adam(Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, Scalar max_grad_norm, Scalar global_grad_norm, Scalar weight_decay, Scalar? step_size=None, int adam_mode=0) -> (Tensor var, Tensor m, Tensor v) - - func: npu_bert_apply_adam.out(Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, Scalar max_grad_norm, Scalar global_grad_norm, Scalar weight_decay, Scalar? step_size=None, int adam_mode=0, *, Tensor(a!) var, Tensor(b!) m, Tensor(c!) v) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - func: npu_conv_transpose2d_backward(Tensor input, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - func: npu_conv_transpose3d_backward(Tensor input, Tensor grad_output, Tensor weight, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - func: npu_convolution_backward(Tensor input, Tensor grad_output, Tensor weight, int[] stride, int[] padding, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) @@ -1891,9 +405,6 @@ custom: - func: npu_conv2d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor - func: npu_conv2d.out(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups, *, Tensor(a!) out) -> Tensor(a!) - func: npu_conv2d_backward(Tensor input, Tensor grad_output, Tensor weight, int[] stride, int[] padding, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - - func: npu_conv3d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor - - func: npu_conv3d.out(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups, *, Tensor(a!) out) -> Tensor(a!) - - func: npu_conv3d_backward(Tensor input, Tensor grad, Tensor weight, int[] stride, int[] padding, int[] dilation, int groups, bool[3] output_mask) -> (Tensor, Tensor, Tensor) - func: get_npu_format(Tensor self) -> int - func: npu_format_cast.Tensor(Tensor self, Tensor dst) -> Tensor - func: npu_format_cast_.acl_format(Tensor(a!) self, int acl_format) -> Tensor(a!) @@ -1905,102 +416,28 @@ custom: - func: npu_slice(Tensor self, int[] offsets, int[] size) -> Tensor - func: npu_slice.out(Tensor self, int[] offsets, int[] size, *, Tensor(a!) out) -> Tensor(a!) - func: npu_indexing(Tensor self, int[] begin, int[] end, int[] strides, int begin_mask=0, int end_mask=0, int ellipsis_mask=0, int new_axis_mask=0, int shrink_axis_mask=0) -> Tensor + - func: npu_softmax_cross_entropy_with_logits(Tensor self, Tensor labels) -> Tensor + variants: function, method - func: npu_indexing.out(Tensor self, int[] begin, int[] end, int[] strides, int begin_mask=0, int end_mask=0, int ellipsis_mask=0, int new_axis_mask=0, int shrink_axis_mask=0, *, Tensor(a!) out) -> Tensor(a!) - func: npu_softmax_cross_entropy_with_logits_backward(Tensor grad, Tensor self, Tensor labels) -> Tensor variants: function, method - func: npu_stride_copy(Tensor self, int[] shape, int[] stride, Scalar storage_offset) -> Tensor - func: npu_stride_copy.out(Tensor self, int[] shape, int[] stride, Scalar storage_offset, *, Tensor(a!) out) -> Tensor(a!) - - func: npu_roi_align(Tensor self, Tensor rois, float spatial_scale, int pooled_height, int pooled_width, int sample_num, int roi_end_mode) -> Tensor - - func: npu_roi_alignbk(Tensor self, Tensor rois, int[] xdiff_shape, int pooled_width, int pooled_height, float spatial_scale, int sample_num, int? roi_end_mode=None) -> Tensor - func: npu_ps_roi_pooling_backward(Tensor output_grad, Tensor rois, float spatial_scale, int group_size, int output_dim, int[] input_size) -> Tensor - - func: npu_sort_v2.out(Tensor self, int dim=-1, bool descending=False, *, Tensor(a!) out) -> Tensor(a!) - - func: npu_sort_v2(Tensor self, int dim=-1, bool descending=False) -> Tensor - - func: npu_confusion_transpose_backward(Tensor grad, int[] perm, int[] shape, bool transpose_first) -> Tensor - func: npu_one_hot(Tensor self, int num_classes=-1, int depth=1, Scalar on_value=1, Scalar off_value=0) -> Tensor variants: function, method - func: npu_linear_backward(Tensor grad, Tensor input, Tensor weight) -> (Tensor, Tensor) - - func: npu_anchor_response_flags(Tensor self, int[2] featmap_size, int[2] stride, int num_base_anchors) -> Tensor - variants: function, method - func: npu_dropout_backward(Tensor grad_output, Tensor mask, float p) -> Tensor - - func: npu_nms_rotated(Tensor self, Tensor scores, float iou_threshold, float scores_threshold=0, int max_output_size=-1, int mode=0) -> (Tensor, Tensor) - variants: function, method - - func: npu_masked_fill_range(Tensor self, Tensor start, Tensor end, Tensor value, int axis=-1) -> Tensor - variants: function, method - - func: npu_sub_sample(Tensor self, int per_images, float positive_fraction) -> Tensor - - func: npu_yolo_boxes_encode(Tensor self, Tensor gt_bboxes, Tensor stride, bool performance_mode=False) -> Tensor - - func: npu_scatter(Tensor self, Tensor indices, Tensor updates, int dim) -> Tensor - - func: npu_layer_norm_eval(Tensor input, int[] normalized_shape, Tensor? weight=None, Tensor? bias=None, float eps=1e-05) -> Tensor - - func: npu_max_backward(Tensor grad, int dim, Tensor indices, int[] sizes, bool keepdim=False) -> Tensor - - func: npu_rotated_box_encode(Tensor self, Tensor gt_bboxes, Tensor weight) -> Tensor - - func: npu_rotated_box_decode(Tensor self, Tensor deltas, Tensor weight) -> Tensor - - func: npu_rotated_overlaps(Tensor self, Tensor query_boxes, bool trans=False) -> Tensor - - func: npu_silu_backward(Tensor grad_output, Tensor x0, Tensor x1) -> Tensor - - func: npu_rotated_iou(Tensor self, Tensor query_boxes, bool trans=False, int mode=0, bool is_cross=True, float v_threshold=0.0, float e_threshold=0.0) -> Tensor - - func: npu_nms_with_mask(Tensor input, Scalar iou_threshold) -> (Tensor, Tensor, Tensor) - - func: npu_gru_backward(Tensor? grady, Tensor? gradh, Tensor input, Tensor weight_input, Tensor weight_hidden, Tensor bias_input, Tensor bias_hidden, Tensor seq_length, Tensor hx, Tensor y_output, Tensor h_output, Tensor output_updata, Tensor output_reset, Tensor output_new, Tensor hidden_new) -> Tensor[] - - func: npu_mish_backward(Tensor grad, Tensor input) -> Tensor - - func: npu_min_backward(Tensor grad, int dim, Tensor indices, int[] sizes, bool keepdim=False) -> Tensor - - func: npu_reshape(Tensor self, int[] shape, bool can_refresh=False) -> Tensor - - func: npu_reshape.out(Tensor self, int[] shape, bool can_refresh=False, *, Tensor(a!) out) -> Tensor(a!) - - func: npu_batch_nms(Tensor self, Tensor scores, float score_threshold, float iou_threshold, int max_size_per_class, int max_total_size, bool change_coordinate_frame=False, bool transpose_box=False) -> (Tensor, Tensor, Tensor, Tensor) - - func: npu_bounding_box_encode(Tensor anchor_box, Tensor ground_truth_box, float means0, float means1, float means2, float means3, float stds0, float stds1, float stds2, float stds3) -> Tensor - - func: npu_bounding_box_decode(Tensor rois, Tensor deltas, float means0, float means1, float means2, float means3, float stds0, float stds1, float stds2, float stds3, int[1] max_shape, float wh_ratio_clip) -> Tensor - - func: npu_apply_adam(Scalar beta1_power, Scalar beta2_power, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, bool? use_locking, bool? use_nesterov) -> (Tensor, Tensor, Tensor) - - func: npu_apply_adam.out(Scalar beta1_power, Scalar beta2_power, Scalar lr, Scalar beta1, Scalar beta2, Scalar epsilon, Tensor grad, bool? use_locking, bool? use_nesterov, *, Tensor(a!) var, Tensor(b!) m, Tensor(c!) v) -> (Tensor(a!), Tensor(b!), Tensor(c!)) - - func: npu_deformable_conv2dbk(Tensor input, Tensor grad_output, Tensor offset_out, Tensor weight, Tensor offset, int[2] kernel_size, int[] stride, int[] padding, int[] dilation=[1,1,1,1], int groups=1, int deformable_groups=1, bool modulated=True) -> (Tensor, Tensor, Tensor, Tensor) - - func: npu_giou_backward(Tensor grad, Tensor bboxes, Tensor gtboxes, bool trans=False, bool is_cross=False, int mode=0) -> (Tensor, Tensor) - - func: npu_diou_backward(Tensor grad, Tensor bboxes, Tensor gtboxes, bool trans=False, bool is_cross=False, int mode=0) -> (Tensor, Tensor) - - func: npu_iou(Tensor bboxes, Tensor gtboxes, int mode=0) -> Tensor - - func: npu_nms_v4(Tensor self, Tensor scores, Scalar max_output_size, Tensor iou_threshold, Tensor scores_threshold, bool pad_to_max_output_size=False) -> (Tensor, Tensor) - - func: npu_pad(Tensor input, int[] paddings) -> Tensor - - func: npu_random_choice_with_mask(Tensor x, int count=256, int seed=0, int seed2=0) -> (Tensor, Tensor) - - func: npu_normalize_batch(Tensor self, Tensor seq_len, int normalize_type=0) -> Tensor - - func: npu_ptiou(Tensor bboxes, Tensor gtboxes, int mode=0) -> Tensor - - func: npu_lstm_backward(Tensor? grady, Tensor? gradh, Tensor? gradc, Tensor input, Tensor weight, Tensor bias, Tensor hx, Tensor cx, Tensor y_output, Tensor h_output, Tensor c_output, Tensor i, Tensor j, Tensor f, Tensor o, Tensor tanhc) -> (Tensor, Tensor, Tensor, Tensor, Tensor) - - func: _dropout_with_byte_mask_backward(Tensor grad_output, Tensor mask, float p) -> Tensor - - func: dropout_with_byte_mask(Tensor self, float p, bool train) -> Tensor - - func: npu_dropout_with_add_softmax_backward(Tensor grad, Tensor mask, Tensor softmax_out, Scalar alpha, float prob, int dim) -> (Tensor, Tensor) - variants: function, method - - func: npu_multi_head_attention_backward(Tensor query, Tensor key, Tensor value, Tensor query_weight, Tensor key_weight, Tensor value_weight, Tensor out_proj_weight, Tensor? query_bias, Tensor? key_bias, Tensor? value_bias, Tensor? out_proj_bias, Tensor query_res, Tensor key_res, Tensor value_res, Tensor attn_scores, Tensor attn_res, Tensor context, Tensor y_grad, Tensor dropout_mask, int attn_head_num, int attn_dim_per_head, int src_len, int tgt_len, float dropout_prob, bool softmax_use_float) -> Tensor[] - - func: npu_dropout_gen_mask(int[] size, float p, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor - - func: npu_ciou_backward(Tensor grad, Tensor bboxes, Tensor gtboxes, Tensor? atan_sub, bool trans=False, bool is_cross=True, int mode=0) -> (Tensor, Tensor) - - func: npu_sign_bits_unpack(Tensor input, int size, ScalarType dtype) -> Tensor custom_autograd: - func: npu_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor - func: npu_convolution_transpose(Tensor input, Tensor weight, Tensor? bias, int[] padding, int[] output_padding, int[] stride, int[] dilation, int groups) -> Tensor - - func: fast_gelu(Tensor self) -> Tensor - - func: npu_confusion_transpose(Tensor self, int[] perm, int[] shape, bool transpose_first) -> Tensor - variants: function, method - - func: npu_ps_roi_pooling(Tensor self, Tensor rois, float spatial_scale, int group_size, int output_dim) -> Tensor - func: npu_linear(Tensor input, Tensor weight, Tensor? bias=None) -> Tensor - - func: _npu_dropout(Tensor self, float p) -> (Tensor, Tensor) - - func: npu_ifmr(Tensor data, Tensor data_min, Tensor data_max, Tensor cumsum, float min_percentile, float max_percentile, float search_start, float search_end, float search_step, bool with_offset) -> (Tensor, Tensor) - - func: npu_grid_assign_positive(Tensor self, Tensor overlaps, Tensor box_responsible_flags, Tensor max_overlaps, Tensor argmax_overlaps, Tensor gt_max_overlaps, Tensor gt_argmax_overlaps, int num_gts, float pos_iou_thr, float min_pos_iou, bool gt_max_assign_all) -> Tensor - - func: npu_softmax_cross_entropy_with_logits(Tensor self, Tensor labels) -> Tensor - - func: npu_max.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) - - func: npu_max.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) + - func: get_storage_size(Tensor self) -> int + - func: npu_reshape(Tensor self, int[] shape, bool can_refresh=False) -> Tensor + - func: npu_reshape.out(Tensor self, int[] shape, bool can_refresh=False, *, Tensor(a!) out) -> Tensor(a!) - func: npu_format_cast(Tensor self, int acl_format) -> Tensor - func: npu_bmmV2(Tensor self, Tensor mat2, int[] output_sizes) -> Tensor variants: function, method - - func: npu_dtype_cast(Tensor self, ScalarType dtype) -> Tensor - variants: function, method - - func: npu_silu(Tensor self) -> Tensor - - func: npu_silu_(Tensor(a!) self) -> Tensor(a!) - - func: npu_gru(Tensor input, Tensor hx, Tensor weight_input, Tensor weight_hidden, Tensor bias_input, Tensor bias_hidden, Tensor seq_length, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> Tensor[] - - func: npu_mish(Tensor self) -> Tensor - variants: function, method - - func: npu_min.dim(Tensor self, int dim, bool keepdim=False) -> (Tensor values, Tensor indices) - - func: npu_min.names_dim(Tensor self, Dimname dim, bool keepdim=False) -> (Tensor values, Tensor indices) - - func: npu_deformable_conv2d(Tensor input, Tensor weight, Tensor offset, Tensor? bias, int[2] kernel_size, int[] stride, int[] padding, int[] dilation=[1,1,1,1], int groups=1, int deformable_groups=1, bool modulated=True) -> (Tensor, Tensor) - - func: npu_giou(Tensor self, Tensor gtboxes, bool trans=False, bool is_cross=False, int mode=0) -> Tensor - - func: npu_diou(Tensor self, Tensor gtboxes, bool trans=False, bool is_cross=False, int mode=0) -> Tensor - - func: npu_lstm(Tensor input, Tensor weight, Tensor bias, Tensor seqMask, Tensor h, Tensor c, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, bool flagSeq, bool direction) -> Tensor[] - variants: function - - func: _dropout_with_byte_mask(Tensor self, float p) -> (Tensor, Tensor) - - func: npu_dropout_with_add_softmax(Tensor self, Tensor x1, Scalar alpha, float prob, int dim) -> (Tensor, Tensor, Tensor) - - func: npu_scaled_masked_softmax(Tensor x, Tensor mask, Scalar scale=1, bool fixed_triu_mask=False) -> Tensor - variants: function, method - - func: npu_multi_head_attention(Tensor query, Tensor key, Tensor value, Tensor query_weight, Tensor key_weight, Tensor value_weight, Tensor attn_mask, Tensor out_proj_weight, Tensor? query_bias, Tensor? key_bias, Tensor? value_bias, Tensor? out_proj_bias, Tensor? dropout_mask, int attn_head_num, int attn_dim_per_head, int src_len, int tgt_len, float dropout_prob, bool softmax_use_float) -> Tensor[] - - func: npu_dropout_do_mask(Tensor self, Tensor mask, float p) -> (Tensor, Tensor) - - func: npu_ciou(Tensor self, Tensor gtboxes, bool trans=False, bool is_cross=True, int mode=0, bool atan_sub_flag=False) -> Tensor - - func: get_storage_size(Tensor self) -> int \ No newline at end of file + - func: npu_dropout_gen_mask(int[] size, float p, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor + - func: _npu_dropout(Tensor self, float p) -> (Tensor, Tensor) + - func: npu_dropout_do_mask(Tensor self, Tensor mask, float p) -> (Tensor, Tensor) \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AbsKernelNpu.cpp b/torch_npu/csrc/aten/ops/AbsKernelNpu.cpp index 65bf701255..484787dfab 100644 --- a/torch_npu/csrc/aten/ops/AbsKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/AbsKernelNpu.cpp @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -28,7 +28,7 @@ at::Tensor& abs_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { return result; } -at::Tensor& NPUNativeFunctions::abs_out(const at::Tensor& self, at::Tensor& result) { +at::Tensor& XLANativeFunctions::abs_out(const at::Tensor& self, at::Tensor& result) { OpPreparation::CheckOut( {self}, result, @@ -39,14 +39,14 @@ at::Tensor& NPUNativeFunctions::abs_out(const at::Tensor& self, at::Tensor& resu .Call(result); } -at::Tensor NPUNativeFunctions::abs(const at::Tensor& self) { +at::Tensor XLANativeFunctions::abs(const at::Tensor& self) { OpPipeWithApplyOut pipe; return pipe.ApplyOutputSameAs(self) .Func([&self](at::Tensor& result) {abs_out_npu_nocheck(result, self);}) .Call(); } -at::Tensor& NPUNativeFunctions::abs_(at::Tensor& self) { +at::Tensor& XLANativeFunctions::abs_(at::Tensor& self) { abs_out(self, self); return self; } diff --git a/torch_npu/csrc/aten/ops/AcosKernelNpu.cpp b/torch_npu/csrc/aten/ops/AcosKernelNpu.cpp deleted file mode 100644 index 731ac93999..0000000000 --- a/torch_npu/csrc/aten/ops/AcosKernelNpu.cpp +++ /dev/null @@ -1,56 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& acos_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Acos") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::acos_out(const at::Tensor& self, at::Tensor& result) { - OpPipeWithDefinedOut pipe; - OpPreparation::CheckOut( - {self}, - result, - self); - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){acos_out_npu_nocheck(self, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::acos(const at::Tensor& self) { - OpPipeWithApplyOut pipe; - return pipe.ApplyOutputSameAs(self) - .Func([&self](at::Tensor& result) {acos_out_npu_nocheck(self, result);}) - .Call(); -} - -at::Tensor& NPUNativeFunctions::acos_(at::Tensor& self) { - acos_out(self, self); - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AcoshKernelNpu.cpp b/torch_npu/csrc/aten/ops/AcoshKernelNpu.cpp deleted file mode 100644 index 4bc8e8faa6..0000000000 --- a/torch_npu/csrc/aten/ops/AcoshKernelNpu.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2022, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& acosh_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Acosh") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::acosh_out( - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - acosh_out_npu_nocheck(contiguousResult, self); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - acosh_out_npu_nocheck(result, self); - } - return result; - -} - -at::Tensor NPUNativeFunctions::acosh(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - acosh_out_npu_nocheck(result, self); - return result; -} - -at::Tensor& NPUNativeFunctions::acosh_(at::Tensor& self) { - - return acosh_out(self, self); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/AddKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddKernelNpu.cpp index 9a8d28691f..860d760166 100644 --- a/torch_npu/csrc/aten/ops/AddKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/AddKernelNpu.cpp @@ -20,7 +20,7 @@ #include "torch_npu/csrc/core/npu/register/OptionsManager.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" namespace at_npu @@ -71,7 +71,7 @@ namespace at_npu cmd.Name("Add") .Input(self) .Input(at::Scalar(value), self.scalar_type()) - .Output(result, "", c10::nullopt, real_type) + .Output(result, real_type) .Run(); return result; @@ -117,7 +117,7 @@ namespace at_npu cmd.Name("Add") .Input(self) .Input(other) - .Output(result, "", c10::nullopt, real_type) + .Output(result, real_type) .Run(); } else @@ -170,7 +170,7 @@ namespace at_npu } } - at::Tensor NPUNativeFunctions::add(const at::Tensor &self, const at::Tensor &other, at::Scalar alpha) + at::Tensor XLANativeFunctions::add(const at::Tensor &self, const at::Tensor &other, const at::Scalar &alpha) { alpha_check_npu(self.scalar_type(), alpha); if ((!(self.is_contiguous() && other.is_contiguous())) && @@ -186,7 +186,7 @@ namespace at_npu at::Scalar other_c1_offset( other.storage_offset() / (other.size(2) * other.size(3) * c0_len)); at::Scalar stride_len(self.size(1) / c0_len); - at::Tensor result = NPUNativeFunctions::npu_stride_add( + at::Tensor result = XLANativeFunctions::npu_stride_add( self_use, other_use, self_c1_offset, other_c1_offset, stride_len); return result; } @@ -206,7 +206,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::add(const at::Tensor &self, at::Scalar other, at::Scalar alpha) + at::Tensor XLANativeFunctions::add(const at::Tensor &self, const at::Scalar &other, const at::Scalar &alpha) { alpha_check_npu(self.scalar_type(), alpha); // calculate the output size @@ -221,7 +221,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::add_(at::Tensor &self, const at::Tensor &other, at::Scalar alpha) + at::Tensor &XLANativeFunctions::add_(at::Tensor &self, const at::Tensor &other, const at::Scalar &alpha) { c10::SmallVector inputs = {self, other}; c10::SmallVector outputs = {self}; @@ -241,7 +241,7 @@ namespace at_npu return self; } - at::Tensor &NPUNativeFunctions::add_(at::Tensor &self, at::Scalar other, at::Scalar alpha) + at::Tensor &XLANativeFunctions::add_(at::Tensor &self, const at::Scalar &other, const at::Scalar &alpha) { if (!NpuUtils::check_match(&self)) { @@ -257,10 +257,10 @@ namespace at_npu return self; } - at::Tensor &NPUNativeFunctions::add_out( + at::Tensor &XLANativeFunctions::add_out( const at::Tensor &self, const at::Tensor &other, - at::Scalar alpha, + const at::Scalar &alpha, at::Tensor &result) { bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); diff --git a/torch_npu/csrc/aten/ops/AddReluKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddReluKernelNpu.cpp deleted file mode 100644 index 39008dd516..0000000000 --- a/torch_npu/csrc/aten/ops/AddReluKernelNpu.cpp +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2022, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor &add_relu_out_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Scalar alpha, - at::Tensor& result){ - at::Tensor addResult = NPUNativeFunctions::add(self, other, alpha); - OpCommand cmd; - cmd.Name("Relu") - .Input(addResult) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::_add_relu_out( - const at::Tensor& self, - const at::Tensor& other, - at::Scalar alpha, - at::Tensor& result) { - if (!NpuUtils::check_match(&result)) - { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - add_relu_out_nocheck(self, other, alpha, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - }else{ - add_relu_out_nocheck(self, other, alpha, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::_add_relu(const at::Tensor& self, const at::Tensor& other, at::Scalar alpha) { - at::Tensor result = OpPreparation::ApplyTensor(self); - return _add_relu_out(self, other, alpha, result); -} - -at::Tensor& NPUNativeFunctions::_add_relu_(at::Tensor& self, const at::Tensor& other, at::Scalar alpha) { - c10::SmallVector inputs = {self, other}; - c10::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - return _add_relu_out(self, other, alpha, self); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AddbmmKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddbmmKernelNpu.cpp deleted file mode 100644 index dff97430b1..0000000000 --- a/torch_npu/csrc/aten/ops/AddbmmKernelNpu.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::addbmm_out( - const at::Tensor& self, - const at::Tensor& batch1, - const at::Tensor& batch2, - at::Scalar beta, - at::Scalar alpha, - at::Tensor& result) { - at::Tensor MulResult = at::mul(batch1, alpha); - at::Tensor bmmResult = at::bmm(MulResult,batch2); - int64_t dim[2] = {batch1.size(1), batch2.size(2)}; - at::Tensor sumResult = at::sum_to(bmmResult, dim); - // sumResult + self*beta - at::add_out(result, sumResult, self, beta); - return result; -} - -at::Tensor NPUNativeFunctions::addbmm( - const at::Tensor& self, - const at::Tensor& batch1, - const at::Tensor& batch2, - at::Scalar beta, - at::Scalar alpha) { - // calculate the output size - auto outputSize = addbmm_npu_output_size(self, batch1, batch2, beta, alpha); - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - // calculate the output result of the NPU - addbmm_out(self, batch1, batch2, beta, alpha, result); - return result; -} - -at::Tensor& NPUNativeFunctions::addbmm_( - at::Tensor& self, - const at::Tensor& batch1, - const at::Tensor& batch2, - at::Scalar beta, - at::Scalar alpha) { - OpPreparation::CheckMemory({self, batch1, batch2}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = addbmm_out(contiguousSelf, batch1, batch2, beta, alpha, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - addbmm_out(self, batch1, batch2, beta, alpha, self); - } - return self; -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AddcdivKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddcdivKernelNpu.cpp index 34555c4b57..3741e1cbf7 100644 --- a/torch_npu/csrc/aten/ops/AddcdivKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/AddcdivKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -25,29 +25,35 @@ at::Tensor& addcdiv_npu_nocheck( const at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - at::Scalar value, + const at::Scalar& value, at::Tensor& result) { + at::Tensor selfCp = self.scalar_type() == at::kFloat ? self : XLANativeFunctions::npu_dtype_cast(self, at::kFloat); + at::Tensor tensor1Cp = tensor1.scalar_type() == at::kFloat ? tensor1 : XLANativeFunctions::npu_dtype_cast(tensor1, at::kFloat); + at::Tensor tensor2Cp = tensor2.scalar_type() == at::kFloat ? tensor2 : XLANativeFunctions::npu_dtype_cast(tensor2, at::kFloat); OpCommand cmd; cmd.Name("Addcdiv") - .Input(self) - .Input(tensor1) - .Input(tensor2) - .Input(value, self.scalar_type()) + .Input(selfCp) + .Input(tensor1Cp) + .Input(tensor2Cp) + .Input(value, selfCp.scalar_type()) .Output(result) .Run(); return result; } -at::Tensor& NPUNativeFunctions::addcdiv_out( +at::Tensor& XLANativeFunctions::addcdiv_out( const at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - at::Scalar value, + const at::Scalar& value, at::Tensor& result) { auto divOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2); auto outputSize = broadcast_ops_npu_output_size(self.sizes(), divOutputSize); - at::Tensor temp = OpPreparation::ApplyTensor(self, outputSize); + bool isFp32 = self.scalar_type() == at::kFloat && tensor1.scalar_type() == at::kFloat && tensor2.scalar_type() == at::kFloat; + at::Tensor temp = isFp32 ? OpPreparation::ApplyTensor(self, outputSize) + : OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kFloat), self); addcdiv_npu_nocheck(self, tensor1, tensor2, value, temp); + temp = isFp32 ? temp : XLANativeFunctions::npu_dtype_cast(temp, self.scalar_type()); OpPreparation::CheckOut( {temp}, result, @@ -56,30 +62,33 @@ at::Tensor& NPUNativeFunctions::addcdiv_out( return result; } -at::Tensor NPUNativeFunctions::addcdiv( +at::Tensor XLANativeFunctions::addcdiv( const at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - at::Scalar value) { + const at::Scalar& value) { auto divOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2); auto outputSize = broadcast_ops_npu_output_size(self.sizes(), divOutputSize); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); + bool isFp32 = self.scalar_type() == at::kFloat && tensor1.scalar_type() == at::kFloat && tensor2.scalar_type() == at::kFloat; + at::Tensor result = isFp32 ? OpPreparation::ApplyTensor(self, outputSize) + : OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kFloat), self); addcdiv_npu_nocheck(self, tensor1, tensor2, value, result); + result = isFp32 ? result : XLANativeFunctions::npu_dtype_cast(result, self.scalar_type()); return result; } -at::Tensor& NPUNativeFunctions::addcdiv_( +at::Tensor& XLANativeFunctions::addcdiv_( at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - at::Scalar value) { + const at::Scalar& value) { OpPreparation::CheckMemory({self, tensor1, tensor2}, {self}); if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::addcdiv_out(contiguousSelf, tensor1, tensor2, value, contiguousSelf); + at::Tensor result = XLANativeFunctions::addcdiv_out(contiguousSelf, tensor1, tensor2, value, contiguousSelf); NpuUtils::format_fresh_view(self, result); } else { - NPUNativeFunctions::addcdiv_out(self, tensor1, tensor2, value, self); + XLANativeFunctions::addcdiv_out(self, tensor1, tensor2, value, self); } return self; } diff --git a/torch_npu/csrc/aten/ops/AddcmulKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddcmulKernelNpu.cpp index d769e2ef30..1a5b5fb66d 100644 --- a/torch_npu/csrc/aten/ops/AddcmulKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/AddcmulKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -39,11 +39,11 @@ at::Tensor& addcmul_out_npu_nocheck( return result; } -at::Tensor& NPUNativeFunctions::addcmul_out( +at::Tensor& XLANativeFunctions::addcmul_out( const at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - const at::Scalar value, + const at::Scalar& value, at::Tensor& result) { auto mulOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2); auto outputSize = broadcast_ops_npu_output_size(self.sizes(), mulOutputSize); @@ -61,11 +61,11 @@ at::Tensor& NPUNativeFunctions::addcmul_out( .Call(result); } -at::Tensor NPUNativeFunctions::addcmul( +at::Tensor XLANativeFunctions::addcmul( const at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - at::Scalar value) { + const at::Scalar& value) { auto mulOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2); auto outputSize = broadcast_ops_npu_output_size(self.sizes(), mulOutputSize); @@ -76,11 +76,11 @@ at::Tensor NPUNativeFunctions::addcmul( return result; } -at::Tensor& NPUNativeFunctions::addcmul_( +at::Tensor& XLANativeFunctions::addcmul_( at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2, - at::Scalar value) { + const at::Scalar& value) { OpPreparation::CheckMemory({self}, {self}); if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); diff --git a/torch_npu/csrc/aten/ops/AddmmKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddmmKernelNpu.cpp index 7ee8fb7fdd..ac4f8e64bf 100644 --- a/torch_npu/csrc/aten/ops/AddmmKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/AddmmKernelNpu.cpp @@ -19,19 +19,19 @@ #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - at::Tensor &NPUNativeFunctions::addmm_out( + at::Tensor &XLANativeFunctions::addmm_out( const at::Tensor &self, const at::Tensor &mat1, const at::Tensor &mat2, - at::Scalar beta, - at::Scalar alpha, + const at::Scalar &beta, + const at::Scalar &alpha, at::Tensor &result) { // mat1*alpha @@ -46,12 +46,12 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::addmm( + at::Tensor XLANativeFunctions::addmm( const at::Tensor &self, const at::Tensor &mat1, const at::Tensor &mat2, - at::Scalar beta, - at::Scalar alpha) + const at::Scalar &beta, + const at::Scalar &alpha) { // calculate the output size auto outputSize = addmm_npu_output_size(self, mat1, mat2, beta, alpha); @@ -61,17 +61,17 @@ namespace at_npu at::Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, self.options(), resFormat); // calculate the output result of the NPU - NPUNativeFunctions::addmm_out(self, mat1, mat2, beta, alpha, result); + XLANativeFunctions::addmm_out(self, mat1, mat2, beta, alpha, result); return result; } - at::Tensor &NPUNativeFunctions::addmm_( + at::Tensor &XLANativeFunctions::addmm_( at::Tensor &self, const at::Tensor &mat1, const at::Tensor &mat2, - at::Scalar beta, - at::Scalar alpha) + const at::Scalar &beta, + const at::Scalar &alpha) { c10::SmallVector inputs = {self, mat1, mat2}; c10::SmallVector outputs = {self}; @@ -80,12 +80,12 @@ namespace at_npu { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); at::Tensor result = - NPUNativeFunctions::addmm_out(contiguousSelf, mat1, mat2, beta, alpha, contiguousSelf); + XLANativeFunctions::addmm_out(contiguousSelf, mat1, mat2, beta, alpha, contiguousSelf); NpuUtils::format_fresh_view(self, result); } else { - NPUNativeFunctions::addmm_out(self, mat1, mat2, beta, alpha, self); + XLANativeFunctions::addmm_out(self, mat1, mat2, beta, alpha, self); } return self; diff --git a/torch_npu/csrc/aten/ops/AddmvKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddmvKernelNpu.cpp deleted file mode 100644 index 1335693ee7..0000000000 --- a/torch_npu/csrc/aten/ops/AddmvKernelNpu.cpp +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::addmv_out( - const at::Tensor& self, - const at::Tensor& mat, - const at::Tensor& vec, - at::Scalar beta, - at::Scalar alpha, - at::Tensor& result) { - NpuUtils::check_1d(vec, "vec", "addmv"); - - at::Tensor mat1 = vec.unsqueeze(1); - - // matmul mat*alpha - at::Tensor mat_alpha = at::mul(mat, alpha); - - // matmul*alpha - at::Tensor mmMulResult = at::mm(mat_alpha, mat1); - - at::Tensor mmMulResult1 = mmMulResult.squeeze(); - - // calculate the output size - auto outputSize = addmv_npu_output_size(self, mat, vec, beta, alpha); - - if (!result.sizes().equals(outputSize)) { - result.resize_(outputSize); - } - // matmul*alpha+self*beta - at::add_out(result, mmMulResult1, self, beta); - - return result; -} - -at::Tensor NPUNativeFunctions::addmv( - const at::Tensor& self, - const at::Tensor& mat, - const at::Tensor& vec, - at::Scalar beta, - at::Scalar alpha) { - auto outputSize = addmv_npu_output_size(self, mat, vec, beta, alpha); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - addmv_out(self, mat, vec, beta, alpha, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::addmv_( - at::Tensor& self, - const at::Tensor& mat, - const at::Tensor& vec, - at::Scalar beta, - at::Scalar alpha) { - OpPreparation::CheckMemory({self, mat, vec}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = - addmv_out(contiguousSelf, mat, vec, beta, alpha, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - addmv_out(self, mat, vec, beta, alpha, self); - } - return self; -} - -} // namespace native -} // namespace at_npu - - diff --git a/torch_npu/csrc/aten/ops/AddrKernelNpu.cpp b/torch_npu/csrc/aten/ops/AddrKernelNpu.cpp deleted file mode 100644 index 00c47b2e9f..0000000000 --- a/torch_npu/csrc/aten/ops/AddrKernelNpu.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::addr_out( - const at::Tensor& self, - const at::Tensor& vec1, - const at::Tensor& vec2, - at::Scalar beta, - at::Scalar alpha, - at::Tensor& result) { - NpuUtils::check_1d(vec1, "vec1", "addr"); - NpuUtils::check_1d(vec2, "vec2", "addr"); - - at::Tensor mat1 = vec1.unsqueeze(1); - at::Tensor mat2 = vec2.unsqueeze(0); - - // vecmul vec1&vec2 - at::Tensor mmResult = at::mm(mat1, mat2); - - // matmul*alpha - at::Tensor mmMulResult = at::mul(mmResult, alpha); - - // matmul*alpha+self*beta - at::add_out(result, mmMulResult, self, beta); - - return result; -} - -at::Tensor NPUNativeFunctions::addr( - const at::Tensor& self, - const at::Tensor& vec1, - const at::Tensor& vec2, - at::Scalar beta, - at::Scalar alpha) { - auto outputSize = addr_npu_output_size(self, vec1, vec2, beta, alpha); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - addr_out(self, vec1, vec2, beta, alpha, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::addr_( - at::Tensor& self, - const at::Tensor& vec1, - const at::Tensor& vec2, - at::Scalar beta, - at::Scalar alpha) { - OpPreparation::CheckMemory({self, vec1, vec2}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = - addr_out(contiguousSelf, vec1, vec2, beta, alpha, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - addr_out(self, vec1, vec2, beta, alpha, self); - } - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/AffineGridGeneratorBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/AffineGridGeneratorBackwardKernelNpu.cpp deleted file mode 100644 index 2afe7b1473..0000000000 --- a/torch_npu/csrc/aten/ops/AffineGridGeneratorBackwardKernelNpu.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -namespace{ -at::Tensor _linspace_from_neg_one(const at::Tensor& grid, int64_t num_steps, bool align_corners) { - if (num_steps <= 1) { - return at::tensor(0, grid.options()); - } - auto range = at::linspace(-1, 1, num_steps, grid.options()); - if (!align_corners && num_steps != 0) { - range = range * (num_steps - 1) / num_steps; - } - return range; -} - -at::Tensor& affine_grid_generator_backward_nocheck( - at::Tensor& result, - const at::Tensor& grad, - at::IntArrayRef size, - bool align_corners) { - at::Tensor assist = OpPreparation::ApplyTensor(grad, {size[0], size[2], size[3], 3}); - assist.select(-1, 0).copy_(_linspace_from_neg_one(grad, size[3], align_corners)); - assist.select(-1, 1).copy_(_linspace_from_neg_one(grad, size[2], align_corners).unsqueeze_(-1)); - assist.select(-1, 2).fill_(1); - AT_ASSERT(grad.sizes() == at::IntArrayRef({size[0], size[2], size[3], 2})); - - auto reassist = assist.view({size[0], size[2]*size[3], 3}).transpose(1, 2); - auto grid = grad.view({size[0], size[2]*size[3], 2}); - - OpCommand cmd; - cmd.Name("BatchMatMul") - .Input(reassist) - .Input(grid) - .Output(result) - .Attr("bias", (int64_t)0) - .Attr("adj_x1", (bool)false) - .Attr("adj_x2", (bool)false) - .Run(); - - return result; -} -} // namespace - -at::Tensor NPUNativeFunctions::affine_grid_generator_backward( - const at::Tensor& grad, - at::IntArrayRef size, - bool align_corners) { - TORCH_CHECK(size.size() == 4, "AffineGridGeneratorBackward needs 4d (spatial) input.") - - // calculate the output size - c10::SmallVector outputSize = {size[0], 3, 2}; - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat(grad, outputSize, ACL_FORMAT_ND); - - // calculate the output result of the NPU - affine_grid_generator_backward_nocheck( - result, - grad, - size, - align_corners); - auto fresult = result.transpose(1, 2); - - return fresult; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/AffineGridGeneratorKernelNpu.cpp b/torch_npu/csrc/aten/ops/AffineGridGeneratorKernelNpu.cpp deleted file mode 100644 index 0b172758bc..0000000000 --- a/torch_npu/csrc/aten/ops/AffineGridGeneratorKernelNpu.cpp +++ /dev/null @@ -1,72 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& affine_grid_generator_npu_nocheck( - at::Tensor& result, - const at::Tensor& theta, - at::IntArrayRef size, - bool align_corners) { - - OpCommand cmd; - cmd.Name("AffineGrid") - .Input(theta) - .Input(size, at::kInt) - .Output(result) - .Attr("align_corners", align_corners) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::affine_grid_generator( - const at::Tensor& theta, - at::IntArrayRef size, - bool align_corners) { - TORCH_CHECK(size.size() == 4 || size.size() == 5, - "AffineGridGenerator needs 4d or 5d size(input)."); - // calculate the output size - at::SmallVector outputSize = { }; - if(size.size() == 4) { - outputSize = {size[0], size[2] * size[3], 2}; - } else { - outputSize = {size[0], size[2] * size[3] * size[4], 3}; - } - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(theta, outputSize); - // calculate the output result of the NPU - affine_grid_generator_npu_nocheck( - result, - theta, - size, - align_corners); - - if(size.size() == 4) { - result = result.view({size[0], size[2], size[3], 2}); - } else { - result = result.view({size[0], size[2], size[3], size[4], 3}); - } - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AllKernelNpu.cpp b/torch_npu/csrc/aten/ops/AllKernelNpu.cpp deleted file mode 100644 index d11a357364..0000000000 --- a/torch_npu/csrc/aten/ops/AllKernelNpu.cpp +++ /dev/null @@ -1,120 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -inline at::Tensor all_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - c10::SmallVector dimList, - bool keepdim) { - OpCommand cmd; - cmd.Name("ReduceAll") - .Input(self) - .Input(dimList, at::kLong) - .Output(result) - .Attr("keep_dims", keepdim) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::all_out( - const at::Tensor& self, - int64_t dim, - bool keepdim, - at::Tensor& result) { - c10::SmallVector dimList = {dim}; - - // check result for return - auto outputSize = reduce_ops_npu_output_size(self, dimList, keepdim); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - - // calculate the output result of the NPU - all_out_npu_nocheck( - result, self, dimList, keepdim); - - return result; -} - -at::Tensor NPUNativeFunctions::all(const at::Tensor& self, int64_t dim, bool keepdim) { - TORCH_CHECK(self.scalar_type() == at::ScalarType::Bool || self.scalar_type() == at::ScalarType::Byte, - "all only supports torch.uint8 and torch.bool dtypes"); - TORCH_CHECK(dim >= -(self.dim()) && dim < self.dim(), - "The value of dim must be greater than or equal to -self.dim() and less than self.dim()"); - if (self.numel() == 0) { - c10::SmallVector outputSize; - for(int64_t i = 0; i < self.dim(); i++){ - if(dim != i){ - outputSize.emplace_back(self.size(i)); - } - } - at::Tensor res = OpPreparation::ApplyTensor( - outputSize, - self.options().dtype(at::kInt), - self).fill_(1).to(at::ScalarType::Bool); - return res; - } - - // calculate the output size - at::IntArrayRef dims(dim); - auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - all_out_npu_nocheck(result, self, {dim}, keepdim); - - return result; -} - -at::Tensor NPUNativeFunctions::all(const at::Tensor& self) { - TORCH_CHECK(self.scalar_type() == at::ScalarType::Bool || self.scalar_type() == at::ScalarType::Byte, - "all only supports torch.uint8 and torch.bool dtypes"); - if (self.numel() == 0) { - at::Tensor res = OpPreparation::ApplyTensor({}, self.options().dtype(at::kInt), self).fill_(1).to(at::ScalarType::Bool); - return res; - } - - // calculate the output size - at::IntArrayRef dims; - auto outputSize = reduce_ops_npu_output_size(self, dims, false); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - all_out_npu_nocheck( - result, - self, - CalcuOpUtil::get_dimlist_for_tensor(self), - false); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AmpForeachNonFiniteCheckAndUnscaleKernelNpu.cpp b/torch_npu/csrc/aten/ops/AmpForeachNonFiniteCheckAndUnscaleKernelNpu.cpp deleted file mode 100644 index eb78fce73d..0000000000 --- a/torch_npu/csrc/aten/ops/AmpForeachNonFiniteCheckAndUnscaleKernelNpu.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2022 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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -const int FLOAT_STATUS_OP_DIMS_SIZE = 8; - -bool NPUNativeFunctions::_amp_foreach_non_finite_check_(at::TensorList scaled_grads) { - TORCH_WARN_ONCE("Non finite check on NPU device!"); - - auto options = at::TensorOptions(at_npu::key::NativeDeviceType).dtype(at::kFloat); - at::Tensor float_status = at::zeros({FLOAT_STATUS_OP_DIMS_SIZE}, options); - auto ans = NPUNativeFunctions::npu_get_float_status(float_status); - - auto result = float_status[0].item().to(); - - if(result == true) { - auto ans_clear = NPUNativeFunctions::npu_clear_float_status(float_status); - } - - return result; -} - -void NPUNativeFunctions::_amp_foreach_non_finite_check_and_unscale_(at::TensorList scaled_grads, - at::Tensor& found_inf, - const at::Tensor& inv_scale) { - TORCH_WARN_ONCE("Non finite check and unscale on NPU device!"); - TORCH_CHECK(at_npu::key::isDeviceTensor(inv_scale), "inv_scale must be NPU-Tensor"); - TORCH_CHECK(inv_scale.numel() == 1, "inv_scale must be a 1-element tensor"); - TORCH_CHECK(inv_scale.scalar_type() == at::ScalarType::Float, "inv_scale must be a float tensor"); - - if (scaled_grads.size() == 0) { - return; - } - - if (NPUNativeFunctions::_amp_foreach_non_finite_check_(scaled_grads) == 0) { - auto expected_device = scaled_grads[0].device(); - auto expected_dtype = scaled_grads[0].dtype(); - for (auto t : scaled_grads) { - TORCH_CHECK(at_npu::key::isDeviceTensor(t), "one of scaled_grads was not a NPU tensor."); - TORCH_CHECK(t.device() == expected_device, "scaled_grads must be on the same device."); - TORCH_CHECK(t.dtype() == expected_dtype, "scaled_grads must have the same dtype."); - TORCH_CHECK(t.layout() == at::kStrided, "one of scaled_grads was not a strided tensor."); - - t.mul_(inv_scale); - } - } else { - found_inf.add_(1); - } -} -} -} \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AnchorResponseFlagsKernelNpu.cpp b/torch_npu/csrc/aten/ops/AnchorResponseFlagsKernelNpu.cpp deleted file mode 100644 index 109d0ff650..0000000000 --- a/torch_npu/csrc/aten/ops/AnchorResponseFlagsKernelNpu.cpp +++ /dev/null @@ -1,66 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -static inline void anchor_response_flags_check( - const at::Tensor& self, - at::IntArrayRef featmap_size, - at::IntArrayRef stride){ - TORCH_CHECK( - featmap_size.size() == 2, - "expected feat_map_size equals to 2, but got size ", - featmap_size.size()); - TORCH_CHECK( - self.dim() == 2 && self.size(1) == 4, - "Non-empty 2D gt_bboxes tensor expected but got a tensor with sizes ", - self.sizes()); - TORCH_CHECK( - self.scalar_type() == at::ScalarType::Half || self.scalar_type() == at::ScalarType::Float, - "float16 or float32 tensor expected but got a tensor with dtype: ", - self.scalar_type()); -} - -at::Tensor NPUNativeFunctions::npu_anchor_response_flags( - const at::Tensor& self, - at::IntArrayRef featmap_size, - at::IntArrayRef stride, - int64_t num_base_anchors){ - anchor_response_flags_check(self, featmap_size, stride); - // calculate output size - int64_t outputValue = featmap_size[0] * featmap_size[1] * num_base_anchors; - c10::SmallVector outputSize = {outputValue}; - auto options = self.options().dtype(at::ScalarType::Byte); - at::Tensor result = OpPreparation::ApplyTensor(outputSize, options, self); - NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - - OpCommand cmd; - cmd.Name("AnchorResponseFlags") - .Input(self) - .Output(result) - .Attr("featmap_size", featmap_size) - .Attr("strides", stride) - .Attr("num_base_anchors", num_base_anchors) - .Run(); - - return result; -} - -} // namespace native -} // namespace at diff --git a/torch_npu/csrc/aten/ops/AnyKernelNpu.cpp b/torch_npu/csrc/aten/ops/AnyKernelNpu.cpp deleted file mode 100644 index c7a287bdab..0000000000 --- a/torch_npu/csrc/aten/ops/AnyKernelNpu.cpp +++ /dev/null @@ -1,115 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -inline at::Tensor& any_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - at::SmallVector dimList, - bool keepdim) { - OpCommand cmd; - cmd.Name("ReduceAny") - .Input(self) - .Input(dimList) - .Output(result) - .Attr("keep_dims", keepdim) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::any_out( - const at::Tensor& self, - int64_t dim, - bool keepdim, - at::Tensor& result) { - at::SmallVector dimList; - if (dim == LLONG_MIN) { - dimList = CalcuOpUtil::get_dimlist_for_tensor(self); - } else { - dimList = {dim}; - } - - // check result for return - auto outputSize = reduce_ops_npu_output_size(self, dimList, keepdim); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - - // calculate the output result of the NPU - any_out_npu_nocheck(result, self, dimList, keepdim); - - return result; -} - -at::Tensor NPUNativeFunctions::any(const at::Tensor& self, int64_t dim, bool keepdim) { - // calculate the output size - at::IntArrayRef dims(dim); - auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - - // calculate the output result of the NPU - if (dim == LLONG_MIN) { - any_out_npu_nocheck( - result, self, CalcuOpUtil::get_dimlist_for_tensor(self), keepdim); - } else { - any_out_npu_nocheck(result, self, {dim}, keepdim); - } - - return result; -} - -at::Tensor NPUNativeFunctions::any(const at::Tensor& self) { - // when self's dim = 0, convert [1] tensor and reduce it - if (self.dim() == 0) { - at::Tensor self_tmp = self; - self_tmp = OpPreparation::ApplyTensorWithFormat( - {1}, - self.options().dtype(at::ScalarType::Float), - CalcuOpUtil::get_tensor_npu_format(self)) - .fill_(self.item()) - .to(at::ScalarType::Bool); - return NPUNativeFunctions::any(self_tmp, 0, false); - } - - // calculate the output size - at::IntArrayRef dims; - auto outputSize = reduce_ops_npu_output_size(self, dims, false); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - any_out_npu_nocheck( - result, self, CalcuOpUtil::get_dimlist_for_tensor(self), false); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ApplyAdamKernelNpu.cpp b/torch_npu/csrc/aten/ops/ApplyAdamKernelNpu.cpp deleted file mode 100644 index 146f64704a..0000000000 --- a/torch_npu/csrc/aten/ops/ApplyAdamKernelNpu.cpp +++ /dev/null @@ -1,134 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -std::tuple apply_adam_out_npu_nocheck( - at::Scalar beta1_power, - at::Scalar beta2_power, - at::Scalar lr, - at::Scalar beta1, - at::Scalar beta2, - at::Scalar epsilon, - const at::Tensor& grad, - c10::optional use_locking, - c10::optional use_nesterov, - at::Tensor& var_out, - at::Tensor& m_out, - at::Tensor& v_out) { - OpCommand cmd; - cmd.Name("ApplyAdamD") - .Input(var_out) - .Input(m_out) - .Input(v_out) - .Input(beta1_power, var_out.scalar_type()) - .Input(beta2_power, var_out.scalar_type()) - .Input(lr, var_out.scalar_type()) - .Input(beta1, var_out.scalar_type()) - .Input(beta2, var_out.scalar_type()) - .Input(epsilon, var_out.scalar_type()) - .Input(grad) - .Output(var_out) - .Output(m_out) - .Output(v_out); - if (use_locking != c10::nullopt) { - cmd.Attr("use_locking", bool(use_locking)); - } - if (use_nesterov != c10::nullopt) { - cmd.Attr("use_nesterov", bool(use_nesterov)); - } - cmd.Run(); - return std::tie(var_out, m_out, v_out); -} - -std::tuple NPUNativeFunctions::npu_apply_adam( - at::Scalar beta1_power, - at::Scalar beta2_power, - at::Scalar lr, - at::Scalar beta1, - at::Scalar beta2, - at::Scalar epsilon, - const at::Tensor& grad, - c10::optional use_locking, - c10::optional use_nesterov) { - AT_ERROR("npu_apply_adam is not implemented for Tensor"); -} - -std::tuple NPUNativeFunctions::npu_apply_adam_out( - at::Scalar beta1_power, - at::Scalar beta2_power, - at::Scalar lr, - at::Scalar beta1, - at::Scalar beta2, - at::Scalar epsilon, - const at::Tensor& grad, - c10::optional use_locking, - c10::optional use_nesterov, - at::Tensor& var, - at::Tensor& m, - at::Tensor& v) { - bool var_match = NpuUtils::check_match(&var); - bool m_match = NpuUtils::check_match(&m); - bool v_match = NpuUtils::check_match(&v); - if (!(var_match && m_match && v_match)) { - at::Tensor contiguous_var = var_match ? var : NpuUtils::format_contiguous(var); - at::Tensor contiguous_m = m_match ? m : NpuUtils::format_contiguous(m); - at::Tensor contiguous_v = v_match ? v : NpuUtils::format_contiguous(v); - apply_adam_out_npu_nocheck( - beta1_power, - beta2_power, - lr, - beta1, - beta2, - epsilon, - grad, - use_locking, - use_nesterov, - contiguous_var, - contiguous_m, - contiguous_v); - if (!var_match) { - NpuUtils::format_fresh_view(var, contiguous_var); - } - if (!m_match) { - NpuUtils::format_fresh_view(m, contiguous_m); - } - if (!v_match) { - NpuUtils::format_fresh_view(v, contiguous_v); - } - } else { - apply_adam_out_npu_nocheck( - beta1_power, - beta2_power, - lr, - beta1, - beta2, - epsilon, - grad, - use_locking, - use_nesterov, - var, - m, - v); - } - return std::tie(var, m, v); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ArangeKernelNpu.cpp b/torch_npu/csrc/aten/ops/ArangeKernelNpu.cpp deleted file mode 100644 index 2f1f82d39a..0000000000 --- a/torch_npu/csrc/aten/ops/ArangeKernelNpu.cpp +++ /dev/null @@ -1,176 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -// bool inputs are considered integral -static inline bool allIntegral( - std::initializer_list> l) { - for (at::Scalar& s : l) { - if (!s.isIntegral(true)) { - return false; - } - } - return true; -} - - -at::Tensor& arange_out_npu_nocheck( - at::Tensor& result, - at::Scalar start, - at::Scalar end, - at::Scalar step) { - OpCommand cmd; - cmd.Name("Range") - .Input(start, result.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Input(end, result.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Input(step, result.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::arange( - at::Scalar start, - at::Scalar end, - at::Scalar step, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - - c10::TensorOptions option = c10::TensorOptions().dtype(dtype_opt) - .device(device_opt) - .layout(layout_opt) - .pinned_memory(pin_memory_opt); - - float start_value = CalcuOpUtil::get_scalar_float_value(start); - float end_value = CalcuOpUtil::get_scalar_float_value(end); - float step_value = CalcuOpUtil::get_scalar_float_value(step); - - // Check step start end - TORCH_CHECK(step_value != 0, "step must be nonzero"); - TORCH_CHECK(((step_value > 0) && (end_value >= start_value)) || ((step_value < 0) && (end_value <= start_value)), - "upper bound and larger bound inconsistent with step sign"); - - bool set_to_integral_dtype = - !option.has_dtype() && allIntegral({start, end, step}); - - // check start == end - if (set_to_integral_dtype) { - option = option.dtype(at::ScalarType::Long); - } - at::Tensor result_check = OpPreparation::ApplyTensorWithFormat({0}, option, ACL_FORMAT_ND); - - if (start_value == end_value) { - return result_check; - } - - // calculate the output size - double size_arange = std::ceil(static_cast(end.toDouble() - start.toDouble()) - / step.toDouble()); - int64_t size_value = static_cast(size_arange); - at::SmallVector outputSize = {size_value}; - at::Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, option, ACL_FORMAT_ND); - - if(option.dtype() == at::kHalf) { - result = result.to(at::kFloat); - } - - arange_out_npu_nocheck(result, start, end, step); - - if(option.dtype() == at::kHalf) { - result = result.to(at::kHalf); - } - - return result; -} - -at::Tensor NPUNativeFunctions::arange( - at::Scalar start, - at::Scalar end, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - - return NPUNativeFunctions::arange(start, end, 1, dtype_opt, layout_opt, device_opt, pin_memory_opt); -} - - -at::Tensor NPUNativeFunctions::arange( - at::Scalar end, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - - return NPUNativeFunctions::arange(0, end, dtype_opt, layout_opt, device_opt, pin_memory_opt); // start = 0 -} - -at::Tensor& NPUNativeFunctions::arange_out( - at::Scalar start, - at::Scalar end, - at::Scalar step, - at::Tensor& result) { - float start_value = CalcuOpUtil::get_scalar_float_value(start); - float end_value = CalcuOpUtil::get_scalar_float_value(end); - float step_value = CalcuOpUtil::get_scalar_float_value(step); - - // Check step start end - TORCH_CHECK(step_value != 0, "step must be nonzero"); - TORCH_CHECK(((step_value > 0) && (end_value >= start_value)) || ((step_value < 0) && (end_value <= start_value)), - "upper bound and larger bound inconsistent with step sign"); - - // calculate the output size - double size_arange = std::ceil(static_cast(end.toDouble() - start.toDouble()) - / step.toDouble()); - int64_t size_value = static_cast(size_arange); - at::SmallVector outputSize = {size_value}; - result.resize_(outputSize); - - arange_out_npu_nocheck(result, start, end, step); - - return result; -} - -at::Tensor& arange_other_out_npu(at::Scalar start, at::Scalar end, at::Tensor& result) { - at::Scalar step = 1; - return NPUNativeFunctions::arange_out(start, end, step, result); -} - -at::Tensor& NPUNativeFunctions::arange_out(at::Scalar end, at::Tensor& result) { - return arange_other_out_npu(0, end, result); -} - -at::Tensor NPUNativeFunctions::_dim_arange(const at::Tensor& self, int64_t dim) { - c10::optional dtype_opt(at::kInt); - c10::optional layout_opt(self.options().layout()); - c10::optional device_opt(self.options().device()); - c10::optional pin_memory_opt(self.options().pinned_memory()); - - at::Tensor result = NPUNativeFunctions::arange(self.size(dim), dtype_opt, layout_opt, device_opt, pin_memory_opt); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ArgmaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/ArgmaxKernelNpu.cpp deleted file mode 100644 index a58d196d3d..0000000000 --- a/torch_npu/csrc/aten/ops/ArgmaxKernelNpu.cpp +++ /dev/null @@ -1,49 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::argmax(const at::Tensor& self, at::optional dim, bool keepdim) { - at::Tensor input = dim.has_value() ? self : self.reshape({-1}); - int64_t realDim = dim.has_value() ? dim.value() : 0; - bool realKeepDim = dim.has_value() ? keepdim : false; - - // calculate the output size - auto outputSize = reduce_ops_npu_output_size(input, realDim, realKeepDim); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithSizes(outputSize, self.options().dtype(at::kInt)); - - at::Scalar DimVec = realDim; - // calculate the output result of the NPU - OpCommand cmd; - cmd.Name("ArgMaxV2") - .Input(input) - .Input(DimVec, at::ScalarType::Int) - .Output(result) - .Attr("keep_dims", realKeepDim) - .Run(); - - result = result.to(at::ScalarType::Long); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ArgminKernelNpu.cpp b/torch_npu/csrc/aten/ops/ArgminKernelNpu.cpp deleted file mode 100644 index c0fd98cc59..0000000000 --- a/torch_npu/csrc/aten/ops/ArgminKernelNpu.cpp +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::argmin( - const at::Tensor& self, - c10::optional dim, - bool keepdim) { - TORCH_CHECK( - self.numel() > 0, - "cannot perform reduction function argmin on a " - "tensor with no elements because the operation does not have an identity"); - at::Tensor input = dim.has_value() ? self : self.reshape({-1}); - int64_t realDim = dim.has_value() ? dim.value() : 0; - bool realKeepDim = dim.has_value() ? keepdim : false; - auto outputSize = reduce_ops_npu_output_size(input, realDim, realKeepDim); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options().dtype(at::kInt), - ACL_FORMAT_ND); - c10::SmallVector DimVec = {realDim}; - OpCommand cmd; - cmd.Name("ArgMin") - .Input(input) - .Input(DimVec, at::kInt) - .Output(result) - .Attr("keep_dims", realKeepDim) - .Run(); - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Long); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ArgsortKernelNpu.cpp b/torch_npu/csrc/aten/ops/ArgsortKernelNpu.cpp deleted file mode 100644 index 2732b1d58e..0000000000 --- a/torch_npu/csrc/aten/ops/ArgsortKernelNpu.cpp +++ /dev/null @@ -1,95 +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. -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& argsort_out_npu_no_transpose( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim, - bool descending) { - OpCommand cmd; - cmd.Name("Sort") - .Input(self) - .Output(values) - .Output(indices) - .Attr("axis", dim) - .Attr("descending", descending) - .Run(); - - return indices; -} - -at::Tensor& argsort_out_npu_nocheck( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim, - bool descending) { - dim = make_wrap_dim(dim, self.dim()); - int64_t lastDim = make_wrap_dim(-1, self.dim()); - - at::SmallVector perm; - for (int64_t i = 0; i < self.dim(); i++) { - perm.emplace_back(i); - } - std::swap(perm[dim], perm[lastDim]); - - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); - auto outputSize = transpose_npu_output_size(values, perm); - at::Tensor transposeValues = OpPreparation::ApplyTensor( - values, - outputSize); - at::Tensor transposeIndices = OpPreparation::ApplyTensor( - indices, - outputSize); - - argsort_out_npu_no_transpose( - transposeValues, transposeIndices, transposeSelf, lastDim, descending); - - NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, true, indices); - - // indices dtype transform to Int64 - indices = NPUNativeFunctions::npu_dtype_cast(indices, at::kLong); - - return indices; -} - -at::Tensor NPUNativeFunctions::argsort(const at::Tensor& self, - int64_t dim, - bool descending) { - // construct the output tensor of the NPU - at::Tensor values = OpPreparation::ApplyTensor(self); - at::Tensor indices = OpPreparation::ApplyTensor(self, self.options().dtype(at::kInt)); - // calculate the output result of the NPU - argsort_out_npu_nocheck(values, indices, self, dim, descending); - - return indices; -} - -at::Tensor NPUNativeFunctions::argsort(const at::Tensor& self, - at::Dimname dim, - bool descending) { - return NPUNativeFunctions::argsort(self, dimname_to_position(self, dim), descending); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/AsStridedKernelNpu.cpp b/torch_npu/csrc/aten/ops/AsStridedKernelNpu.cpp index ebc27e65d8..c111de9ec8 100644 --- a/torch_npu/csrc/aten/ops/AsStridedKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/AsStridedKernelNpu.cpp @@ -12,13 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" -#include "torch_npu/csrc/framework/StorageDescHelper.h" -#include "torch_npu/csrc/framework/utils/NpuStorageOffsetGuard.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" +#include namespace at_npu { namespace native { @@ -28,42 +24,34 @@ at::Tensor& stride_copy_out_npu_nocheck( const at::Tensor& self, at::IntArrayRef shape, at::IntArrayRef stride, - at::Scalar storage_offset) { - if ((result.nbytes() < 32) && (!StorageDescHelper::MetaDataAreMatch(&result))) { - // [算子限制] 对于1. 小于一个block的数据搬运 2.result不match,Astrided暂不支持。 - copy_kernel_npu(result, self, false); - return result; - } - // Set the offset of input discontiguous tensor to be 0. - // The accurate offset would be provided as a attr to op. - NpuStorageOffsetGuard guard_input(const_cast(self)); + const at::Scalar& storage_offset) { RECORD_FUNCTION("npuAsStrided", std::vector({self})); OpCommand cmd; cmd.Name("AsStrided") .InputWithoutContiguous(self) .Input(shape) .Input(stride) - .Input(storage_offset, at::kLong, CompileType::MEMORY_HOST_COMPILE_DEPENDENT) + .Input(storage_offset, at::kLong) .Output(result) .Run(); return result; } -at::Tensor& NPUNativeFunctions::npu_stride_copy_out( +at::Tensor& XLANativeFunctions::npu_stride_copy_out( const at::Tensor& self, c10::IntArrayRef shape, c10::IntArrayRef stride, - c10::Scalar storage_offset, + const c10::Scalar& storage_offset, at::Tensor& result) { stride_copy_out_npu_nocheck(result, self, shape, stride, storage_offset); return result; } -at::Tensor NPUNativeFunctions::npu_stride_copy( +at::Tensor XLANativeFunctions::npu_stride_copy( const at::Tensor& self, c10::IntArrayRef shape, c10::IntArrayRef stride, - c10::Scalar storage_offset) { + const c10::Scalar& storage_offset) { // AsStrided OP only supports ND input at::Tensor result = OpPreparation::ApplyTensorWithFormat( shape, self.options(), ACL_FORMAT_ND); diff --git a/torch_npu/csrc/aten/ops/AsinKernelNpu.cpp b/torch_npu/csrc/aten/ops/AsinKernelNpu.cpp deleted file mode 100644 index b0256aa058..0000000000 --- a/torch_npu/csrc/aten/ops/AsinKernelNpu.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& asin_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Asin") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::asin_out( - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - asin_out_npu_nocheck(result, self); - return result; -} - -at::Tensor NPUNativeFunctions::asin(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - asin_out_npu_nocheck(result, self); - return result; -} - -at::Tensor& NPUNativeFunctions::asin_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = asin_out_npu_nocheck(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - asin_out_npu_nocheck(self, self); - } - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/AsinhKernelNpu.cpp b/torch_npu/csrc/aten/ops/AsinhKernelNpu.cpp deleted file mode 100644 index 70996a72ea..0000000000 --- a/torch_npu/csrc/aten/ops/AsinhKernelNpu.cpp +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) 2022, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& asinh_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Asinh") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::asinh_out( - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - asinh_out_npu_nocheck(contiguousResult, self); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - asinh_out_npu_nocheck(result, self); - } - return result; - -} - -at::Tensor NPUNativeFunctions::asinh(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - asinh_out_npu_nocheck(result, self); - return result; -} - -at::Tensor& NPUNativeFunctions::asinh_(at::Tensor& self) { - - return asinh_out(self, self); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/Atan2KernelNpu.cpp b/torch_npu/csrc/aten/ops/Atan2KernelNpu.cpp deleted file mode 100644 index 3a8b976fb4..0000000000 --- a/torch_npu/csrc/aten/ops/Atan2KernelNpu.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& atan2_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - OpCommand cmd; - cmd.Name("Atan2") - .Expect(unified_result) - .Input(self) - .Input(other) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::atan2_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - atan2_out_npu_nocheck(self, other, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - atan2_out_npu_nocheck(self, other, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::atan2(const at::Tensor& self, const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - atan2_out_npu_nocheck(self, other, result); - return result; -} - -at::Tensor& NPUNativeFunctions::atan2_(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other}, {self}); - NPUNativeFunctions::atan2_out(self, other, self); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/AtanKernelNpu.cpp b/torch_npu/csrc/aten/ops/AtanKernelNpu.cpp deleted file mode 100644 index 0adf46763c..0000000000 --- a/torch_npu/csrc/aten/ops/AtanKernelNpu.cpp +++ /dev/null @@ -1,57 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& atan_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Atan") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::atan_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - atan_out_npu_nocheck(self, result); - return result; -} - -at::Tensor NPUNativeFunctions::atan(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - atan_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::atan_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = atan_out_npu_nocheck(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - atan_out_npu_nocheck(self, self); - } - return self; -} - -}} // namespace at_npu::native \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/AtanhKernelNpu.cpp b/torch_npu/csrc/aten/ops/AtanhKernelNpu.cpp deleted file mode 100644 index 1a780f21fa..0000000000 --- a/torch_npu/csrc/aten/ops/AtanhKernelNpu.cpp +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) 2022 Huawei Technologies Co., Ltd -// Copyright (c) 2022, 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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& atanh_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Atanh") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::atanh_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - atanh_out_npu_nocheck(self, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - atanh_out_npu_nocheck(self, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::atanh(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - atanh_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::atanh_(at::Tensor& self) { - return atanh_out(self, self); -} - -}} // namespace at_npu::native \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BaddbmmKernelNpu.cpp b/torch_npu/csrc/aten/ops/BaddbmmKernelNpu.cpp deleted file mode 100644 index 2284d9b424..0000000000 --- a/torch_npu/csrc/aten/ops/BaddbmmKernelNpu.cpp +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& baddbmm_nocheck( - const at::Tensor& self, - const at::Tensor& tensor1, - const at::Tensor& tensor2, - at::Scalar beta, - at::Scalar alpha, - at::Tensor& result) { - auto outputSize = baddbmm_npu_output_size(tensor1, tensor2); - at::Tensor BatchMatMulTensor = OpPreparation::ApplyTensor(self, outputSize); - - bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(tensor1); - bool isMat2T = CalcuOpUtil::is_transpose_last_two_dims(tensor2); - - - OpCommand cmd; - cmd.Name("BatchMatMul") - .Input(tensor1) - .Input(tensor2) - .Output(BatchMatMulTensor) - .Attr("adj_x1", isSelfT) - .Attr("adj_x2", isMat2T) - .Run(); - - at::Tensor alphaMulTensor = NPUNativeFunctions::mul(BatchMatMulTensor, alpha); - at::Tensor betaMulTensor = NPUNativeFunctions::mul(self, beta); - NPUNativeFunctions::add_out(alphaMulTensor, betaMulTensor, 1, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::baddbmm_out( - const at::Tensor& self, - const at::Tensor& tensor1, - const at::Tensor& tensor2, - at::Scalar beta, - at::Scalar alpha, - at::Tensor& result){ - - OpPreparation::CheckOut( - {self, tensor1, tensor2}, - result, - self); - baddbmm_nocheck(self, tensor1, tensor2, beta, alpha, result); - - return result; -} - -at::Tensor NPUNativeFunctions::baddbmm( - const at::Tensor& self, - const at::Tensor& tensor1, - const at::Tensor& tensor2, - at::Scalar beta, - at::Scalar alpha) { - at::Tensor outputTensor = self; - auto outputSize = baddbmm_npu_output_size(tensor1, tensor2); - at::Tensor result = OpPreparation::ApplyTensor( - outputTensor, - outputSize); - NPUNativeFunctions::baddbmm_out(self, tensor1, tensor2, beta, alpha, result); - return result; -} - -at::Tensor& NPUNativeFunctions::baddbmm_( - at::Tensor& self, - const at::Tensor& tensor1, - const at::Tensor& tensor2, - at::Scalar beta, - at::Scalar alpha) { - c10::SmallVector inputs = {self, tensor1, tensor2}; - c10::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::baddbmm_out(contiguousSelf, tensor1, tensor2, beta, alpha, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::baddbmm_out(self, tensor1, tensor2, beta, alpha, self); - } - - return self; -} -} -} diff --git a/torch_npu/csrc/aten/ops/BatchNMSKernelNpu.cpp b/torch_npu/csrc/aten/ops/BatchNMSKernelNpu.cpp deleted file mode 100644 index 5b803bed92..0000000000 --- a/torch_npu/csrc/aten/ops/BatchNMSKernelNpu.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::npu_batch_nms( - const at::Tensor& self, - const at::Tensor& scores, - double score_threshold, - double iou_threshold, - int64_t max_size_per_class, - int64_t max_total_size, - bool change_coordinate_frame, - bool transpose_box) { - at::Tensor nmsed_boxes = OpPreparation::ApplyTensor( - {self.size(0), max_total_size, 4}, - self.options(), - self); - at::Tensor nmsed_scores = OpPreparation::ApplyTensor( - {self.size(0), max_total_size}, - self.options(), - self); - at::Tensor nmsed_classes = OpPreparation::ApplyTensor( - {self.size(0), max_total_size}, - self.options(), - self); - at::Tensor nmsed_num = OpPreparation::ApplyTensor( - {self.size(0)}, - self.options().dtype(at::kInt), - self); - OpCommand cmd; - cmd.Name("BatchMultiClassNonMaxSuppression") - .Input(self) - .Input(scores) - .Output(nmsed_boxes) - .Output(nmsed_scores) - .Output(nmsed_classes) - .Output(nmsed_num) - .Attr("score_threshold", static_cast(score_threshold)) - .Attr("iou_threshold", static_cast(iou_threshold)) - .Attr("max_size_per_class", max_size_per_class) - .Attr("max_total_size", max_total_size) - .Attr("change_coordinate_frame", change_coordinate_frame) - .Attr("transpose_box", transpose_box) - .Run(); - return std::tie(nmsed_boxes, nmsed_scores, nmsed_classes, nmsed_num); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/BernoulliKernelNpu.cpp b/torch_npu/csrc/aten/ops/BernoulliKernelNpu.cpp deleted file mode 100644 index 384ceccd21..0000000000 --- a/torch_npu/csrc/aten/ops/BernoulliKernelNpu.cpp +++ /dev/null @@ -1,126 +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. - -#include -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUGeneratorImpl.h" - -namespace at_npu { -namespace native { - -at::Tensor& bernoulli_npu_nocheck(at::Tensor& y, at::Tensor& shape, double prob, int64_t seed, int64_t offset) { - shape = NPUNativeFunctions::npu_dtype_cast(shape, at::ScalarType::Long); - OpCommand cmd; - cmd.Name("StatelessBernoulli") - .Input(shape) - .Input(at::Scalar(prob), at::ScalarType::Float) - .Input(at::Scalar(seed), at::ScalarType::Long) - .Input(at::Scalar(offset), at::ScalarType::Long) - .Output(y) - .Run(); - return y; -} - -at::Tensor& bernoulli_npu_nocheck(at::Tensor& y, at::Tensor& shape, const at::Tensor& prob, int64_t seed, int64_t offset) { - shape = NPUNativeFunctions::npu_dtype_cast(shape, at::ScalarType::Long); - OpCommand cmd; - cmd.Name("StatelessBernoulli") - .Input(shape) - .Input(prob) - .Input(at::Scalar(seed), at::ScalarType::Long) - .Input(at::Scalar(offset), at::ScalarType::Long) - .Output(y) - .Run(); - return y; -} - -at::Tensor& NPUNativeFunctions::bernoulli_(at::Tensor& self, double p, c10::optional gen) { - auto gen_ = at::get_generator_or_default(gen, at_npu::detail::getDefaultNPUGenerator()); - auto pair = gen_->philox_engine_inputs(10); - const int64_t seed = pair.first; - const int64_t offset = pair.second; - - at::ScalarType selfType = self.scalar_type(); - at::Tensor selfFp32 = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfFp32 = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfFp32); - at::Tensor result = bernoulli_npu_nocheck(contiguousSelf, contiguousSelf, p, seed, offset); - NpuUtils::format_fresh_view(self, result); - } else { - bernoulli_npu_nocheck(selfFp32, selfFp32, p, seed, offset); - self.copy_(selfFp32); - } - - if(self.scalar_type() != selfType){ - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Half); - } - return self; -} - -at::Tensor& NPUNativeFunctions::bernoulli_(at::Tensor& self, const at::Tensor& p, c10::optional gen) { - auto gen_ = at::get_generator_or_default(gen, at_npu::detail::getDefaultNPUGenerator()); - auto pair = gen_->philox_engine_inputs(10); - const int64_t seed = pair.first; - const int64_t offset = pair.second; - - at::ScalarType selfType = self.scalar_type(); - at::Tensor selfFp32 = self; - at::Tensor pFp32 = OpPreparation::CastBackToOriFormat(p); - if (self.scalar_type() == at::ScalarType::Half) { - selfFp32 = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - pFp32 = NPUNativeFunctions::npu_dtype_cast(p, at::ScalarType::Float); - } - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfFp32); - at::Tensor result = bernoulli_npu_nocheck(contiguousSelf, contiguousSelf, pFp32, seed, offset); - NpuUtils::format_fresh_view(self, result); - } else { - bernoulli_npu_nocheck(selfFp32, selfFp32, pFp32, seed, offset); - self.copy_(selfFp32); - } - - if(self.scalar_type() != selfType){ - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Half); - } - return self; -} - -at::Tensor NPUNativeFunctions::bernoulli(const at::Tensor& self, c10::optional gen) { - at::Tensor selfCopy = OpPreparation::ApplyTensorWithFormat(self.sizes(), self.options(), ACL_FORMAT_ND); - selfCopy.copy_(self); - return NPUNativeFunctions::bernoulli_(selfCopy, self, gen); -} - -at::Tensor NPUNativeFunctions::bernoulli(const at::Tensor& self, double p, c10::optional gen) { - return at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT).bernoulli_(p, gen); -} - -at::Tensor& NPUNativeFunctions::bernoulli_out(const at::Tensor& self, c10::optional gen, at::Tensor& result) { - result.resize_(self.sizes()).bernoulli_(self, gen); - at::namedinference::propagate_names(result, self); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/BertApplyAdamKernelNpu.cpp b/torch_npu/csrc/aten/ops/BertApplyAdamKernelNpu.cpp deleted file mode 100644 index 99a4a6b7c0..0000000000 --- a/torch_npu/csrc/aten/ops/BertApplyAdamKernelNpu.cpp +++ /dev/null @@ -1,100 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -tuple bert_apply_adam_out_npu_nocheck( - at::Tensor& var_out, - at::Tensor& m_out, - at::Tensor& v_out, - const at::Tensor& var, - const at::Tensor& m, - const at::Tensor& v, - at::Scalar lr, - at::Scalar beta1, - at::Scalar beta2, - at::Scalar epsilon, - const at::Tensor& grad, - at::Scalar max_grad_norm, - at::Scalar global_grad_norm, - at::Scalar weight_decay, - c10::optional step_size, - int64_t adam_mode) { - std::string adamMode = adam_mode == 0 ? "adam" : "mbart_adam"; - OpCommand cmd; - cmd.Name("ApplyAdamV2") - .Input(var) - .Input(m) - .Input(v) - .Input(lr, var.scalar_type()) - .Input(beta1, var.scalar_type()) - .Input(beta2, var.scalar_type()) - .Input(epsilon, var.scalar_type()) - .Input(grad) - .Input(max_grad_norm, var.scalar_type()) - .Input(global_grad_norm, var.scalar_type()) - .Input(weight_decay, var.scalar_type()); - if (step_size.has_value()) { - cmd.Input(step_size.value(), var.scalar_type()); - } - cmd.Output(var_out) - .Output(m_out) - .Output(v_out) - .Attr("adam_mode", adamMode) - .Run(); - return std::tie(var_out, m_out, v_out); -} - -std::tuple NPUNativeFunctions::npu_bert_apply_adam( - c10::Scalar lr, - c10::Scalar beta1, - c10::Scalar beta2, - c10::Scalar epsilon, - const at::Tensor& grad, - c10::Scalar max_grad_norm, - c10::Scalar global_grad_norm, - c10::Scalar weight_decay, - c10::optional step_size, - int64_t adam_mode) { - AT_ERROR("npu_bert_apply_adam is not implemented for Tensor"); -} - -tuple NPUNativeFunctions::npu_bert_apply_adam_out( - at::Scalar lr, - at::Scalar beta1, - at::Scalar beta2, - at::Scalar epsilon, - const at::Tensor& grad, - at::Scalar max_grad_norm, - at::Scalar global_grad_norm, - at::Scalar weight_decay, - c10::optional step_size, - int64_t adam_mode, - at::Tensor& var, - at::Tensor& m, - at::Tensor& v) { - bert_apply_adam_out_npu_nocheck( - var, m, v, var, m, v, - lr, beta1, beta2, epsilon, grad, max_grad_norm, global_grad_norm, weight_decay, step_size, adam_mode); - - return std::tie(var, m, v); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BinaryCrossEntropyBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/BinaryCrossEntropyBackwardKernelNpu.cpp deleted file mode 100644 index b32cb34c7c..0000000000 --- a/torch_npu/csrc/aten/ops/BinaryCrossEntropyBackwardKernelNpu.cpp +++ /dev/null @@ -1,71 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" - -namespace at_npu { -namespace native { - -at::Tensor& binary_cross_entropy_backward_out_npu_nocheck( - at::Tensor& gradInput, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - const at::Tensor& weight, - int64_t reduction) { - at::Tensor weightTensor = weight.defined() ? weight : - at::ones(self.sizes(), self.options()); - std::string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - OpCommand cmd; - cmd.Name("BinaryCrossEntropyGrad") - .Input(self) - .Input(target) - .Input(grad_output) - .Input(weightTensor) - .Output(gradInput) - .Attr("reduction", reductionStr) - .Run(); - return gradInput; -} - -at::Tensor& NPUNativeFunctions::binary_cross_entropy_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight_opt, - int64_t reduction, - at::Tensor& gradInput) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - binary_cross_entropy_backward_out_npu_nocheck(gradInput, grad_output, self, target, weight, reduction); - return gradInput; -} - -at::Tensor NPUNativeFunctions::binary_cross_entropy_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight_opt, - int64_t reduction) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - at::Tensor gradInput = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - binary_cross_entropy_backward_out_npu_nocheck(gradInput, grad_output, self, target, weight, reduction); - return gradInput; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp b/torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp deleted file mode 100644 index af1186022f..0000000000 --- a/torch_npu/csrc/aten/ops/BinaryCrossEntropyKernelNpu.cpp +++ /dev/null @@ -1,73 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::binary_cross_entropy_out( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight_opt, - int64_t reduction, - at::Tensor& result) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - at::Tensor weightTensor = weight; - if (!weight.defined()) { - weightTensor = at::ones(self.sizes(), self.options()); - } - - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - OpCommand cmd; - cmd.Name("BinaryCrossEntropy") - .Input(self) - .Input(target) - .Input(weightTensor) - .Output(result) - .Attr("reduction", reductionStr) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::binary_cross_entropy( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight_opt, - int64_t reduction) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - - at::IntArrayRef outputSize; - if (reduction == at::Reduction::None) { - outputSize = input_same_output_size(self); - } else { - outputSize = at::ArrayRef(); - } - - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - if (self.numel() == 0) { - result = result.to(at::kFloat).fill_(0); - result = result / 0; - return result; - } - - NPUNativeFunctions::binary_cross_entropy_out(self, target, weight, reduction, result); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BinaryCrossEntropyWithLogitsBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/BinaryCrossEntropyWithLogitsBackwardKernelNpu.cpp deleted file mode 100644 index 08e86a3afd..0000000000 --- a/torch_npu/csrc/aten/ops/BinaryCrossEntropyWithLogitsBackwardKernelNpu.cpp +++ /dev/null @@ -1,66 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::binary_cross_entropy_with_logits_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight_opt, - const c10::optional& pos_weight_opt, - int64_t reduction) { - - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - const at::Tensor& pos_weight = c10::value_or_else(pos_weight_opt, [] {return at::Tensor();}); - - at::Tensor gradInput = OpPreparation::ApplyTensor(self); - at::Tensor weightTensor; - if (weight.defined()) { - weightTensor = NpuUtils::format_contiguous(weight); - } else { - weightTensor = at::ones(self.sizes(), self.options()); - } - - at::Tensor posWeightTensor; - if (pos_weight.defined()) { - posWeightTensor = NpuUtils::format_contiguous(pos_weight); - } else { - posWeightTensor = at::ones(self.sizes(), self.options()); - } - - at::Tensor doutTensor = NPUNativeFunctions::npu_broadcast(grad_output, self.sizes()); - std::string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - OpCommand cmd; - cmd.Name("SigmoidCrossEntropyWithLogitsGradV2") - .Input(self) - .Input(target) - .Input(doutTensor) - .Input(weightTensor) - .Input(posWeightTensor) - .Output(gradInput) - .Attr("reduction", reductionStr) - .Run(); - - return gradInput; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BinaryCrossEntropyWithLogitsKernelNpu.cpp b/torch_npu/csrc/aten/ops/BinaryCrossEntropyWithLogitsKernelNpu.cpp deleted file mode 100644 index 6b4b2d8eba..0000000000 --- a/torch_npu/csrc/aten/ops/BinaryCrossEntropyWithLogitsKernelNpu.cpp +++ /dev/null @@ -1,71 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::binary_cross_entropy_with_logits( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight_opt, - const c10::optional& pos_weight_opt, - int64_t reduction) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - const at::Tensor& pos_weight = c10::value_or_else(pos_weight_opt, [] {return at::Tensor();}); - at::IntArrayRef outputSize; - int64_t resultformat = CalcuOpUtil::get_tensor_npu_format(self); - - if (reduction == at::Reduction::None) { - outputSize = input_same_output_size(self); - } else { - outputSize = at::ArrayRef(); - resultformat = ACL_FORMAT_ND; - } - - at::Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, target.options(), resultformat); - at::Tensor weightTensor; - if (weight.defined()) { - weightTensor = NpuUtils::format_contiguous(weight); - } else { - weightTensor = at::ones(target.sizes(), target.options()); - } - - at::Tensor posWeightTensor; - if (pos_weight.defined()) { - posWeightTensor = NpuUtils::format_contiguous(pos_weight); - } else { - posWeightTensor = at::ones(target.sizes(), target.options()); - } - - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - OpCommand cmd; - cmd.Name("SigmoidCrossEntropyWithLogitsV2") - .Input(self.to(target.dtype())) - .Input(target) - .Input(weightTensor) - .Input(posWeightTensor) - .Output(result) - .Attr("reduction", reductionStr) - .Run(); - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BincountKernelNpu.cpp b/torch_npu/csrc/aten/ops/BincountKernelNpu.cpp deleted file mode 100644 index 6f159f8042..0000000000 --- a/torch_npu/csrc/aten/ops/BincountKernelNpu.cpp +++ /dev/null @@ -1,76 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& bincount_npu_nocheck( - const at::Tensor& self, - const at::Tensor& weights, - int64_t sizes, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("Bincount") - .Input(self) - .Input(at::Scalar(sizes), at::ScalarType::Int) - .Input(weights) - .Output(result) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::bincount( - const at::Tensor& self, - const c10::optional& weight_opt, - int64_t minlength) { - const at::Tensor& weights = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - if (self.sizes()[0] == 0) { - auto result = OpPreparation::ApplyTensorWithSizes( - {0}, - self.options().dtype(at::ScalarType::Long)); - return result; - } - - // calculate output size - auto sizes = static_cast( - CalcuOpUtil::get_scalar_float_value(NPUNativeFunctions::max(self).item())); - sizes = (sizes < minlength) ? minlength : (sizes + 1); - - // input convert to int32 - if (self.dtype() == at::ScalarType::Long) { - TORCH_WARN_ONCE("CANN: Bincount cann't support dtype int64."); - } - auto input = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Int); - - // weight convert dtype as same as output defined by torch - auto weight = weights; - if (!weights.defined()) { - at::TensorOptions options = input.options(); - weight = NPUNativeFunctions::ones(input.sizes(), at::ScalarType::Long, options.layout(), options.device(), options.pinned_memory()); - } else if (!(weights.dtype() == at::ScalarType::Float)) { - weight = NPUNativeFunctions::npu_dtype_cast(weights, at::ScalarType::Double); - } - - auto result = OpPreparation::ApplyTensor(weight, {sizes}); - bincount_npu_nocheck(input, weight, sizes, result); - - return result; -} -} // namespace native -} // namespace at diff --git a/torch_npu/csrc/aten/ops/BitwiseAndKernelNpu.cpp b/torch_npu/csrc/aten/ops/BitwiseAndKernelNpu.cpp index 1c061170f7..3a36174391 100644 --- a/torch_npu/csrc/aten/ops/BitwiseAndKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/BitwiseAndKernelNpu.cpp @@ -14,7 +14,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -36,7 +36,7 @@ at::Tensor& bitwise_and_out_npu_nocheck( return result; } -at::Tensor & NPUNativeFunctions::bitwise_and_out(const at::Tensor & self, at::Scalar other, at::Tensor & result) { +at::Tensor & XLANativeFunctions::bitwise_and_out(const at::Tensor & self, const at::Scalar& other, at::Tensor & result) { OpPreparation::CheckOut( {self}, result, @@ -55,9 +55,9 @@ at::Tensor& bitwise_and_out_npu_nocheck( const at::Tensor& other) { auto unified_result = OpPreparation::binary_op_check(result, self, other, true); if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) { - NPUNativeFunctions::bitwise_and_out(self, other.item(), result); + XLANativeFunctions::bitwise_and_out(self, other.item(), result); } else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) { - NPUNativeFunctions::bitwise_and_out(other, self.item(), result); + XLANativeFunctions::bitwise_and_out(other, self.item(), result); } else { // executing the NPU operator string real_op_name = (self.dtype() == at::ScalarType::Bool) ? "LogicalAnd" : "BitwiseAnd"; @@ -74,7 +74,7 @@ at::Tensor& bitwise_and_out_npu_nocheck( return result; } -at::Tensor & NPUNativeFunctions::bitwise_and_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & result) { +at::Tensor & XLANativeFunctions::bitwise_and_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & result) { bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); at::Tensor ref_tensor; @@ -98,7 +98,7 @@ at::Tensor & NPUNativeFunctions::bitwise_and_out(const at::Tensor & self, const return result; } -at::Tensor NPUNativeFunctions::bitwise_and(const at::Tensor& self, const at::Tensor& other) { +at::Tensor XLANativeFunctions::bitwise_and(const at::Tensor& self, const at::Tensor& other) { // calculate the output size bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); @@ -123,7 +123,7 @@ at::Tensor NPUNativeFunctions::bitwise_and(const at::Tensor& self, const at::Ten return result; } -at::Tensor NPUNativeFunctions::bitwise_and(const at::Tensor& self, at::Scalar other) { +at::Tensor XLANativeFunctions::bitwise_and(const at::Tensor& self, const at::Scalar& other) { // calculate the output size auto outputSize = input_same_output_size(self); @@ -137,7 +137,7 @@ at::Tensor NPUNativeFunctions::bitwise_and(const at::Tensor& self, at::Scalar ot return result; } -at::Tensor& NPUNativeFunctions::bitwise_and_(at::Tensor& self, const at::Tensor& other) { +at::Tensor& XLANativeFunctions::bitwise_and_(at::Tensor& self, const at::Tensor& other) { c10::SmallVector inputs = {self, other}; c10::SmallVector outputs = {self}; CalcuOpUtil::check_memory_over_laps(inputs, outputs); @@ -153,7 +153,7 @@ at::Tensor& NPUNativeFunctions::bitwise_and_(at::Tensor& self, const at::Tensor& return self; } -at::Tensor& NPUNativeFunctions::bitwise_and_(at::Tensor& self, at::Scalar other) { +at::Tensor& XLANativeFunctions::bitwise_and_(at::Tensor& self, const at::Scalar& other) { if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); at::Tensor result = bitwise_and_out_npu_nocheck(contiguousSelf, contiguousSelf, other); diff --git a/torch_npu/csrc/aten/ops/BitwiseNotKernelNpu.cpp b/torch_npu/csrc/aten/ops/BitwiseNotKernelNpu.cpp deleted file mode 100644 index 81faf2ede0..0000000000 --- a/torch_npu/csrc/aten/ops/BitwiseNotKernelNpu.cpp +++ /dev/null @@ -1,63 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& bitwise_not_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - string real_op_name = - (self.dtype() == at::ScalarType::Bool) ? "LogicalNot" : "Invert"; - - OpCommand cmd; - cmd.Name(real_op_name) - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::bitwise_not_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - bitwise_not_out_npu_nocheck(result, self); - return result; -} - -at::Tensor NPUNativeFunctions::bitwise_not(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - bitwise_not_out_npu_nocheck(result, self); - return result; -} - -at::Tensor& NPUNativeFunctions::bitwise_not_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = bitwise_not_out_npu_nocheck(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - bitwise_not_out_npu_nocheck(self, self); - } - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BitwiseOrKernelNpu.cpp b/torch_npu/csrc/aten/ops/BitwiseOrKernelNpu.cpp deleted file mode 100644 index 164b2e7174..0000000000 --- a/torch_npu/csrc/aten/ops/BitwiseOrKernelNpu.cpp +++ /dev/null @@ -1,160 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& bitwise_or_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Scalar other) { - // executing the NPU operator - string real_op_name = - (self.dtype() == at::ScalarType::Bool) ? "LogicalOr" : "BitwiseOr"; - - OpCommand cmd; - cmd.Name(real_op_name) - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::bitwise_or_out( - const at::Tensor& self, - const at::Scalar other, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - bitwise_or_out_npu_nocheck(result, self, other); - return result; -} - -at::Tensor& bitwise_or_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& other) { - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) { - NPUNativeFunctions::bitwise_or_out(self, other.item(), result); - } else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) { - NPUNativeFunctions::bitwise_or_out(other, self.item(), result); - } else { - // executing the NPU operator - string real_op_name = - (self.dtype() == at::ScalarType::Bool) ? "LogicalOr" : "BitwiseOr"; - - OpCommand cmd; - cmd.Name(real_op_name) - .Expect(unified_result) - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - return result; -} - -at::Tensor& NPUNativeFunctions::bitwise_or_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - - at::Tensor outputTensor; - if (isSelfWrapped) { - outputTensor = other; - } else { - outputTensor = self; - } - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(outputTensor), - outputTensor.scalar_type(), - outputSize); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor newResult = bitwise_or_out_npu_nocheck(contiguousResult, self, other); - NpuUtils::format_fresh_view(result, newResult); - } else { - bitwise_or_out_npu_nocheck(result, self, other); - } - return result; -} - -at::Tensor NPUNativeFunctions::bitwise_or(const at::Tensor& self, const at::Tensor& other) { - // calculate the output size - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - - at::Tensor outputTensor; - if (isSelfWrapped) { - outputTensor = other; - } else { - outputTensor = self; - } - - auto outputSize = broadcast_ops_npu_output_size(self, other); - - // construct the output Tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(outputTensor, outputSize); - // calculate the output result of the NPU - bitwise_or_out_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor NPUNativeFunctions::bitwise_or(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - - // calculate the output result of the NPU - bitwise_or_out_npu_nocheck(result, self, other); - return result; -} - -at::Tensor& NPUNativeFunctions::bitwise_or_(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other}, {self}); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = bitwise_or_out_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - bitwise_or_out_npu_nocheck(self, self, other); - } - return self; -} - -at::Tensor& NPUNativeFunctions::bitwise_or_(at::Tensor& self, at::Scalar other) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = bitwise_or_out_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - bitwise_or_out_npu_nocheck(self, self, other); - } - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/BitwiseXorKernelNpu.cpp b/torch_npu/csrc/aten/ops/BitwiseXorKernelNpu.cpp deleted file mode 100644 index 3e5b0c02c9..0000000000 --- a/torch_npu/csrc/aten/ops/BitwiseXorKernelNpu.cpp +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& bitwise_xor_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Scalar other) { - // executing the NPU operator - at::Tensor selfInput = (self.dtype() == at::ScalarType::Bool) ? self.to(at::ScalarType::Int) : self; - result = (result.dtype() == at::ScalarType::Bool) ? result.to(at::ScalarType::Int) : result; - - OpCommand cmd; - cmd.Name("BitwiseXor") - .Input(selfInput) - .Input(other, selfInput.scalar_type()) - .Output(result) - .Run(); - - return (result = (self.dtype() == at::ScalarType::Bool) ? result.to(at::ScalarType::Bool) : result); -} - -at::Tensor& NPUNativeFunctions::bitwise_xor_out( - const at::Tensor& self, - const at::Scalar other, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - bitwise_xor_out_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor& bitwise_xor_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& other) { - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - - at::Tensor selfInput = (self.dtype() == at::ScalarType::Bool) ? self.to(at::ScalarType::Int) : self; - at::Tensor otherInput = (other.dtype() == at::ScalarType::Bool) ? other.to(at::ScalarType::Int) : other; - result = (result.dtype() == at::ScalarType::Bool) ? result.to(at::ScalarType::Int) : result; - - if (otherInput.dim() == 0 && !at_npu::key::isDeviceTensor(otherInput)) { - NPUNativeFunctions::bitwise_xor_out(selfInput, otherInput.item(), result); - } else if (selfInput.dim() == 0 && !at_npu::key::isDeviceTensor(selfInput)) { - NPUNativeFunctions::bitwise_xor_out(otherInput, selfInput.item(), result); - } else { - // executing the NPU operator - OpCommand cmd; - cmd.Name("BitwiseXor") - .Expect(unified_result) - .Input(selfInput) - .Input(otherInput) - .Output(result) - .Run(); - } - - return (result = (self.dtype() == at::ScalarType::Bool) ? result.to(at::ScalarType::Bool) : result); -} - -at::Tensor& NPUNativeFunctions::bitwise_xor_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - - at::Tensor outputTensor; - if (not isSelfWrapped) { - outputTensor = self; - } else { - outputTensor = other; - } - - auto outputSize = broadcast_ops_npu_output_size(self, other); - - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(outputTensor), - outputTensor.scalar_type(), - outputSize); - - bitwise_xor_out_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor NPUNativeFunctions::bitwise_xor(const at::Tensor& self, const at::Tensor& other) { - // calculate the output size - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - - at::Tensor outputTensor; - if (not isSelfWrapped) { - outputTensor = self; - } else { - outputTensor = other; - } - - auto outputSize = broadcast_ops_npu_output_size(self, other); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(outputTensor, outputSize); - // calculate the output result of the NPU - bitwise_xor_out_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor NPUNativeFunctions::bitwise_xor(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - bitwise_xor_out_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor& NPUNativeFunctions::bitwise_xor_(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = bitwise_xor_out_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - bitwise_xor_out_npu_nocheck(self, self, other); - } - - return self; -} - -at::Tensor& NPUNativeFunctions::bitwise_xor_(at::Tensor& self, at::Scalar other) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = bitwise_xor_out_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - bitwise_xor_out_npu_nocheck(self, self, other); - } - - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/BmmKernelNpu.cpp b/torch_npu/csrc/aten/ops/BmmKernelNpu.cpp deleted file mode 100644 index cfedf7117e..0000000000 --- a/torch_npu/csrc/aten/ops/BmmKernelNpu.cpp +++ /dev/null @@ -1,106 +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. - -#include "torch_npu/csrc/core/npu/register/OptionsManager.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::bmm_out(const at::Tensor& self, const at::Tensor& mat2, at::Tensor& result) { - at::Tensor contiguousResult = result.is_contiguous() ? result : result.contiguous(); - - at::Tensor contiguousSelf = self; - at::Tensor contiguousMat2 = mat2; - bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(self); - bool isMat2T = CalcuOpUtil::is_transpose_last_two_dims(mat2); - - if(!isSelfT){ - contiguousSelf = NpuUtils::format_contiguous_add_copy_optimize(self); - } - if(!isMat2T){ - contiguousMat2 = NpuUtils::format_contiguous_add_copy_optimize(mat2); - } - - // executing the NPU operator - OpCommand cmd; - cmd.Name("BatchMatMul") - .InputWithoutContiguous(contiguousSelf) - .InputWithoutContiguous(contiguousMat2) - .Output(contiguousResult) - .Attr("adj_x1", isSelfT) - .Attr("adj_x2", isMat2T) - .Run(); - - if (!result.is_contiguous()) { - result.copy_(contiguousResult); - } - return result; -} - -at::Tensor NPUNativeFunctions::bmm(const at::Tensor& self, const at::Tensor& mat2) { - // calculate the output size - auto outputSize = {self.size(0), self.size(1), mat2.size(2)}; - - // construct the output tensor of the NPU - at::Tensor result; - const auto &options = self.options(); - - // 检查是否指定mm输出为NCHW。待NLP模型总体策略制定后删去 - if ((self.scalar_type() == at::ScalarType::Half)) { - // check is 16-algined with high-performance - auto isAligin = [&]() { - return (!(static_cast(self.size(1)) & 0x0000000F)) && - (!(static_cast(self.size(2)) & 0x0000000F)) && - (!(static_cast(mat2.size(1)) & 0x0000000F)) && - (!(static_cast(mat2.size(2)) & 0x0000000F)); - }; - static auto mm_bmm_nd = env::CheckMmBmmNDEnable(); - // There is a data trampling problem in non-aligned scenes. For the time being, only aligned scenes are supported. - if (FormatHelper::IsBaseFormatType(self) && FormatHelper::IsBaseFormatType(mat2) && - mm_bmm_nd && isAligin()) { - result = NPUNativeFunctions::empty_with_format( - outputSize, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), - options.device_opt(), options.pinned_memory_opt(), ACL_FORMAT_ND); - } else { - result = NPUNativeFunctions::empty_with_format( - outputSize, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), - options.device_opt(), options.pinned_memory_opt(), ACL_FORMAT_FRACTAL_NZ); - } - } else { - result = NPUNativeFunctions::empty_with_format( - outputSize, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), - options.device_opt(), options.pinned_memory_opt(), ACL_FORMAT_ND); - } - - // calculate the output result of the NPU - NPUNativeFunctions::bmm_out(self, mat2, result); - - return result; -} - -at::Tensor NPUNativeFunctions::_bmm(const at::Tensor& self, const at::Tensor& mat2, bool deterministic) { - return NPUNativeFunctions::bmm(self, mat2); -} - -at::Tensor& NPUNativeFunctions::_bmm_out(const at::Tensor& self, const at::Tensor& mat2, bool deterministic, at::Tensor& result) { - return NPUNativeFunctions::bmm_out(self, mat2, result); -} - -} // namespace native -} // namespace at diff --git a/torch_npu/csrc/aten/ops/BmmV2KernelNpu.cpp b/torch_npu/csrc/aten/ops/BmmV2KernelNpu.cpp index 9bd4560d83..22551314ce 100644 --- a/torch_npu/csrc/aten/ops/BmmV2KernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/BmmV2KernelNpu.cpp @@ -17,7 +17,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -30,7 +30,7 @@ bool is_transpose_last_two_dims_v2(const at::Tensor& Tensors) { return false; } auto storage_size = torch_npu::NPUBridge::GetNpuStorageImpl(Tensors)->get_npu_desc().storage_sizes_; - int64_t numel = at::prod_intlist(storage_size); + int64_t numel = c10::multiply_integers(storage_size); int64_t dim1 = Tensors.dim() - 1; int64_t dim2 = Tensors.dim() - 2; @@ -348,7 +348,7 @@ public: } }; -at::Tensor NPUNativeFunctions::npu_bmmV2(const at::Tensor& self, const at::Tensor& mat2, at::IntArrayRef output_sizes) { +at::Tensor XLANativeFunctions::npu_bmmV2(const at::Tensor& self, const at::Tensor& mat2, at::IntArrayRef output_sizes) { return NPUBmmV2Function::apply(self, mat2, output_sizes); } diff --git a/torch_npu/csrc/aten/ops/BoundingBoxDecodeKernelNpu.cpp b/torch_npu/csrc/aten/ops/BoundingBoxDecodeKernelNpu.cpp deleted file mode 100644 index 58c51e9094..0000000000 --- a/torch_npu/csrc/aten/ops/BoundingBoxDecodeKernelNpu.cpp +++ /dev/null @@ -1,75 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& bounding_box_decode_npu_nocheck( - const at::Tensor& rois, - const at::Tensor& deltas, - c10::SmallVector means, - c10::SmallVector stds, - at::IntArrayRef max_shape, - double wh_ratio_clip, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("BoundingBoxDecode") - .Input(rois) - .Input(deltas) - .Output(result) - .Attr("means", means) - .Attr("stds", stds) - .Attr("max_shape", max_shape) - .Attr("wh_ratio_clip", static_cast(wh_ratio_clip)) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::npu_bounding_box_decode( - const at::Tensor& rois, - const at::Tensor& deltas, - double means0, - double means1, - double means2, - double means3, - double stds0, - double stds1, - double stds2, - double stds3, - at::IntArrayRef max_shape, - double wh_ratio_clip) { - c10::SmallVector outputSize = {rois.size(0), 4}; - at::Tensor result = OpPreparation::ApplyTensor(rois, outputSize); - c10::SmallVector means = { - static_cast(means0), - static_cast(means1), - static_cast(means2), - static_cast(means3)}; - c10::SmallVector stds = { - static_cast(stds0), - static_cast(stds1), - static_cast(stds2), - static_cast(stds3)}; - bounding_box_decode_npu_nocheck( - rois, deltas, means, stds, max_shape, wh_ratio_clip, result); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/BoundingBoxEncodeKernelNpu.cpp b/torch_npu/csrc/aten/ops/BoundingBoxEncodeKernelNpu.cpp deleted file mode 100644 index 3406e6b99e..0000000000 --- a/torch_npu/csrc/aten/ops/BoundingBoxEncodeKernelNpu.cpp +++ /dev/null @@ -1,68 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& bounding_box_encode_npu_nocheck( - const at::Tensor& anchor_box, - const at::Tensor& ground_truth_box, - c10::SmallVector means, - c10::SmallVector stds, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("BoundingBoxEncode") - .Input(anchor_box) - .Input(ground_truth_box) - .Output(result) - .Attr("means", means) - .Attr("stds", stds) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::npu_bounding_box_encode( - const at::Tensor& anchor_box, - const at::Tensor& ground_truth_box, - double means0, - double means1, - double means2, - double means3, - double stds0, - double stds1, - double stds2, - double stds3) { - at::Tensor result = OpPreparation::ApplyTensor(anchor_box, {anchor_box.size(0), 4}); - c10::SmallVector means = { - static_cast(means0), - static_cast(means1), - static_cast(means2), - static_cast(means3)}; - c10::SmallVector stds = { - static_cast(stds0), - static_cast(stds1), - static_cast(stds2), - static_cast(stds3)}; - bounding_box_encode_npu_nocheck( - anchor_box, ground_truth_box, means, stds, result); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/BroadcastKernelNpu.cpp b/torch_npu/csrc/aten/ops/BroadcastKernelNpu.cpp index 8d92f6c525..7dc9843919 100644 --- a/torch_npu/csrc/aten/ops/BroadcastKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/BroadcastKernelNpu.cpp @@ -16,13 +16,13 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - at::Tensor &NPUNativeFunctions::npu_broadcast_out( + at::Tensor &XLANativeFunctions::npu_broadcast_out( const at::Tensor &self, at::IntArrayRef size, at::Tensor &result) @@ -31,13 +31,13 @@ namespace at_npu OpCommand cmd; cmd.Name("BroadcastTo") .Input(self) - .Input(size) + .Input(size, at::kInt) .Output(result) .Run(); return result; } - at::Tensor NPUNativeFunctions::npu_broadcast(const at::Tensor &self, at::IntArrayRef size) + at::Tensor XLANativeFunctions::npu_broadcast(const at::Tensor &self, at::IntArrayRef size) { at::Tensor input = self; if (self.dtype() == at::kBool) @@ -50,7 +50,7 @@ namespace at_npu input.options(), CalcuOpUtil::get_tensor_npu_format(self)); - NPUNativeFunctions::npu_broadcast_out(input, size, result); + XLANativeFunctions::npu_broadcast_out(input, size, result); if (self.dtype() == at::kBool) { diff --git a/torch_npu/csrc/aten/ops/CastKernelNpu.cpp b/torch_npu/csrc/aten/ops/CastKernelNpu.cpp index 48cbaac5ce..950fb32ec1 100644 --- a/torch_npu/csrc/aten/ops/CastKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/CastKernelNpu.cpp @@ -13,19 +13,15 @@ // 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. -#include #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - using torch::autograd::Function; - using torch::autograd::AutogradContext; - using tensor_list = std::vector; namespace { at::Tensor &cast_nocheck(at::Tensor &result, const at::Tensor &self) @@ -41,7 +37,7 @@ namespace at_npu } } // namespace - at::Tensor npu_dtype_cast_impl(const at::Tensor &self, at::ScalarType dtype) + at::Tensor XLANativeFunctions::npu_dtype_cast(const at::Tensor &self, at::ScalarType dtype) { if (self.dtype() == dtype) { @@ -60,7 +56,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::npu_dtype_cast_(at::Tensor &self, const at::Tensor &src) + at::Tensor &XLANativeFunctions::npu_dtype_cast_(at::Tensor &self, const at::Tensor &src) { if (self.dtype() == src.dtype()) { @@ -81,32 +77,5 @@ namespace at_npu return self; } - class NPUDtypeCastFunction : public torch::autograd::Function { - public: - static at::Tensor forward(AutogradContext *ctx, - at::Tensor self, - at::ScalarType dtype) { - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({self}); - return npu_dtype_cast_impl(self, dtype); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto saved = ctx->get_saved_variables(); - auto self = saved[0]; - - at::Tensor result = npu_dtype_cast_impl(grad_outputs[0], self.scalar_type()); - tensor_list output = {result, at::Tensor()}; - - return output; - } - }; - - at::Tensor NPUNativeFunctions::npu_dtype_cast(const at::Tensor &self, - at::ScalarType dtype) { - return NPUDtypeCastFunction::apply(self, dtype); - } - } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CatKernelNpu.cpp b/torch_npu/csrc/aten/ops/CatKernelNpu.cpp index 031e680980..77669c9a89 100644 --- a/torch_npu/csrc/aten/ops/CatKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/CatKernelNpu.cpp @@ -16,28 +16,13 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - namespace - { - template - at_npu::native::DynamicInputRegFunc concat_func = - [](DyNumAndIndex num_and_index, - std::string op_name) -> ge::OperatorPtr - { - auto ge_op = std::make_shared(op_name.c_str()); - ge_op->create_dynamic_input_byindex_x( - num_and_index.front().first, num_and_index.front().second); - return ge_op; - }; - } - c10::SmallVector cat_dest_tensor_list(at::TensorList tensors) { c10::SmallVector dstTensorList; @@ -114,7 +99,7 @@ namespace at_npu return size; } - at::Tensor &NPUNativeFunctions::_cat_out(at::TensorList tensors, int64_t dim, at::Tensor &result) + at::Tensor &XLANativeFunctions::_cat_out(at::TensorList tensors, int64_t dim, at::Tensor &result) { if (tensors.size() == 1) { @@ -133,32 +118,17 @@ namespace at_npu int64_t input_number = 0; OpCommand cmd; cmd.Name("ConcatD"); - - // In graph mode, if all of input tensors are null numel, - // these null tensors should be passed to ConcatD as inputs. - // Otherwise, an error will be reported when infershape. - bool tensors_empty_in_graph_mode = false; - if (c10_npu::NpuRunMode::IsGraphMode()) { - tensors_empty_in_graph_mode = true; - for (int i = 0; i < inputTensors.size(); i++) { - if (inputTensors[i].numel() != 0) { - tensors_empty_in_graph_mode = false; - break; - } - } - } - input_number = 0; for (int i = 0; i < inputTensors.size(); i++) { - if (inputTensors[i].numel() != 0 || tensors_empty_in_graph_mode) + if (inputTensors[i].numel() == 0) { - string inputName = "x" + std::to_string(input_number++); - cmd.Input(inputTensors[i], inputName); + continue; } + string inputName = "x" + std::to_string(input_number++); + cmd.Input(inputTensors[i], inputName); } - cmd.DynamicInputReg(concat_func, {{input_number, 0}}) - .Output(result) + cmd.Output(result) .Attr("N", input_number) .Attr("concat_dim", dim) .Run(); @@ -166,7 +136,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::cat_out(at::TensorList tensors, int64_t dim, at::Tensor &result) + at::Tensor &XLANativeFunctions::cat_out(at::TensorList tensors, int64_t dim, at::Tensor &result) { c10::SmallVector inputTensors = cat_dest_tensor_list(tensors); @@ -186,12 +156,12 @@ namespace at_npu return at::_cat_out(result, tensors, dim); } - at::Tensor &NPUNativeFunctions::cat_out(at::TensorList tensors, at::Dimname dim, at::Tensor &result) + at::Tensor &XLANativeFunctions::cat_out(at::TensorList tensors, at::Dimname dim, at::Tensor &result) { return at::cat_out(result, tensors, dimname_to_position(tensors[0], dim)); } - at::Tensor NPUNativeFunctions::_cat(at::TensorList tensors, int64_t dim) + at::Tensor XLANativeFunctions::_cat(at::TensorList tensors, int64_t dim) { c10::SmallVector inputTensors = cat_dest_tensor_list(tensors); @@ -225,23 +195,23 @@ namespace at_npu if (tensors_dim_check == true) { at::Tensor result = OpPreparation::ApplyTensor(tensors[0], outputSize); - NPUNativeFunctions::_cat_out(tensors, dim, result); + XLANativeFunctions::_cat_out(tensors, dim, result); return result; } else { at::Tensor result = OpPreparation::ApplyTensorWithFormat(tensors[0], outputSize, ACL_FORMAT_ND); - NPUNativeFunctions::_cat_out(tensors, dim, result); + XLANativeFunctions::_cat_out(tensors, dim, result); return result; } } - at::Tensor NPUNativeFunctions::cat(at::TensorList tensors, int64_t dim) + at::Tensor XLANativeFunctions::cat(at::TensorList tensors, int64_t dim) { return at::_cat(tensors, dim); } - at::Tensor NPUNativeFunctions::cat(at::TensorList tensors, at::Dimname dim) + at::Tensor XLANativeFunctions::cat(at::TensorList tensors, at::Dimname dim) { return at::cat(tensors, dimname_to_position(tensors[0], dim)); } diff --git a/torch_npu/csrc/aten/ops/CdistBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/CdistBackwardKernelNpu.cpp deleted file mode 100644 index 6e7077321a..0000000000 --- a/torch_npu/csrc/aten/ops/CdistBackwardKernelNpu.cpp +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -static void check_cdist_backward_input( - const at::Tensor& grad, - const at::Tensor& x1, - const at::Tensor& x2, - const double p, - const at::Tensor& cdist) { - TORCH_CHECK(x1.is_contiguous(), "_cdist_backward requires X1 to be contiguous"); - TORCH_CHECK(x2.is_contiguous(), "_cdist_backward requires X2 to be contiguous"); - TORCH_CHECK(cdist.is_contiguous(), "_cdist_backward requires dist to be contiguous"); - TORCH_CHECK(grad.is_contiguous(), "_cdist_backward requires grad to be contiguous"); - auto device1 = x1.device().type(); - TORCH_CHECK(device1 == at::kCPU || device1 == at::kCUDA || device1 == at_npu::key::NativeDeviceType, "_cdist_backward only supports CPU, CUDA and NPU devices, X1 got: ", device1); - auto device2 = x2.device().type(); - TORCH_CHECK(device2 == at::kCPU || device2 == at::kCUDA || device2 == at_npu::key::NativeDeviceType, "_cdist_backward only supports CPU, CUDA and NPU devices, X2 got: ", device2); - TORCH_CHECK(p <= std::numeric_limits::max(), "npu dose not support float64" ); -} - -at::Tensor NPUNativeFunctions::_cdist_backward( - const at::Tensor& grad, - const at::Tensor& x1, - const at::Tensor& x2, - const double p, - const at::Tensor& cdist) { - check_cdist_backward_input(grad, x1, x2, p, cdist); - float p_float; - if (std::isinf(p)) { - p_float = std::numeric_limits::infinity(); - } - else { - p_float = static_cast(p); - } - - auto dim1 = x1.dim(); - auto dim2 = x2.dim(); - c10::SmallVector tensor1_expand_size = array_to_small_vector(x1.sizes()); - tensor1_expand_size.insert(tensor1_expand_size.begin() + (dim1 - 1), 1); - c10::SmallVector tensor2_expand_size = array_to_small_vector(x2.sizes()); - tensor2_expand_size.insert(tensor2_expand_size.begin() + (dim2 - 2), 1); - c10::SmallVector grad_expand_size = array_to_small_vector(grad.sizes()); - grad_expand_size.insert(grad_expand_size.end(), 1); - c10::SmallVector cdist_expand_size = array_to_small_vector(cdist.sizes()); - cdist_expand_size.insert(cdist_expand_size.end(), 1); - std::vector tensor_broadcast_size = at::infer_size(tensor1_expand_size, tensor2_expand_size); - - at::Tensor tensor1_broadcast = x1.view(tensor1_expand_size).expand(tensor_broadcast_size).contiguous(); - at::Tensor tensor2_broadcast = x2.view(tensor2_expand_size).expand(tensor_broadcast_size).contiguous(); - at::Tensor grad_broadcast = grad.view(grad_expand_size).expand(tensor_broadcast_size).contiguous(); - at::Tensor cdist_broadcast = cdist.view(cdist_expand_size).expand(tensor_broadcast_size).contiguous(); - auto outputSize = x1.sizes(); - at::Tensor result = OpPreparation::ApplyTensor(tensor1_broadcast, outputSize); - - OpCommand cmd; - cmd.Name("CdistGrad") - .Input(grad_broadcast) - .Input(tensor1_broadcast) - .Input(tensor2_broadcast) - .Input(cdist_broadcast) - .Attr("p", p_float) - .Output(result) - .Run(); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CdistKernelNpu.cpp b/torch_npu/csrc/aten/ops/CdistKernelNpu.cpp deleted file mode 100644 index 8f03431a8c..0000000000 --- a/torch_npu/csrc/aten/ops/CdistKernelNpu.cpp +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::_cdist_forward( - const at::Tensor& x1, - const at::Tensor& x2, - const double p, - c10::optional compute_mode) { - TORCH_CHECK(x1.dim() >= 2, "cdist only supports at least 2D tensors, X1 got: ", x1.dim(), "D"); - TORCH_CHECK(x2.dim() >= 2, "cdist only supports at least 2D tensors, X2 got: ", x2.dim(), "D"); - TORCH_CHECK(x1.size(-1) == x2.size(-1), "X1 and X2 must have the same number of columns. X1: ", x1.size(-1), " X2: ", x2.size(-1)); - TORCH_CHECK(at::isFloatingType(x1.scalar_type()), "cdist only supports floating-point dtypes, X1 got: ", x1.scalar_type()); - TORCH_CHECK(at::isFloatingType(x1.scalar_type()), "cdist only supports floating-point dtypes, X2 got: ", x2.scalar_type()); - TORCH_CHECK(p >= 0, "cdist only supports non-negative p values"); - - // Since double is not supported in NPU, the type of P needs to be converted from double to float. - float p_float; - if (std::isinf(p)) { - p_float = -1; - } - else { - TORCH_CHECK(p <= std::numeric_limits::max(), "npu dose not support float64" ); - p_float = static_cast(p); - } - - int64_t mode = compute_mode.value_or(0); - TORCH_CHECK(mode >= 0 && mode <= 2, "possible modes: 0, 1, 2, but was: ", mode); - - // Broadcast - int64_t c1 = x1.size(-1); - int64_t c2 = x2.size(-1); - int64_t r1 = x1.size(-2); - int64_t r2 = x2.size(-2); - auto dim1 = x1.dim(); - auto dim2 = x2.dim(); - - at::IntArrayRef batch_tensor1(x1.sizes().data(), dim1 - 2); - at::IntArrayRef batch_tensor2(x2.sizes().data(), dim2 - 2); - std::vector expand_batch_portion = at::infer_size(batch_tensor1, batch_tensor2); - std::vector tensor1_expand_size(expand_batch_portion); - tensor1_expand_size.insert(tensor1_expand_size.end(), {r1, c1}); - std::vector tensor2_expand_size(expand_batch_portion); - tensor2_expand_size.insert(tensor2_expand_size.end(), {r2, c2}); - - int expand_batch_product = std::accumulate(expand_batch_portion.begin(), expand_batch_portion.end(), 1, std::multiplies()); - std::vector tensor1_view{expand_batch_product, r1, 1, c1}; - std::vector tensor2_view{expand_batch_product, 1, r2, c2}; - std::vector result_size{expand_batch_product, r1, r2}; - std::vector tensor_broadcast_size = at::infer_size(tensor1_view, tensor2_view); - - // Broadcast batch dim. - at::Tensor tensor1_expanded = x1.expand(tensor1_expand_size).contiguous().view(tensor1_view); - at::Tensor tensor2_expanded = x2.expand(tensor2_expand_size).contiguous().view(tensor2_view); - - // Broadcast r1 and r2. - at::Tensor tensor1_broadcast = tensor1_expanded.expand(tensor_broadcast_size).contiguous(); - at::Tensor tensor2_broadcast = tensor2_expanded.expand(tensor_broadcast_size).contiguous(); - - auto output_size = cdist_npu_output_size(x1, x2); - at::Tensor result = OpPreparation::ApplyTensor(tensor1_broadcast, result_size); - - OpCommand cmd; - cmd.Name("Cdist") - .Input(tensor1_broadcast) - .Input(tensor2_broadcast) - .Attr("p", p_float) - .Output(result) - .Run(); - - return result.view(output_size); -} - -at::Tensor NPUNativeFunctions::cdist( - const at::Tensor& x1, - const at::Tensor& x2, - const double p, - c10::optional compute_mode) { - return at::_cdist_forward(x1, x2, p, compute_mode); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CeilKernelNpu.cpp b/torch_npu/csrc/aten/ops/CeilKernelNpu.cpp index 133fca4985..941ded3c5e 100644 --- a/torch_npu/csrc/aten/ops/CeilKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/CeilKernelNpu.cpp @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -28,7 +28,7 @@ at::Tensor& ceil_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { return result; } -at::Tensor& NPUNativeFunctions::ceil_out(const at::Tensor& self, at::Tensor& result) { +at::Tensor& XLANativeFunctions::ceil_out(const at::Tensor& self, at::Tensor& result) { OpPreparation::CheckOut( {self}, result, @@ -36,13 +36,13 @@ at::Tensor& NPUNativeFunctions::ceil_out(const at::Tensor& self, at::Tensor& res return ceil_out_npu_nocheck(result, self); } -at::Tensor NPUNativeFunctions::ceil(const at::Tensor& self) { +at::Tensor XLANativeFunctions::ceil(const at::Tensor& self) { at::Tensor result = OpPreparation::ApplyTensor(self); ceil_out_npu_nocheck(result, self); return result; } -at::Tensor& NPUNativeFunctions::ceil_(at::Tensor& self) { +at::Tensor& XLANativeFunctions::ceil_(at::Tensor& self) { if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); at::Tensor result = ceil_out_npu_nocheck(contiguousSelf, contiguousSelf); diff --git a/torch_npu/csrc/aten/ops/CeluKernelNpu.cpp b/torch_npu/csrc/aten/ops/CeluKernelNpu.cpp deleted file mode 100644 index 6b735451e5..0000000000 --- a/torch_npu/csrc/aten/ops/CeluKernelNpu.cpp +++ /dev/null @@ -1,51 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor celu_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, at::Scalar alpha) { - OpCommand cmd; - cmd.Name("CeluV2") - .Input(self) - .Output(result) - .Attr("alpha", alpha) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::celu(const at::Tensor& self, at::Scalar alpha) { - at::Tensor result = OpPreparation::ApplyTensor(self); - celu_out_npu_nocheck(result, self, alpha); - return result; -} - -at::Tensor& NPUNativeFunctions::celu_(at::Tensor& self, at::Scalar alpha) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = celu_out_npu_nocheck(contiguousSelf, contiguousSelf, alpha); - NpuUtils::format_fresh_view(self, result); - } else { - celu_out_npu_nocheck(self, self, alpha); - } - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ChannelShuffleKernelNpu.cpp b/torch_npu/csrc/aten/ops/ChannelShuffleKernelNpu.cpp deleted file mode 100644 index 3d05181ab8..0000000000 --- a/torch_npu/csrc/aten/ops/ChannelShuffleKernelNpu.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2022, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& channel_shuffle_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, int64_t groups) { - OpCommand cmd; - cmd.Name("ShuffleChannel") - .Input(self) - .Output(result) - .Attr("group", groups) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::channel_shuffle(const at::Tensor& self, int64_t groups) { - at::Tensor result = OpPreparation::ApplyTensor(self); - channel_shuffle_out_npu_nocheck(result, self, groups); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CiouKernelNpu.cpp b/torch_npu/csrc/aten/ops/CiouKernelNpu.cpp deleted file mode 100644 index 7358634654..0000000000 --- a/torch_npu/csrc/aten/ops/CiouKernelNpu.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright (c) 2022 Huawei Technologies Co., Ltd -// Copyright (c) 2012, 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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -c10::SmallVector ciou_output_size( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool is_cross){ - c10::SmallVector output_size; - if(is_cross){ - output_size = {gtboxes.size(1), self.size(1)}; - } else { - output_size = {1, self.size(1)}; - } - return output_size; -} - -tuple ciou_inner_out_npu( - at::Tensor& overlap, - at::Tensor& atan_sub, - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode, - bool atan_sub_flag){ - string mode_str = mode == 1 ? "iof" : "iou"; - OpCommand cmd; - cmd.Name("CIoU") - .Input(self) - .Input(gtboxes) - .Output(overlap) - .Output(atan_sub) - .Attr("trans", trans) - .Attr("is_cross", is_cross) - .Attr("mode", mode_str) - .Attr("atan_sub_flag", atan_sub_flag) - .Run(); - return std::tie(overlap, atan_sub); -} - -tuple ciou_npu( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode, - bool atan_sub_flag) { - at::Tensor selfCp = self; - if (selfCp.scalar_type() == at::kHalf) { - selfCp = NPUNativeFunctions::npu_dtype_cast(selfCp, at::kFloat); - } - at::Tensor gtboxesCp = gtboxes; - if (gtboxesCp.scalar_type() == at::kHalf) { - gtboxesCp = NPUNativeFunctions::npu_dtype_cast(gtboxesCp, at::kFloat); - } - auto output_size = ciou_output_size(selfCp, gtboxesCp, is_cross); - at::Tensor overlap = OpPreparation::ApplyTensor(selfCp, output_size); - at::Tensor atan_sub = OpPreparation::ApplyTensor(selfCp, output_size); - ciou_inner_out_npu(overlap, atan_sub, selfCp, gtboxesCp, trans, is_cross, mode, atan_sub_flag); - if (self.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf) { - overlap = NPUNativeFunctions::npu_dtype_cast(overlap, at::kHalf); - } - return std::tie(overlap, atan_sub); -} - -std::tuple ciou_backward_inner_out_npu( - at::Tensor& dbboxes, - at::Tensor& dgtboxes, - const at::Tensor& grad, - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - const at::Tensor& atan_sub, - bool trans, - bool is_cross, - int64_t mode){ - string mode_str = mode == 1 ? "iof" : "iou"; - OpCommand cmd; - cmd.Name("CIoUGrad") - .Input(grad) - .Input(bboxes) - .Input(gtboxes) - .Input(atan_sub) - .Output(dbboxes) - .Output(dgtboxes) - .Attr("trans", trans) - .Attr("is_cross", is_cross) - .Attr("mode", mode_str) - .Run(); - - return std::tie(dbboxes, dgtboxes); -} - -std::tuple NPUNativeFunctions::npu_ciou_backward( - const at::Tensor& grad, - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - const c10::optional& atan_sub_opt, - bool trans, - bool is_cross, - int64_t mode){ - const at::Tensor& atan_sub = c10::value_or_else(atan_sub_opt, [] {return at::Tensor();}); - at::Tensor gradCp = at::squeeze(grad, 0); - if (gradCp.scalar_type() == at::kHalf) { - gradCp = NPUNativeFunctions::npu_dtype_cast(gradCp, at::kFloat); - } - at::Tensor bboxesCp = bboxes; - if (bboxesCp.scalar_type() == at::kHalf) { - bboxesCp = NPUNativeFunctions::npu_dtype_cast(bboxesCp, at::kFloat); - } - at::Tensor gtboxesCp = gtboxes; - if (gtboxesCp.scalar_type() == at::kHalf) { - gtboxesCp = NPUNativeFunctions::npu_dtype_cast(gtboxesCp, at::kFloat); - } - at::Tensor dbboxes = OpPreparation::ApplyTensor(bboxesCp); - at::Tensor dgtboxes = OpPreparation::ApplyTensor(gtboxesCp); - - ciou_backward_inner_out_npu(dbboxes, dgtboxes, gradCp, bboxesCp, gtboxesCp, atan_sub, trans, is_cross, mode); - - if (bboxes.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf) { - dbboxes = NPUNativeFunctions::npu_dtype_cast(dbboxes, at::kHalf); - dgtboxes = NPUNativeFunctions::npu_dtype_cast(dgtboxes, at::kHalf); - } - return std::tie(dbboxes, dgtboxes); -} - -class NPUCiouFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode, - bool atan_sub_flag) { - ctx->saved_data["trans"] = trans; - ctx->saved_data["is_cross"] = is_cross; - ctx->saved_data["mode"] = mode; - at::AutoNonVariableTypeMode g; - auto result = ciou_npu(self, gtboxes, trans, is_cross, mode, atan_sub_flag); - ctx->save_for_backward({self, gtboxes, std::get<1>(result)}); - return std::get<0>(result); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto trans = ctx->saved_data["trans"].toBool(); - auto is_cross = ctx->saved_data["is_cross"].toBool(); - auto mode = ctx->saved_data["mode"].toInt(); - auto saved = ctx->get_saved_variables(); - auto bboxes = saved[0]; - auto gtboxes = saved[1]; - auto atan_sub = saved[2]; - - tuple result = NPUNativeFunctions::npu_ciou_backward(grad_outputs[0], - bboxes, gtboxes, atan_sub, trans, is_cross, mode); - - tensor_list output = {std::get<0>(result), - std::get<1>(result), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_ciou( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode, - bool atan_sub_flag) { - return NPUCiouFunction::apply(self, gtboxes, trans, is_cross, mode, atan_sub_flag); -} -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ClampKernelNpu.cpp b/torch_npu/csrc/aten/ops/ClampKernelNpu.cpp deleted file mode 100644 index 81a839bd13..0000000000 --- a/torch_npu/csrc/aten/ops/ClampKernelNpu.cpp +++ /dev/null @@ -1,165 +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. - -#include -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& clamp_min_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - at::Scalar min) { - // Set max according to self.dtype() - at::Scalar max; - if (self.dtype() == at::kInt) { - max = INT_MAX; - } else if (self.dtype() == at::kFloat) { - max = FLT_MAX; - } else { - max = NPU_HALF_MAX; - } - OpCommand cmd; - cmd.Name("ClipByValue") - .Input(self) - .Input(min, self.scalar_type()) - .Input(max, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::clamp_min_out( - const at::Tensor& self, - at::Scalar min, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self, &min](at::Tensor& result){clamp_min_out_npu_nocheck(result, self, min);}) - .Call(result); - return result; -} - -at::Tensor& NPUNativeFunctions::clamp_max_out(const at::Tensor& self, at::Scalar max, at::Tensor& result) { - // Set min according to self.dtype() - at::Scalar min; - if (self.dtype() == at::kInt) { - min = INT_MIN; - } else if (self.dtype() == at::kFloat) { - min = -FLT_MAX; - } else { - min = NPU_HALF_MIN; - } - OpCommand cmd; - cmd.Name("ClipByValue") - .Input(self) - .Input(min, self.scalar_type()) - .Input(max, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& clamp_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - c10::optional min, - c10::optional max) { - if (!min.has_value()) { - at::Scalar maxScalar = max.value(); - NPUNativeFunctions::clamp_max_out(self, maxScalar, result); - } else if (!max.has_value()) { - at::Scalar minScalar = min.value(); - NPUNativeFunctions::clamp_min_out(self, minScalar, result); - } else { - OpCommand cmd; - cmd.Name("ClipByValue") - .Input(self) - .Input(min.value(), self.scalar_type()) - .Input(max.value(), self.scalar_type()) - .Output(result) - .Run(); - } - return result; -} - -at::Tensor& NPUNativeFunctions::clamp_out( - const at::Tensor& self, - c10::optional min, - c10::optional max, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self, &min, &max](at::Tensor& result){clamp_out_npu_nocheck(result, self, min, max);}) - .Call(result); - return result; -} - -at::Tensor NPUNativeFunctions::clamp_min(const at::Tensor& self, at::Scalar min) { - at::Tensor result = OpPreparation::ApplyTensor(self); - clamp_min_out_npu_nocheck(result, self, min); - return result; -} - -at::Tensor& NPUNativeFunctions::clamp_min_(at::Tensor& self, at::Scalar min) { - NPUNativeFunctions::clamp_min_out(self, min, self); - return self; -} - -at::Tensor NPUNativeFunctions::clamp_max(const at::Tensor& self, at::Scalar max) { - at::Tensor result = OpPreparation::ApplyTensor(self); - NPUNativeFunctions::clamp_max_out(self, max, result); - return result; -} - -at::Tensor& NPUNativeFunctions::clamp_max_(at::Tensor& self, at::Scalar max) { - OpPreparation::CheckMemory({self}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::clamp_max_out(contiguousSelf, max, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::clamp_max_out(self, max, self); - } - return self; -} - -at::Tensor NPUNativeFunctions::clamp( - const at::Tensor& self, - c10::optional min, - c10::optional max) { - at::Tensor result = OpPreparation::ApplyTensor(self); - clamp_out_npu_nocheck(result, self, min, max); - return result; -} - -at::Tensor& NPUNativeFunctions::clamp_(at::Tensor& self, c10::optional min, c10::optional max) { - NPUNativeFunctions::clamp_out(self, min, max, self); - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ConfusionTransposeKernelNpu.cpp b/torch_npu/csrc/aten/ops/ConfusionTransposeKernelNpu.cpp deleted file mode 100644 index 82cf9adc1d..0000000000 --- a/torch_npu/csrc/aten/ops/ConfusionTransposeKernelNpu.cpp +++ /dev/null @@ -1,129 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -at::Tensor confusion_transpose_npu( - const at::Tensor& self, - at::IntArrayRef perm, - at::IntArrayRef shape, - bool transpose_first) { - c10::SmallVector output_size; - if (transpose_first){ - output_size = array_to_small_vector(shape); - } else { - for (int i = 0; i < perm.size(); i++){ - output_size.emplace_back(shape[perm[i]]); - } - } - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, output_size); - OpCommand cmd; - cmd.Name("ConfusionTransposeD") - .Input(self) - .Output(result) - .Attr("perm", perm) - .Attr("shape", shape) - .Attr("transpose_first", transpose_first) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::npu_confusion_transpose_backward( - const at::Tensor& grad, - at::IntArrayRef perm, - at::IntArrayRef shape, - bool transpose_first) { - c10::SmallVector svec_shape; - if (transpose_first){ - svec_shape = array_to_small_vector(shape); - } else { - for (int i = 0; i < perm.size(); i++){ - svec_shape.emplace_back(shape[perm[i]]); - } - } - std::vector vec_perm; - int64_t perm_len = perm.size(); - int64_t temp_perm[perm_len] = {0}; - for (int64_t i = 0; i < perm_len; i++){ - temp_perm[perm[i]] = i; - } - vec_perm = std::vector(temp_perm, temp_perm+perm_len); - perm = at::IntArrayRef(vec_perm); - - at::Tensor result = OpPreparation::ApplyTensor(grad, shape); - - OpCommand cmd; - cmd.Name("ConfusionTransposeD") - .Input(grad) - .Output(result) - .Attr("perm", perm) - .Attr("shape", svec_shape) - .Attr("transpose_first", transpose_first) - .Run(); - - return result; -} - -class NPUConfusionTransposeFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - at::IntArrayRef perm, - at::IntArrayRef shape, - bool transpose_first) { - ctx->saved_data["perm"] = perm; - ctx->saved_data["shape"] = self.sizes(); - ctx->saved_data["transpose_first"] = !transpose_first; - at::AutoNonVariableTypeMode g; - return confusion_transpose_npu(self, perm, shape, transpose_first); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto perm = ctx->saved_data["perm"].toIntVector(); - auto shape = ctx->saved_data["shape"].toIntVector(); - auto transpose_first = ctx->saved_data["transpose_first"].toBool(); - at::Tensor result = NPUNativeFunctions::npu_confusion_transpose_backward(grad_outputs[0], perm, shape, transpose_first); - - tensor_list output = {result, - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_confusion_transpose(const at::Tensor& self, - at::IntArrayRef perm, - at::IntArrayRef shape, - bool transpose_first) { - return NPUConfusionTransposeFunction::apply(self, perm, shape, transpose_first); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ConstantPadNdKernelNpu.cpp b/torch_npu/csrc/aten/ops/ConstantPadNdKernelNpu.cpp deleted file mode 100644 index 6f90951625..0000000000 --- a/torch_npu/csrc/aten/ops/ConstantPadNdKernelNpu.cpp +++ /dev/null @@ -1,127 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor constant_pad_nd_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, at::IntArrayRef pad, at::Scalar value) { - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(pad); - paddingsVector.resize(2 * self.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 0; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - - float val = CalcuOpUtil::get_scalar_float_value(value); - - at::Tensor value_tensor = at::empty({1}, self.options()).fill_(val); - - OpCommand cmd; - cmd.Name("PadV3") - .Input(self) - .Input(vectorInt, at::kInt) - .Input(value_tensor) - .Output(result) - .Attr("mode", (string)"constant") - .Attr("paddings_contiguous", true) - .Run(); - - return result; -} - -bool is_backward(at::IntArrayRef pad) { - for (int i = 0; i= (int64_t)l_pad, "Length of pad should be no more than twice the number of " - "dimensions of the input. Pad length is ", pad.size(), "while the input has ", - l_inp, "dimensions."); - - std::vector new_shape; - for (size_t i = 0; i < (size_t)l_diff; i++) { - new_shape.emplace_back(input_sizes[i]); - } - - for (size_t i = 0; i < (size_t)l_pad; i++) { - auto pad_idx = pad.size() - ((i + 1) * 2); - auto new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1]; - TORCH_CHECK(new_dim > 0, "The input size ", input_sizes[l_diff + i], ", plus negative padding ", - pad[pad_idx], " and ", pad[pad_idx + 1], "resulted in a negative output size, " - "which is invalid. Check dimension ", l_diff + i, "of your input."); - new_shape.emplace_back(new_dim); - } - - if (is_backward(pad)) { - TORCH_CHECK(pad.size() % 2 == 0, - "Length of pad must be even but instead it equals ", pad.size()); - - int64_t max_pad_size = 2 * self.dim(); - auto pad_vec = array_to_small_vector(pad); - if (pad.size() < max_pad_size) { - for (int64_t i = 0; i < max_pad_size - pad.size(); i++) { - pad_vec.emplace_back(0); - } - } - - c10::SmallVector begin_list(self.dim(), 0); - c10::SmallVector end_list; - for (auto i: self.sizes()) { - end_list.push_back(i); - } - c10::SmallVector strides(self.dim(), 1); - - at::Tensor result = self; - for (int64_t i = 0; i < self.dim(); i++) { - if (pad_vec[max_pad_size - 2 * (i + 1)] == 0 && pad_vec[max_pad_size - 1 - 2 * i] == 0) { - continue; - } - begin_list[i] = begin_list[i] + (-pad_vec[max_pad_size - 2 * (i + 1)]); - end_list[i] = end_list[i] + pad_vec[max_pad_size - 1 - 2 * i]; - result = NPUNativeFunctions::npu_indexing(result, begin_list, end_list, strides, 0, 0, 0, 0, 0); - begin_list[i] = 0; - end_list[i] = result.size(i); - } - - return result; - } - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, new_shape); - - // calculate the output result of the NPU - constant_pad_nd_out_npu_nocheck(result, self, pad, value); - - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CosKernelNpu.cpp b/torch_npu/csrc/aten/ops/CosKernelNpu.cpp deleted file mode 100644 index 79611211c6..0000000000 --- a/torch_npu/csrc/aten/ops/CosKernelNpu.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& cos_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Cos") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::cos_out( - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor checkResult = cos_out_npu_nocheck(contiguousResult, self); - NpuUtils::format_fresh_view(result, checkResult); - } else { - cos_out_npu_nocheck(result, self); - } - return result; -} - -at::Tensor NPUNativeFunctions::cos(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - cos_out_npu_nocheck(result, self); - return result; -} - -at::Tensor& NPUNativeFunctions::cos_(at::Tensor& self) { - return cos_out(self, self); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/CoshKernelNpu.cpp b/torch_npu/csrc/aten/ops/CoshKernelNpu.cpp deleted file mode 100644 index 4a1e1e612a..0000000000 --- a/torch_npu/csrc/aten/ops/CoshKernelNpu.cpp +++ /dev/null @@ -1,54 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - at::Tensor& NPUNativeFunctions::cosh_out(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Cosh") - .Input(self) - .Output(result) - .Run(); - - return result; -} - - at::Tensor& NPUNativeFunctions::cosh_( at::Tensor& self) { - OpPreparation::CheckMemory({self}, {self}); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::cosh_out(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::cosh_out(self, self); - } - - return self; -} - - at::Tensor NPUNativeFunctions::cosh(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - NPUNativeFunctions::cosh_out(self, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/CrossKernelNpu.cpp b/torch_npu/csrc/aten/ops/CrossKernelNpu.cpp deleted file mode 100644 index 6f3b663c86..0000000000 --- a/torch_npu/csrc/aten/ops/CrossKernelNpu.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor cross_dest_output(const at::Tensor& self, const at::Tensor& other) { - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - return isSelfWrapped ? other : self; -} - -at::Tensor& cross_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - c10::optional dim, - at::Tensor& result) { - int64_t realDim = dim.has_value() ? dim.value() : -65530; - OpCommand cmd; - cmd.Name("Cross") - .Input(self) - .Input(other) - .Output(result) - .Attr("dim", realDim) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::cross_out( - const at::Tensor& self, - const at::Tensor& other, - c10::optional dim, - at::Tensor& result){ - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor outputTensor = cross_dest_output(self, other); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(outputTensor), - self.scalar_type(), - outputSize); - cross_out_npu_nocheck(self, other, dim, result); - return result; -} - -at::Tensor NPUNativeFunctions::cross( - const at::Tensor& self, - const at::Tensor& other, - c10::optional dim) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor outputTensor = cross_dest_output(self, other); - at::Tensor result = OpPreparation::ApplyTensor(outputSize, self.options(), outputTensor); - cross_out_npu_nocheck(self, other, dim, result); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CtcLossBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/CtcLossBackwardKernelNpu.cpp deleted file mode 100644 index 44b7fd9c65..0000000000 --- a/torch_npu/csrc/aten/ops/CtcLossBackwardKernelNpu.cpp +++ /dev/null @@ -1,88 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::_ctc_loss_backward( - const at::Tensor& gradOut, - const at::Tensor& logProbs, - const at::Tensor& targets, - at::IntArrayRef inputLengths, - at::IntArrayRef targetLengths, - const at::Tensor& negLogLikelihood, - const at::Tensor& logAlpha, - int64_t blank, - bool zeroInfinity) { - at::Tensor gradOutNeed = gradOut; - if (gradOut.scalar_type() == at::ScalarType::Half) { - gradOutNeed = NPUNativeFunctions::npu_dtype_cast(gradOutNeed, at::ScalarType::Float); - } - - at::Tensor logProbsNeed = logProbs; - if (logProbs.scalar_type() == at::ScalarType::Half) { - logProbsNeed = NPUNativeFunctions::npu_dtype_cast(logProbsNeed, at::ScalarType::Float); - } - - at::Tensor negLogLikelihoodNeed = negLogLikelihood; - if (negLogLikelihood.scalar_type() == at::ScalarType::Half) { - negLogLikelihoodNeed = NPUNativeFunctions::npu_dtype_cast(negLogLikelihoodNeed, at::ScalarType::Float); - } - - at::Tensor logAlphaNeed = logAlpha; - if (logAlpha.scalar_type() == at::ScalarType::Half) { - logAlphaNeed = NPUNativeFunctions::npu_dtype_cast(logAlphaNeed, at::ScalarType::Float); - - } - - at::Tensor targetsCast = targets; - if(targets.scalar_type() == at::ScalarType::Long){ - targetsCast = NPUNativeFunctions::npu_dtype_cast(targetsCast, at::ScalarType::Int); - } - - auto inputLengthsTensor = at::tensor(inputLengths, targetsCast.options().dtype(at::kInt)); - auto targetLengthsTensor = at::tensor(targetLengths, targetsCast.options().dtype(at::kInt)); - - auto outputSize = input_same_output_size(logProbs); - - // construct the output tensor of the NPU - at::Tensor grad = OpPreparation::ApplyTensor(logProbsNeed, outputSize); - // calculate the output result of the NPU - OpCommand cmd; - cmd.Name("CTCLossV2Grad") - .Input(gradOutNeed) - .Input(logProbsNeed) - .Input(targetsCast) - .Input(inputLengthsTensor) - .Input(targetLengthsTensor) - .Input(negLogLikelihoodNeed) - .Input(logAlphaNeed) - .Output(grad) - .Attr("blank", blank) - .Attr("zero_infinity", zeroInfinity) - .Run(); - - if (gradOut.scalar_type() == at::ScalarType::Half) { - grad = NPUNativeFunctions::npu_dtype_cast(grad, at::ScalarType::Half); - } - - return grad; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CtcLossKernelNpu.cpp b/torch_npu/csrc/aten/ops/CtcLossKernelNpu.cpp deleted file mode 100644 index cdb30e30cf..0000000000 --- a/torch_npu/csrc/aten/ops/CtcLossKernelNpu.cpp +++ /dev/null @@ -1,170 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::_ctc_loss( - const at::Tensor& logProbs, - const at::Tensor& targets, - at::IntArrayRef inputLengths, - at::IntArrayRef targetLengths, - int64_t blank, - bool zeroInfinity) { - at::Tensor logProbsNeed = logProbs; - if (logProbs.scalar_type() == at::ScalarType::Half) { - logProbsNeed = NPUNativeFunctions::npu_dtype_cast(logProbsNeed, at::ScalarType::Float); - } - - // Aicore supports only the int type - at::Tensor targetsCast = targets; - if(targets.scalar_type() == at::ScalarType::Long){ - targetsCast = NPUNativeFunctions::npu_dtype_cast(targetsCast, at::ScalarType::Int); - } - - // IntArrayRef to Tensor - auto inputLengthsTensor = at::tensor(inputLengths, targetsCast.options()); - auto targetLengthsTensor = at::tensor(targetLengths, targetsCast.options()); - - int64_t maxLength = 0; - if (targetsCast.dim() == 2) { - maxLength = targetsCast.size(1); - } else if (targetsCast.dim() == 1) { - for (auto &i : targetLengths) { - if (i > maxLength) { - maxLength = i; - } - } - } - - auto shape = logProbs.sizes(); - - auto blankNew = blank + maxLength * shape[2]; - - // calculate the output size - auto outputSizes = ctc_loss_npu_output_size(logProbs, targetsCast, targetLengths, maxLength); - - // construct the output tensor of the NPU - at::Tensor negLogLikelihood = OpPreparation::ApplyTensorWithFormat( - std::get<0>(outputSizes), - logProbsNeed.options(), - CalcuOpUtil::get_tensor_npu_format(logProbsNeed)); - - at::Tensor logAlpha = OpPreparation::ApplyTensorWithFormat( - std::get<1>(outputSizes), - logProbsNeed.options(), - CalcuOpUtil::get_tensor_npu_format(logProbsNeed)); - - // calculate the output result of the NPU - OpCommand cmd; - if (targetsCast.dim() == 2) { - cmd.Name("CTCLossV2") - .Input(logProbsNeed) - .Input(targetsCast) - .Input(inputLengthsTensor) - .Input(targetLengthsTensor) - .Output(negLogLikelihood) - .Output(logAlpha) - .Attr("blank", blank) - .Attr("zero_infinity", zeroInfinity) - .Run(); - } else if (targetsCast.dim() == 1) { - cmd.Name("CTCLossV2") - .Input(logProbsNeed) - .Input(targetsCast) - .Input(inputLengthsTensor) - .Input(targetLengthsTensor) - .Output(negLogLikelihood) - .Output(logAlpha) - .Attr("blank", blankNew) - .Attr("zero_infinity", zeroInfinity) - .Run(); - } - - - if (logProbs.scalar_type() == at::ScalarType::Half) { - negLogLikelihood = NPUNativeFunctions::npu_dtype_cast(negLogLikelihood, at::ScalarType::Half); - logAlpha = NPUNativeFunctions::npu_dtype_cast(logAlpha, at::ScalarType::Half); - } - - return std::tuple(negLogLikelihood, logAlpha); -} - -at::Tensor NPUNativeFunctions::ctc_loss( - const at::Tensor& logProbs, - const at::Tensor& targets, - at::IntArrayRef inputLengths, - at::IntArrayRef targetLengths, - int64_t blank, - int64_t reduction, - bool zeroInfinity) { - at::Tensor res = std::get<0>(at::_ctc_loss( - logProbs, - targets, - inputLengths, - targetLengths, - blank, - zeroInfinity)); - - if (zeroInfinity) { - res = at::where( - res == at::Scalar(std::numeric_limits::infinity()), - at::zeros({}, res.options()), - res); - } - - if (reduction == at::Reduction::Mean) { - std::vector targetLengthsVector = targetLengths.vec(); - - auto targetLengthsTensor = CalcuOpUtil::copy_tensor_host_to_device( - at::from_blob(targetLengthsVector.data(), {targetLengthsVector.size()}, at::kLong)).clamp_min(1); - - at::Tensor targetLengthsTensor_ = targetLengthsTensor.to(res.dtype()); - - return (res / targetLengthsTensor_).mean(); - - } else if (reduction == at::Reduction::Sum) { - return res.sum(); - } - - return res; -} - -at::Tensor NPUNativeFunctions::ctc_loss( - const at::Tensor& logProbs, - const at::Tensor& targets, - const at::Tensor& inputLengths, - const at::Tensor& targetLengths, - int64_t blank, - int64_t reduction, - bool zeroInfinity) { - TORCH_CHECK(isIntegralType(inputLengths.scalar_type(), false), "input_lengths must be integral"); - TORCH_CHECK(isIntegralType(targetLengths.scalar_type(), false), "target_lengths must be integral"); - - at::Tensor inputLengthsTensor = inputLengths.to(at::Device(at::kCPU), at::kLong).contiguous(); - at::Tensor targetLengthsTensor = targetLengths.to(at::Device(at::kCPU), at::kLong).contiguous(); - - at::IntArrayRef inputLengthsList(inputLengthsTensor.data_ptr(), inputLengthsTensor.numel()); - at::IntArrayRef targetLengthsList(targetLengthsTensor.data_ptr(), targetLengthsTensor.numel()); - - return at::ctc_loss(logProbs, targets, inputLengthsList, targetLengthsList, blank, reduction, zeroInfinity); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/CummaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/CummaxKernelNpu.cpp deleted file mode 100644 index 574c84f700..0000000000 --- a/torch_npu/csrc/aten/ops/CummaxKernelNpu.cpp +++ /dev/null @@ -1,46 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -void cummax_out_npu_nocheck ( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim) { - OpCommand cmd; - cmd.Name("Cummax") - .Input(self) - .Output(values) - .Output(indices) - .Attr("dim", dim) - .Run(); -} - -void NPUNativeFunctions::_cummax_helper(const at::Tensor& self, at::Tensor& values, at::Tensor& indices, int64_t dim) { - at::Tensor valuesTemp = OpPreparation::ApplyTensor(self); - at::Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(at::kLong)); - - cummax_out_npu_nocheck(valuesTemp, indicesTemp, self, dim); - - values.copy_(valuesTemp); - indices.copy_(indicesTemp); -} - -}} diff --git a/torch_npu/csrc/aten/ops/CumminKernelNpu.cpp b/torch_npu/csrc/aten/ops/CumminKernelNpu.cpp deleted file mode 100644 index 79c368e738..0000000000 --- a/torch_npu/csrc/aten/ops/CumminKernelNpu.cpp +++ /dev/null @@ -1,76 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -void cummin_out_npu_nocheck ( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim) { - OpCommand cmd; - cmd.Name("Cummin") - .Input(self) - .Output(values) - .Output(indices) - .Attr("dim", dim) - .Run(); -} - -void NPUNativeFunctions::_cummin_helper(const at::Tensor& self, at::Tensor& values, at::Tensor& indices, int64_t dim) { - // process aicpu - if(self.scalar_type() == at::ScalarType::Long){ - at::Tensor valuesTemp = OpPreparation::ApplyTensor(self); - at::Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(at::kLong)); - cummin_out_npu_nocheck(valuesTemp, indicesTemp, self, dim); - values.copy_(valuesTemp); - indices.copy_(indicesTemp); - } else { - // process aicore - int64_t firstDim = CalcuOpUtil::make_wrap_dim(0, self.dim()); - if (dim != firstDim) { - c10::SmallVector perm; - for (int64_t i = 0; i < self.dim(); i++) { - perm.emplace_back(i); - } - std::swap(perm[dim], perm[firstDim]); - - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); - auto outputSize = transpose_npu_output_size(values, perm); - at::Tensor transposeValue = OpPreparation::ApplyTensor(self, outputSize); - at::Tensor transposeIndices = OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kInt), self); - - cummin_out_npu_nocheck(transposeValue, transposeIndices, transposeSelf, firstDim); - // Indices must to be long - transposeIndices = transposeIndices.to(at::kLong); - NPUNativeFunctions::npu_transpose_out(transposeValue, perm, true, values); - NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, true, indices); - } else { - at::Tensor valuesTemp = OpPreparation::ApplyTensor(self); - at::Tensor indicesTemp = OpPreparation::ApplyTensor(self, self.options().dtype(at::kInt)); - cummin_out_npu_nocheck(valuesTemp, indicesTemp, self, dim); - indicesTemp = indicesTemp.to(at::kLong); - values.copy_(valuesTemp); - indices.copy_(indicesTemp); - } - } -} - -}} diff --git a/torch_npu/csrc/aten/ops/CumprodKernelNpu.cpp b/torch_npu/csrc/aten/ops/CumprodKernelNpu.cpp deleted file mode 100644 index ceb9fd359e..0000000000 --- a/torch_npu/csrc/aten/ops/CumprodKernelNpu.cpp +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& NPUNativeFunctions::_cumprod_out(const at::Tensor& self, int64_t dim, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Cumprod") - .Input(self) - .Output(result) - .Attr("axis", dim) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::cumprod_out(const at::Tensor& self, int64_t dim, c10::optional dtype, at::Tensor& result) { - at::ScalarType dstType; - if (dtype.has_value()) { - dstType = dtype.value(); - } else if (result.defined()) { - dstType = result.scalar_type(); - } else { - dstType = self.scalar_type(); - } - if (dstType == self.scalar_type()) { - return NPUNativeFunctions::_cumprod_out(self, dim, result); - } - return NPUNativeFunctions::_cumprod_out(self.toType(dstType), dim, result); -} - -at::Tensor& NPUNativeFunctions::cumprod_out(const at::Tensor& self, at::Dimname dim, c10::optional dtype, at::Tensor& result) { - at::ScalarType dstType; - if (dtype.has_value()) { - dstType = dtype.value(); - } else if (result.defined()) { - dstType = result.scalar_type(); - } else { - dstType = self.scalar_type(); - return NPUNativeFunctions::cumprod_out(self, dimname_to_position(self, dim), dstType, result); - } - return NPUNativeFunctions::cumprod_out(self.toType(dstType), dimname_to_position(self, dim), dstType, result); -} - -at::Tensor NPUNativeFunctions::_cumprod(const at::Tensor& self, int64_t dim) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - NPUNativeFunctions::_cumprod_out(self, dim, result); - - return result; -} - -at::Tensor NPUNativeFunctions::cumprod(const at::Tensor& self, int64_t dim, c10::optional dtype) { - at::ScalarType dstType = dtype.has_value() ? dtype.value() : self.scalar_type(); - if (dstType == self.scalar_type()) { - return NPUNativeFunctions::_cumprod(self, dim); - } - return NPUNativeFunctions::_cumprod(self.toType(dstType), dim); -} - -at::Tensor NPUNativeFunctions::cumprod(const at::Tensor& self, at::Dimname dim, c10::optional dtype) { - at::ScalarType dstType = dtype.has_value() ? dtype.value() : self.scalar_type(); - if (dstType == self.scalar_type()) { - return NPUNativeFunctions::cumprod(self, dimname_to_position(self, dim), dstType); - } - return NPUNativeFunctions::cumprod(self, dimname_to_position(self.toType(dstType), dim), self.scalar_type()); -} - -at::Tensor& NPUNativeFunctions::cumprod_(at::Tensor& self, int64_t dim, c10::optional dtype) { - TORCH_CHECK( - !dtype.has_value() || (self.scalar_type() == dtype.value()), - "provided dtype must match the dtype of self tensor in cumprod. Got ", - toString(self.scalar_type()), - " and ", - toString(dtype.value()), - "."); - at::Tensor result = OpPreparation::ApplyTensor(self); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - NPUNativeFunctions::_cumprod_out(contiguousSelf, dim, result); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::_cumprod_out(self, dim, result); - } - self.copy_(result); - return self; -} - -at::Tensor& NPUNativeFunctions::cumprod_(at::Tensor& self, at::Dimname dim, c10::optional dtype) { - return NPUNativeFunctions::cumprod_(self, dimname_to_position(self, dim), dtype); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/CumsumKernelNpu.cpp b/torch_npu/csrc/aten/ops/CumsumKernelNpu.cpp deleted file mode 100644 index 682e5b8bd8..0000000000 --- a/torch_npu/csrc/aten/ops/CumsumKernelNpu.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::_cumsum_out(const at::Tensor& self, int64_t dim, at::Tensor& result) { - OpCommand cmd; - // if dim = 0, performance in Aicpu is better than Aicore - // if dim > INT32_MAX, we should use long to store dim for ensuring function correctness. - // use host memory instead of scalar to improve delivery performance - at::Scalar dimScalar(dim); - cmd.Name("Cumsum") - .Input(self); - if (dim == 0 || dim > INT32_MAX) { - cmd.Input(dimScalar, at::kLong, CompileType::MEMORY_HOST_COMPILE_DEPENDENT); - } else { - cmd.Input(dimScalar, at::kInt, CompileType::MEMORY_HOST_COMPILE_DEPENDENT); - } - cmd.Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::_cumsum(const at::Tensor& self, int64_t dim) { - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - NPUNativeFunctions::_cumsum_out(self, dim, result); - - return result; -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/DefaultKernelNpu.cpp b/torch_npu/csrc/aten/ops/DefaultKernelNpu.cpp deleted file mode 100644 index 17a4af15a0..0000000000 --- a/torch_npu/csrc/aten/ops/DefaultKernelNpu.cpp +++ /dev/null @@ -1,31 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::isnan(const at::Tensor& self) { - return at::native::isnan(self); -} - -at::Tensor NPUNativeFunctions::unfold(const at::Tensor& self, int64_t dimension, int64_t size, int64_t step) { - return at::native::unfold(self, dimension, size, step); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/DeformableConv2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/DeformableConv2dKernelNpu.cpp deleted file mode 100644 index 193aa97192..0000000000 --- a/torch_npu/csrc/aten/ops/DeformableConv2dKernelNpu.cpp +++ /dev/null @@ -1,221 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -tuple NPUNativeFunctions::npu_deformable_conv2dbk( - const at::Tensor& input, - const at::Tensor& grad_output, - const at::Tensor& offset_out, - const at::Tensor& weight, - const at::Tensor& offset, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups, - int64_t deformable_groups, - bool modulated) { - at::Tensor grad_input = OpPreparation::ApplyTensorWithFormat(input, ACL_FORMAT_NCHW); - at::Tensor grad_offset = OpPreparation::ApplyTensorWithFormat(offset, ACL_FORMAT_NCHW); - - // deformable_conv2d_backward includes conv2d_backward and DeformableOffsetsGrad - c10::SmallVector conv2dStride = array_to_small_vector(kernel_size); - c10::SmallVector conv2dPadding = {0, 0, 0, 0}; - c10::SmallVector conv2dDilation = {1, 1}; - auto conv2dBackwardOutput = NPUNativeFunctions::npu_conv2d_backward( - offset_out, grad_output, weight, conv2dStride, conv2dPadding, conv2dDilation, groups, {true, true, true}); - - // DeformableOffsetsGrad's input 'grad' is the output[0] of conv2d_backward - at::Tensor deformableOffsetsBackwardInput = std::get<0>(conv2dBackwardOutput); - at::Tensor grad_weight = std::get<1>(conv2dBackwardOutput); - at::Tensor grad_bias = std::get<2>(conv2dBackwardOutput); - - string dataFormat = "NCHW"; - OpCommand cmd; - cmd.Name("DeformableOffsetsGrad") - .Input(deformableOffsetsBackwardInput) - .Input(input) - .Input(offset) - .Output(grad_input) - .Output(grad_offset) - .Attr("strides", stride) - .Attr("pads", padding) - .Attr("ksize", kernel_size) - .Attr("dilations", dilation) - .Attr("data_format",dataFormat) - .Attr("deformable_groups", deformable_groups) - .Attr("modulated",modulated) - .Run(); - - return std::tie(grad_input, grad_weight, grad_offset, grad_bias); -} - -tuple deformable_conv2d_npu( - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& offset, - const c10::optional& bias_opt, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups, - int64_t deformable_groups, - bool modulated) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = deformable_conv2d_npu_output_size( - input, weight, offset, bias, kernel_size, stride, padding, dilation, groups, deformable_groups, modulated); - - at::Tensor deformableOffsetsOutput = OpPreparation::ApplyTensorWithFormat(outputSize, input.options(), ACL_FORMAT_NCHW); - - string dataFormat = "NCHW"; - OpCommand cmd; - cmd.Name("DeformableOffsets") - .Input(input) - .Input(offset) - .Output(deformableOffsetsOutput) - .Attr("ksize", kernel_size) - .Attr("strides", stride) - .Attr("pads", padding) - .Attr("dilations", dilation) - .Attr("deformable_groups", deformable_groups) - .Attr("data_format",dataFormat) - .Attr("modulated",modulated) - .Run(); - - c10::SmallVector conv2dStride = array_to_small_vector(kernel_size); - c10::SmallVector conv2dPadding = {0, 0, 0, 0}; - c10::SmallVector conv2dDilation = {1, 1}; - at::Tensor conv2dOutput = NPUNativeFunctions::npu_conv2d( - deformableOffsetsOutput, weight, bias, conv2dStride, conv2dPadding, conv2dDilation, groups); - - return std::tie(conv2dOutput, deformableOffsetsOutput); -} - -class NPUDeformableConv2dFunction : public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& offset, - const c10::optional& bias_opt, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups, - int64_t deformable_groups, - bool modulated) { - ctx->saved_data["kernel_size"] = kernel_size; - ctx->saved_data["stride"] = stride; - ctx->saved_data["padding"] = padding; - ctx->saved_data["dilation"] = dilation; - ctx->saved_data["groups"] = groups; - ctx->saved_data["deformable_groups"] = deformable_groups; - ctx->saved_data["modulated"] = modulated; - ctx->saved_data["bias_has_value"] = (bias_opt.has_value() == true) ? bias_opt.value().requires_grad() : false; - - at::AutoNonVariableTypeMode g; - auto result = deformable_conv2d_npu( - input, weight, offset, bias_opt, kernel_size, stride, padding, dilation, groups, deformable_groups, modulated); - auto result1 = std::get<1>(result); - ctx->save_for_backward({input, weight, offset, result1}); - tensor_list result_list = {std::get<0>(result), result1}; - return result_list; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto kernel_size = ctx->saved_data["kernel_size"].toIntVector(); - auto stride = ctx->saved_data["stride"].toIntVector(); - auto padding = ctx->saved_data["padding"].toIntVector(); - auto dilation = ctx->saved_data["dilation"].toIntVector(); - auto groups = ctx->saved_data["groups"].toInt(); - auto deformable_groups = ctx->saved_data["deformable_groups"].toInt(); - auto modulated = ctx->saved_data["modulated"].toBool(); - auto bias_has_value = ctx->saved_data["bias_has_value"].toBool(); - - auto saved = ctx->get_saved_variables(); - auto input = saved[0]; - auto weight = saved[1]; - auto offset = saved[2]; - auto offset_out = saved[3]; - - tuple result = NPUNativeFunctions::npu_deformable_conv2dbk( - input, grad_outputs[0], offset_out, weight, offset, kernel_size, - stride, padding, dilation, groups, deformable_groups, modulated); - - tensor_list output; - if (bias_has_value) { - output = {std::get<0>(result), - std::get<1>(result), - std::get<2>(result), - std::get<3>(result), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - } else { - output = {std::get<0>(result), - std::get<1>(result), - std::get<2>(result), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - } - return output; - } -}; - -tuple NPUNativeFunctions::npu_deformable_conv2d( - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& offset, - const c10::optional& bias_opt, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups, - int64_t deformable_groups, - bool modulated) { - auto result = NPUDeformableConv2dFunction::apply( - input, weight, offset, bias_opt, kernel_size, stride, padding, dilation, groups, deformable_groups, modulated); - std::tuple output(result[0], result[1]); - return output; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/DiagKernelNpu.cpp b/torch_npu/csrc/aten/ops/DiagKernelNpu.cpp deleted file mode 100644 index ac13a89763..0000000000 --- a/torch_npu/csrc/aten/ops/DiagKernelNpu.cpp +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -namespace { -c10::SmallVector diag_npu_output_size( - const at::Tensor& self, - int64_t diagonal) { - c10::SmallVector shape; - if (self.dim() == 1) { - shape.emplace_back(self.size(0) + diagonal); - shape.emplace_back(self.size(0) + diagonal); - return shape; - } - int64_t m = self.size(0); - int64_t n = self.size(1); - if (m == n) { - shape.emplace_back(m - diagonal); - } else if (m < n) { - shape.emplace_back(diagonal <= n - m ? m : n - diagonal); - } else { - shape.emplace_back(n - diagonal); - } - return shape; -} -} // namespace - -at::Tensor& diag_out_npu_nocheck( - const at::Tensor& self, - int64_t diagonal, - at::Tensor& result) { - OpCommand cmd; - if (self.dim() == 1) { - cmd.Name("Diag"); - } else { - cmd.Name("DiagPart"); - } - cmd.Input(self) - .Output(result) - .Attr("diagonal", diagonal) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::diag_out( - const at::Tensor& self, - int64_t diagonal, - at::Tensor& result) { - TORCH_CHECK((self.dim() == 1) || (self.dim() == 2), - "Value should be a 1-dimensional tensor or 2-dimensional tensor, but got ", self.dim()); - diagonal = make_wrap_dim(diagonal, self.dim()); - TORCH_CHECK((self.dim() == 1) || (self.dim() == 2 && diagonal <= self.size(0) && diagonal <= self.size(1)), - "If the value is 2-dimensional tensor, the diagonal shoule less than shape.Diagonal is ", diagonal); - - auto outputSize = diag_npu_output_size(self, diagonal); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self, &diagonal](at::Tensor& result){diag_out_npu_nocheck(self, diagonal, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::diag( - const at::Tensor& self, - int64_t diagonal) { - TORCH_CHECK((self.dim() == 1) || (self.dim() == 2), - "Value should be a 1-dimensional tensor or 2-dimensional tensor, but got ", self.dim()); - diagonal = make_wrap_dim(diagonal, self.dim()); - TORCH_CHECK((self.dim() == 1) || (self.dim() == 2 && diagonal <= self.size(0) && diagonal <= self.size(1)), - "If the value is 2-dimensional tensor, the diagonal shoule less than shape.Diagonal is ", diagonal); - - auto outputSize = diag_npu_output_size(self, diagonal); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - diag_out_npu_nocheck(self, diagonal, result); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/DiouKernelNpu.cpp b/torch_npu/csrc/aten/ops/DiouKernelNpu.cpp deleted file mode 100644 index 28dbf1ad2c..0000000000 --- a/torch_npu/csrc/aten/ops/DiouKernelNpu.cpp +++ /dev/null @@ -1,193 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -c10::SmallVector diou_output_size( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool is_cross){ - c10::SmallVector output_size; - if(is_cross){ - output_size = {gtboxes.size(1), self.size(1)}; - } else { - output_size = {1, self.size(1)}; - } - return output_size; -} - -at::Tensor& diou_inner_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode){ - auto output_size = diou_output_size(self, gtboxes, is_cross); - string mode_str = mode == 1 ? "iof" : "iou"; - - OpCommand cmd; - cmd.Name("DIoU") - .Input(self) - .Input(gtboxes) - .Output(result) - .Attr("trans", trans) - .Attr("is_cross", is_cross) - .Attr("mode", mode_str) - .Run(); - return result; -} - -at::Tensor diou_npu( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode) { - // Op need form of [n, 4], but pass should be [4, n]; - // Note: temp avoid! it'll be removed while op deal with fp16 issue! - at::Tensor selfCp = self; - if (selfCp.scalar_type() == at::kHalf) { - selfCp = NPUNativeFunctions::npu_dtype_cast(selfCp, at::kFloat); - } - at::Tensor gtboxesCp = gtboxes; - if (gtboxesCp.scalar_type() == at::kHalf) { - gtboxesCp = NPUNativeFunctions::npu_dtype_cast(gtboxesCp, at::kFloat); - } - auto output_size = diou_output_size(selfCp, gtboxesCp, is_cross); - at::Tensor result = OpPreparation::ApplyTensor(selfCp, output_size); - - diou_inner_out_npu(result, selfCp, gtboxesCp, trans, is_cross, mode); - if (self.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::kHalf); - } - return result; -} - -std::tuple diou_backward_inner_out_npu( - at::Tensor& dbboxes, - at::Tensor& dgtboxes, - const at::Tensor& grad, - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode){ - string mode_str = mode == 1 ? "iof" : "iou"; - - OpCommand cmd; - cmd.Name("DIoUGrad") - .Input(grad) - .Input(bboxes) - .Input(gtboxes) - .Output(dbboxes) - .Output(dgtboxes) - .Attr("trans", trans) - .Attr("is_cross", is_cross) - .Attr("mode", mode_str) - .Run(); - return std::tie(dbboxes, dgtboxes); -} - -std::tuple NPUNativeFunctions::npu_diou_backward( - const at::Tensor& grad, - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode){ - // Op need form of [n] grad - // Note: temp avoid! it'll be remove while op deal with fp16 issue! - at::Tensor gradCp = at::squeeze(grad, 0); - if (gradCp.scalar_type() == at::kHalf) { - gradCp = NPUNativeFunctions::npu_dtype_cast(gradCp, at::kFloat); - } - at::Tensor bboxesCp = bboxes; - if (bboxesCp.scalar_type() == at::kHalf) { - bboxesCp = NPUNativeFunctions::npu_dtype_cast(bboxesCp, at::kFloat); - } - at::Tensor gtboxesCp = gtboxes; - if (gtboxesCp.scalar_type() == at::kHalf) { - gtboxesCp = NPUNativeFunctions::npu_dtype_cast(gtboxesCp, at::kFloat); - } - at::Tensor dbboxes = OpPreparation::ApplyTensor(bboxesCp); - at::Tensor dgtboxes = OpPreparation::ApplyTensor(gtboxesCp); - - diou_backward_inner_out_npu(dbboxes, dgtboxes, gradCp, bboxesCp, gtboxesCp, trans, is_cross, mode); - if (bboxes.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf) { - dbboxes = NPUNativeFunctions::npu_dtype_cast(dbboxes, at::kHalf); - dgtboxes = NPUNativeFunctions::npu_dtype_cast(dgtboxes, at::kHalf); - } - return std::tie(dbboxes, dgtboxes); -} - -class NPUDiouFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode) { - ctx->saved_data["trans"] = trans; - ctx->saved_data["is_cross"] = is_cross; - ctx->saved_data["mode"] = mode; - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({self, gtboxes}); - return diou_npu(self, gtboxes, trans, is_cross, mode); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto trans = ctx->saved_data["trans"].toBool(); - auto is_cross = ctx->saved_data["is_cross"].toBool(); - auto mode = ctx->saved_data["mode"].toInt(); - auto saved = ctx->get_saved_variables(); - auto bboxes = saved[0]; - auto gtboxes = saved[1]; - - tuple result = NPUNativeFunctions::npu_diou_backward(grad_outputs[0], - bboxes, gtboxes, trans, is_cross, mode); - - tensor_list output = {std::get<0>(result), - std::get<1>(result), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_diou(const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode) { - return NPUDiouFunction::apply(self, gtboxes, trans, is_cross, mode); -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/DivKernelNpu.cpp b/torch_npu/csrc/aten/ops/DivKernelNpu.cpp index ad9009caec..56a72fa8e2 100644 --- a/torch_npu/csrc/aten/ops/DivKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/DivKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -27,7 +27,7 @@ namespace at_npu { auto unified_result = OpPreparation::binary_op_check(result, self, other, true); OpCommand cmd; - cmd.Name("RealDiv") + cmd.Name("Div") .Expect(unified_result) .Input(self) .Input(other, self.scalar_type()) @@ -41,7 +41,7 @@ namespace at_npu { // executing the NPU operator - if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) + if (other.dim() == 0) { div_scalar_out_npu(self, other.item(), result); } @@ -49,7 +49,7 @@ namespace at_npu { auto unified_result = OpPreparation::binary_op_check(result, self, other, true); OpCommand cmd; - cmd.Name("RealDiv") + cmd.Name("Div") .Expect(unified_result) .Input(self) .Input(other) @@ -60,7 +60,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::div_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) + at::Tensor &XLANativeFunctions::div_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) { // calculate the output size at::Tensor outputTensor = CalcuOpUtil::is_scalar_wrapped_to_tensor(self) ? other : self; @@ -76,7 +76,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::div(const at::Tensor &self, const at::Tensor &other) + at::Tensor XLANativeFunctions::div(const at::Tensor &self, const at::Tensor &other) { // calculate the output size bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); @@ -96,7 +96,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::div(const at::Tensor &self, at::Scalar other) + at::Tensor XLANativeFunctions::div(const at::Tensor &self, const at::Scalar& other) { // calculate the output size auto outputSize = input_same_output_size(self); @@ -113,7 +113,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::div_(at::Tensor &self, const at::Tensor &other) + at::Tensor &XLANativeFunctions::div_(at::Tensor &self, const at::Tensor &other) { c10::SmallVector inputs = {self, other}; c10::SmallVector outputs = {self}; @@ -133,7 +133,7 @@ namespace at_npu return self; } - at::Tensor &NPUNativeFunctions::div_(at::Tensor &self, at::Scalar other) + at::Tensor &XLANativeFunctions::div_(at::Tensor &self, const at::Scalar& other) { if (!NpuUtils::check_match(&self)) { @@ -150,102 +150,5 @@ namespace at_npu return self; } - at::Tensor NPUNativeFunctions::div( - const at::Tensor& self, - const at::Tensor& other, - std::string rounding_mode) { - if (rounding_mode == "floor") { - return NPUNativeFunctions::floor_divide(self, other); - } - at::Tensor true_div_res = NPUNativeFunctions::div(self, other); - if (rounding_mode == "true") { - return true_div_res; - } else if (rounding_mode == "trunc") { - return NPUNativeFunctions::trunc(true_div_res); - } - - TORCH_CHECK(false, - "div expected rounding_mode to be one of 'true', 'trunc', or 'floor' " - "but found '", rounding_mode, "'"); - } - - at::Tensor& NPUNativeFunctions::div_( - at::Tensor& self, - const at::Tensor& other, - std::string rounding_mode) { - if (rounding_mode == "floor") { - return NPUNativeFunctions::floor_divide_(self, other); - } - NPUNativeFunctions::div_(self, other); - if (rounding_mode == "true") { - return self; - } else if (rounding_mode == "trunc") { - return NPUNativeFunctions::trunc_(self); - } - - TORCH_CHECK(false, - "div expected rounding_mode to be one of 'true', 'trunc', or 'floor' " - "but found '", rounding_mode, "'"); - } - - at::Tensor& NPUNativeFunctions::div_out( - const at::Tensor& self, - const at::Tensor& other, - std::string rounding_mode, - at::Tensor& result) { - TORCH_CHECK((rounding_mode == "true" || rounding_mode == "trunc" || rounding_mode == "floor"), - "div expected rounding_mode to be one of 'true', 'trunc', or 'floor' " - "but found '", rounding_mode, "'"); - - if (rounding_mode == "floor") { - NPUNativeFunctions::floor_divide_out(self, other, result); - return result; - } - NPUNativeFunctions::div_out(self, other, result); - if (rounding_mode == "trunc") { - NPUNativeFunctions::trunc_(result); - } - - return result; - } - - at::Tensor NPUNativeFunctions::div( - const at::Tensor& self, - at::Scalar other, - std::string rounding_mode) { - TORCH_CHECK((rounding_mode == "true" || rounding_mode == "trunc" || rounding_mode == "floor"), - "div expected rounding_mode to be one of 'true', 'trunc', or 'floor' " - "but found '", rounding_mode, "'"); - - if (rounding_mode == "floor") { - return NPUNativeFunctions::floor_divide(self, other); - } - at::Tensor true_div_res = NPUNativeFunctions::div(self, other); - if (rounding_mode == "true") { - return true_div_res; - } else if (rounding_mode == "trunc") { - return NPUNativeFunctions::trunc(true_div_res); - } - } - - at::Tensor& NPUNativeFunctions::div_( - at::Tensor& self, - at::Scalar other, - std::string rounding_mode) { - if (rounding_mode == "floor") { - return NPUNativeFunctions::floor_divide_(self, other); - } - NPUNativeFunctions::div_(self, other); - if (rounding_mode == "true") { - return self; - } else if (rounding_mode == "trunc") { - return NPUNativeFunctions::trunc_(self); - } - - TORCH_CHECK(false, - "div expected rounding_mode to be one of 'true', 'trunc', or 'floor' " - "but found '", rounding_mode, "'"); - } - } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/DotKernelNpu.cpp b/torch_npu/csrc/aten/ops/DotKernelNpu.cpp deleted file mode 100644 index c6337abfc3..0000000000 --- a/torch_npu/csrc/aten/ops/DotKernelNpu.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::dot_out(const at::Tensor& self, const at::Tensor& tensor, at::Tensor& result) { - c10::SmallVector outputSize = dot_npu_output_size(self, tensor); - OpPreparation::CheckOut( - {self, tensor}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - - OpCommand cmd; - cmd.Name("Dot") - .Input(self) - .Input(tensor) - .Output(result) - .Run(); - c10::SmallVector shape = {}; - result.resize_(shape); - return result; -} -at::Tensor NPUNativeFunctions::dot(const at::Tensor& self, const at::Tensor& tensor) { - c10::SmallVector outputSize = dot_npu_output_size(self, tensor); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - dot_out(self, tensor, result); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/DropoutKernelNpu.cpp b/torch_npu/csrc/aten/ops/DropoutKernelNpu.cpp index 4a6d3f45db..f360425751 100644 --- a/torch_npu/csrc/aten/ops/DropoutKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/DropoutKernelNpu.cpp @@ -20,7 +20,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/interface/EnvVariables.h" #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/aten/NPUGeneratorImpl.h" @@ -65,7 +65,7 @@ at::Tensor dropout_gen_mask(const at::Tensor& self, at::Scalar prob) { bool isFuzzyCompile = env::CheckFuzzyEnable(); int64_t numels; auto desc_ = torch_npu::NPUBridge::GetNpuStorageImpl(self)->get_npu_desc(); - numels = isFuzzyCompile ? at::prod_intlist(desc_.storage_sizes_) : self.numel(); + numels = isFuzzyCompile ? c10::multiply_integers(desc_.storage_sizes_) : self.numel(); uint32_t length = (numels + 128 - 1) / 128 * 128; at::Tensor mask = OpPreparation::ApplyTensorWithFormat( @@ -94,7 +94,7 @@ at::Tensor dropout_gen_mask(const at::Tensor& self, at::Scalar prob) { return mask; } -at::Tensor NPUNativeFunctions::npu_dropout_gen_mask( +at::Tensor XLANativeFunctions::npu_dropout_gen_mask( at::IntArrayRef size, double p, c10::optional dtype_opt, c10::optional layout_opt, @@ -106,7 +106,7 @@ at::Tensor NPUNativeFunctions::npu_dropout_gen_mask( .pinned_memory(pin_memory_opt); at::Scalar prob = at::Scalar(1. - p); - int64_t numels = at::prod_intlist(size); + int64_t numels = c10::multiply_integers(size); uint32_t length = (numels + 128 - 1) / 128 * 128; at::Tensor mask = OpPreparation::ApplyTensorWithFormat(at::IntArrayRef{length / 8}, options.dtype(at::kByte), @@ -160,7 +160,7 @@ std::tuple dropout_v1_npu_impl( return std::tie(result, mask); } -at::Tensor NPUNativeFunctions::npu_dropout_backward( +at::Tensor XLANativeFunctions::npu_dropout_backward( const at::Tensor& grad_output, const at::Tensor& mask, double scale) { @@ -210,13 +210,13 @@ public: auto p = ctx->saved_data["p"].toDouble(); auto saved = ctx->get_saved_variables(); auto mask = saved[0]; - at::Tensor result = NPUNativeFunctions::npu_dropout_backward(grad_outputs[0], mask, p); + at::Tensor result = XLANativeFunctions::npu_dropout_backward(grad_outputs[0], mask, p); tensor_list output = {result, at::Tensor()}; return output; } }; -std::tuple NPUNativeFunctions::_npu_dropout( +std::tuple XLANativeFunctions::_npu_dropout( const at::Tensor& self, double p) { auto result = NPUdropoutFunction::apply(self, p); @@ -244,13 +244,13 @@ public: auto p = ctx->saved_data["p"].toDouble(); auto saved = ctx->get_saved_variables(); auto mask = saved[0]; - at::Tensor result = NPUNativeFunctions::npu_dropout_backward(grad_outputs[0], mask, p); + at::Tensor result = XLANativeFunctions::npu_dropout_backward(grad_outputs[0], mask, p); tensor_list output = {result, at::Tensor(), at::Tensor()}; return output; } }; -std::tuple NPUNativeFunctions::npu_dropout_do_mask( +std::tuple XLANativeFunctions::npu_dropout_do_mask( const at::Tensor& self, const at::Tensor& mask, double p) { @@ -259,14 +259,14 @@ std::tuple NPUNativeFunctions::npu_dropout_do_mask( return output; } -at::Tensor NPUNativeFunctions::dropout(const at::Tensor& self, double p, bool train) { +at::Tensor XLANativeFunctions::dropout(const at::Tensor& self, double p, bool train) { if (p == 0 || !train || self.numel() == 0) { return self; } if (p == 1) { return self.mul(at::zeros(self.sizes(), self.options())); } - at::Tensor result = std::get<0>(NPUNativeFunctions::_npu_dropout(self, p)); + at::Tensor result = std::get<0>(XLANativeFunctions::_npu_dropout(self, p)); return result; } diff --git a/torch_npu/csrc/aten/ops/DropoutWithAddSoftmaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/DropoutWithAddSoftmaxKernelNpu.cpp deleted file mode 100644 index 3a9b726643..0000000000 --- a/torch_npu/csrc/aten/ops/DropoutWithAddSoftmaxKernelNpu.cpp +++ /dev/null @@ -1,164 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/core/npu/SecondaryStreamGuard.h" -#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -at::Tensor dropout_genmask(const at::Tensor& self, at::Scalar prob){ - uint32_t length = (self.numel() + 128 - 1) / 128 * 128; - at::Tensor mask = OpPreparation::ApplyTensorWithFormat( - {length}, - self.options().dtype(at::kByte), - ACL_FORMAT_ND); - at::IntArrayRef selfShape = self.sizes(); - - int64_t seed = 2; - int64_t seed2 = 0; - OpCommand cmd; - cmd.Name("DropOutGenMaskV3") - .Input(selfShape) - .Input(prob, self.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Output(mask) - .Attr("seed", seed) - .Attr("seed2", seed2) - .Run(); - return mask; -} - -std::tuple npu_dropout_with_add_softmax_forward( - const at::Tensor& self, - const at::Tensor& x1, - at::Scalar alpha, - double p, - int64_t dim){ - at::Tensor result_softmax = OpPreparation::ApplyTensor(x1); - at::Tensor result_dropout = OpPreparation::ApplyTensor(self); - c10::SmallVector dimList = {dim}; - double retain = 1. - p; - at::Scalar prob = at::Scalar(retain); - at::Tensor mask; - auto original_stream = c10_npu::getCurrentNPUStream(); - { - c10_npu::SecondaryStreamGuard guard(c10_npu::getCurrentSecondaryStream()); - mask = dropout_genmask(x1, prob); - } - c10_npu::NPUCachingAllocator::recordStream(mask.storage().data_ptr(), original_stream); - - OpCommand cmd; - cmd.Name("AxpyWithSoftmaxAndDropOutDoMask") - .Input(x1) - .Input(self) - .Input(mask) - .Output(result_softmax) - .Output(result_dropout) - .Attr("alpha", alpha) - .Attr("input_keep_prob", prob) - .Attr("axis", dimList) - .Run(); - return std::tie(mask, result_softmax, result_dropout); -} - -tuple NPUNativeFunctions::npu_dropout_with_add_softmax_backward( - const at::Tensor& grad_out, - const at::Tensor& mask, - const at::Tensor& softmax_out, - at::Scalar alpha, - double p, - int64_t dim){ - at::Tensor result = OpPreparation::ApplyTensor(softmax_out); - c10::SmallVector dimList = {dim}; - double retain = 1. - p; - at::Scalar prob = at::Scalar(retain); - - OpCommand cmd; - cmd.Name("DropoutWithMulsAndSoftmaxGrad") - .Input(grad_out) - .Input(mask) - .Input(softmax_out) - .Output(result) - .Attr("alpha", alpha) - .Attr("input_keep_prob", prob) - .Attr("axes", dimList) - .Run(); - return std::tie(result, grad_out); -} - -class NPUdropoutwasFunction: public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& self, - const at::Tensor& x1, - at::Scalar alpha, - double p, - int64_t dim) { - ctx->saved_data["alpha"] = alpha; - ctx->saved_data["p"] = p; - ctx->saved_data["dim"] = dim; - at::AutoNonVariableTypeMode g; - auto result = npu_dropout_with_add_softmax_forward(self, x1, alpha, p, dim); - auto result0 = std::get<0>(result); - auto result1 = std::get<1>(result); - ctx->save_for_backward({result0, result1}); - tensor_list result_list = {result0, result1, std::get<2>(result)}; - return result_list; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto alpha = ctx->saved_data["alpha"].toScalar(); - auto p = ctx->saved_data["p"].toDouble(); - auto dim = ctx->saved_data["dim"].toInt(); - auto saved = ctx->get_saved_variables(); - auto result0 = saved[0]; - auto result1 = saved[1]; - auto result = NPUNativeFunctions::npu_dropout_with_add_softmax_backward( - grad_outputs[2], - result0, - result1, - alpha, - p, - dim); - tensor_list output = {std::get<0>(result), - std::get<1>(result), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -std::tuple NPUNativeFunctions::npu_dropout_with_add_softmax( - const at::Tensor& self, - const at::Tensor& x1, - at::Scalar alpha, - double p, - int64_t dim){ - auto result = NPUdropoutwasFunction::apply(self, x1, alpha, p, dim); - return std::tie(result[0], result[1], result[2]); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/DropoutWithByteMaskKernelNpu.cpp b/torch_npu/csrc/aten/ops/DropoutWithByteMaskKernelNpu.cpp deleted file mode 100644 index d604ab6390..0000000000 --- a/torch_npu/csrc/aten/ops/DropoutWithByteMaskKernelNpu.cpp +++ /dev/null @@ -1,189 +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. - -#include - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/core/npu/SecondaryStreamGuard.h" -#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUGeneratorImpl.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; -at::Tensor dropout_do_mask_with_byte_mask( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& mask, - at::Scalar prob) { - OpCommand cmd; - cmd.Name("DropOutDoMaskV3") - .Input(self) - .Input(mask) - .Input(prob, self.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Output(result) - .Run(); - return result; -} - -at::Tensor dropout_gen_byte_mask(const at::Tensor& self, at::Scalar prob) { - at::IntArrayRef selfShape = self.sizes(); - at::Tensor mask = OpPreparation::ApplyTensorWithFormat( - selfShape, - self.options().dtype(at::kByte), - ACL_FORMAT_ND); - OpCommand cmd; - // If either seed or seed2 are set to be non-zero, the random number generator - // is seeded by the given seed. Otherwise, it is seeded by a random seed. - // DropOutGenMaskV3 use seed and seed2 to generator a seed, like this: - // seed2 seed - // 127~64 63~0 - // so, we set seed2 = 0 to ensure the seed which user set is equal to the seed - // used by the operator DropOutGenMaskV3 - const auto gen = at_npu::detail::getDefaultNPUGenerator(); - const int64_t seed = static_cast(gen.current_seed()); - const int64_t seed2 = 0; - cmd.Name("DropOutGenMaskV3") - .Input(selfShape) - .Input(prob, self.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Output(mask) - .Attr("seed", seed) - .Attr("seed2", seed2) - .Run(); - return mask; -} - -std::tuple dropout_npu_impl( - at::Tensor result, - const at::Tensor& self, - double p) { - at::Tensor selfCp = NpuUtils::format_contiguous(self); - TORCH_CHECK( - p >= 0 && p <= 1, - "dropout probability has to be between 0 and 1, but got ", p); - TORCH_CHECK( - at::isFloatingType(selfCp.scalar_type()), - "dropout only supports floating-point dtypes"); - - double retain = 1. - p; - at::Scalar prob = at::Scalar(retain); - at::Tensor mask; - auto original_stream = c10_npu::getCurrentNPUStream(); - { - // During the life cycle of this raii instance, the calcu stream is set as the - // secondary stream, and tasks are distributed to the secondary stream. At the - // same time, according to the one-stream-one-pool principle, memory is also - // alloced from the pool of the secondary stream. - c10_npu::SecondaryStreamGuard guard(c10_npu::getCurrentSecondaryStream()); - mask = dropout_gen_byte_mask(selfCp, prob); - } - // When tasks on multiple streams read and write the same block of memory, - // recordStream needs to be called to ensure the correctness of memory reuse. - c10_npu::NPUCachingAllocator::recordStream(mask.storage().data_ptr(), original_stream); - dropout_do_mask_with_byte_mask(result, selfCp, mask, prob); - - return std::tie(result, mask); -} - -std::tuple _dropout_with_byte_mask_new( - const at::Tensor& self, - double p) { - at::Tensor result = OpPreparation::ApplyTensor(self); - return dropout_npu_impl(result, self, p); -} - -std::tuple _dropout_with_byte_mask_inplace_new( - at::Tensor& self, - double p) { - return dropout_npu_impl(self, self, p); -} - -at::Tensor NPUNativeFunctions::_dropout_with_byte_mask_backward( - const at::Tensor& grad_output, - const at::Tensor& mask, - double scale) { - TORCH_CHECK( - at::isFloatingType(grad_output.scalar_type()), - "dropoutbackward only supports floating-point dtypes"); - TORCH_CHECK( - mask.scalar_type() == at::ScalarType::Byte, - "mask should be torch.uint8 dtype"); - double retain = 1. - scale; - at::Tensor result = OpPreparation::ApplyTensor(grad_output); - - OpCommand cmd; - cmd.Name("DropOutDoMaskV3") - .Input(grad_output) - .Input(mask) - .Input(retain, grad_output.scalar_type(), CompileType::MEMORY_HOST_COMPILE_DEPENDENT) - .Output(result) - .Run(); - - return result; -} - -class NPUdropoutwbmFunction: public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& self, - double p) { - ctx->saved_data["p"] = p; - at::AutoNonVariableTypeMode g; - auto result = _dropout_with_byte_mask_new(self, p); - auto result1 = std::get<1>(result); - ctx->save_for_backward({result1}); - tensor_list result_list = {std::get<0>(result), result1}; - return result_list; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto p = ctx->saved_data["p"].toDouble(); - auto saved = ctx->get_saved_variables(); - auto mask = saved[0]; - at::Tensor result = NPUNativeFunctions::_dropout_with_byte_mask_backward(grad_outputs[0], mask, p); - tensor_list output = {result, at::Tensor()}; - return output; - } -}; - -std::tuple NPUNativeFunctions::_dropout_with_byte_mask( - const at::Tensor& self, - double p) { - auto result = NPUdropoutwbmFunction::apply(self, p); - std::tuple output(result[0], result[1]); - return output; -} - -at::Tensor NPUNativeFunctions::dropout_with_byte_mask(const at::Tensor& self, double p, bool train) { - TORCH_CHECK( - at_npu::key::isDeviceTensor(self), - "dropout_with_byte_mask only supports device for NPU!"); - if (p == 0 || !train || self.numel() == 0) { - return self; - } - if (p == 1) { - return self.mul(at::zeros(self.sizes(), self.options())); - } - return std::get<0>(NPUNativeFunctions::_dropout_with_byte_mask(self, p)); -} - - -} // namespace native -} // namespace at diff --git a/torch_npu/csrc/aten/ops/EluKernelNpu.cpp b/torch_npu/csrc/aten/ops/EluKernelNpu.cpp deleted file mode 100644 index 4bca755e19..0000000000 --- a/torch_npu/csrc/aten/ops/EluKernelNpu.cpp +++ /dev/null @@ -1,128 +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. -#include -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -at::Tensor& elu_out_nocheck(const at::Tensor& self, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale, at::Tensor& result) { - float alphaValue = CalcuOpUtil::get_scalar_float_value(alpha); - float scaleValue = CalcuOpUtil::get_scalar_float_value(scale); - float inputScaleValue = CalcuOpUtil::get_scalar_float_value(input_scale); - OpCommand cmd; - cmd.Name("Elu") - .Input(self) - .Output(result) - .Attr("alpha", alphaValue) - .Attr("scale", scaleValue) - .Attr("input_scale", inputScaleValue) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::elu_out(const at::Tensor& self, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor checkResult = elu_out_nocheck(self, alpha, scale, input_scale, contiguousResult); - NpuUtils::format_fresh_view(result, checkResult); - } else { - elu_out_nocheck(self, alpha, scale, input_scale, result); - } - return result; -} - -at::Tensor elu_npu_impl(const at::Tensor& self, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale) { - at::Tensor result = OpPreparation::ApplyTensor(self); - elu_out_nocheck(self, alpha, scale, input_scale, result); - return result; -} - -at::Tensor& elu_backward_out_npu(at::Tensor& grad_input, const at::Tensor& grad_output, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale, const at::Tensor& output) { - float value = CalcuOpUtil::get_scalar_float_value(alpha); - OpCommand cmd; - cmd.Name("EluGradV2") - .Input(grad_output) - .Input(output) - .Output(grad_input) - .Attr("alpha", value) - .Run(); - return grad_input; -} -at::Tensor elu_backward_npu_impl(const at::Tensor& grad_output, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale, const at::Tensor& output) { - at::Tensor result = OpPreparation::ApplyTensor(grad_output); - elu_backward_out_npu(result, grad_output, alpha, scale, input_scale, output); - return result; -} - -class NPUEluFunction: public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - at::Scalar alpha, - at::Scalar scale, - at::Scalar input_scale) { - ctx->saved_data["alpha"] = alpha; - ctx->saved_data["scale"] = scale; - ctx->saved_data["input_scale"] = input_scale; - at::AutoNonVariableTypeMode g; - at::Tensor result = elu_npu_impl(self, alpha, scale, input_scale); - ctx->save_for_backward({result}); - return result; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto alpha = ctx->saved_data["alpha"].toScalar(); - auto scale = ctx->saved_data["scale"].toScalar(); - auto input_scale = ctx->saved_data["input_scale"].toScalar(); - auto saved = ctx->get_saved_variables(); - auto result = saved[0]; - auto grad_input = elu_backward_npu_impl( - grad_outputs[0], - alpha, - scale, - input_scale, - result); - tensor_list output = {grad_input, - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::elu(const at::Tensor& self, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale) { - return NPUEluFunction::apply(self, alpha, scale, input_scale); -} - -at::Tensor& NPUNativeFunctions::elu_(at::Tensor& self, at::Scalar alpha, at::Scalar scale, at::Scalar input_scale) { - auto result = NPUEluFunction::apply(self, alpha, scale, input_scale); - self.copy_(result); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/EmbeddingBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/EmbeddingBackwardKernelNpu.cpp deleted file mode 100644 index 0155cd7895..0000000000 --- a/torch_npu/csrc/aten/ops/EmbeddingBackwardKernelNpu.cpp +++ /dev/null @@ -1,36 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::embedding_backward( - const at::Tensor& grad, - const at::Tensor& indices, - int64_t num_weights, - int64_t padding_idx, - bool scale_grad_by_freq, - bool sparse) { - TORCH_CHECK(sparse == false, "NPU error, not yet support sparse tensor, when sparse == True"); - - // run dense tensor backward - return at::embedding_dense_backward( - grad, indices, num_weights, padding_idx, scale_grad_by_freq); -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/EmbeddingBagBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/EmbeddingBagBackwardKernelNpu.cpp deleted file mode 100644 index 756c601f06..0000000000 --- a/torch_npu/csrc/aten/ops/EmbeddingBagBackwardKernelNpu.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2021 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor NPUNativeFunctions::_embedding_bag_backward( - const at::Tensor& grad, - const at::Tensor& indices, - const at::Tensor& offsets, - const at::Tensor& offset2bag, - const at::Tensor& bag_size, - const at::Tensor& maximum_indices, - int64_t num_weights, - bool scale_grad_by_freq, - int64_t mode, - bool sparse, - const c10::optional& per_sample_weights_opt) { - const at::Tensor& per_sample_weights = c10::value_or_else(per_sample_weights_opt, [] {return at::Tensor();}); - - at::Tensor grad_cpu = grad.to("cpu"); - at::Tensor indices_cpu = indices.to("cpu"); - at::Tensor offsets_cpu = offsets.to("cpu"); - at::Tensor offset2bag_cpu = offset2bag.to("cpu"); - at::Tensor bag_size_cpu = bag_size.to("cpu"); - at::Tensor maximum_indices_cpu = maximum_indices.to("cpu"); - at::Tensor per_sample_weights_cpu = per_sample_weights; - if (per_sample_weights_cpu.defined()) { - at::Tensor per_sample_weights_cpu = per_sample_weights_cpu.to("cpu"); - } - - at::Tensor result = at::_embedding_bag_backward( - grad_cpu, indices_cpu, offsets_cpu, offset2bag_cpu, bag_size_cpu, - maximum_indices_cpu, num_weights, scale_grad_by_freq, mode, sparse, per_sample_weights_cpu); - - result = at::native::sparse_to_dense(result); - result = result.to(indices.device()); - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/EmbeddingBagKernelNpu.cpp b/torch_npu/csrc/aten/ops/EmbeddingBagKernelNpu.cpp deleted file mode 100644 index fba1bd5681..0000000000 --- a/torch_npu/csrc/aten/ops/EmbeddingBagKernelNpu.cpp +++ /dev/null @@ -1,87 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -c10::SmallVector _embedding_bag_npu_output_size( - const at::Tensor& weight, - const at::Tensor& indices, - const at::Tensor& offsets) { - c10::SmallVector outputSize = {}; - if (indices.dim() == 1) { - outputSize = {offsets.size(0), weight.size(1)}; - } else { - outputSize = {indices.size(0), weight.size(1)}; - } - return outputSize; -} - -string get_mode_str(bool mode) { - string modeStr = "mean"; - if (mode == 0) { - modeStr = "sum"; - } else if (mode == 1) { - modeStr = "mean"; - } else { - modeStr = "max"; - } - return modeStr; -} - -tuple NPUNativeFunctions::_embedding_bag( - const at::Tensor& weight, - const at::Tensor& indices, - const at::Tensor& offsets, - bool scale_grad_by_freq, - int64_t mode, - bool sparse, - const c10::optional& per_sample_weights_opt, - bool include_last_offset) { - const at::Tensor& per_sample_weights = c10::value_or_else(per_sample_weights_opt, [] {return at::Tensor();}); - - at::Tensor weight_cpu = weight.to("cpu").requires_grad_(); - at::Tensor indices_cpu = indices.to("cpu"); - at::Tensor offsets_cpu = offsets.to("cpu"); - at::Tensor per_sample_weights_cpu = per_sample_weights; - if (per_sample_weights_cpu.defined()) { - at::Tensor per_sample_weights_cpu = per_sample_weights_cpu.to("cpu"); - } - - auto result = at::native::_embedding_bag_cpu(weight_cpu, indices_cpu, offsets_cpu, scale_grad_by_freq, mode, sparse, per_sample_weights_cpu, include_last_offset); - - at::Tensor output = std::get<0>(result).to(weight.device()); - at::Tensor offset2bag = std::get<1>(result).to(weight.device()); - at::Tensor bag_size = std::get<2>(result).to(weight.device()); - at::Tensor max_indices = std::get<3>(result).to(weight.device()); - - return std::tie(output, offset2bag, bag_size, max_indices); -} -tuple NPUNativeFunctions::_embedding_bag_forward_only( - const at::Tensor& weight, - const at::Tensor& indices, - const at::Tensor& offsets, - bool scale_grad_by_freq, - int64_t mode, - bool sparse, - const c10::optional& per_sample_weights_opt, - bool include_last_offset) { - return _embedding_bag(weight, indices, offsets, scale_grad_by_freq, mode, sparse, per_sample_weights_opt, include_last_offset); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/EmbeddingDenseBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/EmbeddingDenseBackwardKernelNpu.cpp deleted file mode 100644 index b76147c9c2..0000000000 --- a/torch_npu/csrc/aten/ops/EmbeddingDenseBackwardKernelNpu.cpp +++ /dev/null @@ -1,65 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -namespace { -at::Tensor& embedding_dense_backward_nocheck( - at::Tensor& result, - const at::Tensor& grad_output, - const at::Tensor& indices, - int64_t num_weights, - int64_t padding_idx, - bool scale_grad_by_freq) { - // indices must be int64 in pytorch, but npu can only support int32 - auto indices_int32 = indices.to(at::kInt); - - OpCommand cmd; - cmd.Name("EmbeddingDenseGrad") - .Input(grad_output) - .Input(indices_int32) - .Attr("num_weights", num_weights) - .Attr("padding_idx", padding_idx) - .Attr("scale_grad_by_freq", scale_grad_by_freq) - .Output(result) - .Run(); - return result; -} -} // namespace - -at::Tensor NPUNativeFunctions::embedding_dense_backward( - const at::Tensor& grad_weight, - const at::Tensor& indices, - int64_t num_weights, - int64_t padding_idx, - bool scale_grad_by_freq) { - // calculate the output size - auto outputSize = {num_weights, grad_weight.size(-1)}; - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(grad_weight, outputSize); - - // calculate the output resugt of the NPU - embedding_dense_backward_nocheck( - result, grad_weight, indices, num_weights, padding_idx, scale_grad_by_freq); - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/EmbeddingKernelNpu.cpp b/torch_npu/csrc/aten/ops/EmbeddingKernelNpu.cpp deleted file mode 100644 index 9a7f2e5757..0000000000 --- a/torch_npu/csrc/aten/ops/EmbeddingKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& embedding_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& weight, - const at::Tensor& indices) { - c10::SmallVector dimVec = {0}; - - OpCommand cmd; - cmd.Name("GatherV2") - .Input(weight) - .Input(indices) - .Input(dimVec) - .Output(result) - .Run(); - -return result; - -} - -at::Tensor NPUNativeFunctions::embedding( - const at::Tensor& weight, - const at::Tensor& indices, - int64_t padding_idx, - bool scale_grad_by_freq, - bool sparse) { - // calculate the output size - auto outputSize = array_to_small_vector(indices.sizes()); - outputSize.emplace_back(weight.size(weight.dim() - 1)); - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - weight.options(), - CalcuOpUtil::get_tensor_npu_format(weight)); - - // calculate the output resugt of the NPU - embedding_out_npu_nocheck(result, weight, indices); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/EmbeddingRenormKernelNpu.cpp b/torch_npu/csrc/aten/ops/EmbeddingRenormKernelNpu.cpp deleted file mode 100644 index 6bcf1d2b82..0000000000 --- a/torch_npu/csrc/aten/ops/EmbeddingRenormKernelNpu.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& embedding_renorm_gather2d_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& indices) { - OpCommand cmd; - cmd.Name("GatherV2D") - .Input(self) - .Input(indices) - .Output(result) - .Attr("axis", (int64_t)0) - .Run(); - return result; -} - -at::Tensor& embedding_renorm_execute_out_npu( - at::Tensor& result, - const at::Tensor& self, - double max_norm, - double norm_type) { - OpCommand cmd; - cmd.Name("Renorm") - .Input(self) - .Output(result) - .Attr("p", (float)norm_type) - .Attr("dim", (int64_t)0) - .Attr("maxnorm", (float)max_norm) - .Run(); - return result; -} - -at::Tensor& embedding_renorm_scatter_update_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& indices, - const at::Tensor& update) { - OpCommand cmd; - cmd.Name("ScatterUpdate") - .Input(self) - .Input(indices) - .Input(update) - .Output(result) - .Attr("use_locking", false) - .Run(); - return result; -} - -at::Tensor& embedding_renorm_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& indices, - double max_norm, - double norm_type){ - - at::SmallVector midSize = {indices.size(0), self.size(1)}; - at::Tensor mid_input = OpPreparation::ApplyTensor(self, midSize); - at::Tensor mid_output = OpPreparation::ApplyTensor(self, midSize); - - embedding_renorm_gather2d_out_npu(mid_input,self,indices); - - embedding_renorm_execute_out_npu(mid_output, mid_input, max_norm, norm_type); - - at::Tensor mid_output_copy = mid_output.clone(); - auto num_indices = indices.numel(); - at::Tensor input_indices; - - if (num_indices - 1 == 0) { - input_indices = NPUNativeFunctions::npu_dtype_cast(at::zeros({1}, self.options()), at::kLong); - } else { - input_indices = NPUNativeFunctions::npu_dtype_cast(at::range(0, num_indices-1, self.options()), at::kLong); - } - - auto num_mid_output = mid_output.numel(); - at::native::resize_(mid_output_copy, num_mid_output); - at::Tensor scalar_out = OpPreparation::ApplyTensor(self, {num_indices, 1}); - embedding_renorm_gather2d_out_npu(scalar_out, mid_output_copy, input_indices); - at::Tensor out_res = mid_input * scalar_out; - - embedding_renorm_scatter_update_out_npu(result, self, indices, out_res); - - return result; -} - -at::Tensor& NPUNativeFunctions::embedding_renorm_( - at::Tensor& self, - const at::Tensor& indices, - double max_norm, - double norm_type) { - - auto self_arg = at::TensorArg(self, "self", 1); - auto indices_arg = at::TensorArg(indices, "indices", 2); - at::checkDim("embedding_renorm_", self_arg, 2); - at::checkScalarType("embedding_renorm_", indices_arg, at::kLong); - - at::Tensor indices_copy = indices.clone(); - auto num_indices = indices.numel(); - at::native::resize_(indices_copy, num_indices); - - OpPipeWithDefinedOut pipe; - pipe.CheckMemory({self, indices_copy}, {self}) - .Func([&self, &indices_copy, max_norm, norm_type](at::Tensor& result){ - embedding_renorm_out_npu(self, self, indices_copy, max_norm, norm_type);}) - .Call(self); - - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/EqKernelNpu.cpp b/torch_npu/csrc/aten/ops/EqKernelNpu.cpp index 0b05e8361d..01f6101ad0 100644 --- a/torch_npu/csrc/aten/ops/EqKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/EqKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -44,7 +44,7 @@ namespace at_npu return result; } - at::Tensor &eq_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, at::Scalar other) + at::Tensor &eq_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, const at::Scalar& other) { at::Tensor selfCast = self; if (self.dtype() == c10::ScalarType::Int) @@ -61,7 +61,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::eq_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) + at::Tensor &XLANativeFunctions::eq_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) { auto outputSize = broadcast_ops_npu_output_size(self, other); OpPreparation::CheckOut( @@ -74,7 +74,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::eq_out(const at::Tensor &self, at::Scalar other, at::Tensor &result) + at::Tensor &XLANativeFunctions::eq_out(const at::Tensor &self, const at::Scalar& other, at::Tensor &result) { OpPreparation::CheckOut( {self}, @@ -86,7 +86,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::eq(const at::Tensor &self, const at::Tensor &other) + at::Tensor XLANativeFunctions::eq(const at::Tensor &self, const at::Tensor &other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -105,7 +105,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::eq(const at::Tensor &self, at::Scalar other) + at::Tensor XLANativeFunctions::eq(const at::Tensor &self, const at::Scalar& other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); @@ -123,7 +123,7 @@ namespace at_npu return result; } - at::Tensor& NPUNativeFunctions::eq_(at::Tensor &self, const at::Tensor &other) + at::Tensor &eq_npu_(at::Tensor &self, const at::Tensor &other) { OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -147,12 +147,12 @@ namespace at_npu } // uint8 to self dtype - NPUNativeFunctions::npu_dtype_cast_(self, result); + XLANativeFunctions::npu_dtype_cast_(self, result); return self; } - at::Tensor& NPUNativeFunctions::eq_(at::Tensor &self, at::Scalar other) + at::Tensor &eq_npu_(at::Tensor &self, const at::Scalar& other) { OpPreparation::CastBackToOriFormat(self); c10::SmallVector inputs = {self}; @@ -175,7 +175,7 @@ namespace at_npu } // uint8 to self dtype - NPUNativeFunctions::npu_dtype_cast_(self, result); + XLANativeFunctions::npu_dtype_cast_(self, result); return self; } diff --git a/torch_npu/csrc/aten/ops/EqualKernelNpu.cpp b/torch_npu/csrc/aten/ops/EqualKernelNpu.cpp index 4ae82b7198..4957d116ec 100644 --- a/torch_npu/csrc/aten/ops/EqualKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/EqualKernelNpu.cpp @@ -16,12 +16,12 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -bool NPUNativeFunctions::equal(const at::Tensor& self, const at::Tensor& other) { +bool XLANativeFunctions::equal(const at::Tensor& self, const at::Tensor& other) { // check the shape of self and other if(self.sizes() != other.sizes()) { return false; diff --git a/torch_npu/csrc/aten/ops/ErfKernelNpu.cpp b/torch_npu/csrc/aten/ops/ErfKernelNpu.cpp index ef46051274..2ac4578c8a 100644 --- a/torch_npu/csrc/aten/ops/ErfKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ErfKernelNpu.cpp @@ -13,7 +13,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -27,7 +27,7 @@ at::Tensor& erf_npu_nocheck(const at::Tensor& self, at::Tensor& out) { return out; } -at::Tensor& NPUNativeFunctions::erf_out(const at::Tensor& self, at::Tensor& out) { +at::Tensor& XLANativeFunctions::erf_out(const at::Tensor& self, at::Tensor& out) { OpPreparation::CheckOut( {self}, out, @@ -43,15 +43,15 @@ at::Tensor& NPUNativeFunctions::erf_out(const at::Tensor& self, at::Tensor& out) return out; } -at::Tensor NPUNativeFunctions::erf(const at::Tensor& self) { +at::Tensor XLANativeFunctions::erf(const at::Tensor& self) { auto outputSize = input_same_output_size(self); at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); erf_npu_nocheck(self, result); return result; } -at::Tensor& NPUNativeFunctions::erf_(at::Tensor& self) { - NPUNativeFunctions::erf_out(self, self); +at::Tensor& XLANativeFunctions::erf_(at::Tensor& self) { + XLANativeFunctions::erf_out(self, self); return self; } diff --git a/torch_npu/csrc/aten/ops/ErfcKernelNpu.cpp b/torch_npu/csrc/aten/ops/ErfcKernelNpu.cpp deleted file mode 100644 index 007cff6ed0..0000000000 --- a/torch_npu/csrc/aten/ops/ErfcKernelNpu.cpp +++ /dev/null @@ -1,57 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& erfc_out_npu_no_check(at::Tensor& out, const at::Tensor& self){ - OpCommand cmd; - cmd.Name("Erfc") - .Input(self) - .Output(out) - .Run(); - return out; -} - -at::Tensor& NPUNativeFunctions::erfc_out(const at::Tensor& self, at::Tensor& out) { - OpPreparation::CheckOut( - {self}, - out, - self, - self.sizes()); - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {out}) - .Func([&self](at::Tensor& out){erfc_out_npu_no_check(out, self);}) - .Call(out); -} - -at::Tensor NPUNativeFunctions::erfc(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - erfc_out_npu_no_check(result, self); - return result; -} - -at::Tensor& NPUNativeFunctions::erfc_(at::Tensor& self) { - NPUNativeFunctions::erfc_out(self, self); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ErfinvKernelNpu.cpp b/torch_npu/csrc/aten/ops/ErfinvKernelNpu.cpp deleted file mode 100644 index ac8b82c6b6..0000000000 --- a/torch_npu/csrc/aten/ops/ErfinvKernelNpu.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::erfinv_out(const at::Tensor& self, at::Tensor& result) -{ - OpCommand cmd; - cmd.Name("Erfinv") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::erfinv(const at::Tensor &self) { - auto output_size = self.sizes(); - auto output_t = OpPreparation::ApplyTensor(self, output_size); - NPUNativeFunctions::erfinv_out(self, output_t); - - return output_t; -} - - -at::Tensor& NPUNativeFunctions::erfinv_(at::Tensor& self) -{ - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::erfinv_out(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::erfinv_out(self, self); - } - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ExpKernelNpu.cpp b/torch_npu/csrc/aten/ops/ExpKernelNpu.cpp index e49b70c15f..1355a457d6 100644 --- a/torch_npu/csrc/aten/ops/ExpKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ExpKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -30,7 +30,7 @@ at::Tensor& exp_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { return result; } -at::Tensor& NPUNativeFunctions::exp_out(const at::Tensor& self, at::Tensor& result) { +at::Tensor& XLANativeFunctions::exp_out(const at::Tensor& self, at::Tensor& result) { OpPreparation::CheckOut( {self}, result, @@ -42,13 +42,13 @@ at::Tensor& NPUNativeFunctions::exp_out(const at::Tensor& self, at::Tensor& resu .Call(result); } -at::Tensor& NPUNativeFunctions::exp_(at::Tensor& self) { +at::Tensor& XLANativeFunctions::exp_(at::Tensor& self) { exp_out(self, self); return self; } -at::Tensor NPUNativeFunctions::exp(const at::Tensor& self) { +at::Tensor XLANativeFunctions::exp(const at::Tensor& self) { at::Tensor result = OpPreparation::ApplyTensor(self); exp_out_npu_nocheck(result, self); return result; diff --git a/torch_npu/csrc/aten/ops/Expm1KernelNpu.cpp b/torch_npu/csrc/aten/ops/Expm1KernelNpu.cpp deleted file mode 100644 index a0c8b106af..0000000000 --- a/torch_npu/csrc/aten/ops/Expm1KernelNpu.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::expm1_out(const at::Tensor& self, at::Tensor& out) { - OpCommand cmd; - cmd.Name("Expm1") - .Input(self) - .Output(out) - .Run(); - return out; -} - -at::Tensor NPUNativeFunctions::expm1(const at::Tensor& self) { - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - NPUNativeFunctions::expm1_out(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::expm1_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::expm1_out(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::expm1_out(self, self); - } - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/EyeKernelNpu.cpp b/torch_npu/csrc/aten/ops/EyeKernelNpu.cpp deleted file mode 100644 index d21a423622..0000000000 --- a/torch_npu/csrc/aten/ops/EyeKernelNpu.cpp +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& eye_out_npu_nocheck(at::Tensor& result, int64_t n, int64_t m) { - OpCommand cmd; - cmd.Name("Eye") - .Output(result) - .Attr("num_rows", n) - .Attr("num_columns", m) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::eye_out(int64_t n, at::Tensor& result) { - return NPUNativeFunctions::eye_out(n, -1, result); -} - -at::Tensor& NPUNativeFunctions::eye_out(int64_t n, int64_t m, at::Tensor& result) { - TORCH_CHECK(n >= 0, "n must be greater or equal to 0, got ", n); - - if (m < 0) { - m = n; - } - - result.resize_({n, m}); - eye_out_npu_nocheck(result, n, m); - return result; -} - -at::Tensor NPUNativeFunctions::eye( - int64_t n, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - auto device = device_or_default(device_opt); - at::TensorOptions option; - option = option.dtype(dtype_opt) - .layout(layout_opt) - .device(device) - .pinned_memory(pin_memory_opt); - - // get the output size - c10::SmallVector outputSize = {n, n}; - - // The operator does not support the bool type and needs to be converted to an integer. - at::Tensor result = (option.dtype() == at::kBool) - ? OpPreparation::ApplyTensorWithFormat(outputSize, option.dtype(at::ScalarType::Int), ACL_FORMAT_ND) - : OpPreparation::ApplyTensorWithFormat(outputSize, option, ACL_FORMAT_ND); - - NPUNativeFunctions::eye_out(n, result); - - if (option.dtype() == at::kBool) { - result = result.to(at::kBool); - } - - return result; -} - -at::Tensor NPUNativeFunctions::eye( - int64_t n, - int64_t m, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - auto device = device_or_default(device_opt); - at::TensorOptions option; - option = option.dtype(dtype_opt) - .layout(layout_opt) - .device(device) - .pinned_memory(pin_memory_opt); - - // get the output size - c10::SmallVector outputSize = {n, m}; - - // The operator does not support the bool type and needs to be converted to an integer. - at::Tensor result = (option.dtype() == at::kBool) - ? OpPreparation::ApplyTensorWithFormat(outputSize, option.dtype(at::ScalarType::Int), ACL_FORMAT_ND) - : OpPreparation::ApplyTensorWithFormat(outputSize, option, ACL_FORMAT_ND); - - eye_out_npu_nocheck(result, n, m); - - if (option.dtype() == at::kBool) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::kBool); - } - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/FastGeluKernelNpu.cpp b/torch_npu/csrc/aten/ops/FastGeluKernelNpu.cpp deleted file mode 100644 index f3e2c5ada1..0000000000 --- a/torch_npu/csrc/aten/ops/FastGeluKernelNpu.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; -namespace { -at::Tensor fast_gelu_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - - OpCommand cmd; - cmd.Name("FastGelu") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -} // namespace - -namespace { -at::Tensor& fast_gelu_backward_npu_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad, - const at::Tensor& self) { - // constructs the input and output NPUTensorDesc - OpCommand cmd; - cmd.Name("FastGeluGrad") - .Input(grad) - .Input(self) - .Output(grad_input) - .Run(); - - return grad_input; -} -} - -class NPUFastGeluFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self) { - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({self}); - at::Tensor result = OpPreparation::ApplyTensor(self); - return fast_gelu_npu_nocheck(result, self); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto saved = ctx->get_saved_variables(); - auto input = saved[0]; - - at::Tensor result = NPUNativeFunctions::fast_gelu_backward(grad_outputs[0], input); - tensor_list output = {result}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::fast_gelu_backward( - const at::Tensor& grad, - const at::Tensor& self) { - // construct the output tensor of the NPU - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - fast_gelu_backward_npu_nocheck(grad_input, grad, self); - - return grad_input; -} - -at::Tensor NPUNativeFunctions::fast_gelu(const at::Tensor& self) { - return NPUFastGeluFunction::apply(self); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/FillDiagonalKernelNpu.cpp b/torch_npu/csrc/aten/ops/FillDiagonalKernelNpu.cpp deleted file mode 100644 index cc667c074d..0000000000 --- a/torch_npu/csrc/aten/ops/FillDiagonalKernelNpu.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& fill_diagonal_out_npu( - at::Tensor& result, - const at::Tensor& self, - at::Scalar& value, - bool wrap) { - float fill_value = CalcuOpUtil::get_scalar_float_value(value); - OpCommand cmd; - cmd.Name("FillDiagonal") - .Input(self) - .Output(result) - .Attr("fill_value", fill_value) - .Attr("wrap", wrap) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::fill_diagonal_(at::Tensor& self, at::Scalar value, bool wrap) { - OpPreparation::CastBackToOriFormat(self); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = - fill_diagonal_out_npu(contiguousSelf, contiguousSelf, value, wrap); - NpuUtils::format_fresh_view(self, result); - } else { - fill_diagonal_out_npu(self, self, value, wrap); - } - - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/FillKernelNpu.cpp b/torch_npu/csrc/aten/ops/FillKernelNpu.cpp index b5478cd6cb..7486fa26e0 100644 --- a/torch_npu/csrc/aten/ops/FillKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/FillKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -50,7 +50,7 @@ at::Tensor& fills_out_npu(at::Tensor& result, at::Tensor& self, at::Scalar value return result; } -at::Tensor& NPUNativeFunctions::fill_(at::Tensor& self, const at::Tensor& other) { +at::Tensor& XLANativeFunctions::fill_(at::Tensor& self, const at::Tensor& other) { if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) { fills_out_npu(self, self, other.item()); } else { @@ -60,7 +60,7 @@ at::Tensor& NPUNativeFunctions::fill_(at::Tensor& self, const at::Tensor& other) return self; } -at::Tensor& NPUNativeFunctions::fill_(at::Tensor& self, at::Scalar value) { +at::Tensor& XLANativeFunctions::fill_(at::Tensor& self, const at::Scalar& value) { if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); at::Tensor result = fills_out_npu(contiguousSelf, contiguousSelf, value); diff --git a/torch_npu/csrc/aten/ops/FlipKernelNpu.cpp b/torch_npu/csrc/aten/ops/FlipKernelNpu.cpp deleted file mode 100644 index a5a2b7824e..0000000000 --- a/torch_npu/csrc/aten/ops/FlipKernelNpu.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::flip(const at::Tensor& self, at::IntArrayRef dims){ - at::Tensor result = OpPreparation::ApplyTensor(self); - at::SmallVector dimVec = array_to_small_vector(dims); - OpCommand cmd; - cmd.Name("ReverseV2") - .Input(self) - .Input(dimVec, at::kLong) - .Output(result) - .Run(); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/FloatStatusKernelNpu.cpp b/torch_npu/csrc/aten/ops/FloatStatusKernelNpu.cpp index 1697aebc88..00d61b793b 100644 --- a/torch_npu/csrc/aten/ops/FloatStatusKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/FloatStatusKernelNpu.cpp @@ -15,14 +15,14 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { const int FLOAT_STATUS_OP_DIMS_SIZE = 8; -at::Tensor NPUNativeFunctions::npu_alloc_float_status(const at::Tensor& self) { +at::Tensor XLANativeFunctions::npu_alloc_float_status(const at::Tensor& self) { auto options = at::TensorOptions(at_npu::key::NativeDeviceType).dtype(at::kFloat); at::Tensor result = at::empty({FLOAT_STATUS_OP_DIMS_SIZE}, options); OpCommand cmd; @@ -33,7 +33,7 @@ at::Tensor NPUNativeFunctions::npu_alloc_float_status(const at::Tensor& self) { return result; } -at::Tensor NPUNativeFunctions::npu_get_float_status(const at::Tensor& self) { +at::Tensor XLANativeFunctions::npu_get_float_status(const at::Tensor& self) { at::Tensor result = at::empty({FLOAT_STATUS_OP_DIMS_SIZE}, self.options()); OpCommand cmd; cmd.Name("NPUGetFloatStatus") @@ -44,7 +44,7 @@ at::Tensor NPUNativeFunctions::npu_get_float_status(const at::Tensor& self) { return result; } -at::Tensor NPUNativeFunctions::npu_clear_float_status(const at::Tensor& self) { +at::Tensor XLANativeFunctions::npu_clear_float_status(const at::Tensor& self) { at::Tensor result = at::empty({FLOAT_STATUS_OP_DIMS_SIZE}, self.options()); OpCommand cmd; cmd.Name("NPUClearFloatStatus") diff --git a/torch_npu/csrc/aten/ops/FloorDivideKernelNpu.cpp b/torch_npu/csrc/aten/ops/FloorDivideKernelNpu.cpp deleted file mode 100644 index 0c9c74fe95..0000000000 --- a/torch_npu/csrc/aten/ops/FloorDivideKernelNpu.cpp +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) 2022 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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& floor_divide_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, at::Scalar other) { - OpCommand cmd; - cmd.Name("FloorDiv") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& floor_divide_out_scalar_npu(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - auto outputSize = formatCastOfSelf.sizes(); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - result.scalar_type(), - outputSize); - floor_divide_out_npu_nocheck(result, formatCastOfSelf, other); - return result; -} - -at::Tensor& floor_divide_out_npu(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - auto outputSize = formatCastOfSelf.sizes(); - OpPreparation::CheckOut( - {self, other}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - result.scalar_type(), - outputSize); - // executing the NPU operator - if (other.dim() == 0) { - floor_divide_out_npu_nocheck(result, self, other.item()); - } else { - OpCommand cmd; - cmd.Name("FloorDiv") - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - return result; -} - -at::Tensor& check_self_dtype_npu(at::Tensor& self){ - if (self.dtype() == at::ScalarType::Bool || - self.dtype() == at::ScalarType::Int) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - return self; -} - -std::tuple check_dtype_npu(at::Tensor& self, at::Tensor& other){ - if (self.dtype() == at::ScalarType::Bool || - self.dtype() == at::ScalarType::Int && - other.scalar_type() == at::ScalarType::Double) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - if (other.scalar_type() == at::ScalarType::Double) { - other = other.to(at::ScalarType::Float); - } - if (other.scalar_type() == at::ScalarType::Long) { - other = other.to(at::ScalarType::Int); - } - return std::tie(self, other); -} - -at::Tensor& NPUNativeFunctions::floor_divide_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - at::Tensor selfCast = self; - at::Tensor otherCast = other; - check_dtype_npu(selfCast, otherCast); - floor_divide_out_npu(selfCast, otherCast, result); - return result; -} - -at::Tensor NPUNativeFunctions::floor_divide(const at::Tensor& self, const at::Tensor& other) { - at::Tensor selfCast = self; - at::Tensor otherCast = other; - check_dtype_npu(selfCast, otherCast); - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(selfCast); - at::Tensor outputTensor = isSelfWrapped ? otherCast : selfCast; - auto outputSize = broadcast_ops_npu_output_size(selfCast, otherCast); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - outputTensor.options(), - CalcuOpUtil::get_tensor_npu_format(selfCast)); - floor_divide_out_npu(selfCast, otherCast, result); - return result; -} - -at::Tensor NPUNativeFunctions::floor_divide(const at::Tensor& self, at::Scalar other) { - at::Tensor selfCast = self; - check_self_dtype_npu(selfCast); - at::Tensor result = OpPreparation::ApplyTensor(selfCast); - floor_divide_out_scalar_npu(selfCast, other, result); - return result; -} - -at::Tensor& NPUNativeFunctions::floor_divide_(at::Tensor& self, const at::Tensor& other) { - at::Tensor otherCast = other; - check_dtype_npu(self, otherCast); - - at::SmallVector inputs = {self, otherCast}; - at::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = floor_divide_out_npu(contiguousSelf, otherCast, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - floor_divide_out_npu(self, otherCast, self); - } - return self; -} - -at::Tensor& NPUNativeFunctions::floor_divide_(at::Tensor& self, at::Scalar other) { - check_self_dtype_npu(self); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - floor_divide_out_scalar_npu(contiguousSelf, other, contiguousSelf); - NpuUtils::format_fresh_view(self, contiguousSelf); - } else { - floor_divide_out_scalar_npu(self, other, self); - } - return self; -} -} // namespace native -} // at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/FloorKernelNpu.cpp b/torch_npu/csrc/aten/ops/FloorKernelNpu.cpp deleted file mode 100644 index ffecfd9a82..0000000000 --- a/torch_npu/csrc/aten/ops/FloorKernelNpu.cpp +++ /dev/null @@ -1,57 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& floor_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Floor") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::floor_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){floor_out_npu_nocheck(self, result);}) - .Call(result); -} - -at::Tensor& NPUNativeFunctions::floor_(at::Tensor& self) { - NPUNativeFunctions::floor_out(self, self); - - return self; -} - -at::Tensor NPUNativeFunctions::floor(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - floor_out_npu_nocheck(self, result); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/FmodKernelNpu.cpp b/torch_npu/csrc/aten/ops/FmodKernelNpu.cpp deleted file mode 100644 index 5574288508..0000000000 --- a/torch_npu/csrc/aten/ops/FmodKernelNpu.cpp +++ /dev/null @@ -1,104 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& fmod_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, const at::Tensor& other) { - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - OpCommand cmd; - cmd.Name("FloorMod") - .Expect(unified_result) - .Input(self) - .Input(other) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& fmod_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, at::Scalar other) { - OpCommand cmd; - cmd.Name("FloorMod") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::fmod_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self, other}, - result, - self, - outputSize); - - fmod_out_npu_nocheck(result, self, other); - return result; -} - -at::Tensor& NPUNativeFunctions::fmod_out(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - OpPreparation::CheckOut({self}, result, self); - fmod_out_npu_nocheck(result, self, other); - return result; -} - -at::Tensor& NPUNativeFunctions::fmod_(at::Tensor& self, at::Scalar other) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = fmod_out_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - fmod_out_npu_nocheck(self, self, other); - } - - return self; -} - -at::Tensor& NPUNativeFunctions::fmod_(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = fmod_out_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - fmod_out_npu_nocheck(self, self, other); - } - - return self; -} - -at::Tensor NPUNativeFunctions::fmod(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - fmod_out_npu_nocheck(result, self, other); - return result; -} - -at::Tensor NPUNativeFunctions::fmod(const at::Tensor& self, const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - fmod_out_npu_nocheck(result, self, other); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/FracKernelNpu.cpp b/torch_npu/csrc/aten/ops/FracKernelNpu.cpp deleted file mode 100644 index 823721065f..0000000000 --- a/torch_npu/csrc/aten/ops/FracKernelNpu.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::frac_out(const at::Tensor& self, at::Tensor& out) { - OpPreparation::CheckOut( - {self}, - out, - self); - at::Tensor cast_return_Tensor = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Int); - at::sub_out(out, self, cast_return_Tensor); - return out; -} - -at::Tensor NPUNativeFunctions::frac(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - at::Tensor cast_return_Tensor = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Int); - NPUNativeFunctions::frac_out(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::frac_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::frac_out(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::frac_out(self, self); - } - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/FullKernelNpu.cpp b/torch_npu/csrc/aten/ops/FullKernelNpu.cpp deleted file mode 100644 index f2fe8936c3..0000000000 --- a/torch_npu/csrc/aten/ops/FullKernelNpu.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::full_out(at::IntArrayRef size, at::Scalar fill_value, at::Tensor& out) { - OpPreparation::CheckOut( - {}, - out, - out, - size); - fill_(out, fill_value); - return out; -} - -at::Tensor NPUNativeFunctions::full( - at::IntArrayRef size, - at::Scalar fill_value, - c10::optional names, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - c10::TensorOptions option = c10::TensorOptions().dtype(dtype_opt) - .device(device_opt) - .layout(layout_opt) - .pinned_memory(pin_memory_opt); - at::Tensor result = OpPreparation::ApplyTensorWithSizes(size, option); - return result.fill_(fill_value); -} - -} -} \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GatherKernelNpu.cpp b/torch_npu/csrc/aten/ops/GatherKernelNpu.cpp deleted file mode 100644 index 92d3c95012..0000000000 --- a/torch_npu/csrc/aten/ops/GatherKernelNpu.cpp +++ /dev/null @@ -1,102 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& gather_out_npu_nocheck( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - bool sparse_grad, - at::Tensor& result) { - at::Tensor dtypeCastOfSelf = self; - at::Tensor dtypeCastOfResult = result; - if (self.scalar_type() == at::ScalarType::Half) { - dtypeCastOfSelf = NPUNativeFunctions::npu_dtype_cast(dtypeCastOfSelf, at::ScalarType::Float); - dtypeCastOfResult = NPUNativeFunctions::npu_dtype_cast(dtypeCastOfResult, at::ScalarType::Float); - } - - if (self.scalar_type() == at::kLong) { - TORCH_WARN_ONCE("The oprator of gather is executed, Currently High Accuracy but Low Performance OP" - "with 64-bit has been used,Please Do Some Cast at Python Functions with 32-bit for Better Performance!"); - } - - OpCommand cmd; - cmd.Name("GatherElements") - .Input(dtypeCastOfSelf) - .Input(index) - .Attr("dim", dim) - .Output(dtypeCastOfResult) - .Run(); - result.copy_(dtypeCastOfResult); - return result; -} - -at::Tensor& NPUNativeFunctions::gather_out( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - bool sparse_grad, - at::Tensor& result) { - auto outputSize = index.sizes(); - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - return gather_out_npu_nocheck(self, dim, index, sparse_grad, result); -} - -at::Tensor& NPUNativeFunctions::gather_out( - const at::Tensor& self, - at::Dimname dim, - const at::Tensor& index, - bool sparse_grad, - at::Tensor& result) { - auto outputSize = index.sizes(); - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - return gather_out_npu_nocheck(self, dimname_to_position(self, dim), index, sparse_grad, result); -} - -at::Tensor NPUNativeFunctions::gather( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - bool sparse_grad) { - auto outputSize = input_same_output_size(index); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - gather_out_npu_nocheck(self, dim, index, sparse_grad, result); - return result; -} - -at::Tensor NPUNativeFunctions::gather( - const at::Tensor& self, - at::Dimname dim, - const at::Tensor& index, - bool sparse_grad) { - return gather(self, dimname_to_position(self, dim), index, sparse_grad); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GeKernelNpu.cpp b/torch_npu/csrc/aten/ops/GeKernelNpu.cpp index 6a71323f79..afef990477 100644 --- a/torch_npu/csrc/aten/ops/GeKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/GeKernelNpu.cpp @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -39,7 +39,7 @@ at::Tensor& ge_out_npu_nocheck(const at::Tensor& self, const at::Tensor& other, return result; } -at::Tensor& NPUNativeFunctions::ge_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { +at::Tensor& XLANativeFunctions::ge_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); auto outputSize = broadcast_ops_npu_output_size(formatCastOfSelf, formatCastOfOther); @@ -55,7 +55,7 @@ at::Tensor& NPUNativeFunctions::ge_out(const at::Tensor& self, const at::Tensor& return result; } -at::Tensor& ge_out_npu_nocheck(const at::Tensor& self, at::Scalar other, at::Tensor& result) { +at::Tensor& ge_out_npu_nocheck(const at::Tensor& self, const at::Scalar& other, at::Tensor& result) { at::Tensor selfCast = self; if (self.dtype() == at::ScalarType::Int || self.dtype() == at::ScalarType::Bool) { selfCast = self.to(at::ScalarType::Float); @@ -70,7 +70,7 @@ at::Tensor& ge_out_npu_nocheck(const at::Tensor& self, at::Scalar other, at::Ten return result; } -at::Tensor& NPUNativeFunctions::ge_out(const at::Tensor& self, at::Scalar other, at::Tensor& result) { +at::Tensor& XLANativeFunctions::ge_out(const at::Tensor& self, const at::Scalar& other, at::Tensor& result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); auto outputSize = formatCastOfSelf.sizes(); OpPreparation::CheckOut( @@ -84,7 +84,7 @@ at::Tensor& NPUNativeFunctions::ge_out(const at::Tensor& self, at::Scalar other, return result; } -at::Tensor NPUNativeFunctions::ge(const at::Tensor& self, const at::Tensor& other) { +at::Tensor XLANativeFunctions::ge(const at::Tensor& self, const at::Tensor& other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); auto outputSize = broadcast_ops_npu_output_size(formatCastOfSelf, formatCastOfOther); @@ -96,7 +96,7 @@ at::Tensor NPUNativeFunctions::ge(const at::Tensor& self, const at::Tensor& othe return result; } -at::Tensor NPUNativeFunctions::ge(const at::Tensor& self, at::Scalar other) { +at::Tensor XLANativeFunctions::ge(const at::Tensor& self, const at::Scalar& other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor result = OpPreparation::ApplyTensorWithFormat( formatCastOfSelf.sizes(), @@ -106,7 +106,7 @@ at::Tensor NPUNativeFunctions::ge(const at::Tensor& self, at::Scalar other) { return result; } -at::Tensor& NPUNativeFunctions::ge_(at::Tensor& self, const at::Tensor& other) { +at::Tensor& XLANativeFunctions::ge_(at::Tensor& self, const at::Tensor& other) { OpPreparation::CastBackToOriFormat(self); at::Tensor ori_other = OpPreparation::CastBackToOriFormat(other); OpPreparation::CheckMemory({self, ori_other}, {self}); @@ -125,7 +125,7 @@ at::Tensor& NPUNativeFunctions::ge_(at::Tensor& self, const at::Tensor& other) { return self; } -at::Tensor& NPUNativeFunctions::ge_(at::Tensor& self, at::Scalar other) { +at::Tensor& XLANativeFunctions::ge_(at::Tensor& self, const at::Scalar& other) { OpPreparation::CastBackToOriFormat(self); OpPreparation::CheckMemory({self}, {self}); at::Tensor result = OpPreparation::ApplyTensor( diff --git a/torch_npu/csrc/aten/ops/GeluBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/GeluBackwardKernelNpu.cpp deleted file mode 100644 index 0e6c809960..0000000000 --- a/torch_npu/csrc/aten/ops/GeluBackwardKernelNpu.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& gelu_backward_out_npu_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad, - const at::Tensor& self) { - at::Tensor unused = grad; - OpCommand cmd; - cmd.Name("GeluGrad") - .Input(grad) - .Input(self) - .Input(unused) - .Output(grad_input) - .Run(); - - return grad_input; -} - -at::Tensor NPUNativeFunctions::gelu_backward( - const at::Tensor& grad, - const at::Tensor& self) { - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - gelu_backward_out_npu_nocheck(grad_input, grad, self); - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GeluKernelNpu.cpp b/torch_npu/csrc/aten/ops/GeluKernelNpu.cpp deleted file mode 100644 index 51180b051a..0000000000 --- a/torch_npu/csrc/aten/ops/GeluKernelNpu.cpp +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::gelu(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - OpCommand cmd; - cmd.Name("Gelu") - .Input(self) - .Output(result) - .Run(); - - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/GerKernelNpu.cpp b/torch_npu/csrc/aten/ops/GerKernelNpu.cpp deleted file mode 100644 index 6256544e31..0000000000 --- a/torch_npu/csrc/aten/ops/GerKernelNpu.cpp +++ /dev/null @@ -1,84 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector ger_npu_output_size( - const at::Tensor& self, - const at::Tensor& vec2) { - int64_t outputsize_0 = self.size(0); - int64_t outputsize_1 = vec2.size(0); - c10::SmallVector outputsize = {outputsize_0, outputsize_1}; - - return outputsize; -} - -at::Tensor& ger_out_npu_nocheck(const at::Tensor& self , const at::Tensor& vec2, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Ger") - .Input(self) - .Input(vec2) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::ger_out(const at::Tensor& self , const at::Tensor& vec2, at::Tensor& result) { - // check shape - TORCH_CHECK( - self.dim() == 1, "Input1 must have only1 dims."); - TORCH_CHECK( - vec2.dim() == 1, "Input2 must have only1 dims."); - - // calculate the output size - auto outputSize = ger_npu_output_size(self, vec2); - - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - - OpPipeWithDefinedOut pipe; - return pipe.Func([&self, &vec2](at::Tensor& result){ger_out_npu_nocheck(self, vec2, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::ger(const at::Tensor& self, const at::Tensor& vec2) { - // check shape - TORCH_CHECK( - self.dim() == 1, "Input1 must have only1 dims."); - TORCH_CHECK( - vec2.dim() == 1, "Input2 must have only1 dims."); - - // calculate the output size - auto outputSize = ger_npu_output_size(self, vec2); - - // construct the output Tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - ger_out_npu_nocheck(self, vec2, result); - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GiouKernelNpu.cpp b/torch_npu/csrc/aten/ops/GiouKernelNpu.cpp deleted file mode 100644 index 06a47f35e9..0000000000 --- a/torch_npu/csrc/aten/ops/GiouKernelNpu.cpp +++ /dev/null @@ -1,206 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -c10::SmallVector giou_output_size( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool is_cross){ - c10::SmallVector output_size; - if(is_cross){ - output_size = {gtboxes.size(0), self.size(0)}; - } else { - output_size = {1, self.size(0)}; - } - return output_size; -} - -at::Tensor& giou_inner_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode){ - auto output_size = giou_output_size(self, gtboxes, is_cross); - string mode_str = mode == 1 ? "iof" : "iou"; - - OpCommand cmd; - cmd.Name("GIoU") - .Input(self) - .Input(gtboxes) - .Output(result) - .Attr("trans", trans) - .Attr("is_cross", is_cross) - .Attr("mode", mode_str) - .Run(); - return result; -} - -at::Tensor giou_npu( - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode) { - TORCH_CHECK(trans && !is_cross && mode == 0, - "giou backward only support trans==True, ", - "is_cross==False, ", - "mode==0('iou') current version ", - "if you need to back propagation, ", - "please ensure your parameter is correct!"); - // Op need form of [n, 4], but pass should be [4, n]; - // Note: temp avoid! it'll be removed while op deal with fp16 issue! - at::Tensor selfCp = self.permute({1, 0}); - if (selfCp.scalar_type() == at::kHalf) { - selfCp = NPUNativeFunctions::npu_dtype_cast(selfCp, at::kFloat); - } - at::Tensor gtboxesCp = gtboxes.permute({1, 0}); - if (gtboxesCp.scalar_type() == at::kHalf) { - gtboxesCp = NPUNativeFunctions::npu_dtype_cast(gtboxesCp, at::kFloat); - } - auto output_size = giou_output_size(selfCp, gtboxesCp, is_cross); - at::Tensor result = OpPreparation::ApplyTensor(selfCp, output_size); - - giou_inner_out_npu(result, selfCp, gtboxesCp, trans, is_cross, mode); - result = result.permute({1, 0}); - if (self.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::kHalf); - } - return result; -} - -std::tuple giou_backward_inner_out_npu( - at::Tensor& dbboxes, - at::Tensor& dgtboxes, - const at::Tensor& grad, - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode){ - string mode_str = mode == 1 ? "iof" : "iou"; - - OpCommand cmd; - cmd.Name("GIoUGrad") - .Input(grad) - .Input(bboxes) - .Input(gtboxes) - .Output(dbboxes) - .Output(dgtboxes) - .Attr("trans", trans) - .Attr("is_cross", is_cross) - .Attr("mode", mode_str) - .Run(); - return std::tie(dbboxes, dgtboxes); -} - -std::tuple NPUNativeFunctions::npu_giou_backward( - const at::Tensor& grad, - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode){ - TORCH_CHECK(trans && !is_cross && mode == 0, - "giou backward only support trans==True, ", - "is_cross==False, ", - "mode==0('iou') current version ", - "if you need to back propagation, ", - "please ensure your parameter is correct!"); - // Op need form of [n] grad - // Note: temp avoid! it'll be remove while op deal with fp16 issue! - at::Tensor gradCp = at::squeeze(grad, 0); - if (gradCp.scalar_type() == at::kHalf) { - gradCp = NPUNativeFunctions::npu_dtype_cast(gradCp, at::kFloat); - } - at::Tensor bboxesCp = bboxes; - if (bboxesCp.scalar_type() == at::kHalf) { - bboxesCp = NPUNativeFunctions::npu_dtype_cast(bboxesCp, at::kFloat); - } - at::Tensor gtboxesCp = gtboxes; - if (gtboxesCp.scalar_type() == at::kHalf) { - gtboxesCp = NPUNativeFunctions::npu_dtype_cast(gtboxesCp, at::kFloat); - } - at::Tensor dbboxes = OpPreparation::ApplyTensor(bboxesCp); - at::Tensor dgtboxes = OpPreparation::ApplyTensor(gtboxesCp); - - giou_backward_inner_out_npu(dbboxes, dgtboxes, gradCp, bboxesCp, gtboxesCp, trans, is_cross, mode); - if (bboxes.scalar_type() == at::kHalf || gtboxes.scalar_type() == at::kHalf) { - dbboxes = NPUNativeFunctions::npu_dtype_cast(dbboxes, at::kHalf); - dgtboxes = NPUNativeFunctions::npu_dtype_cast(dgtboxes, at::kHalf); - } - return std::tie(dbboxes, dgtboxes); -} - -class NPUGiouFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode) { - ctx->saved_data["trans"] = trans; - ctx->saved_data["is_cross"] = is_cross; - ctx->saved_data["mode"] = mode; - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({self, gtboxes}); - return giou_npu(self, gtboxes, trans, is_cross, mode); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto trans = ctx->saved_data["trans"].toBool(); - auto is_cross = ctx->saved_data["is_cross"].toBool(); - auto mode = ctx->saved_data["mode"].toInt(); - auto saved = ctx->get_saved_variables(); - auto bboxes = saved[0]; - auto gtboxes = saved[1]; - - tuple result = NPUNativeFunctions::npu_giou_backward(grad_outputs[0], - bboxes, gtboxes, trans, is_cross, mode); - - tensor_list output = {std::get<0>(result), - std::get<1>(result), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_giou(const at::Tensor& self, - const at::Tensor& gtboxes, - bool trans, - bool is_cross, - int64_t mode) { - return NPUGiouFunction::apply(self, gtboxes, trans, is_cross, mode); -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GluGradKernelNpu.cpp b/torch_npu/csrc/aten/ops/GluGradKernelNpu.cpp deleted file mode 100644 index 9ec04528db..0000000000 --- a/torch_npu/csrc/aten/ops/GluGradKernelNpu.cpp +++ /dev/null @@ -1,61 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::glu_backward_out(const at::Tensor &grad_output, const at::Tensor &self, int64_t dim, at::Tensor &result) { - auto outputSize = input_same_output_size(self); - OpPreparation::CheckOut( - {grad_output, self}, - result, - grad_output, - outputSize); - - TORCH_CHECK(self.dim() > 0, "glu does not support 0-dimensional Tensors"); - auto wrap_dim = at::maybe_wrap_dim(dim, self.dim()); - const int64_t nIn = self.size(wrap_dim); - TORCH_CHECK(nIn % 2 == 0, "Halving dimension must be even, but dimension ", - wrap_dim, " is size ", nIn); - - auto chunkedInput = self.chunk(2, dim); - at::Tensor firstHalf = chunkedInput[0]; - at::Tensor secondHalf = chunkedInput[1]; - - secondHalf = secondHalf.sigmoid(); - - at::Tensor gradFirst = secondHalf.mul(grad_output); - - at::Tensor gradSecond = firstHalf.mul(secondHalf).mul_(1-secondHalf).mul_(grad_output); - - result = at::cat({gradFirst, gradSecond}, dim); - return result; -} - -at::Tensor NPUNativeFunctions::glu_backward(const at::Tensor &grad_output, const at::Tensor &self, int64_t dim) { - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - NPUNativeFunctions::glu_backward_out(grad_output, self, dim, result); - return result; - -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GluKernelNpu.cpp b/torch_npu/csrc/aten/ops/GluKernelNpu.cpp deleted file mode 100644 index c444e51d7b..0000000000 --- a/torch_npu/csrc/aten/ops/GluKernelNpu.cpp +++ /dev/null @@ -1,52 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::glu_out(const at::Tensor& self, int64_t dim, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - TORCH_CHECK(self.dim() > 0, "glu does not support 0-dimensional at::Tensors"); - auto wrap_dim = at::maybe_wrap_dim(dim, self.dim()); - const int64_t nIn = self.size(wrap_dim); - TORCH_CHECK(nIn % 2 == 0, "Halving dimension must be even, but dimension ", - wrap_dim, " is size ", nIn); - - auto chunkedInput = self.chunk(2, dim); - at::Tensor firstHalf = chunkedInput[0]; - at::Tensor secondHalf = chunkedInput[1]; - result = firstHalf.mul(secondHalf.sigmoid()); - return result; -} - -at::Tensor NPUNativeFunctions::glu(const at::Tensor& self, int64_t dim) { - auto outputSize = glu_npu_output_size(self, dim); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - NPUNativeFunctions::glu_out(self, dim, result); - return result; - -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GridAssignPositiveKernelNpu.cpp b/torch_npu/csrc/aten/ops/GridAssignPositiveKernelNpu.cpp deleted file mode 100644 index 46ceebef0d..0000000000 --- a/torch_npu/csrc/aten/ops/GridAssignPositiveKernelNpu.cpp +++ /dev/null @@ -1,77 +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. -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using namespace torch::autograd; - -static inline void grid_assign_positive_check( - const at::Tensor& argmax_overlaps, - const at::Tensor& gt_argmax_overlaps){ - TORCH_CHECK( - at::isIntegralType(argmax_overlaps.scalar_type(), true) && argmax_overlaps.scalar_type() != at::ScalarType::Long, - "int32 argmax_overlaps tensor expected but got a tensor with dtype: ", - argmax_overlaps.scalar_type()); - TORCH_CHECK( - at::isIntegralType(gt_argmax_overlaps.scalar_type(), true) && gt_argmax_overlaps.scalar_type() != at::ScalarType::Long, - "int32 gt_argmax_overlaps tensor expected but got a tensor with dtype: ", - gt_argmax_overlaps.scalar_type()); -} - -at::Tensor NPUNativeFunctions::npu_grid_assign_positive( - const at::Tensor& assigned_gt_inds, - const at::Tensor& overlaps, - const at::Tensor& box_responsible_flags, - const at::Tensor& max_overlaps, - const at::Tensor& argmax_overlaps, - const at::Tensor& gt_max_overlaps, - const at::Tensor& gt_argmax_overlaps, - int64_t num_gts, - double pos_iou_thr, - double min_pos_iou, - bool gt_max_assign_all){ - grid_assign_positive_check(argmax_overlaps, gt_argmax_overlaps); - at::Tensor result = OpPreparation::ApplyTensor(assigned_gt_inds); - auto option = assigned_gt_inds.options().dtype(at::kInt); - at::Scalar s(num_gts); - at::Tensor numOfGts = at::empty({}, option).fill_(s); - - at::Tensor argmaxOverLaps = NPUNativeFunctions::npu_dtype_cast(argmax_overlaps, at::ScalarType::Int); - at::Tensor gtArgmaxOverLaps = NPUNativeFunctions::npu_dtype_cast(gt_argmax_overlaps, at::ScalarType::Int); - - OpCommand cmd; - cmd.Name("GridAssignPositive") - .Input(assigned_gt_inds) - .Input(overlaps) - .Input(box_responsible_flags) - .Input(max_overlaps) - .Input(argmaxOverLaps) - .Input(gt_max_overlaps) - .Input(gtArgmaxOverLaps) - .Input(numOfGts) - .Output(result) - .Attr("pos_iou_thr", (float) pos_iou_thr) - .Attr("min_pos_iou", (float) min_pos_iou) - .Attr("gt_max_assign_all", gt_max_assign_all) - .Run(); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/GridSampler2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/GridSampler2dBackwardKernelNpu.cpp deleted file mode 100644 index c469f8c814..0000000000 --- a/torch_npu/csrc/aten/ops/GridSampler2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,78 +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. - -#include "torch_npu/csrc/core/npu/register/OptionsManager.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::grid_sampler_2d_backward( - const at::Tensor& grad, - const at::Tensor& input, - const at::Tensor& grid, - int64_t interpolation_mode, - int64_t padding_mode, - bool align_corners) { - TORCH_CHECK( - (0 <= interpolation_mode && interpolation_mode <= 2), - "interpolation_mode must be in range [0~2].") - TORCH_CHECK( - (0 <= padding_mode && padding_mode <= 2), - "padding_mode must be in range [0~2].") - - at::Tensor formatCastOfGrad = grad; - at::Tensor formatCastOfInput = input; - at::Tensor formatCastOfGrid = grid; - if (formatCastOfGrad.scalar_type() == at::ScalarType::Half) { - formatCastOfGrad = NPUNativeFunctions::npu_dtype_cast(formatCastOfGrad, at::ScalarType::Float); - } - if (formatCastOfInput.scalar_type() == at::ScalarType::Half) { - formatCastOfInput = NPUNativeFunctions::npu_dtype_cast(formatCastOfInput, at::ScalarType::Float); - } - if (formatCastOfGrid.scalar_type() == at::ScalarType::Half) { - formatCastOfGrid = NPUNativeFunctions::npu_dtype_cast(formatCastOfGrid, at::ScalarType::Float); - } - - at::Tensor dx = OpPreparation::ApplyTensor(formatCastOfInput); - at::Tensor dgrid = OpPreparation::ApplyTensor(formatCastOfGrid); - - c10::SmallVectorinterMode = {"bilinear", "nearest", "bicubic"}; - c10::SmallVectorpaddingMode = {"zeros", "border", "reflection"}; - - OpCommand cmd; - cmd.Name("GridSampler2DGrad") - .Input(formatCastOfGrad) - .Input(formatCastOfInput) - .Input(formatCastOfGrid) - .Output(dx) - .Output(dgrid) - .Attr("interpolation_mode", interMode[interpolation_mode]) - .Attr("padding_mode", paddingMode[padding_mode]) - .Attr("align_corners", align_corners) - .Run(); - - at::ScalarType inputScalarType(input.scalar_type()); - if (dx.scalar_type() != inputScalarType) { - dx = NPUNativeFunctions::npu_dtype_cast(dx, inputScalarType); - dgrid = NPUNativeFunctions::npu_dtype_cast(dgrid, inputScalarType); - } - - return std::tuple(dx, dgrid); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/GridSampler2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/GridSampler2dKernelNpu.cpp deleted file mode 100644 index 38e32044c8..0000000000 --- a/torch_npu/csrc/aten/ops/GridSampler2dKernelNpu.cpp +++ /dev/null @@ -1,69 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::grid_sampler_2d( - const at::Tensor& self, - const at::Tensor& grid, - int64_t interpolation_mode, - int64_t padding_mode, - bool align_corners) { - TORCH_CHECK( - (0 <= interpolation_mode && interpolation_mode <= 2), - "interpolation_mode must be in range [0~2].") - TORCH_CHECK( - (0 <= padding_mode && padding_mode <= 2), - "padding_mode must be in range [0~2].") - - at::Tensor dtypeCastOfSelf = self; - at::Tensor dtypeCastOfGrid = grid; - if (dtypeCastOfSelf.scalar_type() == c10::ScalarType::Half) { - dtypeCastOfSelf = NPUNativeFunctions::npu_dtype_cast(dtypeCastOfSelf, c10::ScalarType::Float); - } - if (dtypeCastOfGrid.scalar_type() == c10::ScalarType::Half) { - dtypeCastOfGrid = NPUNativeFunctions::npu_dtype_cast(dtypeCastOfGrid, c10::ScalarType::Float); - } - - c10::SmallVector outputSize = {dtypeCastOfSelf.size(0), - dtypeCastOfSelf.size(1), - dtypeCastOfGrid.size(1), - dtypeCastOfGrid.size(2)}; - - at::Tensor result = OpPreparation::ApplyTensorWithFormat(dtypeCastOfSelf, outputSize, ACL_FORMAT_ND); - - OpCommand cmd; - cmd.Name("GridSampler2D") - .Input(dtypeCastOfSelf) - .Input(dtypeCastOfGrid) - .Output(result) - .Attr("interpolation_mode", interpolation_mode) - .Attr("padding_mode", padding_mode) - .Attr("align_corners", align_corners) - .Run(); - - c10::ScalarType selfScalarType(self.scalar_type()); - if (result.scalar_type() != selfScalarType) { - result = NPUNativeFunctions::npu_dtype_cast(result,selfScalarType); - } - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/GridSampler3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/GridSampler3dBackwardKernelNpu.cpp deleted file mode 100644 index f94572ae2b..0000000000 --- a/torch_npu/csrc/aten/ops/GridSampler3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,91 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple grid_sampler_3d_backward_npu_nocheck( - const at::Tensor& grad, - const at::Tensor& input, - const at::Tensor& grid, - std::string interMode, - std::string paddingMode, - bool align_corners, - at::Tensor& dx, - at::Tensor& dgrid) { - OpCommand cmd; - cmd.Name("GridSampler3DGrad") - .Input(grad) - .Input(input) - .Input(grid) - .Output(dx) - .Output(dgrid) - .Attr("interpolation_mode", interMode) - .Attr("padding_mode", paddingMode) - .Attr("align_corners", align_corners) - .Run(); - return std::tie(dx, dgrid); -} - -std::tuple NPUNativeFunctions::grid_sampler_3d_backward( - const at::Tensor& grad, - const at::Tensor& input, - const at::Tensor& grid, - int64_t interpolation_mode, - int64_t padding_mode, - bool align_corners) { - TORCH_CHECK( - (0 <= interpolation_mode && interpolation_mode <= 2), - "interpolation_mode must be in range [0~2].") - TORCH_CHECK( - (0 <= padding_mode && padding_mode <= 2), - "padding_mode must be in range [0~2].") - at::Tensor formatCastOfGrad = grad; - at::Tensor formatCastOfInput = input; - at::Tensor formatCastOfGrid = grid; - if (formatCastOfGrad.scalar_type() == at::ScalarType::Half) { - formatCastOfGrad = NPUNativeFunctions::npu_dtype_cast(formatCastOfGrad, at::ScalarType::Float); - } - if (formatCastOfInput.scalar_type() == at::ScalarType::Half) { - formatCastOfInput = NPUNativeFunctions::npu_dtype_cast(formatCastOfInput, at::ScalarType::Float); - } - if (formatCastOfGrid.scalar_type() == at::ScalarType::Half) { - formatCastOfGrid = NPUNativeFunctions::npu_dtype_cast(formatCastOfGrid, at::ScalarType::Float); - } - - // construct the output tensor of the NPU - at::Tensor dx = OpPreparation::ApplyTensor(formatCastOfInput); - at::Tensor dgrid = OpPreparation::ApplyTensor(formatCastOfGrid); - std::string interMode[] = {"bilinear", "nearest", "bicubic"}; - std::string paddingMode[] = {"zeros", "border", "reflection"}; - - // calculate the output result of the NPU - grid_sampler_3d_backward_npu_nocheck( - formatCastOfGrad, - formatCastOfInput, - formatCastOfGrid, - interMode[interpolation_mode], - paddingMode[padding_mode], - align_corners, - dx, - dgrid); - return std::tie(dx, dgrid); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GridSampler3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/GridSampler3dKernelNpu.cpp deleted file mode 100644 index baf0771573..0000000000 --- a/torch_npu/csrc/aten/ops/GridSampler3dKernelNpu.cpp +++ /dev/null @@ -1,92 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& grid_sampler_3d_npu_nocheck( - const at::Tensor& self, - const at::Tensor& grid, - std::string interMode, - std::string paddingMode, - bool align_corners, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("GridSampler3D") - .Input(self) - .Input(grid) - .Output(result) - .Attr("interpolation_mode", interMode) - .Attr("padding_mode", paddingMode) - .Attr("align_corners", align_corners) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::grid_sampler_3d( - const at::Tensor& self, - const at::Tensor& grid, - int64_t interpolation_mode, - int64_t padding_mode, - bool align_corners) { - TORCH_CHECK( - (0 <= interpolation_mode && interpolation_mode <= 2), - "interpolation_mode must be in range [0~2].") - TORCH_CHECK( - (0 <= padding_mode && padding_mode <= 2), - "padding_mode must be in range [0~2].") - at::Tensor formatCastOfSelf = self; - at::Tensor formatCastOfGrid = grid; - if (formatCastOfSelf.scalar_type() == at::ScalarType::Half) { - formatCastOfSelf = NPUNativeFunctions::npu_dtype_cast(formatCastOfSelf, at::ScalarType::Float); - } - if (formatCastOfGrid.scalar_type() == at::ScalarType::Half) { - formatCastOfGrid = NPUNativeFunctions::npu_dtype_cast(formatCastOfGrid, at::ScalarType::Float); - } - - // calculate the output size - c10::SmallVector outputSize = {formatCastOfSelf.size(0), - formatCastOfSelf.size(1), - formatCastOfGrid.size(1), - formatCastOfGrid.size(2), - formatCastOfGrid.size(3)}; - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, formatCastOfSelf.options(), ACL_FORMAT_ND); - std::string interMode[] = {"bilinear", "nearest", "bicubic"}; - std::string paddingMode[] = {"zeros", "border", "reflection"}; - - // calculate the output result of the NPU - grid_sampler_3d_npu_nocheck( - formatCastOfSelf, - formatCastOfGrid, - interMode[interpolation_mode], - paddingMode[padding_mode], - align_corners, - result); - - at::ScalarType selfScalarType(self.scalar_type()); - if (result.scalar_type() != selfScalarType) { - result = NPUNativeFunctions::npu_dtype_cast(result, selfScalarType); - } - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GruKernelNpu.cpp b/torch_npu/csrc/aten/ops/GruKernelNpu.cpp deleted file mode 100644 index dbabbe9548..0000000000 --- a/torch_npu/csrc/aten/ops/GruKernelNpu.cpp +++ /dev/null @@ -1,570 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -struct CellParams { - CellParams(const at::Tensor& _w_ih, const at::Tensor& _w_hh) - : w_ih(_w_ih), w_hh(_w_hh), b_ih({}), b_hh({}) {}; - CellParams(const at::Tensor& _w_ih, const at::Tensor& _w_hh, const at::Tensor& _b_ih, const at::Tensor& _b_hh) - : w_ih(_w_ih), w_hh(_w_hh), b_ih(_b_ih), b_hh(_b_hh) {}; - const at::Tensor& w_ih; - const at::Tensor& w_hh; - const at::Tensor& b_ih; /* optional */ - const at::Tensor& b_hh; /* optional */ -}; - -using BidirectCellParams = std::pair; -using pair_of = std::pair; -static std::vector make_pair_vec(const std::vector& vals) { - TORCH_CHECK(vals.size() % 2 == 0, "Odd number of params or hiddens given to a bidirectional RNN"); - std::vector result; - result.reserve(vals.size() / 2); - for (size_t i = 0; i < vals.size(); i += 2) { - result.emplace_back(vals[i], vals[i + 1]); - } - return result; -} - -std::vector gru_npu( - const at::Tensor& input, - const at::Tensor& hx, - const at::Tensor& weight_input, - const at::Tensor& weight_hidden, - const at::Tensor& bias_input, - const at::Tensor& bias_hidden, - const at::Tensor& seq_length, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - int64_t numStep = input.size(0); - int64_t batchSize = input.size(1); - int64_t hiddenSize = bias_input.size(0) / 3; - c10::SmallVector outputSize = {numStep, batchSize, hiddenSize}; - int64_t npu_format = ACL_FORMAT_FRACTAL_NZ; - - at::Tensor output_y = OpPreparation::ApplyTensorWithFormat( - outputSize, - bias_input.options(), - npu_format); - at::Tensor output_h = OpPreparation::ApplyTensorWithFormat( - outputSize, - bias_input.options(), - ACL_FORMAT_ND); - at::Tensor output_updata = OpPreparation::ApplyTensorWithFormat( - outputSize, - bias_input.options(), - npu_format); - at::Tensor output_reset = OpPreparation::ApplyTensorWithFormat( - outputSize, - bias_input.options(), - npu_format); - at::Tensor output_new = OpPreparation::ApplyTensorWithFormat( - outputSize, - bias_input.options(), - npu_format); - at::Tensor hidden_new = OpPreparation::ApplyTensorWithFormat( - outputSize, - bias_input.options(), - npu_format); - - OpCommand cmd; - cmd.Name("DynamicGRUV2") - .Input(input) - .Input(weight_input) - .Input(weight_hidden) - .Input(bias_input) - .Input(bias_hidden) - .Input() - .Input(hx) - .Output(output_y) - .Output(output_h) - .Output(output_updata) - .Output(output_reset) - .Output(output_new) - .Output(hidden_new) - .Attr("direction", (string)"UNIDIRECTIONAL") - .Attr("cell_depth", (int64_t)1) - .Attr("keep_prob", (float)1.0) - .Attr("cell_clip", (float)-1.0) - .Attr("num_proj", (int64_t)0) - .Attr("time_major", true) - .Attr("activation", (string)"tanh") - .Attr("gate_order", (string)"rzh") - .Attr("reset_after", true) - .Attr("is_training", true) - .Run(); - tensor_list results = {output_y, output_h, output_updata, output_reset, output_new, hidden_new}; - return results; -} - -std::vector NPUNativeFunctions::npu_gru_backward( - const c10::optional& grady_opt, - const c10::optional& gradh_opt, - const at::Tensor& input, - const at::Tensor& weight_input, - const at::Tensor& weight_hidden, - const at::Tensor& bias_input, - const at::Tensor& bias_hidden, - const at::Tensor& seq_length, - const at::Tensor& init_h, - const at::Tensor& output_y, - const at::Tensor& output_h, - const at::Tensor& output_updata, - const at::Tensor& output_reset, - const at::Tensor& output_new, - const at::Tensor& hidden_new) { - const at::Tensor& grady = c10::value_or_else(grady_opt, [] {return at::Tensor();}); - const at::Tensor& gradh = c10::value_or_else(gradh_opt, [] {return at::Tensor();}); - at::Tensor inh = at::squeeze(init_h, 0); - auto grad_y = - grady.defined() ? grady : OpPreparation::ApplyTensorWithFormat(output_y.sizes(), output_y.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - auto grad_h = - gradh.defined() ? gradh[input.size(0)-1] : OpPreparation::ApplyTensorWithFormat(inh.sizes(), output_h.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - - at::Tensor mask = at::zeros({}, input.options().dtype(at::kByte)); // uint8 - at::Tensor seq_lengths = at::zeros({}, input.options()); - - int64_t npu_format = ACL_FORMAT_ND; - - at::Tensor grad_w_input = OpPreparation::ApplyTensorWithFormat(weight_input.sizes(), input.options(), npu_format); - at::Tensor grad_w_hidden = OpPreparation::ApplyTensorWithFormat(weight_hidden.sizes(), input.options(), npu_format); - at::Tensor grad_x = OpPreparation::ApplyTensorWithFormat(input.sizes(), input.options(), npu_format); - at::Tensor grad_b_input = OpPreparation::ApplyTensorWithFormat(bias_input.sizes(), input.options(), npu_format); - at::Tensor grad_b_hidden = OpPreparation::ApplyTensorWithFormat(bias_hidden.sizes(), input.options(), npu_format); - at::Tensor grad_h_prev = OpPreparation::ApplyTensorWithFormat(init_h.sizes(), input.options(), npu_format); - - OpCommand cmd; - cmd.Name("DynamicGRUV2Grad") - .Input(input) - .Input(weight_input) - .Input(weight_hidden) - .Input(output_y) - .Input(inh) - .Input(output_h) - .Input(grad_y) - .Input(grad_h) - .Input(output_updata) - .Input(output_reset) - .Input(output_new) - .Input(hidden_new) - .Input(seq_lengths) - .Input(mask) - .Output(grad_w_input) - .Output(grad_w_hidden) - .Output(grad_b_input) - .Output(grad_b_hidden) - .Output(grad_x) - .Output(grad_h_prev) - .Attr("direction", (string) "UNIDIRECTIONAL") - .Attr("cell_depth", (int64_t)1) - .Attr("keep_prob", (float)1.0) - .Attr("cell_clip", (float)-1.0) - .Attr("num_proj", (int64_t)0) - .Attr("time_major", (bool)true) - .Attr("bias_type", (string) "no_bias") - .Attr("gate_order", (string) "rzh") - .Attr("reset_after", (bool)true) - .Run(); - tensor_list results = {grad_x, grad_h_prev, grad_w_input, grad_w_hidden, grad_b_input, grad_b_hidden}; - return results; -} - -class NPUGruFunction : public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& input, - const at::Tensor& hx, - const at::Tensor& weight_input, - const at::Tensor& weight_hidden, - const at::Tensor& bias_input, - const at::Tensor& bias_hidden, - const at::Tensor& seq_length, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - auto result = gru_npu(input, hx, weight_input, weight_hidden, - bias_input, bias_hidden, seq_length, has_biases, num_layers, dropout, train, bidirectional, batch_first); - auto result0 = result[0]; - auto result1 = result[1]; - auto result2 = result[2]; - auto result3 = result[3]; - auto result4 = result[4]; - auto result5 = result[5]; - - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({weight_input, - weight_hidden, - input, - bias_input, - bias_hidden, - hx, - result0, - result1, - result2, - result3, - result4, - result5, - seq_length - }); - return result; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto saved = ctx->get_saved_variables(); - auto weight_input = saved[0]; - auto weight_hidden = saved[1]; - auto input = saved[2]; - auto bias_input = saved[3]; - auto bias_hidden = saved[4]; - auto hx = saved[5]; - auto result0 = saved[6]; - auto result1 = saved[7]; - auto result2 = saved[8]; - auto result3 = saved[9]; - auto result4 = saved[10]; - auto result5 = saved[11]; - auto seq_length = saved[12]; - - tensor_list result = NPUNativeFunctions::npu_gru_backward( - grad_outputs[0], - grad_outputs[1], - input, - weight_input, - weight_hidden, - bias_input, - bias_hidden, - seq_length, - hx, - result0, - result1, - result2, - result3, - result4, - result5); - - tensor_list output = { - result[0], - result[1], - result[2], - result[3], - result[4], - result[5], - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; -std::vector NPUNativeFunctions::npu_gru( - const at::Tensor& input, - const at::Tensor& hx, - const at::Tensor& weight_input, - const at::Tensor& weight_hidden, - const at::Tensor& bias_input, - const at::Tensor& bias_hidden, - const at::Tensor& seq_length, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - return NPUGruFunction::apply(input, hx, weight_input, weight_hidden, - bias_input, bias_hidden, seq_length, has_biases, num_layers, dropout, train, bidirectional, batch_first); -} - -tuple gru_single_layer_bidirec_npu( - const at::Tensor& input, - pair_of& hx, - BidirectCellParams params, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - at::Tensor fw_weight_input = params.first.w_ih.t(); - at::Tensor fw_weight_hidden = params.first.w_hh.t(); - at::Tensor rev_weight_input = params.second.w_ih.t(); - at::Tensor rev_weight_hidden = params.second.w_hh.t(); - at::Tensor fw_bias_input; - at::Tensor fw_bias_hidden; - at::Tensor rev_bias_input; - at::Tensor rev_bias_hidden; - if (has_biases) { - fw_bias_input = params.first.b_ih.to(input.dtype()); - fw_bias_hidden = params.first.b_hh.to(input.dtype()); - rev_bias_input = params.second.b_ih.to(input.dtype()); - rev_bias_hidden = params.second.b_hh.to(input.dtype()); - } else { - fw_bias_input = OpPreparation::ApplyTensorWithFormat(fw_weight_input.size(1), input.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - fw_bias_hidden = OpPreparation::ApplyTensorWithFormat(fw_weight_hidden.size(1), input.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - rev_bias_input = OpPreparation::ApplyTensorWithFormat(rev_weight_input.size(1), input.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - rev_bias_hidden = OpPreparation::ApplyTensorWithFormat(rev_weight_hidden.size(1), input.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - } - at::Tensor seq_length = OpPreparation::ApplyTensorWithFormat({}, input.options(), ACL_FORMAT_ND); - auto results = NPUNativeFunctions::npu_gru( - input, - hx.first, - fw_weight_input, - fw_weight_hidden, - fw_bias_input, - fw_bias_hidden, - seq_length, - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - int64_t numStep = input.size(0); - at::Tensor fw_output_hy = at::unsqueeze(results[1][numStep - 1], 0); - at::Tensor fw_output = results[0]; - auto rev_inputs = at::flip(input, {0}); // reverse input; - auto rev_results = NPUNativeFunctions::npu_gru( - rev_inputs, - hx.second, - rev_weight_input, - rev_weight_hidden, - rev_bias_input, - rev_bias_hidden, - seq_length, - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - at::Tensor rev_output_hy = at::unsqueeze(rev_results[1][numStep - 1], 0); - at::Tensor rev_output = at::flip(rev_results[0],{0}); - return std::make_tuple(at::cat({fw_output, rev_output}, -1), - at::cat({fw_output_hy, rev_output_hy})); -} - -tuple gru_single_layer_direc_npu( - const at::Tensor& input, - const at::Tensor& hx, - CellParams params, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - // get weight fp16 - at::Tensor weight_input = params.w_ih.t(); - at::Tensor weight_hidden = params.w_hh.t(); - - // get bias fp16 / fp32 - at::Tensor bias_input; - at::Tensor bias_hidden; - if (has_biases) { - bias_input = params.b_ih.to(input.dtype()); - bias_hidden = params.b_hh.to(input.dtype()); - } else { - bias_input = OpPreparation::ApplyTensorWithFormat(weight_input.size(1), input.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - bias_hidden = OpPreparation::ApplyTensorWithFormat(weight_hidden.size(1), input.options(), ACL_FORMAT_FRACTAL_NZ).mul(0); - } - - at::Tensor seq_length = OpPreparation::ApplyTensorWithFormat({}, input.options(), ACL_FORMAT_ND); - - auto results = NPUNativeFunctions::npu_gru( - input, - hx, - weight_input, - weight_hidden, - bias_input, - bias_hidden, - seq_length, - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - int64_t numStep = input.size(0); - at::Tensor output_hy = at::unsqueeze(results[1][numStep - 1], 0); - return std::tuple(results[0], output_hy); -} - -tuple apply_layer_stack( - const at::Tensor& input, - std::vector hx, - std::vector params, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - auto layer_input = input; - auto hidden_it = hx.begin(); - auto params_size = params.size(); - - std::vector weights; - std::vector::iterator params_it = params.begin(); - if (has_biases) { - for (int64_t i = 0; i < params_size; i = i + 4){ - weights.emplace_back(CellParams((*(params_it+i)).first, (*(params_it+i)).second, - (*(params_it+i+1)).first, (*(params_it+i+1)).second), - CellParams((*(params_it+i+2)).first, (*(params_it+i+2)).second, - (*(params_it+i+3)).first, (*(params_it+i+3)).second)); - } - } else { - for (int64_t i = 0; i < params_size; i = i + 2){ - weights.emplace_back(CellParams((*(params_it+i)).first, (*(params_it+i)).second), - CellParams((*(params_it+i+1)).first, (*(params_it+i+1)).second)); - } - } - auto weights_it = weights.begin(); - std::vector final_hiddens; - for (int64_t l = 0; l < num_layers; ++l) { - auto layer_output = gru_single_layer_bidirec_npu( - layer_input, - *(hidden_it++), - *(weights_it++), - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - final_hiddens.push_back(std::move(std::get<1>(layer_output))); - layer_input = std::get<0>(layer_output); - } - return std::make_tuple(layer_input, at::cat(final_hiddens, 0)); -} - -tuple apply_layer_stack( - const at::Tensor& input, - std::vector& hx, - std::vector& params, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - auto layer_input = input; - auto hidden_it = hx.begin(); - - auto params_size = params.size(); - std::vector weights; - std::vector::iterator params_it = params.begin(); - if (has_biases) { - for (int64_t i = 0; i < params_size; i = i + 4){ - weights.emplace_back(CellParams(*(params_it+i), *(params_it+i+1), - *(params_it+i+2), *(params_it+i+3))); - } - } else { - for (int64_t i = 0; i < params_size; i = i + 2){ - weights.emplace_back(CellParams(*(params_it+i), *(params_it+i+1))); - } - } - auto weights_it = weights.begin(); - std::vector final_hiddens; - - for (int64_t l = 0; l < num_layers; ++l) { - auto layer_output = gru_single_layer_direc_npu( - layer_input, - *(hidden_it++), - *(weights_it++), - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - final_hiddens.push_back(std::move(std::get<1>(layer_output))); - layer_input = std::get<0>(layer_output); - } - auto hidden_state = at::cat(final_hiddens, 0); - return std::make_tuple(layer_input, hidden_state); -} - -tuple NPUNativeFunctions::gru( - const at::Tensor& input_, - const at::Tensor& hx, - at::TensorList params, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first) { - // The operator of DynamicGRU only supports the T axis as the first axis. - auto input = batch_first ? input_.transpose(0, 1) : input_; - - auto layer_hx = hx.unbind(0); - int64_t total_layers = layer_hx.size(); - std::vector hiddens; - for (int64_t i = 0; i < total_layers; ++i) { - hiddens.emplace_back(std::move(layer_hx[i])); - } - std::vector paramsVec; - for (int64_t i = 0; i < params.size(); ++i) { - paramsVec.emplace_back(std::move(params[i])); - } - tuple result; - if (bidirectional) { - result = apply_layer_stack( - input, - make_pair_vec(hiddens), - make_pair_vec(paramsVec), - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - } else { - result = apply_layer_stack( - input, - hiddens, - paramsVec, - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first); - } - std::get<0>(result) = batch_first ? std::get<0>(result).transpose(0, 1) : std::get<0>(result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/GtKernelNpu.cpp b/torch_npu/csrc/aten/ops/GtKernelNpu.cpp index 4b453091b6..fa2f4a185e 100644 --- a/torch_npu/csrc/aten/ops/GtKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/GtKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -46,7 +46,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::gt_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) + at::Tensor &XLANativeFunctions::gt_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -63,7 +63,7 @@ namespace at_npu return result; } - at::Tensor >_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, at::Scalar other) + at::Tensor >_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, const at::Scalar &other) { at::Tensor selfCast = self; if (self.dtype() == at::ScalarType::Bool) @@ -81,7 +81,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::gt_out(const at::Tensor &self, at::Scalar other, at::Tensor &result) + at::Tensor &XLANativeFunctions::gt_out(const at::Tensor &self, const at::Scalar &other, at::Tensor &result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); auto outputSize = formatCastOfSelf.sizes(); @@ -96,7 +96,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::gt(const at::Tensor &self, const at::Tensor &other) + at::Tensor XLANativeFunctions::gt(const at::Tensor &self, const at::Tensor &other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -114,7 +114,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::gt(const at::Tensor &self, at::Scalar other) + at::Tensor XLANativeFunctions::gt(const at::Tensor &self, const at::Scalar &other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); // calculate the output size @@ -131,7 +131,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::gt_(at::Tensor &self, const at::Tensor &other) + at::Tensor &XLANativeFunctions::gt_(at::Tensor &self, const at::Tensor &other) { OpPreparation::CastBackToOriFormat(self); at::Tensor ori_other = OpPreparation::CastBackToOriFormat(other); @@ -160,7 +160,7 @@ namespace at_npu return self; } - at::Tensor &NPUNativeFunctions::gt_(at::Tensor &self, at::Scalar other) + at::Tensor &XLANativeFunctions::gt_(at::Tensor &self, const at::Scalar &other) { OpPreparation::CastBackToOriFormat(self); c10::SmallVector inputs = {self}; diff --git a/torch_npu/csrc/aten/ops/HardShrinkBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardShrinkBackwardKernelNpu.cpp deleted file mode 100644 index bb13b8eb64..0000000000 --- a/torch_npu/csrc/aten/ops/HardShrinkBackwardKernelNpu.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& hardshrink_backward_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar lambd) { - OpCommand cmd; - cmd.Name("HardShrinkGrad") - .Input(grad_output) - .Input(self) - .Attr("lambd", lambd) - .Output(grad_input) - .Run(); - - return grad_input; -} - -at::Tensor NPUNativeFunctions::hardshrink_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar lambd) { - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - hardshrink_backward_nocheck(grad_input, grad_output, self, lambd); - - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/HardShrinkKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardShrinkKernelNpu.cpp deleted file mode 100644 index 21a56c56f4..0000000000 --- a/torch_npu/csrc/aten/ops/HardShrinkKernelNpu.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& hardshrink_nocheck(at::Tensor& result, const at::Tensor& self, at::Scalar lambd) { - OpCommand cmd; - cmd.Name("HardShrink") - .Input(self) - .Attr("lambd", lambd) - .Output(result).Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::hardshrink(const at::Tensor& self, at::Scalar lambd) { - at::Tensor result = OpPreparation::ApplyTensor(self); - hardshrink_nocheck(result, self, lambd); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/HardSwishBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardSwishBackwardKernelNpu.cpp deleted file mode 100644 index b42687cc6e..0000000000 --- a/torch_npu/csrc/aten/ops/HardSwishBackwardKernelNpu.cpp +++ /dev/null @@ -1,44 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& hardswish_backward_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self) { - - OpCommand cmd; - cmd.Name("HardSwishGrad") - .Input(grad_output) - .Input(self) - .Output(grad_input) - .Run(); - - return grad_input; -} - -at::Tensor NPUNativeFunctions::hardswish_backward(const at::Tensor& grad_output, const at::Tensor& self) { - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output); - - return hardswish_backward_nocheck(grad_input, grad_output, self); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/HardSwishKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardSwishKernelNpu.cpp deleted file mode 100644 index 9329f7d6b0..0000000000 --- a/torch_npu/csrc/aten/ops/HardSwishKernelNpu.cpp +++ /dev/null @@ -1,61 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& hardswish_out_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("HardSwish") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::hardswish_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut({self}, result, self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - hardswish_out_nocheck(self, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - hardswish_out_nocheck(self, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::hardswish(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - - hardswish_out_nocheck(self, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::hardswish_(at::Tensor& self) { - NPUNativeFunctions::hardswish_out(self, self); - - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/HardsigmoidBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardsigmoidBackwardKernelNpu.cpp deleted file mode 100644 index ae79c90a7c..0000000000 --- a/torch_npu/csrc/aten/ops/HardsigmoidBackwardKernelNpu.cpp +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -namespace { - -at::Tensor& hardsigmoid_backward_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self) { - OpCommand cmd; - cmd.Name("HardSigmoidGrad") - .Input(grad_output) - .Input(self) - .Output(grad_input) - .Run(); - - return grad_input; -} -} // namespace - -at::Tensor NPUNativeFunctions::hardsigmoid_backward( - const at::Tensor& grad_output, - const at::Tensor& self) { - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output); - // calculate the output result of the NPU - hardsigmoid_backward_nocheck(grad_input, grad_output, self); - - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/HardsigmoidKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardsigmoidKernelNpu.cpp deleted file mode 100644 index da0c09cb23..0000000000 --- a/torch_npu/csrc/aten/ops/HardsigmoidKernelNpu.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& hardsigmoid_out_nocheck( - const at::Tensor& self, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("HardSigmoid") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::hardsigmoid_out( - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor checkResult = hardsigmoid_out_nocheck(self, contiguousResult); - NpuUtils::format_fresh_view(result, checkResult); - } else { - hardsigmoid_out_nocheck(self, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::hardsigmoid(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - hardsigmoid_out_nocheck(self, result); - return result; -} - -at::Tensor& hardsigmoid_(at::Tensor& self) { - OpPreparation::CheckMemory({self}, {self}); - hardsigmoid_out(self, self); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/HardtanhBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardtanhBackwardKernelNpu.cpp deleted file mode 100644 index 5cde99fc27..0000000000 --- a/torch_npu/csrc/aten/ops/HardtanhBackwardKernelNpu.cpp +++ /dev/null @@ -1,52 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::hardtanh_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar min_val, - at::Scalar max_val, - at::Tensor& grad_input) { - OpPreparation::CheckMemory({grad_output, self}, {grad_input}); - OpCommand cmd; - cmd.Name("HardtanhGrad") - .Input(self) - .Input(grad_output) - .Output(grad_input) - .Attr("max_val", max_val) - .Attr("min_val", min_val) - .Run(); - return grad_input; -} - -at::Tensor NPUNativeFunctions::hardtanh_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar min_val, - at::Scalar max_val) { - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - hardtanh_backward_out(grad_output, self, min_val, max_val, grad_input); - return grad_input; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/HardtanhKernelNpu.cpp b/torch_npu/csrc/aten/ops/HardtanhKernelNpu.cpp deleted file mode 100644 index 3acf16cdc4..0000000000 --- a/torch_npu/csrc/aten/ops/HardtanhKernelNpu.cpp +++ /dev/null @@ -1,57 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::hardtanh_out( - const at::Tensor& self, - at::Scalar min, - at::Scalar max, - at::Tensor& result) { - OpPreparation::CheckMemory({self}, {result}); - OpCommand cmd; - cmd.Name("ClipByValue") - .Input(self) - .Input(min, self.scalar_type()) - .Input(max, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::hardtanh(const at::Tensor& self, at::Scalar min, at::Scalar max) { - at::Tensor result = OpPreparation::ApplyTensor(self); - hardtanh_out(self, min, max, result); - return result; -} - -at::Tensor& NPUNativeFunctions::hardtanh_(at::Tensor& self, at::Scalar min, at::Scalar max) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = hardtanh_out(contiguousSelf, min, max, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - hardtanh_out(self, min, max, self); - } - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/HasCompatibleShallowCopyType.cpp b/torch_npu/csrc/aten/ops/HasCompatibleShallowCopyType.cpp index f46d046188..5fdc6c2711 100644 --- a/torch_npu/csrc/aten/ops/HasCompatibleShallowCopyType.cpp +++ b/torch_npu/csrc/aten/ops/HasCompatibleShallowCopyType.cpp @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include @@ -34,7 +34,7 @@ bool _has_compatible_shallow_copy_type(const at::Tensor &self, return (self_key == from_key) || (is_dense(self_key) && is_dense(from_key)); } -TORCH_LIBRARY_IMPL(aten, Math, m) { +TORCH_LIBRARY_IMPL(aten, CatchAll, m) { m.impl("_has_compatible_shallow_copy_type", TORCH_FN(_has_compatible_shallow_copy_type)); } diff --git a/torch_npu/csrc/aten/ops/IfmrKernelNpu.cpp b/torch_npu/csrc/aten/ops/IfmrKernelNpu.cpp deleted file mode 100644 index ed4796729c..0000000000 --- a/torch_npu/csrc/aten/ops/IfmrKernelNpu.cpp +++ /dev/null @@ -1,62 +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. -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using namespace torch::autograd; - -tuple NPUNativeFunctions::npu_ifmr( - const at::Tensor& data, - const at::Tensor& data_min, - const at::Tensor& data_max, - const at::Tensor& cumsum, - const double min_percentile=0.999999, - const double max_percentile=0.999999, - const double search_start=0.7, - const double search_end=1.3, - const double search_step=0.01, - const bool with_offset=true) { - at::Tensor scale = OpPreparation::ApplyTensorWithFormat(data_min, ACL_FORMAT_NCHW); - at::Tensor offset = OpPreparation::ApplyTensorWithFormat(data_min, ACL_FORMAT_NCHW); - - std::vector tmp; - tmp.push_back(static_cast(search_start)); - tmp.push_back(static_cast(search_end)); - at::ArrayRef searchRange(tmp); - - OpCommand cmd; - cmd.Name("IFMR") - .Input(data) - .Input(data_min) - .Input(data_max) - .Input(cumsum) - .Attr("min_percentile", static_cast(min_percentile)) - .Attr("max_percentile", static_cast(max_percentile)) - .Attr("search_range", searchRange) - .Attr("search_step", static_cast(search_step)) - .Attr("with_offset", with_offset) - .Output(scale) - .Output(offset) - .Run(); - - return std::tie(scale, offset); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/Im2colBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/Im2colBackwardKernelNpu.cpp deleted file mode 100644 index 756f0253f8..0000000000 --- a/torch_npu/csrc/aten/ops/Im2colBackwardKernelNpu.cpp +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& im2col_backward_out_npu_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - at::IntArrayRef input_size, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride) { - at::Tensor gradOutput = grad_output; - gradOutput = gradOutput.view({ - grad_output.size(0), - grad_output.size(1) / (kernel_size[0] * kernel_size[1]), - kernel_size[0] * kernel_size[1], - grad_output.size(2)}); - c10::SmallVector inputSize = {input_size[0], input_size[1]}; - c10::SmallVector kernelSize = {kernel_size[0], kernel_size[1]}; - c10::SmallVector dilations = {dilation[0], dilation[1]}; - c10::SmallVector paddings = {padding[0], padding[1]}; - c10::SmallVector stridesSize = {stride[0], stride[1]}; - OpCommand cmd; - cmd.Name("Col2im") - .Input(gradOutput) - .Input(inputSize, at::kInt) - .Output(grad_input) - .Attr("kernel_size", kernelSize) - .Attr("dilation", dilations) - .Attr("padding", paddings) - .Attr("stride", stridesSize) - .Run(); - return grad_input; -} - -at::Tensor& NPUNativeFunctions::im2col_backward_out( - const at::Tensor& grad_output, - at::IntArrayRef input_size, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride, - at::Tensor& grad_input) { - c10::SmallVector outputSize = { - grad_output.size(0), - grad_output.size(1) / (kernel_size[0] * kernel_size[1]), - input_size[0], - input_size[1]}; - OpPreparation::CheckOut( - {grad_output}, - grad_input, - grad_output, - outputSize); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({grad_output}, {grad_input}) - .Func([&grad_output, &input_size, &kernel_size, &dilation, &padding, &stride] - (at::Tensor& grad_input) - {im2col_backward_out_npu_nocheck( - grad_input, - grad_output, - input_size, - kernel_size, - dilation, - padding, - stride);}) - .Call(grad_input); -} - -at::Tensor NPUNativeFunctions::im2col_backward( - const at::Tensor& grad_output, - at::IntArrayRef input_size, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride) { - c10::SmallVector outputSize = { - grad_output.size(0), - grad_output.size(1) / (kernel_size[0] * kernel_size[1]), - input_size[0], - input_size[1]}; - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output, outputSize); - im2col_backward_out_npu_nocheck( - grad_input, - grad_output, - input_size, - kernel_size, - dilation, - padding, - stride); - return grad_input; -} - -at::Tensor& NPUNativeFunctions::col2im_out( - const at::Tensor& grad_output, - at::IntArrayRef input_size, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride, - at::Tensor& grad_input){ - return im2col_backward_out( - grad_output, - input_size, - kernel_size, - dilation, - padding, - stride, - grad_input); -} - -at::Tensor NPUNativeFunctions::col2im( - const at::Tensor& grad_output, - at::IntArrayRef input_size, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride) { - return im2col_backward( - grad_output, - input_size, - kernel_size, - dilation, - padding, - stride); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/Im2colKernelNpu.cpp b/torch_npu/csrc/aten/ops/Im2colKernelNpu.cpp deleted file mode 100644 index 368cade959..0000000000 --- a/torch_npu/csrc/aten/ops/Im2colKernelNpu.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector image_to_col_npu_output_size( - const at::Tensor& self, - at::IntArrayRef ksizes, - at::IntArrayRef strides, - at::IntArrayRef dilations, - at::IntArrayRef pads) { - - if (ksizes.size() == 1) { - c10::SmallVector kernel_sizes = {ksizes[0], ksizes[0]}; - ksizes = at::IntArrayRef(kernel_sizes); - } - - strides = strides.empty() ? at::IntArrayRef({1}) : strides; - if (strides.size() == 1) { - c10::SmallVector stride_sizes = {strides[0], strides[0]}; - strides = at::IntArrayRef(stride_sizes); - } - - dilations = dilations.empty() ? at::IntArrayRef({1}) : dilations; - if (dilations.size() == 1) { - c10::SmallVector dilation_sizes = {dilations[0], dilations[0]}; - dilations = at::IntArrayRef(dilation_sizes); - } - - pads = pads.empty() ? at::IntArrayRef({0}) : pads; - if (pads.size() == 1) { - c10::SmallVector pad_sizes = {pads[0], pads[0]}; - pads = at::IntArrayRef(pad_sizes); - } - - int64_t out_h = (self.size(2) + 2 * pads[0] - (dilations[0] * (ksizes[0] - 1) + 1)) / strides[0] + 1; - int64_t out_w = (self.size(3) + 2 * pads[1] - (dilations[1] * (ksizes[1] - 1) + 1)) / strides[1] + 1; - return {self.size(0), self.size(1) * ksizes[0] * ksizes[1], out_h * out_w}; -} - -at::Tensor& im2col_out_npu_nocheck( - at::Tensor& result, - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride) { - TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 2, - "im2col: kernel_size must either be a single int, or a tuple of two ints"); - if (kernel_size.size() == 1) { - c10::SmallVector kernel_sizes = {kernel_size[0], kernel_size[0]}; - kernel_size = at::IntArrayRef(kernel_sizes); - } - - TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 2, - "im2col: stride must either be omitted, a single int, or a tuple of two ints"); - stride = stride.empty() ? at::IntArrayRef({1}) : stride; - - TORCH_CHECK(dilation.empty() || dilation.size() == 1 || dilation.size() == 2, - "im2col: dilation must either be omitted, a single int, or a tuple of two ints"); - dilation = dilation.empty() ? at::IntArrayRef({1}) : dilation; - - TORCH_CHECK(padding.empty() || padding.size() == 1 || padding.size() == 2, - "im2col: padding must either be omitted, a single int, or a tuple of two ints"); - auto padding_ = padding.empty() ? at::IntArrayRef({0}) : padding; - c10::SmallVector pads; - if (padding_.size() == 1) { - pads = {padding_[0], padding_[0], padding_[0], padding_[0]}; - } else if (padding_.size() == 2) { - pads = {padding_[0], padding_[0], padding_[1], padding_[1]}; - } - - auto padding_4d = at::IntArrayRef(pads); - - int64_t strideH = 1; - int64_t strideW = 1; - if (stride.size() == 1) { - strideH = stride[0]; - strideW = stride[0]; - } else if (stride.size() == 2) { - strideH = stride[0]; - strideW = stride[1]; - } - - int64_t dilationH = 1; - int64_t dilationW = 1; - if (dilation.size() == 1) { - dilationH = dilation[0]; - dilationW = dilation[0]; - } else if (dilation.size() == 2) { - dilationH = dilation[0]; - dilationW = dilation[1]; - } - - c10::SmallVector kernelSize = {kernel_size[0], kernel_size[1]}; - c10::SmallVector stridesSize = {strideH, strideW}; - c10::SmallVector dilationsSize = {dilationH, dilationW}; - c10::SmallVector padsSize = {padding_4d[0], padding_4d[1], padding_4d[2], padding_4d[3]}; - string padding_mode = "CALCULATED"; - - OpCommand cmd; - cmd.Name("Im2col") - .Input(self) - .Output(result) - .Attr("ksizes", kernelSize) - .Attr("strides", stridesSize) - .Attr("dilations", dilationsSize) - .Attr("padding_mode", padding_mode) - .Attr("pads", padsSize) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::im2col_out( - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self, - image_to_col_npu_output_size(self, kernel_size, stride, dilation, padding)); - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self, kernel_size, dilation, padding, stride](at::Tensor& result){im2col_out_npu_nocheck(result, self, kernel_size, dilation, padding, stride);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::im2col( - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride) { - auto outputSize = - image_to_col_npu_output_size(self, kernel_size, stride, dilation, padding); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - im2col_out_npu_nocheck(result, self, kernel_size, dilation, padding, stride); - return result; -} - -at::Tensor NPUNativeFunctions::col2im_backward( - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride) { - return im2col(self, kernel_size, dilation, padding, stride); -} - -at::Tensor& NPUNativeFunctions::col2im_backward_out( - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef dilation, - at::IntArrayRef padding, - at::IntArrayRef stride, - at::Tensor& result) { - return im2col_out(self, kernel_size, dilation, padding, stride, result); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/IndexAddKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexAddKernelNpu.cpp deleted file mode 100644 index ae046b7eda..0000000000 --- a/torch_npu/csrc/aten/ops/IndexAddKernelNpu.cpp +++ /dev/null @@ -1,82 +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. -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" - -namespace at_npu { -namespace native { - -at::Tensor& index_add_out_npu( - at::Tensor& result, - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& source) { - at::Tensor indices = index; - if (index.scalar_type() != at::ScalarType::Int) { - indices = index.to(at::kInt); - } - - at::SmallVector pad_size = array_to_small_vector(self.sizes()); - pad_size[dim] = index.sizes()[0]; - at::Tensor source_broadcast = NPUNativeFunctions::npu_broadcast(source, pad_size); - OpCommand cmd; - cmd.Name("InplaceIndexAdd") - .Input(self) - .Input(indices) - .Input(source_broadcast) - .Output(result) - .Attr("axis", dim) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::index_add_( - at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& source) { - OpPreparation::CheckMemory({self, index, source}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = index_add_out_npu(contiguousSelf, contiguousSelf, dim, index, source); - NpuUtils::format_fresh_view(self, result); - } else { - index_add_out_npu(self, self, dim, index, source); - } - return self; -} - -at::Tensor NPUNativeFunctions::index_add( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& source) { - return self.clone().index_add_(dim, index, source); -} - -at::Tensor NPUNativeFunctions::index_add( - const at::Tensor& self, - at::Dimname dim, - const at::Tensor& index, - const at::Tensor& source) { - return NPUNativeFunctions::index_add(self, dimname_to_position(self, dim), index, source); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/IndexCopyKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexCopyKernelNpu.cpp deleted file mode 100644 index 74b0b18244..0000000000 --- a/torch_npu/csrc/aten/ops/IndexCopyKernelNpu.cpp +++ /dev/null @@ -1,136 +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. - -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -void index_copy_npu_par_check( - const int64_t dim, - const at::Tensor& index, - const at::Tensor& source, - const at::Tensor& result) { - int64_t newDim = at::maybe_wrap_dim(dim, result.dim()); - TORCH_CHECK_INDEX(index.dim() < 2, "index_copy_(): Index should have dimension 1 or 0 (got ", index.dim(), ")"); - - int64_t numIndices = index.numel(); - TORCH_CHECK_INDEX(!(source.dim() == 0 && numIndices != 1), - "index_copy_(): When source is scalar, index should have one element (got ", numIndices, ")"); - TORCH_CHECK_INDEX(!((source.dim() != result.dim()) && (source.dim() != 0 && result.dim() != 0)), - "index_copy_(): When source and destination are not scalars, \ -their dimensionality must match. Source dimensionality (", - source.dim(), "), destination dimensionality (", result.dim(), ")"); - - TORCH_CHECK_INDEX(index.scalar_type() == at::ScalarType::Long, "index_copy_(): Expected LongTensor for index"); - - // Check that source and destination slices have the same size - auto selfSlicedSizes = result.sizes().vec(); - if (selfSlicedSizes.size() > 0) { - selfSlicedSizes.erase(selfSlicedSizes.begin() + newDim); - } - auto sourceSlicedSizes = source.sizes().vec(); - if (sourceSlicedSizes.size() > 0) { - sourceSlicedSizes.erase(sourceSlicedSizes.begin() + newDim); - } - if (selfSlicedSizes.size() != sourceSlicedSizes.size() || - !std::equal(selfSlicedSizes.begin(), selfSlicedSizes.end(), - sourceSlicedSizes.begin())) { - std::stringstream ss; - ss << "index_copy_(): Source/destination tensor must have same slice shapes. "; - ss << "Destination slice shape: " << selfSlicedSizes << " at dimension " << newDim; - ss << " and source slice shape: " << sourceSlicedSizes << " at dimension 0."; - TORCH_CHECK(false, ss.str()); - } - TORCH_CHECK_INDEX(source.dim() == 0 || numIndices == source.size(newDim), - "index_copy_(): Number of indices (", numIndices, - ") should be equal to source.size(newDim) (", source.size(newDim), ")"); -} - -at::Tensor& index_copy_npu_impl( - const int64_t dim, - const at::Tensor& index, - const at::Tensor& source, - at::Tensor& result) { - index_copy_npu_par_check(dim, index, source, result); - int64_t numIndices = index.numel(); - int64_t i; - if (result.dim() > 1) { - at::Tensor des; - at::Tensor src; - for (i = 0; i < numIndices; i++) { - des = at::native::select(result, dim, index[i].item()); - src = at::native::select(source, dim, i); - NPUNativeFunctions::copy_(des, src, false); - } - } else { - for (i = 0; i < numIndices; i++) { - result[i] = source[index[i].item()]; - } - } - return result; -} - -at::Tensor index_copy_npu( - const at::Tensor& self, - const int64_t dim, - const at::Tensor& index, - const at::Tensor& source) { - at::Tensor result(self.clone()); - return index_copy_npu_impl(dim, index, source, result); -} - -at::Tensor index_copy_npu( - const at::Tensor& self, - const at::Dimname dim, - const at::Tensor& index, - const at::Tensor& source) { - at::Tensor result(self.clone()); - return index_copy_npu_impl(dimname_to_position(self, dim), index, source, result); -} - -at::Tensor& NPUNativeFunctions::_index_copy_( - at::Tensor& self, - const int64_t dim, - const at::Tensor& index, - const at::Tensor& source) { - at::Tensor contiguousSelf(self); - if (!NpuUtils::check_match(&self)) { - contiguousSelf = NpuUtils::format_contiguous(self); - } - at::Tensor result = index_copy_npu_impl(dim, index, source, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - - return self; -} - -at::Tensor& index_copy_npu_( - at::Tensor& self, - const at::Dimname dim, - const at::Tensor& index, - const at::Tensor& source) { - at::Tensor contiguousSelf(self); - if (!NpuUtils::check_match(&self)) { - contiguousSelf = NpuUtils::format_contiguous(self); - } - at::Tensor result = index_copy_npu_impl(dimname_to_position(self, dim), index, source, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/IndexFillKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexFillKernelNpu.cpp deleted file mode 100644 index f1fc41cae8..0000000000 --- a/torch_npu/csrc/aten/ops/IndexFillKernelNpu.cpp +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include - -namespace at_npu{ -namespace native{ - -namespace { - -void index_fill_d_check_index(at::IntArrayRef shape, const at::Tensor &index, int64_t dim) -{ - TORCH_CHECK(index.dim() == 1,"Index should be a one-dimensional tensor"); - int index_temp = INT_MAX; - for (int i = 0; i < index.sizes()[0]; i++) - { - index_temp = static_cast(CalcuOpUtil::get_scalar_float_value(index[i].item())); - TORCH_CHECK(shape[dim] > index_temp, - "Index out of range, it should be in [0,", shape[dim], ")"); - } -} - -c10::SmallVector index_fill_d_assist_help_init( - int64_t dim, - at::IntArrayRef sizes, - vector index, - bool flag, - float value) -{ - int blocksize = 0; - int blocknum = 1; - int n = 1; - - for (int i = 0; i < sizes.size(); i++) - { - if (i <= dim) - { - blocknum *= sizes[i]; - } - n *= sizes[i]; - } - blocksize = n / blocknum; - - c10::SmallVector ast; - ast.resize(n); - - if (flag) { - ast = c10::SmallVector(n, 1); - } else { - ast = c10::SmallVector(n, 0); - } - for (int i = 0; i < index.size(); i++) - { - int start = 0, end = 0; - int idx = index[i]; - int k = idx, count = 0; - while (k < blocknum) - { - start = blocksize * k; - end = start + blocksize; - for (int j = start; j < end; j++) - { - ast[j] = value; - } - count++; - k = idx + sizes[dim] * count; - } - } - return ast; -} - -at::Tensor index_fill_d_assist_help( - const at::Tensor &self, - const at::Tensor &index, - int64_t dim, - at::Scalar value, - bool flag) -{ - c10::SmallVector assist; - at::IntArrayRef size = self.sizes(); - vector index_vector; - for (int i = 0; i < index.sizes()[0]; i++) - { - int index_temp = static_cast(CalcuOpUtil::get_scalar_float_value(index[i].item())); - index_vector.push_back(index_temp); - } - // input - // index is a 1-D tensor - // value is a tensor which has only one item - float value_float = CalcuOpUtil::get_scalar_float_value(value); - assist = index_fill_d_assist_help_init(dim, size, index_vector, flag, value_float); - at::Tensor assistHelp = at::from_blob(assist.data(), size, dtype(at::ScalarType::Float)); - return assistHelp.to(at::device(at_npu::key::NativeDeviceType)); -} - -at::Tensor& index_fill_d_nocheck( - at::Tensor& result, - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - at::Scalar value) { - - // Special case - // There is a zero in shape - // example : shape = [1,3,4,0] return itself else return - // processed_data(result) - if (self.numel() == 0) { - return result; - } - at::Scalar value_zeros = at::Scalar(0.0); - const at::Tensor* aclInput = &self; - at::Tensor assistHelp1 = - index_fill_d_assist_help(self, index, dim, value_zeros, true); - at::Tensor assistHelp2 = index_fill_d_assist_help(self, index, dim, value, false); - if (aclInput->scalar_type() == at::ScalarType::Int) - { - assistHelp1 = assistHelp1.to(at::ScalarType::Int); - assistHelp2 = assistHelp2.to(at::ScalarType::Int); - } else if (aclInput->scalar_type() == at::ScalarType::Half) - { - assistHelp1 = assistHelp1.to(at::ScalarType::Half); - assistHelp2 = assistHelp2.to(at::ScalarType::Half); - } - - OpCommand cmd; - cmd.Name("IndexFillD") - .Input(self) - .Input(assistHelp1) - .Input(assistHelp2) - .Attr("dim", dim) - .Output(result) - .Run(); - return result; -} -} // namespace - -at::Tensor NPUNativeFunctions::index_fill( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - at::Scalar value) { - at::Tensor result = OpPreparation::ApplyTensor(self); - index_fill_d_nocheck(result, self, dim, index, value); - - return result; -} - -at::Tensor& NPUNativeFunctions::index_fill_( - at::Tensor& self, - int64_t dim, - const at::Tensor& index, - at::Scalar value) { - - // In-Place-Scalar - at::IntArrayRef shape_self = self.sizes(); - index_fill_d_check_index(shape_self, index, dim); - index_fill_d_nocheck(self, self, dim, index, value); - return self; -} - -at::Tensor NPUNativeFunctions::index_fill( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& value) { - - // Out-Place-Tensor - at::IntArrayRef shape_self = self.sizes(); - index_fill_d_check_index(shape_self, index, dim); - TORCH_CHECK(value.dim() == 0, - "Value should be a 0-dimensional tensor,but got ", value.dim()); - at::Scalar value_scalar = value.item(); - at::Tensor result = OpPreparation::ApplyTensor(self); - index_fill_d_nocheck(result, self, dim, index, value_scalar); - return result; -} - -at::Tensor& NPUNativeFunctions::index_fill_( - at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& value) { - - // In-Place-Tensor - at::IntArrayRef shape_self = self.sizes(); - index_fill_d_check_index(shape_self, index, dim); - TORCH_CHECK(value.dim() == 0, - "Value should be a 0-dimensional tensor,but got ",value.dim()); - at::Scalar value_scalar = value.item(); - index_fill_d_nocheck(self, self, dim, index, value_scalar); - return self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp index 1aa6ffb9dc..f6dbc0ed86 100644 --- a/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/IndexKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -38,11 +38,11 @@ at::Tensor& index_out_nocheck_npu( return result; } -at::Tensor NPUNativeFunctions::index(const at::Tensor& self, const torch::List>& orig) { +at::Tensor XLANativeFunctions::index(const at::Tensor& self, const torch::List>& orig) { at::native::checkIndexTensorTypes(orig); // first expand BoolTensor (masks) or ByteTensor (masks) into 1 or more LongTensors auto indices = at::native::expandTensors(self, orig); - at::Tensor formatCastOfSelf = NPUNativeFunctions::npu_format_cast(self, ACL_FORMAT_ND); + at::Tensor formatCastOfSelf = XLANativeFunctions::npu_format_cast(self, ACL_FORMAT_ND); // calculate the output size auto outputSize = index_npu_output_size(formatCastOfSelf, indices); diff --git a/torch_npu/csrc/aten/ops/IndexPutKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexPutKernelNpu.cpp index ebc88ab87e..056ce6b23c 100644 --- a/torch_npu/csrc/aten/ops/IndexPutKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/IndexPutKernelNpu.cpp @@ -17,7 +17,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -25,13 +25,23 @@ namespace native { at::Tensor& index_put_nocheck( at::Tensor& result, const at::Tensor& self, - std::vector allDefinedIndices, - at::SmallVector masks, + const at::TensorList& indices, const at::Tensor& value, bool accumulate) { if (value.numel() == 0) { return result; } + + at::SmallVector masks; + std::vector allDefinedIndices; + for (int64_t i = 0; i < indices.size(); i++) { + if (indices[i].defined()) { + masks.emplace_back(1); + allDefinedIndices.emplace_back(indices[i]); + } else { + masks.emplace_back(0); + } + } auto masksTensor = CalcuOpUtil::copy_tensor_host_to_device( at::from_blob(masks.data(), {masks.size()}, dtype(at::ScalarType::Long))); @@ -39,9 +49,9 @@ at::Tensor& index_put_nocheck( at::Tensor tempSelf = self; at::Tensor tempValue = value; if (self.scalar_type() == at::ScalarType::Half) { - tempSelf = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - tempValue = NPUNativeFunctions::npu_dtype_cast(value, at::ScalarType::Float); - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Float); + tempSelf = XLANativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); + tempValue = XLANativeFunctions::npu_dtype_cast(value, at::ScalarType::Float); + result = XLANativeFunctions::npu_dtype_cast(result, at::ScalarType::Float); } OpCommand cmd; @@ -55,12 +65,12 @@ at::Tensor& index_put_nocheck( .Run(); if (self.scalar_type() == at::ScalarType::Half) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); + result = XLANativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); } return result; } -at::Tensor NPUNativeFunctions::index_put( +at::Tensor XLANativeFunctions::index_put( const at::Tensor& self, const c10::List> & indices, const at::Tensor& value, @@ -69,7 +79,7 @@ at::Tensor NPUNativeFunctions::index_put( .index_put_(indices, value, accumulate); } -at::Tensor& NPUNativeFunctions::index_put_( +at::Tensor& XLANativeFunctions::index_put_( at::Tensor& self, const c10::List> & indices, const at::Tensor& value, @@ -78,28 +88,14 @@ at::Tensor& NPUNativeFunctions::index_put_( self, indices, value, accumulate, false); } -at::Tensor& NPUNativeFunctions::_index_put_impl_( +at::Tensor& XLANativeFunctions::_index_put_impl_( at::Tensor& self, const c10::List> & indices, const at::Tensor& value, const bool accumulate, const bool unsafe) { at::native::checkIndexTensorTypes(indices); - at::SmallVector masks; - std::vector allDefinedIndices; - for (c10::optional index_opt : indices) { - if (index_opt.has_value()) { - at::Tensor index = std::move(*index_opt); - if (index.defined()) { - allDefinedIndices.emplace_back(index); - masks.emplace_back(1); - } else { - masks.emplace_back(0); - } - } else { - masks.emplace_back(0); - } - } + auto indices_cast = at::native::expandTensors(self, indices); OpPreparation::CastBackToOriFormat(self); at::Tensor valueCopy = value; @@ -109,10 +105,10 @@ at::Tensor& NPUNativeFunctions::_index_put_impl_( if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfCopy); at::Tensor result = index_put_nocheck( - contiguousSelf, contiguousSelf, allDefinedIndices, masks, valueCopy, accumulate); + contiguousSelf, contiguousSelf, indices_cast, valueCopy, accumulate); self.copy_(result); } else { - index_put_nocheck(selfCopy, selfCopy, allDefinedIndices, masks, valueCopy, accumulate); + index_put_nocheck(selfCopy, selfCopy, indices_cast, valueCopy, accumulate); self.copy_(selfCopy); } return self; diff --git a/torch_npu/csrc/aten/ops/IndexSelectKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexSelectKernelNpu.cpp index 334a6b7798..3a4805095d 100644 --- a/torch_npu/csrc/aten/ops/IndexSelectKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/IndexSelectKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -35,13 +35,13 @@ at::Tensor& index_select_out_npu_nocheck( cmd.Name("GatherV2") .Input(self) .Input(index) - .Input(dimVec) + .Input(dimVec, at::kInt) .Output(result) .Run(); return result; } -at::Tensor& NPUNativeFunctions::index_select_out( +at::Tensor& XLANativeFunctions::index_select_out( const at::Tensor& self, int64_t dim, const at::Tensor& index, @@ -57,7 +57,7 @@ at::Tensor& NPUNativeFunctions::index_select_out( } at::Tensor input = self; if (self.dtype() == at::kBool) { - input = NPUNativeFunctions::npu_dtype_cast(input, at::kInt); + input = XLANativeFunctions::npu_dtype_cast(input, at::kInt); } OpPreparation::CheckOut( {input}, @@ -76,7 +76,7 @@ at::Tensor& NPUNativeFunctions::index_select_out( return result; } -at::Tensor NPUNativeFunctions::index_select( +at::Tensor XLANativeFunctions::index_select( const at::Tensor& self, int64_t dim, const at::Tensor& index) { @@ -91,17 +91,17 @@ at::Tensor NPUNativeFunctions::index_select( } at::Tensor input = self; if (self.dtype() == at::kBool) { - input = NPUNativeFunctions::npu_dtype_cast(input, at::kInt); + input = XLANativeFunctions::npu_dtype_cast(input, at::kInt); } at::Tensor result = OpPreparation::ApplyTensorWithFormat(input, outputSize, npu_format); index_select_out_npu_nocheck(input, dim, indexTmp, result); if (self.dtype() == at::kBool) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::kBool); + result = XLANativeFunctions::npu_dtype_cast(result, at::kBool); } return result; } -at::Tensor& NPUNativeFunctions::index_select_out( +at::Tensor& XLANativeFunctions::index_select_out( const at::Tensor& self, at::Dimname dim, const at::Tensor& index, @@ -114,7 +114,7 @@ at::Tensor& NPUNativeFunctions::index_select_out( self, dimname_to_position(self, dim), indexTmp, result); } -at::Tensor NPUNativeFunctions::index_select( +at::Tensor XLANativeFunctions::index_select( const at::Tensor& self, at::Dimname dim, const at::Tensor& index) { diff --git a/torch_npu/csrc/aten/ops/IndexingKernelNpu.cpp b/torch_npu/csrc/aten/ops/IndexingKernelNpu.cpp index 632baa34d2..13b19885f1 100644 --- a/torch_npu/csrc/aten/ops/IndexingKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/IndexingKernelNpu.cpp @@ -15,12 +15,12 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::npu_indexing_out(const at::Tensor& self, +at::Tensor& XLANativeFunctions::npu_indexing_out(const at::Tensor& self, c10::IntArrayRef begin, c10::IntArrayRef end, c10::IntArrayRef strides, @@ -47,7 +47,7 @@ at::Tensor& NPUNativeFunctions::npu_indexing_out(const at::Tensor& self, return result; } -at::Tensor NPUNativeFunctions::npu_indexing( +at::Tensor XLANativeFunctions::npu_indexing( const at::Tensor& self, c10::IntArrayRef begin, c10::IntArrayRef end, diff --git a/torch_npu/csrc/aten/ops/InverseKernelNpu.cpp b/torch_npu/csrc/aten/ops/InverseKernelNpu.cpp deleted file mode 100644 index aa14462654..0000000000 --- a/torch_npu/csrc/aten/ops/InverseKernelNpu.cpp +++ /dev/null @@ -1,71 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& inverse_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self) { - at::Tensor selfCast = self; - at::Tensor resultCast = result; - if(self.scalar_type() == at::kHalf) { - selfCast = self.to(at::kFloat); - } - if(result.scalar_type() == at::kHalf) { - resultCast = resultCast.to(at::kFloat); - } - OpCommand cmd; - cmd.Name("MatrixInverse") - .Input(selfCast) - .Output(resultCast) - .Attr("adjoint", false) - .Run(); - result.copy_(resultCast); - return result; -} - -at::Tensor& NPUNativeFunctions::inverse_out( - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor newResult = inverse_out_npu_nocheck(contiguousResult, self); - NpuUtils::format_fresh_view(result, newResult); - } else { - inverse_out_npu_nocheck(result, self); - } - - return result; -} - -at::Tensor NPUNativeFunctions::inverse(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - - inverse_out_npu_nocheck(result, self); - - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/IouKernelNpu.cpp b/torch_npu/csrc/aten/ops/IouKernelNpu.cpp deleted file mode 100644 index 30b70c7536..0000000000 --- a/torch_npu/csrc/aten/ops/IouKernelNpu.cpp +++ /dev/null @@ -1,68 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::npu_iou( - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - int64_t mode) { - at::Tensor bboxesFP16 = bboxes; - if (bboxes.scalar_type() != at::ScalarType::Half) { - bboxesFP16 = bboxes.to(at::kHalf); - } - at::Tensor gtboxesFP16 = gtboxes; - if (gtboxes.scalar_type() != at::ScalarType::Half) { - gtboxesFP16 = gtboxes.to(at::kHalf); - } - - auto outputSize = {gtboxes.size(0), bboxes.size(0)}; - at::Tensor overlap = OpPreparation::ApplyTensorWithFormat( - bboxesFP16, - outputSize, - CalcuOpUtil::get_tensor_npu_format(bboxes)); - string modeStr = "iou"; - if (mode == 1) { - modeStr = "iof"; - } - OpCommand cmd; - cmd.Name("Iou") - .Input(bboxesFP16) - .Input(gtboxesFP16) - .Output(overlap) - .Attr("mode", modeStr) - .Attr("eps", static_cast(0.01)) - .Run(); - if (overlap.scalar_type() != bboxes.scalar_type()) { - overlap = overlap.to(bboxes.scalar_type()); - } - return overlap; -} - -at::Tensor NPUNativeFunctions::npu_ptiou( - const at::Tensor& bboxes, - const at::Tensor& gtboxes, - int64_t mode) { - return NPUNativeFunctions::npu_iou(bboxes, gtboxes, mode); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/IscloseKernelNpu.cpp b/torch_npu/csrc/aten/ops/IscloseKernelNpu.cpp deleted file mode 100644 index cbaa3c8aee..0000000000 --- a/torch_npu/csrc/aten/ops/IscloseKernelNpu.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -namespace { - -at::Tensor& isclose_nocheck( - const at::Tensor& self, - const at::Tensor& other, - double rtol, - double atol, - bool equal_nan, - at::Tensor& result) { - auto rtol1 = static_cast(rtol); - auto atol1 = static_cast(atol); - OpCommand cmd; - cmd.Name("IsClose") - .Input(self) - .Input(other) - .Attr("rtol", rtol1) - .Attr("atol", atol1) - .Attr("equal_nan", equal_nan) - .Output(result) - .Run(); - return result; -} -} // namespace - -at::Tensor NPUNativeFunctions::isclose( - const at::Tensor& self, - const at::Tensor& other, - double rtol, - double atol, - bool equal_nan) { - TORCH_CHECK(self.scalar_type() == other.scalar_type(), self.scalar_type(), " did not match ", other.scalar_type()); - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(outputSize, self.options().dtype(at::kBool), self); - result = isclose_nocheck(self, other, rtol, atol, equal_nan, result); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/IsfiniteKernelNpu.cpp b/torch_npu/csrc/aten/ops/IsfiniteKernelNpu.cpp deleted file mode 100644 index 3daaaa4cb7..0000000000 --- a/torch_npu/csrc/aten/ops/IsfiniteKernelNpu.cpp +++ /dev/null @@ -1,45 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/core/NPUBridge.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::isfinite(const at::Tensor& self_ex) { - at::Tensor self = self_ex; - if (torch_npu::NPUBridge::GetNpuStorageImpl(self)->npu_desc_.npu_format_ != - ACL_FORMAT_ND) { - self = NPUNativeFunctions::npu_format_cast(self_ex, ACL_FORMAT_ND); - } - if (self.scalar_type() == at::ScalarType::Half) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - auto outputSize = self.sizes(); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options().dtype(at::kBool), ACL_FORMAT_ND); - OpCommand cmd; - cmd.Name("IsFinite") - .Input(self) - .Output(result) - .Run(); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/KlDivBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/KlDivBackwardKernelNpu.cpp index e6591cb903..dfb3a01338 100644 --- a/torch_npu/csrc/aten/ops/KlDivBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/KlDivBackwardKernelNpu.cpp @@ -15,12 +15,12 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor NPUNativeFunctions::kl_div_backward( +at::Tensor XLANativeFunctions::kl_div_backward( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -47,7 +47,7 @@ at::Tensor NPUNativeFunctions::kl_div_backward( .Run(); if (reduction == at::Reduction::Mean) { auto inputShape = self.sizes(); - int batchSquareSize = at::prod_intlist(inputShape) / inputShape[0]; + int batchSquareSize = c10::multiply_integers(inputShape) / inputShape[0]; grad_input.div_(batchSquareSize); } return grad_input; diff --git a/torch_npu/csrc/aten/ops/KlDivKernelNpu.cpp b/torch_npu/csrc/aten/ops/KlDivKernelNpu.cpp deleted file mode 100644 index 50e7fe366e..0000000000 --- a/torch_npu/csrc/aten/ops/KlDivKernelNpu.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::kl_div( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - bool log_target) { - at::Tensor result = - reduction == at::Reduction::None ? - OpPreparation::ApplyTensor(self) : - OpPreparation::ApplyTensor({}, self.options(), self); - string reductionStr; - if (reduction == at::Reduction::Mean) { - reductionStr = "batchmean"; - } else if (reduction == at::Reduction::Sum) { - reductionStr = "sum"; - } else if (reduction == at::Reduction::None) { - reductionStr = "none"; - } - OpCommand cmd; - cmd.Name("KLDiv") - .Input(self) - .Input(target) - .Output(result) - .Attr("reduction", reductionStr) - .Attr("log_target", log_target) - .Run(); - if (reduction == at::Reduction::Mean) { - auto inputShape = self.sizes(); - int batchSquareSize = at::prod_intlist(inputShape) / inputShape[0]; - result.div_(batchSquareSize); - } - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/KthvalueKernelNpu.cpp b/torch_npu/csrc/aten/ops/KthvalueKernelNpu.cpp deleted file mode 100644 index 0dfade122b..0000000000 --- a/torch_npu/csrc/aten/ops/KthvalueKernelNpu.cpp +++ /dev/null @@ -1,170 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector kthvalue_npu_output_size( - const at::Tensor& self, - int64_t dim, - bool keepdim) { - at::IntArrayRef dims(dim); - return reduce_ops_npu_output_size(self, dims, keepdim); -} - -void kthvalue_shape_modify( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim, - bool keepdim) { - at::Tensor _self = self.rename(c10::nullopt); - auto outputSize = kthvalue_npu_output_size(self, dim, keepdim); - if (values.defined()) { - TORCH_CHECK( - values.dtype() == self.dtype(), - "output values must be of same type as input"); - TORCH_CHECK( - values.device() == self.device(), - "output values must be on same values as input"); - values.resize_(outputSize); - } else { - values = at::empty(outputSize, _self.options()); - } - if (indices.defined()) { - TORCH_CHECK( - indices.dtype() == at::kLong, - "output indices must be of scalar type Long"); - TORCH_CHECK( - indices.device() == self.device(), - "output indices must be on same device as input"); - indices.resize_(outputSize); - } else { - indices = at::empty(outputSize, _self.options().dtype(at::kLong)); - } - return; -} - -void kthvalue_calculate( - const at::Tensor& self, - at::Tensor& result, - at::Tensor x, - int64_t k, - int64_t dim, - bool keepdim, - bool changeType, - bool isIndices) { - at::Tensor index = OpPreparation::ApplyTensor( - {1}, - self.options().dtype(at::kInt), - self); - index.fill_(k - 1); - at::Tensor y = index_select(x, dim, index); - if (!keepdim) { - y.squeeze_(dim); - } - - if (changeType) { - y = NPUNativeFunctions::npu_dtype_cast(y, self.scalar_type()); - } - if (isIndices) { - y = NPUNativeFunctions::npu_dtype_cast(y, at::kLong); - } - result.copy_(y, false); - at::namedinference::propagate_names_for_reduction(result, self, dim, keepdim); - return; -} - -tuple NPUNativeFunctions::kthvalue( - const at::Tensor& self, int64_t k, int64_t dim, bool keepdim) { - auto outputSize = kthvalue_npu_output_size(self, dim, keepdim); - at::Tensor values = OpPreparation::ApplyTensor(self, outputSize); - at::Tensor indices = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options().dtype(at::kLong), - ACL_FORMAT_NCHW); - kthvalue_out(self, k, dim, keepdim, values, indices); - return tuple(values, indices); -} - -tuple NPUNativeFunctions::kthvalue( - const at::Tensor& self, int64_t k, at::Dimname dim, bool keepdim) { - return kthvalue(self, k, dimname_to_position(self, dim), keepdim); -} - -tuple NPUNativeFunctions::kthvalue_out( - const at::Tensor& self, - int64_t k, - int64_t dim, - bool keepdim, - at::Tensor& values, - at::Tensor& indices) { - at::SmallVector dims = {dim }; - auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim); - OpPreparation::CheckOut( - {self}, - values, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - OpPreparation::CheckOut( - {self}, - indices, - ACL_FORMAT_ND, - at::ScalarType::Long, - outputSize); - TORCH_CHECK( - self.scalar_type() == at::kHalf || - self.scalar_type() == at::kFloat || - self.scalar_type() == at::kInt, - "the type of input must be float16, float32, or int32"); - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - - TORCH_CHECK( - k >= 0 && k <= (self.dim() > 0 ? self.size(dim) : 1), - "selected index k out of range"); - - at::Tensor _self = self.rename(c10::nullopt); - kthvalue_shape_modify(values, indices, self, dim, keepdim); - bool changeType = false; - if (self.scalar_type() != at::kHalf) { - changeType = true; - _self = NPUNativeFunctions::npu_dtype_cast(_self, at::kHalf); - } - auto ret = at::topk(_self, k, dim, false, true); - kthvalue_calculate(self, values, std::get<0>(ret), k, dim, keepdim, changeType, false); - kthvalue_calculate(self, indices, std::get<1>(ret), k, dim, keepdim, false, true); - return tuple(values, indices); -} - -tuple NPUNativeFunctions::kthvalue_out( - const at::Tensor& self, - int64_t k, - at::Dimname dim, - bool keepdim, - at::Tensor& values, - at::Tensor& indices) { - return kthvalue_out( - self, k, dimname_to_position(self, dim), keepdim, values, indices); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LayerNormBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/LayerNormBackwardKernelNpu.cpp deleted file mode 100644 index 40fcfd5027..0000000000 --- a/torch_npu/csrc/aten/ops/LayerNormBackwardKernelNpu.cpp +++ /dev/null @@ -1,149 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple layer_norm_backward_npu_nocheck( - at::Tensor& dX, - at::Tensor& dgamma, - at::Tensor& dbeta, - const at::Tensor& dY, - const at::Tensor& X, - const at::Tensor& mean, - const at::Tensor& variance, - const at::Tensor& gamma, - int64_t M, - int64_t N) -{ - // constructs the input and output NPUTensorDesc - at::SmallVector tmpSize = array_to_small_vector(X.sizes()); - for (int i = X.dim() - gamma.dim(); i < X.dim(); i++) { - tmpSize[i] = 1; - } - at::Tensor mean_ex = mean.reshape(tmpSize); - at::Tensor variance_ex = variance.reshape(tmpSize); - double eps = 1e-05; - - OpCommand cmd; - cmd.Name("LayerNormGrad") - .Input(dY) - .Input(X) - .Input(variance_ex) - .Input(mean_ex) - .Input(gamma) - .Output(dX) - .Output(dgamma) - .Output(dbeta) - .Run(); - - return tuple(dX, dgamma, dbeta); -} - -std::tuple layer_norm_backward_npu_support( - const at::Tensor& dY, - const at::Tensor& X, - const at::Tensor& mean, - const at::Tensor& variance, - const c10::optional& gamma_ex, - int64_t M, - int64_t N, - std::array output_mask) { - const at::Tensor& gamma = c10::value_or_else(gamma_ex, [] {return at::Tensor();}); - at::Tensor dX; - at::Tensor dgamma; - at::Tensor dbeta; - at::Tensor gammaTemp = gamma; - - at::SmallVector tmpSize; - int64_t numels = 1; - for (int64_t i = X.dim() - 1; i >= 0; i--) { - numels *= X.size(i); - tmpSize.emplace_back(X.size(i)); - if(numels == N) { - break; - } - } - std::reverse(tmpSize.begin(), tmpSize.end()); - if (!gamma.defined()) { - gammaTemp = at::ones(tmpSize, X.options()); - } else if (!gamma.sizes().equals(tmpSize)) { - gammaTemp.resize_(tmpSize); - } - - // calculate the output size - auto outputSizes = layer_norm_backward_npu_output_size(dY, X, mean, variance, gammaTemp, M, N); - - if (M <= 0) { - dX = at::native::empty_like(X, LEGACY_CONTIGUOUS_MEMORY_FORMAT); - dgamma = at::native::zeros_like(gammaTemp, LEGACY_CONTIGUOUS_MEMORY_FORMAT); - dbeta = at::native::zeros_like(gammaTemp, LEGACY_CONTIGUOUS_MEMORY_FORMAT); - return std::make_tuple(std::move(dX), std::move(dgamma), std::move(dbeta)); - } - - // construct the output tensor - dX = OpPreparation::ApplyTensor(X, std::get<0>(outputSizes)); - dgamma = OpPreparation::ApplyTensor(gammaTemp, std::get<1>(outputSizes)); - dbeta = OpPreparation::ApplyTensor(gammaTemp, std::get<2>(outputSizes)); - - // calculate the output result of the NPU - return layer_norm_backward_npu_nocheck(dX, dgamma, dbeta, dY, X, mean, variance, gammaTemp, M, N); -} - -std::tuple NPUNativeFunctions::native_layer_norm_backward( - const at::Tensor& dY, - const at::Tensor& X, - at::IntArrayRef normalized_shape, - const at::Tensor& mean, - const at::Tensor& variance, - const c10::optional& gamma, - const c10::optional& beta, - std::array output_mask) { - const int normalized_ndim = normalized_shape.size(); - const auto input_shape = X.sizes(); - const auto input_ndim = X.dim(); - - if (input_ndim < normalized_ndim || - !input_shape.slice(input_ndim - normalized_ndim) - .equals(normalized_shape)) { - std::stringstream ss; - ss << "Given normalized_shape=" << normalized_shape - << ", expected input with shape [*"; - for (auto size : normalized_shape) { - ss << ", " << size; - } - ss << "], but got input of size" << input_shape; - AT_ERROR(ss.str()); - } - - const int axis = input_ndim - normalized_ndim; - const int64_t M = std::accumulate( - input_shape.cbegin(), - input_shape.cbegin() + axis, - 1LL, - std::multiplies()); - const int64_t N = std::accumulate( - input_shape.cbegin() + axis, - input_shape.cend(), - 1LL, - std::multiplies()); - - return layer_norm_backward_npu_support(dY, X, mean, variance, gamma, M, N, output_mask); -} - -}} // namespace at_npu::native \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LayerNormEvalKernelNpu.cpp b/torch_npu/csrc/aten/ops/LayerNormEvalKernelNpu.cpp deleted file mode 100644 index 68ef8f4cde..0000000000 --- a/torch_npu/csrc/aten/ops/LayerNormEvalKernelNpu.cpp +++ /dev/null @@ -1,87 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::npu_layer_norm_eval( - const at::Tensor& input, - at::IntArrayRef normalized_shape, - const c10::optional &weight_opt, - const c10::optional &bias_opt, - double eps) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - const int normalized_ndim = normalized_shape.size(); - const auto input_shape = input.sizes(); - const auto input_ndim = input.dim(); - const int axis = input_ndim - normalized_ndim; - const int64_t M = std::accumulate( - input_shape.cbegin(), - input_shape.cbegin() + axis, - 1LL, - std::multiplies()); - const int64_t N = std::accumulate( - input_shape.cbegin() + axis, - input_shape.cend(), - 1LL, - std::multiplies()); - at::Tensor result = OpPreparation::ApplyTensor(input); - int64_t numels = 1; - int64_t begin_dim = 0; - c10::SmallVector tmpSize; - for (int64_t i = input.dim() - 1; i >= 0; i--) { - numels *= input.size(i); - tmpSize.emplace_back(input.size(i)); - if(numels == N) { - begin_dim = i; - break; - } - } - std::reverse(tmpSize.begin(), tmpSize.end()); - at::Tensor resizeWeight = weight.detach().clone(); - at::Tensor resizeBias = bias.detach().clone(); - if (!resizeWeight.defined()) { - resizeWeight = at::ones(tmpSize, input.options()); - } else if (!resizeWeight.sizes().equals(tmpSize)) { - resizeWeight.resize_(tmpSize); - } - if (!resizeBias.defined()) { - resizeBias = at::zeros(tmpSize, input.options()); - } else if (!resizeBias.sizes().equals(tmpSize)) { - resizeBias.resize_(tmpSize); - } - at::Tensor mean = OpPreparation::ApplyTensor(resizeWeight, {M}); - at::Tensor rstd = OpPreparation::ApplyTensor(resizeWeight, {M}); - OpCommand cmd; - cmd.Name("LayerNorm") - .Input(input) - .Input(resizeWeight) - .Input(resizeBias) - .Output(result) - .Output(mean) - .Output(rstd) - .Attr("begin_norm_axis", begin_dim) - .Attr("begin_params_axis", begin_dim) - .Attr("epsilon", static_cast(eps)) - .Run(); - return result; -} -}} diff --git a/torch_npu/csrc/aten/ops/LayerNormKernelNpu.cpp b/torch_npu/csrc/aten/ops/LayerNormKernelNpu.cpp deleted file mode 100644 index 698f68aec5..0000000000 --- a/torch_npu/csrc/aten/ops/LayerNormKernelNpu.cpp +++ /dev/null @@ -1,166 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple layer_norm_npu_support( - const at::Tensor& input, - const c10::optional& weight_ex, - const c10::optional& bias_ex, - int64_t M, - int64_t N, - double eps) { - const at::Tensor& weight_ = c10::value_or_else(weight_ex, [] {return at::Tensor();}); - at::Tensor weight = weight_; - const at::Tensor& bias_ = c10::value_or_else(bias_ex, [] {return at::Tensor();}); - at::Tensor bias = bias_; - - DCHECK_EQ(input.numel(), M * N); - DCHECK(!weight.defined() || weight.numel() == N); - DCHECK(!bias.defined() || bias.numel() == N); - - at::Tensor Y = OpPreparation::ApplyTensor(input); - at::Tensor mean; - at::Tensor variance; - if (M < 0) { - mean = OpPreparation::ApplyTensorWithFormat({M}, input.options(), ACL_FORMAT_ND); - variance = OpPreparation::ApplyTensorWithFormat({M}, input.options(), ACL_FORMAT_ND); - } else { - int64_t numels = 1; - int64_t begin_dim = 0; - - // the output of mean and rstd is Multidimension - at::SmallVector reduceDims; - - // the input of weight is Multidimension - at::SmallVector weightDims; - for (int64_t i = 0; i < input.dim(); i++) { - numels *= input.size(i); - reduceDims.emplace_back(input.size(i)); - if(numels == M){ - begin_dim = i + 1; - while (++i < input.dim()) { - reduceDims.emplace_back(1); - weightDims.emplace_back(input.size(i)); - } - break; - } - } - - if (!weight.defined()) { - weight = at::ones(weightDims, input.options()); - } else if (!weight.sizes().equals(weightDims)) { - weight.resize_(weightDims); - } - - if (!bias.defined()) { - bias = at::zeros(weightDims, input.options()); - } else if (!bias.sizes().equals(weightDims)) { - bias.resize_(weightDims); - } - - mean = OpPreparation::ApplyTensorWithFormat(reduceDims, weight.options(), ACL_FORMAT_ND); - variance = OpPreparation::ApplyTensorWithFormat(reduceDims, weight.options(), ACL_FORMAT_ND); - - OpCommand cmd; - cmd.Name("LayerNorm") - .Input(input) - .Input(weight) - .Input(bias) - .Output(Y) - .Output(mean) - .Output(variance) - .Attr("begin_norm_axis", begin_dim) - .Attr("begin_params_axis", begin_dim) - .Attr("epsilon", static_cast(eps)) - .Run(); - - } - - mean = mean.reshape({M}); - variance = variance.reshape({M}); - - return std::tie(Y, mean, variance); -} - -std::tuple NPUNativeFunctions::native_layer_norm( - const at::Tensor& input, - at::IntArrayRef normalized_shape, - const c10::optional& weight_ex, - const c10::optional& bias_ex, - double eps) { - const at::Tensor& weight = c10::value_or_else(weight_ex, [] {return at::Tensor();}); - const at::Tensor& bias = c10::value_or_else(bias_ex, [] {return at::Tensor();}); - const int normalized_ndim = normalized_shape.size(); - TORCH_CHECK( - normalized_ndim >= 1, - "Expected normalized_shape to be at least 1-dimensional, i.e., ", - "containing at least one element, but got normalized_shape = ", - normalized_shape); - TORCH_CHECK( - !weight.defined() || weight.sizes().equals(normalized_shape), - "Expected weight to be of same shape as normalized_shape, but got ", - "weight of shape ", - weight.sizes(), - " and normalized_shape = ", - normalized_shape); - TORCH_CHECK( - !bias.defined() || bias.sizes().equals(normalized_shape), - "Expected bias to be of same shape as normalized_shape, but got ", - "bias of shape ", - bias.sizes(), - " and normalized_shape = ", - normalized_shape); - - const auto input_shape = input.sizes(); - const auto input_ndim = input.dim(); - - if (input_ndim < normalized_ndim || - !input_shape.slice(input_ndim - normalized_ndim) - .equals(normalized_shape)) { - std::stringstream ss; - ss << "Given normalized_shape=" << normalized_shape - << ", expected input with shape [*"; - for (auto size : normalized_shape) { - ss << ", " << size; - } - ss << "], but got input of size" << input_shape; - AT_ERROR(ss.str()); - } - - const int axis = input_ndim - normalized_ndim; - const int64_t M = std::accumulate( - input_shape.cbegin(), - input_shape.cbegin() + axis, - 1LL, - std::multiplies()); - const int64_t N = std::accumulate( - input_shape.cbegin() + axis, - input_shape.cend(), - 1LL, - std::multiplies()); - - const auto& X = input.is_contiguous() ? input : input.contiguous(); - const auto& gamma = weight.is_contiguous() ? weight : weight.contiguous(); - const auto& beta = bias.is_contiguous() ? bias : bias.contiguous(); - return layer_norm_npu_support(X, gamma, beta, M, N, eps); -} - -}} \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LeKernelNpu.cpp b/torch_npu/csrc/aten/ops/LeKernelNpu.cpp deleted file mode 100644 index 44404cf8f9..0000000000 --- a/torch_npu/csrc/aten/ops/LeKernelNpu.cpp +++ /dev/null @@ -1,134 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& le_out_npu_nocheck(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - OpCommand cmd; - cmd.Name("LessEqual") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::le_out(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - auto outputSize = formatCastOfSelf.sizes(); - OpPreparation::CheckOut( - {self}, - result, - ACL_FORMAT_ND, - result.scalar_type(), - outputSize); - - le_out_npu_nocheck(formatCastOfSelf, other, result); - return result; -} - -at::Tensor& le_out_npu_nocheck(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - auto unified_result = OpPreparation::comparison_op_check(result, self, other, true); - OpCommand cmd; - cmd.Name("LessEqual") - .Expect(unified_result) - .Input(self) - .Input(other) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::le_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); - auto outputSize = broadcast_ops_npu_output_size(formatCastOfSelf, formatCastOfOther); - - OpPreparation::CheckOut( - {self}, - result, - ACL_FORMAT_ND, - result.scalar_type(), - outputSize); - - le_out_npu_nocheck(formatCastOfSelf, formatCastOfOther, result); - return result; -} - -at::Tensor NPUNativeFunctions::le(const at::Tensor& self, at::Scalar other) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - formatCastOfSelf.sizes(), - formatCastOfSelf.options().dtype(at::kBool), - ACL_FORMAT_ND); - le_out_npu_nocheck(formatCastOfSelf, other, result); - return result; -} - -at::Tensor NPUNativeFunctions::le(const at::Tensor& self, const at::Tensor& other) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); - - auto outputSize = broadcast_ops_npu_output_size(formatCastOfSelf, formatCastOfOther); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - formatCastOfSelf.options().dtype(at::kBool), - ACL_FORMAT_ND); - - le_out_npu_nocheck(formatCastOfSelf, formatCastOfOther, result); - return result; -} - -at::Tensor& NPUNativeFunctions::le_(at::Tensor& self, at::Scalar other) { - OpPreparation::CastBackToOriFormat(self); - OpPreparation::CheckMemory({self}, {self}); - at::Tensor result = OpPreparation::ApplyTensor( - self, - self.options().dtype(at::ScalarType::Byte)); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - le_out_npu_nocheck(contiguousSelf, other, result); - } else { - le_out_npu_nocheck(self, other, result); - } - self.copy_(result); - return self; -} - -at::Tensor& NPUNativeFunctions::le_(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CastBackToOriFormat(self); - at::Tensor ori_other = OpPreparation::CastBackToOriFormat(other); - OpPreparation::CheckMemory({self, ori_other}, {self}); - at::Tensor result = OpPreparation::ApplyTensor( - self, - self.options().dtype(at::ScalarType::Byte)); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - le_out_npu_nocheck(contiguousSelf, ori_other, result); - } else { - le_out_npu_nocheck(self, ori_other, result); - } - self.copy_(result); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LeakyReluBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/LeakyReluBackwardKernelNpu.cpp deleted file mode 100644 index 37c664e131..0000000000 --- a/torch_npu/csrc/aten/ops/LeakyReluBackwardKernelNpu.cpp +++ /dev/null @@ -1,50 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor leaky_relu_backward_out_npu( - at::Tensor result, - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar negval, - bool is_result) { - OpCommand cmd; - cmd.Name("LeakyReluGrad") - .Input(grad_output) - .Input(self) - .Output(result) - .Attr("negative_slope", negval) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::leaky_relu_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar negval, - bool is_result) { - at::Tensor result = OpPreparation::ApplyTensor(self); - leaky_relu_backward_out_npu(result, grad_output, self, negval, is_result); - return result; - -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LeakyReluKernelNpu.cpp b/torch_npu/csrc/aten/ops/LeakyReluKernelNpu.cpp deleted file mode 100644 index b42a6e0ea8..0000000000 --- a/torch_npu/csrc/aten/ops/LeakyReluKernelNpu.cpp +++ /dev/null @@ -1,65 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& leaky_relu_out_nocheck(at::Tensor& result, const at::Tensor& self, at::Scalar negval) { - OpCommand cmd; - cmd.Name("LeakyRelu") - .Input(self) - .Output(result) - .Attr("negative_slope", negval) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::leaky_relu_out(const at::Tensor& self, at::Scalar negval, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor newResult = leaky_relu_out_nocheck(contiguousResult, self, negval); - NpuUtils::format_fresh_view(result, newResult); - } else { - leaky_relu_out_nocheck(result, self, negval); - } - - return result; -} - -at::Tensor NPUNativeFunctions::leaky_relu(const at::Tensor& self, at::Scalar negval) { - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - leaky_relu_out_nocheck(result, self, negval); - return result; -} - -at::Tensor& NPUNativeFunctions::leaky_relu_(at::Tensor& self, at::Scalar neg_val) { - NPUNativeFunctions::leaky_relu_out(self, neg_val, self); - - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LerpKernelNpu.cpp b/torch_npu/csrc/aten/ops/LerpKernelNpu.cpp deleted file mode 100644 index 7757fc931e..0000000000 --- a/torch_npu/csrc/aten/ops/LerpKernelNpu.cpp +++ /dev/null @@ -1,118 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& lerp_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& end, - const at::Tensor& weight, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("Lerp") - .Input(self) - .Input(end) - .Input(weight) - .Output(result) - .Run(); - return result; -} - -at::Tensor& lerp_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& end, - at::Scalar weight, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("Lerp") - .Input(self) - .Input(end) - .Input(weight, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::lerp_out( - const at::Tensor& self, - const at::Tensor& end, - const at::Tensor& weight, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - lerp_out_npu_nocheck(self, end, weight, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - lerp_out_npu_nocheck(self, end, weight, result); - } - return result; -} - -at::Tensor& NPUNativeFunctions::lerp_out( - const at::Tensor& self, - const at::Tensor& end, - at::Scalar weight, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - lerp_out_npu_nocheck(self, end, weight, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - lerp_out_npu_nocheck(self, end, weight, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::lerp(const at::Tensor& start, const at::Tensor& end, const at::Tensor& weight) { - at::Tensor result = OpPreparation::ApplyTensor(start); - lerp_out_npu_nocheck(start, end, weight, result); - return result; -} - -at::Tensor NPUNativeFunctions::lerp(const at::Tensor& start, const at::Tensor& end, at::Scalar weight) { - at::Tensor result = OpPreparation::ApplyTensor(start); - lerp_out_npu_nocheck(start, end, weight, result); - return result; -} - -at::Tensor& NPUNativeFunctions::lerp_(at::Tensor& self, const at::Tensor& end, const at::Tensor& weight) { - OpPreparation::CheckMemory({self, end, weight}, {self}); - lerp_out(self, end, weight, self); - return self; -} - -at::Tensor& NPUNativeFunctions::lerp_(at::Tensor& self, const at::Tensor& end, at::Scalar weight) { - OpPreparation::CheckMemory({self, end}, {self}); - lerp_out(self, end, weight, self); - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LinearKernelNpu.cpp b/torch_npu/csrc/aten/ops/LinearKernelNpu.cpp index ffe290ab1e..d03b8e0a3a 100644 --- a/torch_npu/csrc/aten/ops/LinearKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/LinearKernelNpu.cpp @@ -18,7 +18,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -70,7 +70,7 @@ at::Tensor linear_backward_out_npu( return result; } -tuple NPUNativeFunctions::npu_linear_backward( +tuple XLANativeFunctions::npu_linear_backward( const at::Tensor& grad, const at::Tensor& input, const at::Tensor& weight) { @@ -88,7 +88,7 @@ tuple NPUNativeFunctions::npu_linear_backward( linear_backward_out_npu(weightGrad, grad, input, true, false); } else { at::Tensor gradFormatcast = OpPreparation::ApplyTensor(grad, grad.sizes()); - gradFormatcast = NPUNativeFunctions::npu_format_cast(grad, CalcuOpUtil::get_tensor_npu_format(weight)); + gradFormatcast = XLANativeFunctions::npu_format_cast(grad, CalcuOpUtil::get_tensor_npu_format(weight)); linear_backward_out_npu(inputGrad, gradFormatcast, weight, false, false); linear_backward_out_npu(weightGrad, gradFormatcast, input, true, false); } @@ -116,7 +116,7 @@ public: auto input = saved[0]; auto weight = saved[1]; - tuple result = NPUNativeFunctions::npu_linear_backward(grad_outputs[0], input, weight); + tuple result = XLANativeFunctions::npu_linear_backward(grad_outputs[0], input, weight); tensor_list output; if (bias_has_value) { @@ -132,7 +132,7 @@ public: } }; -at::Tensor NPUNativeFunctions::npu_linear(const at::Tensor& input, +at::Tensor XLANativeFunctions::npu_linear(const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias_opt) { return NPULinearFunction::apply(input, weight, bias_opt); diff --git a/torch_npu/csrc/aten/ops/LinspaceKernelNpu.cpp b/torch_npu/csrc/aten/ops/LinspaceKernelNpu.cpp deleted file mode 100644 index 9bbe4f603a..0000000000 --- a/torch_npu/csrc/aten/ops/LinspaceKernelNpu.cpp +++ /dev/null @@ -1,97 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor linspace_assist(int64_t steps) { - c10::SmallVector assist; - assist.resize(steps); - - for (int64_t i = 0; i < steps; i++) { - assist[i] = (float)(i); - } - at::Tensor assistTensor = - at::from_blob(assist.data(), {steps}, dtype(at::ScalarType::Float)); - return CalcuOpUtil::copy_tensor_host_to_device(assistTensor); -} - -at::Tensor& NPUNativeFunctions::linspace_out(at::Scalar start, at::Scalar end, c10::optional step, at::Tensor& result) { - int64_t steps = step.has_value()? step.value():-65530; - TORCH_CHECK(steps >= 0, "number of steps must be non-negative"); - - if (result.numel() != steps) { - result.resize_({steps}); - } - at::Tensor r = result.is_contiguous() ? result : result.contiguous(); - r = r.to(at::kFloat); - if(steps == 0){ - // skip - } else if (steps == 1) { - r.fill_(start); - } else { - c10::SmallVector sizeVec = {steps}; - OpCommand cmd; - cmd.Name("LinSpace") - .Input(start, at::ScalarType::Float) - .Input(end, at::ScalarType::Float) - .Input(sizeVec, at::ScalarType::Int) - .Output(r) - .Run(); - } - - if(r.dtype() != result.dtype()) { - r = r.to(result.dtype()); - } - - return result.copy_(r); -} - -at::Tensor NPUNativeFunctions::linspace(at::Scalar start, at::Scalar end, - c10::optional step, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt -) { - int64_t steps = step.has_value()? step.value():-65530; - TORCH_CHECK(steps >= 0, "number of steps must be non-negative"); - - auto device = device_or_default(device_opt); - at::TensorOptions option; - option = option.dtype(dtype_opt) - .layout(layout_opt) - .device(device) - .pinned_memory(pin_memory_opt); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat({steps}, option, ACL_FORMAT_ND); - at::Tensor resultCast = result.to(at::kFloat); - - // calculate the output result of the NPU - NPUNativeFunctions::linspace_out(start, end, steps, resultCast); - - if(option.dtype() != resultCast.dtype()) { - resultCast = resultCast.to(option.dtype()); - } - - return resultCast; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/Log10KernelNpu.cpp b/torch_npu/csrc/aten/ops/Log10KernelNpu.cpp deleted file mode 100644 index b4e69e64b3..0000000000 --- a/torch_npu/csrc/aten/ops/Log10KernelNpu.cpp +++ /dev/null @@ -1,57 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& log10_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Log") - .Input(self) - .Output(result) - .Attr("base", (float)10.0) - .Attr("scale", (float)1.0) - .Attr("shift", (float)0.0) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::log10_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){log10_out_npu_nocheck(self, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::log10(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - log10_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::log10_(at::Tensor& self) { - log10_out(self, self); - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/Log1pKernelNpu.cpp b/torch_npu/csrc/aten/ops/Log1pKernelNpu.cpp deleted file mode 100644 index 33ea209f16..0000000000 --- a/torch_npu/csrc/aten/ops/Log1pKernelNpu.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& log1p_out_npu_nocheck(const at::Tensor& self, at::Tensor& result){ - OpCommand cmd; - cmd.Name("Log1p") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::log1p_out(const at::Tensor& self, at::Tensor& result){ - OpPreparation::CheckOut( - {self}, - result, - self); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){log1p_out_npu_nocheck(self, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::log1p(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - log1p_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::log1p_(at::Tensor& self) { - log1p_out(self, self); - return self; -} -}} diff --git a/torch_npu/csrc/aten/ops/Log2KernelNpu.cpp b/torch_npu/csrc/aten/ops/Log2KernelNpu.cpp deleted file mode 100644 index 0633d0743f..0000000000 --- a/torch_npu/csrc/aten/ops/Log2KernelNpu.cpp +++ /dev/null @@ -1,64 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& log2_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Log") - .Input(self) - .Output(result) - .Attr("base", (float)2.0) - .Attr("scale", (float)1.0) - .Attr("shift", (float)0.0) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::log2_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - log2_out_npu_nocheck(self, result); - - return result; -} - -at::Tensor NPUNativeFunctions::log2(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - log2_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::log2_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = log2_out_npu_nocheck(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - log2_out_npu_nocheck(self, self); - } - - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LogAddExp2KernelNpu.cpp b/torch_npu/csrc/aten/ops/LogAddExp2KernelNpu.cpp deleted file mode 100644 index 33fb91b5f3..0000000000 --- a/torch_npu/csrc/aten/ops/LogAddExp2KernelNpu.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) 2022, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& logaddexp2_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - at::Tensor self_exp2 = OpPreparation::ApplyTensor(self); - at::Tensor other_exp2 = OpPreparation::ApplyTensor(self); - - at::Scalar base(2); - - OpCommand cmd_exp2_1, cmd_exp2_2, cmd_add, cmd_log; - cmd_exp2_1.Name("Pow") - .Input(base, self.scalar_type()) - .Input(self) - .Output(self_exp2) - .Run(); - - cmd_exp2_2.Name("Pow") - .Input(base, other.scalar_type()) - .Input(other) - .Output(other_exp2) - .Run(); - - at::Tensor add_result = OpPreparation::ApplyTensor(self); - auto unified_result = - OpPreparation::binary_op_check(add_result, self_exp2, other_exp2, true); - - cmd_add.Name("Add") - .Expect(unified_result) - .Input(self_exp2) - .Input(other_exp2) - .Output(add_result) - .Run(); - - cmd_log.Name("Log") - .Input(add_result) - .Output(result) - .Attr("base", (float)2.0) - .Attr("scale", (float)1.0) - .Attr("shift", (float)0.0) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::logaddexp2_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut({self}, result, self, outputSize); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - logaddexp2_out_npu_nocheck(self, other, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - logaddexp2_out_npu_nocheck(self, other, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::logaddexp2( - const at::Tensor& self, - const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - logaddexp2_out_npu_nocheck(self, other, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LogAddExpKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogAddExpKernelNpu.cpp deleted file mode 100644 index 61e7eeb506..0000000000 --- a/torch_npu/csrc/aten/ops/LogAddExpKernelNpu.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2022, Huawei Technologies.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. - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -namespace at_npu { -namespace native { - -at::Tensor& logaddexp_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - at::Tensor self_exp = OpPreparation::ApplyTensor(self); - at::Tensor other_exp = OpPreparation::ApplyTensor(self); - - OpCommand cmd_exp_1, cmd_exp_2, cmd_add, cmd_log; - cmd_exp_1.Name("Exp") - .Input(self) - .Output(self_exp) - .Run(); - - cmd_exp_2.Name("Exp") - .Input(other) - .Output(other_exp) - .Run(); - - at::Tensor add_result = OpPreparation::ApplyTensor(self); - auto unified_result = - OpPreparation::binary_op_check(add_result, self_exp, other_exp, true); - - cmd_add.Name("Add") - .Expect(unified_result) - .Input(self_exp) - .Input(other_exp) - .Output(add_result) - .Run(); - - cmd_log.Name("Log") - .Input(add_result) - .Output(result) - .Attr("base", (float)-1) - .Attr("scale", (float)1) - .Attr("shift", (float)0) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::logaddexp_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut({self, other}, result, self, outputSize); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - logaddexp_out_npu_nocheck(self, other, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - logaddexp_out_npu_nocheck(self, other, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::logaddexp( - const at::Tensor& self, - const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - logaddexp_out_npu_nocheck(self, other, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LogKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogKernelNpu.cpp deleted file mode 100644 index 5ecb403c68..0000000000 --- a/torch_npu/csrc/aten/ops/LogKernelNpu.cpp +++ /dev/null @@ -1,72 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -namespace { - -at::Tensor& log_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Log") - .Input(self) - .Output(result) - .Attr("base", (float)-1) - .Attr("scale", (float)1) - .Attr("shift", (float)0) - .Run(); - - return result; -} - -} // namespace - -at::Tensor& NPUNativeFunctions::log_out(const at::Tensor& self, at::Tensor& result) { - if (!result.is_same(self)) { - OpPreparation::CheckOut( - {self}, - result, - ACL_FORMAT_ND, - self.scalar_type(), - self.sizes()); - } - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){log_out_npu_nocheck(result, self);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::log(const at::Tensor& self) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - - // calculate the output result of the NPU - log_out_npu_nocheck(result, self); - - return result; -} - -at::Tensor& NPUNativeFunctions::log_(at::Tensor& self) { - NPUNativeFunctions::log_out(self, self); - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LogSigmoidBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogSigmoidBackwardKernelNpu.cpp deleted file mode 100644 index 8f6ab4c337..0000000000 --- a/torch_npu/csrc/aten/ops/LogSigmoidBackwardKernelNpu.cpp +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::log_sigmoid_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& buffer, - at::Tensor& grad_input) { - OpPreparation::CheckMemory({grad_output, self, buffer}, {grad_input}); - OpCommand cmd; - cmd.Name("LogSigmoidGrad") - .Input(grad_output) - .Input(self) - .Output(grad_input) - .Run(); - return grad_input; -} - -at::Tensor NPUNativeFunctions::log_sigmoid_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& buffer) { - // construct the output tensor of the NPU - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output); - // calculate the output result of the NPU - log_sigmoid_backward_out(grad_output, self, buffer, grad_input); - - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LogSigmoidKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogSigmoidKernelNpu.cpp deleted file mode 100644 index 0deb27b73d..0000000000 --- a/torch_npu/csrc/aten/ops/LogSigmoidKernelNpu.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple NPUNativeFunctions::log_sigmoid_forward_out( - const at::Tensor& self, - at::Tensor& output, - at::Tensor& buffer) { - OpCommand cmd; - cmd.Name("LogSigmoid") - .Input(self) - .Output(output) - .Run(); - return std::tie(output, buffer); -} - -tuple NPUNativeFunctions::log_sigmoid_forward(const at::Tensor& self) { - at::Tensor output = OpPreparation::ApplyTensor(self); - at::Tensor buffer = OpPreparation::ApplyTensorWithSizes({0}, self.options()); - // calculate the output result of the NPU - log_sigmoid_forward_out(self, output, buffer); - return tuple(output, buffer); -} - -at::Tensor& NPUNativeFunctions::log_sigmoid_out(const at::Tensor& self, at::Tensor& result) { - at::Tensor buffer = OpPreparation::ApplyTensorWithSizes({0}, self.options()); - return std::get<0>(at::log_sigmoid_forward_out(result, buffer, self)); -} - -at::Tensor NPUNativeFunctions::log_sigmoid(const at::Tensor& self) { - return std::get<0>(at::log_sigmoid_forward(self)); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LogSoftmaxBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogSoftmaxBackwardKernelNpu.cpp index de4f300b59..d7442f4ee2 100644 --- a/torch_npu/csrc/aten/ops/LogSoftmaxBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/LogSoftmaxBackwardKernelNpu.cpp @@ -18,16 +18,16 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor NPUNativeFunctions::_log_softmax_backward_data( +at::Tensor XLANativeFunctions::_log_softmax_backward_data( const at::Tensor& grad_output, const at::Tensor& output, int64_t dim, - const at::Tensor& self) { + at::ScalarType input_dtype) { c10::SmallVector dimList = {dim}; at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output); diff --git a/torch_npu/csrc/aten/ops/LogSoftmaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogSoftmaxKernelNpu.cpp index 654fee8794..80218afd20 100644 --- a/torch_npu/csrc/aten/ops/LogSoftmaxKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/LogSoftmaxKernelNpu.cpp @@ -20,7 +20,7 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -63,7 +63,7 @@ at::Tensor log_softmax_nocheck( } } // namespace -at::Tensor NPUNativeFunctions::log_softmax( +at::Tensor XLANativeFunctions::log_softmax( const at::Tensor& self, int64_t dim, c10::optional dtype) { @@ -76,14 +76,14 @@ at::Tensor NPUNativeFunctions::log_softmax( return at::_log_softmax(self.toType(dstType), dim, false); } -at::Tensor NPUNativeFunctions::log_softmax( +at::Tensor XLANativeFunctions::log_softmax( const at::Tensor& self, at::Dimname dim, c10::optional dtype) { - return NPUNativeFunctions::log_softmax(self, dimname_to_position(self, dim), dtype); + return XLANativeFunctions::log_softmax(self, dimname_to_position(self, dim), dtype); } -at::Tensor NPUNativeFunctions::_log_softmax(const at::Tensor& self, int64_t dim, bool half_to_float) { +at::Tensor XLANativeFunctions::_log_softmax(const at::Tensor& self, int64_t dim, bool half_to_float) { // construct the output tensor of the NPU at::Tensor result; if (half_to_float) { diff --git a/torch_npu/csrc/aten/ops/LogSpaceKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogSpaceKernelNpu.cpp deleted file mode 100644 index 8ec2c51e0b..0000000000 --- a/torch_npu/csrc/aten/ops/LogSpaceKernelNpu.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& logspace_out_npu_nocheck( - at::Scalar start, - at::Scalar end, - int64_t steps, - double base, - at::Tensor& result) { - if (steps < 0){ - TORCH_CHECK("please input steps > 0"); - } - if (base <= 0) { - printf("if base<=0, please input intenger start, end, (end-start)/(steps-1)"); - } - at::Tensor inputs; - if (result.scalar_type() == at::ScalarType::Half) { - inputs = NPUNativeFunctions::npu_dtype_cast(at::arange(0, steps, at::device(at_npu::key::NativeDeviceType)), at::kHalf); - } else if (result.scalar_type() == at::ScalarType::Float) { - inputs = at::arange(0, steps, at::device(at_npu::key::NativeDeviceType).dtype(at::kFloat)); - } - int64_t dtype = 0; - if (result.scalar_type() == at::ScalarType::Half) { - dtype = 0; - } else if (result.scalar_type() == at::ScalarType::Float) { - dtype = 1; - } else { - TORCH_CHECK("only support float32 and float16"); - } - OpCommand cmd; - cmd.Name("LogSpaceD") - .Input(inputs) - .Output(result) - .Attr("start", start) - .Attr("end", end) - .Attr("steps", steps) - .Attr("base", static_cast(base)) - .Attr("dtype", dtype) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::logspace_out( - at::Scalar start, - at::Scalar end, - c10::optional steps_opt, - double base, - at::Tensor& result) { - int64_t steps = steps_opt.value(); - OpPreparation::CheckOut( - { }, - result, - ACL_FORMAT_ND, - result.scalar_type(), - {steps}); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({},{result}) - .Func([&start, &end, &steps, &base](at::Tensor& result) - {logspace_out_npu_nocheck(start, end, steps, base, result);}) - .Call(result); - return result; -} - -at::Tensor NPUNativeFunctions::logspace( - at::Scalar start, - at::Scalar end, - c10::optional steps_opt, - double base, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - auto device = device_or_default(device_opt); - int64_t steps = steps_opt.value(); - at::TensorOptions options; - options = options.dtype(dtype_opt) - .layout(layout_opt) - .device(device) - .pinned_memory(pin_memory_opt); - at::Tensor result = OpPreparation::ApplyTensorWithFormat({steps}, options, ACL_FORMAT_ND); - return logspace_out_npu_nocheck(start, end, steps, base, result); -} -} -} diff --git a/torch_npu/csrc/aten/ops/LogSumExpKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogSumExpKernelNpu.cpp deleted file mode 100644 index a14ddfbb4a..0000000000 --- a/torch_npu/csrc/aten/ops/LogSumExpKernelNpu.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector logsumexp_npu_output_size( - const at::Tensor& self, - at::IntArrayRef dims, - bool keepdim) { - return reduce_ops_npu_output_size(self, dims, keepdim); -} - -at::Tensor& logsumexp_out_nocheck(const at::Tensor& self, at::IntArrayRef dims, bool keepdim, at::Tensor& result) { - return at::native::logsumexp_out(result, self, dims, keepdim); -} - -at::Tensor& NPUNativeFunctions::logsumexp_out(const at::Tensor& self, at::DimnameList dims, bool keepdim, at::Tensor& result) { - return logsumexp_out(self, dimnames_to_positions(self, dims), keepdim, result); -} - -at::Tensor& NPUNativeFunctions::logsumexp_out(const at::Tensor& self, at::IntArrayRef dims, bool keepdim, at::Tensor& result) { - auto outputSize = logsumexp_npu_output_size(self, dims, keepdim); - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - return logsumexp_out_nocheck(self, dims, keepdim, result); -} - -at::Tensor NPUNativeFunctions::logsumexp(const at::Tensor& self, at::IntArrayRef dims, bool keepdim) { - auto outputSize = logsumexp_npu_output_size(self, dims, keepdim); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - return logsumexp_out_nocheck(self, dims, keepdim, result); -} - -at::Tensor NPUNativeFunctions::logsumexp(const at::Tensor& self, at::DimnameList dims, bool keepdim) { - return logsumexp(self, dimnames_to_positions(self, dims), keepdim); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/LogicalAndKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogicalAndKernelNpu.cpp deleted file mode 100644 index 4b50920f47..0000000000 --- a/torch_npu/csrc/aten/ops/LogicalAndKernelNpu.cpp +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -namespace at_npu { -namespace native { - -at::Tensor& logical_and_out_npu_nocheck( - const at::Tensor& self, - const at::Scalar other, - at::Tensor& result) { - auto selfCopy = (self.dtype() == at::kBool) ? - self : NPUNativeFunctions::npu_dtype_cast(self, at::kBool); - OpCommand cmd; - cmd.Name("LogicalAnd") - .Input(selfCopy) - .Input(other, selfCopy.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& logical_and_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - if (self.dim() == 0) { - logical_and_out_npu_nocheck(other, self.item(), result); - } else if (other.dim() == 0) { - logical_and_out_npu_nocheck(self, other.item(), result); - } else { - auto selfCopy = (self.dtype() == at::kBool) ? - self : NPUNativeFunctions::npu_dtype_cast(self, at::kBool); - auto otherCopy = (other.dtype() == at::kBool) ? - other : NPUNativeFunctions::npu_dtype_cast(other, at::kBool); - - OpCommand cmd; - cmd.Name("LogicalAnd") - .Input(selfCopy) - .Input(otherCopy) - .Output(result) - .Run(); - } - return result; -} - -at::Tensor& NPUNativeFunctions::logical_and_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - result.scalar_type(), - outputSize); - if (NpuUtils::check_match(&result) && (result.dtype() == at::kBool)) { - logical_and_out_npu_nocheck(self, other, result); - } else { - auto resultCopy = OpPreparation::ApplyTensorWithSizes( - outputSize, self.options().dtype(at::kBool)); - logical_and_out_npu_nocheck(self, other, resultCopy); - resultCopy = NPUNativeFunctions::npu_dtype_cast(resultCopy, self.scalar_type()); - NpuUtils::format_fresh_view(result, resultCopy); - } - return result; -} - -at::Tensor NPUNativeFunctions::logical_and(const at::Tensor& self, const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options().dtype(at::kBool), - CalcuOpUtil::get_tensor_npu_format(self)); - logical_and_out_npu_nocheck(self, other, result); - return result; -} - -at::Tensor& NPUNativeFunctions::logical_and_(at::Tensor& self, const at::Tensor& other) { - TORCH_CHECK( - self.dtype() == other.dtype(), - "Expected object of scalar type ", self.dtype(), - " but got scalar type ", other.dtype(), " for argument 'other'"); - OpPreparation::CheckMemory({self, other}, {self}); - logical_and_out(self, other, self); - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LogicalNotKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogicalNotKernelNpu.cpp deleted file mode 100644 index a7c2b43910..0000000000 --- a/torch_npu/csrc/aten/ops/LogicalNotKernelNpu.cpp +++ /dev/null @@ -1,70 +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. - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -namespace at_npu { -namespace native { - -at::Tensor& logical_not_out_npu_nocheck( - const at::Tensor& self, - at::Tensor& result) { - at::ScalarType src_type = self.scalar_type(); - at::Tensor selfCast = self; - if (src_type != at::ScalarType::Bool) { - selfCast = NPUNativeFunctions::npu_dtype_cast(self, at::kBool); - result = NPUNativeFunctions::npu_dtype_cast(result, at::kBool); - } - OpCommand cmd; - cmd.Name("LogicalNot") - .Input(selfCast) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::logical_not_out(const at::Tensor& self, at::Tensor& result) { - auto resultDtype = result.scalar_type(); - OpPreparation::CheckOut( - {self}, - result, - ACL_FORMAT_NCHW, - resultDtype, - self.sizes()); - OpPipeWithDefinedOut pipe; - result = pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){logical_not_out_npu_nocheck(self, result);}) - .Call(result); - result = NPUNativeFunctions::npu_dtype_cast(result, resultDtype); - return result; -} - -at::Tensor NPUNativeFunctions::logical_not(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - self.sizes(), - self.options().dtype(at::kBool), - ACL_FORMAT_NCHW); - logical_not_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::logical_not_(at::Tensor& self) { - logical_not_out(self, self); - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LogicalOrKernelNpu.cpp b/torch_npu/csrc/aten/ops/LogicalOrKernelNpu.cpp deleted file mode 100644 index c31ecb3d01..0000000000 --- a/torch_npu/csrc/aten/ops/LogicalOrKernelNpu.cpp +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -namespace at_npu { -namespace native { - -at::Tensor& logical_or_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("LogicalOr") - .Input(self) - .Input(other) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::logical_or_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - result.scalar_type(), - outputSize); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - logical_or_out_npu_nocheck(self, other, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - logical_or_out_npu_nocheck(self, other, result); - } - return result; -} - -at::Tensor NPUNativeFunctions::logical_or(const at::Tensor& self, const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - logical_or_out_npu_nocheck(self, other, result); - result = NPUNativeFunctions::npu_dtype_cast(result, at::kBool); - return result; -} - -at::Tensor& NPUNativeFunctions::logical_or_(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other},{self}); - logical_or_out(self, other, self); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LstmKernelNpu.cpp b/torch_npu/csrc/aten/ops/LstmKernelNpu.cpp deleted file mode 100644 index 3b9af150a3..0000000000 --- a/torch_npu/csrc/aten/ops/LstmKernelNpu.cpp +++ /dev/null @@ -1,855 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -std::vector npu_lstm_npu( - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& bias, - const at::Tensor& seqMask, - const at::Tensor& h, - const at::Tensor& c, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first, - bool flagSeq, - bool flagDirection) { - // calculate the output size - int64_t numStep = input.size(0); - int64_t batchSize = input.size(1); - int64_t hiddenSize = bias.size(0) / 4; - - c10::SmallVector outputSize = {numStep, batchSize, hiddenSize}; - - // construct the output tensor of the NPU - at::Tensor yOutput = OpPreparation::ApplyTensor(input, outputSize); - at::Tensor hOutput = OpPreparation::ApplyTensor(input, outputSize); - at::Tensor cOutput = OpPreparation::ApplyTensor(input, outputSize); - at::Tensor iOutput = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_FRACTAL_NZ); - at::Tensor jOutput = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_FRACTAL_NZ); - at::Tensor fOutput = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_FRACTAL_NZ); - at::Tensor oOutput = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_FRACTAL_NZ); - at::Tensor tanhc = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_FRACTAL_NZ); - - string direction = flagDirection? "REDIRECTIONAL" : "UNIDIRECTIONAL"; - OpCommand cmd; - cmd.Name("DynamicRNN") - .Input(input, "x") - .Input(weight, "w") - .Input(bias, "b"); - - // if input is PackSequence, seqMask is not None, Otherwise, it is None. - if (!flagSeq){ - cmd.Input(); - } else{ - cmd.Input(seqMask, "seq_length"); - } - cmd.Input(h, "init_h") - .Input(c, "init_c") - .Output(yOutput) - .Output(hOutput) - .Output(cOutput) - .Output(iOutput) - .Output(jOutput) - .Output(fOutput) - .Output(oOutput) - .Output(tanhc) - .Attr("cell_type", (string)"LSTM") - .Attr("direction", direction) - .Attr("cell_depth", (int64_t)1) - .Attr("use_peephole", (bool)false) - .Attr("keep_prob", (float)1.0) - .Attr("cell_clip", (float)-1.0) - .Attr("num_proj", (int64_t)0) - .Attr("time_major", (bool)true) - .Attr("activation", (string)"tanh") - .Attr("forget_bias", (float)0.0) - .Attr("is_training", train) - .Run(); - tensor_list results = {yOutput, hOutput, cOutput, iOutput, jOutput, fOutput, oOutput, tanhc}; - return results; -} - -tuple get_wb_single_layer_direc( - const at::Tensor& input, - at::TensorList params, - bool hasBiases) { - // get weight - at::Tensor ihWeight = params[0]; - at::Tensor hhWeight = params[1]; - - at::Tensor weight = at::cat({ihWeight, hhWeight}, 1).t().to(input.dtype()); - - // get bias - at::Tensor bias = at::zeros(weight.size(1), weight.options()); - if (hasBiases) { - bias = at::add(params[2], params[3]).to(input.dtype()); - } - return std::tie(weight, bias); -} - -tuple get_wb_double_layer_or_bidirec( - const at::Tensor& input, - at::TensorList params, - bool hasBiases) { - at::Tensor weight; - at::Tensor bias; - if (hasBiases) { - weight = at::cat({params[4], params[5]}, 1).t().to(input.dtype()); - bias = at::add(params[6], params[7]).to(input.dtype()); - } else { - weight = at::cat({params[2], params[3]}, 1).t().to(input.dtype()); - bias = at::zeros(weight.size(1), weight.options()); - } - return std::tie(weight, bias); -} - -tuple lstm_single_layer_direc_npu( - const at::Tensor& input, - at::TensorList hx, - at::TensorList params, - bool hasBiases, - int64_t numLayers, - double dropout, - bool train, - bool bidirectional, - bool batchFirst, - bool direction) { - int64_t numStep = input.size(0); - - // get weight - at::Tensor ihWeight = params[0]; - at::Tensor hhWeight = params[1]; - - at::Tensor weight = at::cat({ihWeight, hhWeight}, 1).t().to(input.dtype()); - - // get bias - at::Tensor bias = at::zeros(weight.size(1), weight.options()); - if (hasBiases) { - bias = at::add(params[2], params[3]).to(input.dtype()); - } - - // get init_h, init_c - at::Tensor h = hx[0]; - at::Tensor c = hx[1]; - - at::Tensor seqMask = at::empty({0}, input.options()); - auto results = NPUNativeFunctions::npu_lstm(input, weight, bias, seqMask, h, c, hasBiases, numLayers, dropout, - train, bidirectional, batchFirst, false, direction); - - // get the last dimension of the T-axis - at::Tensor thOutput = at::unsqueeze(results[1][numStep-1], 0); - at::Tensor tcOutput = at::unsqueeze(results[2][numStep-1], 0); - - return std::tie(results[0], thOutput, tcOutput); -} - -tuple lstm_single_layer_bidirec_npu( - const at::Tensor& input, - at::TensorList hx, - at::TensorList params, - bool hasBiases, - int64_t numLayers, - double dropout, - bool train, - bool bidirectional, - bool batchFirst) { - int64_t numStep = input.size(0); - // get h and c of forward direction - at::Tensor h = hx[0].slice(0, 0, 1); - at::Tensor c = hx[1].slice(0, 0, 1); - - // caculate forward direction, direction of attr is UNIDIRECTIONAL(npu_lstm need add the attr of direction) - auto resultsForward = lstm_single_layer_direc_npu(input, {h, c}, params, hasBiases, - numLayers, dropout, train, bidirectional, batchFirst, false); - - // get w/ b/ h/ c of backward direction - at::Tensor weightBack; - at::Tensor biasBack; - at::Tensor hBack = hx[0].slice(0, 1, 2); - at::Tensor cBack = hx[1].slice(0, 1, 2); - std::tie(weightBack, biasBack) = get_wb_double_layer_or_bidirec(input, params, hasBiases); - - at::Tensor seqMask = at::empty({0}, input.options()); - auto revInputs = at::flip(input, {0}); - - // caculate backward direction, direction of attr is REDIRECTIONAL, - // but the inverse operator does not support the specified direction, - // it is necessary to flip the input and output at the adaptation layer. - auto resultsBackward = NPUNativeFunctions::npu_lstm(revInputs, weightBack, biasBack, seqMask, hBack, cBack, - hasBiases, numLayers, dropout, train, bidirectional, batchFirst, false, false); - - // get the first dimension of the T-axis when caculate reverse direction - at::Tensor revY = at::flip(resultsBackward[0],{0}); - at::Tensor th = at::flip(resultsBackward[1],{0}); - at::Tensor tc = at::flip(resultsBackward[2],{0}); - at::Tensor thOutput = at::unsqueeze(th[0], 0); - at::Tensor tcOutput = at::unsqueeze(tc[0], 0); - - at::Tensor y = at::cat({std::get<0>(resultsForward), revY}, 2); - at::Tensor hOut = at::cat({std::get<1>(resultsForward), thOutput}, 0); - at::Tensor cOut = at::cat({std::get<2>(resultsForward), tcOutput}, 0); - - return std::tie(y, hOut, cOut); -} - -tuple lstm_double_layer_direc_npu( - const at::Tensor& input, - at::TensorList hx, - at::TensorList params, - bool hasBiases, - int64_t numLayers, - double dropout, - bool train, - bool bidirectional, - bool batchFirst) { - int64_t numStep = input.size(0); - // get h and c of first layer - at::Tensor h = hx[0].slice(0, 0, 1); - at::Tensor c = hx[1].slice(0, 0, 1); - - // caculate first layer - auto results = lstm_single_layer_direc_npu(input, {h, c}, params, hasBiases, - numLayers, dropout, train, bidirectional, batchFirst, false); - - // get w/ b/ h/ c of twice layer - at::Tensor weight2Layer; - at::Tensor bias2Layer; - at::Tensor h2layer = hx[0].slice(0, 1, 2); - at::Tensor c2layer = hx[1].slice(0, 1, 2); - std::tie(weight2Layer, bias2Layer) = get_wb_double_layer_or_bidirec(input, params, hasBiases); - - // output of first layer as input of second layer - at::Tensor input2Layer = std::get<0>(results); - - at::Tensor seqMask = at::empty({0}, input.options()); - // caculate output of second layer - auto results2Layer = NPUNativeFunctions::npu_lstm(input2Layer, weight2Layer, bias2Layer, seqMask, h2layer, c2layer, - hasBiases, numLayers, dropout, train, bidirectional, batchFirst, false, false); - at::Tensor thOutput2Layer = at::unsqueeze(results2Layer[1][numStep-1], 0); - at::Tensor tcOutput2Layer = at::unsqueeze(results2Layer[2][numStep-1], 0); - at::Tensor th = at::cat({std::get<1>(results), thOutput2Layer}, 0); - at::Tensor tc = at::cat({std::get<2>(results), tcOutput2Layer}, 0); - - return std::tie(results2Layer[0], th, tc); -} - -tuple lstm_double_layer_bidirec_npu( - const at::Tensor& input, - at::TensorList hx, - at::TensorList params, - bool hasBiases, - int64_t numLayers, - double dropout, - bool train, - bool bidirectional, - bool batchFirst) { - int64_t numStep = input.size(0); - - // get h and c of first layer - at::Tensor hL0 = hx[0].slice(0, 0, 2); - at::Tensor cL0 = hx[1].slice(0, 0, 2); - - // get h and c of second layer - at::Tensor hL1 = hx[0].slice(0, 2, 4); - at::Tensor cL1 = hx[1].slice(0, 2, 4); - - // first Single-layer bidirectional LSTM - auto resultsLayer1 = lstm_single_layer_bidirec_npu(input, {hL0, cL0}, params, hasBiases, - numLayers, dropout, train, bidirectional, batchFirst); - - // second Single-layer bidirectional LSTM, output of Single-layer bidirectional LSTM as input of second layer - at::Tensor inputLayer2 = std::get<0>(resultsLayer1); - at::Tensor y; - at::Tensor h; - at::Tensor c; - if(hasBiases){ - std::tie(y, h, c) = lstm_single_layer_bidirec_npu(inputLayer2, {hL1, cL1}, params.slice(8, 8), - hasBiases, numLayers, dropout, train, bidirectional, batchFirst); - } else { - std::tie(y, h, c) = lstm_single_layer_bidirec_npu(inputLayer2, {hL1, cL1}, params.slice(4, 4), - hasBiases, numLayers, dropout, train, bidirectional, batchFirst); - } - - at::Tensor th = at::cat({std::get<1>(resultsLayer1), h}, 0); - at::Tensor tc = at::cat({std::get<2>(resultsLayer1), c}, 0); - return std::tie(y, th, tc); -} - -tuple NPUNativeFunctions::lstm( - const at::Tensor& _input, - at::TensorList hx, - at::TensorList params, - bool hasBiases, - int64_t numLayers, - double dropout, - bool train, - bool bidirectional, - bool batchFirst) { - // The operator of DynamicRnn only supports the T axis as the first axis. - auto input = batchFirst ? _input.transpose(0, 1) : _input; - at::Tensor y; - at::Tensor h; - at::Tensor c; - - // single layer - if(numLayers == 1){ - if(!bidirectional){ - std::tie(y, h, c) = lstm_single_layer_direc_npu(input, hx, params, hasBiases, numLayers, - dropout, train, bidirectional, batchFirst, false); - } else { - std::tie(y, h, c) = lstm_single_layer_bidirec_npu(input, hx, params, hasBiases, numLayers, - dropout, train, bidirectional, batchFirst); - } - } - - // double layer - if(numLayers == 2){ - if(!bidirectional) { - std::tie(y, h, c) = lstm_double_layer_direc_npu(input, hx, params, hasBiases, numLayers, - dropout, train, bidirectional, batchFirst); - } else { - std::tie(y, h, c) = lstm_double_layer_bidirec_npu(input, hx, params, hasBiases, numLayers, - dropout, train, bidirectional, batchFirst); - } - } - - // the Bacth axis of output should be first axis when batchFirst is True! - auto output = batchFirst ? y.transpose(0, 1) : y; - return std::tie(output, h, c); -} - -at::Tensor get_mask(const at::Tensor& input, const at::Tensor& batchSizes, const at::Tensor& h, int64_t maxLen){ - // caculate lengths, but input expected to be sorted - std::vector lens; - for (int64_t i = 0; i < input.size(1); ++i){ - auto batchSizesTemp = at::sub(batchSizes , i); - auto batchSizesBool = at::gt(batchSizesTemp, 0); - auto batchSizesInt = batchSizesBool.to(at::ScalarType::Int); - auto coutLen = at::sum(batchSizesInt, at::ScalarType::Int); - int64_t len = coutLen.item().toInt(); - lens.emplace_back(len); - } - at::Tensor length = CalcuOpUtil::copy_tensor_host_to_device( - at::from_blob(lens.data(), {lens.size()}, at::kLong)); - - c10::SmallVector maskList; - // Slice by T axis - for (int64_t i = 0; i < maxLen; ++i) { - // cacl mask - at::Tensor maskTemp1 = at::gt(length, i); - at::Tensor maskTemp2 = maskTemp1.reshape({1, input.size(1), 1}); - - // mask need to be expanded to (1,batch_size,hidden_size) - at::Tensor maskExpand = maskTemp2.expand({1, input.size(1), h.size(2)}); - maskList.emplace_back(maskExpand); - } - - // mask mast be half - at::Tensor mask = at::cat(maskList, 0).to(at::ScalarType::Half); - - return mask; -} - -std::tuple lstm_onelayer_direc_packseq( - const at::Tensor& data, const at::Tensor& batchSizes, at::TensorList hx, - at::TensorList params, bool hasBiases, - int64_t numLayers, double dropoutP, bool train, bool bidirectional) { - // length of T axis - int64_t t_size = batchSizes.numel(); - if (t_size == 0) { - AT_ERROR("lstm_onelayer_direc_packseq: t_size is zero!"); - } - - // T * B ** - at::Tensor input = data.reshape({t_size, data.size(0)/t_size, data.size(1)}); - - // batch_first is false - bool batchFirst = false; - - // get init_h, init_c - at::Tensor h = hx[0]; - at::Tensor c = hx[1]; - - int64_t numStep = input.size(0); - - // get weight - at::Tensor ihWeight = params[0]; - at::Tensor hhWeight = params[1]; - at::Tensor weight = at::cat({ihWeight, hhWeight}, 1).t().to(input.dtype()); - - // get bias - at::Tensor bias = at::zeros(weight.size(1), weight.options()); - if (hasBiases) { - bias = at::add(params[2], params[3]).to(input.dtype()); - } - - int64_t maxLen = input.size(0); - - at::Tensor mask = get_mask(input, batchSizes, h, maxLen); - auto results = NPUNativeFunctions::npu_lstm(input, weight, bias, mask, h, c, hasBiases, numLayers, - dropoutP, train, bidirectional, false, true, false); - - at::Tensor thOutput = at::unsqueeze(results[1][numStep-1], 0); - at::Tensor tcOutput = at::unsqueeze(results[2][numStep-1], 0); - - return std::tuple(results[0], thOutput, tcOutput); -} - -std::tuple lstm_onelayer_bidirec_packseq( - const at::Tensor& data, const at::Tensor& batchSizes, at::TensorList hx, - at::TensorList params, bool hasBiases, - int64_t numLayers, double dropoutP, bool train, bool bidirectional) { - // length of T axis - int64_t t_size = batchSizes.numel(); - if (t_size == 0) { - AT_ERROR("lstm_onelayer_bidirec_packseq: t_size is zero!"); - } - - // T * B ** - at::Tensor input = data.reshape({t_size, data.size(0)/t_size, data.size(1)}); - - // batch_first is false - bool batchFirst = false; - - // get h and c of forward direction - at::Tensor h = hx[0].slice(0, 0, 1); - at::Tensor c = hx[1].slice(0, 0, 1); - - auto resultsForward = lstm_onelayer_direc_packseq(data, batchSizes, {h, c}, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - - // get w/ b/ h/ c of backward direction - at::Tensor hBack = hx[0].slice(0, 1, 2); - at::Tensor cBack = hx[1].slice(0, 1, 2); - - at::Tensor weightBack; - at::Tensor biasBack; - std::tie(weightBack, biasBack) = get_wb_double_layer_or_bidirec(input, params, hasBiases); - - int64_t maxLen = input.size(0); - - at::Tensor mask = get_mask(input, batchSizes, h, maxLen); - // caculate forward direction, direction of attr is REDIRECTIONAL - auto resultsBackward = NPUNativeFunctions::npu_lstm(input, weightBack, biasBack, mask, hBack, cBack, - hasBiases, numLayers, dropoutP, train, bidirectional, batchFirst, true, true); - - // get the first dimension of the T-axis when caculate reverse direction - at::Tensor thOutput = at::unsqueeze(resultsBackward[1][0], 0); - at::Tensor tcOutput = at::unsqueeze(resultsBackward[2][0], 0); - - at::Tensor y = at::cat({std::get<0>(resultsForward), resultsBackward[0]}, 2); - at::Tensor hOut = at::cat({std::get<1>(resultsForward), thOutput}, 0); - at::Tensor cOut = at::cat({std::get<2>(resultsForward), tcOutput}, 0); - - return std::tie(y, hOut, cOut); -} - -std::tuple lstm_double_layer_direc_packseq( - const at::Tensor& data, const at::Tensor& batchSizes, at::TensorList hx, - at::TensorList params, bool hasBiases, - int64_t numLayers, double dropoutP, bool train, bool bidirectional) { - // length of T axis - int64_t t_size = batchSizes.numel(); - if (t_size == 0) { - AT_ERROR("lstm_double_layer_direc_packseq: t_size is zero!"); - } - - // T * B ** - at::Tensor input = data.reshape({t_size, data.size(0)/t_size, data.size(1)}); - - // batch_first is false - bool batchFirst = false; - - // get h and c of forward direction - at::Tensor h = hx[0].slice(0, 0, 1); - at::Tensor c = hx[1].slice(0, 0, 1); - - int64_t numStep = input.size(0); - - auto results = lstm_onelayer_direc_packseq(data, batchSizes, {h, c}, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - - // get w/ b/ h/ c of twice layer - at::Tensor weight2Layer; - at::Tensor bias2Layer; - at::Tensor h2layer = hx[0].slice(0, 1, 2); - at::Tensor c2layer = hx[1].slice(0, 1, 2); - std::tie(weight2Layer, bias2Layer) = get_wb_double_layer_or_bidirec(input, params, hasBiases); - - int64_t maxLen = input.size(0); - at::Tensor mask = get_mask(input, batchSizes, h, maxLen); - - // output of first layer as input of second layer - at::Tensor input2Layer = std::get<0>(results); - - // caculate output of second layer - auto results2Layer = NPUNativeFunctions::npu_lstm(input2Layer, weight2Layer, bias2Layer, mask, h2layer, c2layer, - hasBiases, numLayers, dropoutP, train, bidirectional, batchFirst, true, false); - at::Tensor thOutput2Layer = at::unsqueeze(results2Layer[1][numStep-1], 0); - at::Tensor tcOutput2Layer = at::unsqueeze(results2Layer[2][numStep-1], 0); - at::Tensor th = at::cat({std::get<1>(results), thOutput2Layer}, 0); - at::Tensor tc = at::cat({std::get<2>(results), tcOutput2Layer}, 0); - - return std::tie(results2Layer[0], th, tc); -} - -std::tuple lstm_double_layer_bidirec_packseq( - const at::Tensor& data, const at::Tensor& batchSizes, at::TensorList hx, - at::TensorList params, bool hasBiases, - int64_t numLayers, double dropoutP, bool train, bool bidirectional) { - // length of T axis - int64_t t_size = batchSizes.numel(); - TORCH_CHECK(t_size > 0, "batchSizes can not be empty."); - - // T * B ** - at::Tensor input = data.reshape({t_size, data.size(0)/t_size, data.size(1)}); - - // batch_first is false - bool batchFirst = false; - - // get h and c of first layer - at::Tensor hL0 = hx[0].slice(0, 0, 2); - at::Tensor cL0 = hx[1].slice(0, 0, 2); - - // get h and c of second layer - at::Tensor hL1 = hx[0].slice(0, 2, 4); - at::Tensor cL1 = hx[1].slice(0, 2, 4); - - // first Single-layer bidirectional LSTM - auto resultsLayer1 = lstm_onelayer_bidirec_packseq(data, batchSizes, {hL0, cL0}, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - - // second Single-layer bidirectional LSTM, output of Single-layer bidirectional LSTM as input of second layer - at::Tensor inputLayer2 = std::get<0>(resultsLayer1); - at::Tensor dataLayer2 = inputLayer2.contiguous().view({-1, inputLayer2.size(2)}); - at::Tensor y; - at::Tensor h; - at::Tensor c; - if(hasBiases){ - std::tie(y, h, c) = lstm_onelayer_bidirec_packseq(dataLayer2, batchSizes, {hL1, cL1}, params.slice(8, 8), - hasBiases, numLayers, dropoutP, train, bidirectional); - } else { - std::tie(y, h, c) = lstm_onelayer_bidirec_packseq(dataLayer2, batchSizes, {hL1, cL1}, params.slice(4, 4), - hasBiases, numLayers, dropoutP, train, bidirectional); - } - - at::Tensor th = at::cat({std::get<1>(resultsLayer1), h}, 0); - at::Tensor tc = at::cat({std::get<2>(resultsLayer1), c}, 0); - return std::tie(y, th, tc); - -} - -std::tuple NPUNativeFunctions::lstm( - const at::Tensor& data, const at::Tensor& batchSizes_, at::TensorList hx, - at::TensorList params, bool hasBiases, - int64_t numLayers, double dropoutP, bool train, bool bidirectional) { - at::Tensor batchSizes = batchSizes_.to("cpu"); - at::Tensor y; - at::Tensor h; - at::Tensor c; - - // single layer - if(numLayers == 1){ - if(!bidirectional){ - std::tie(y, h, c) = lstm_onelayer_direc_packseq(data, batchSizes, hx, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - } else { - std::tie(y, h, c) = lstm_onelayer_bidirec_packseq(data, batchSizes, hx, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - } - } - - // double layer - if(numLayers == 2) { - if(!bidirectional){ - std::tie(y, h, c) = lstm_double_layer_direc_packseq(data, batchSizes, hx, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - } else { - std::tie(y, h, c) = lstm_double_layer_bidirec_packseq(data, batchSizes, hx, params, hasBiases, - numLayers, dropoutP, train, bidirectional); - } - } - return std::tie(y, h, c); -} - -std::tuple lstm_backward_out_npu( - at::Tensor& dw, - at::Tensor& db, - at::Tensor& dx, - at::Tensor& dht, - at::Tensor& dct, - const at::Tensor& x, - const at::Tensor& w, - const at::Tensor& b, - const at::Tensor& init_h, - const at::Tensor& init_c, - const at::Tensor& dy, - const at::Tensor& dh, - const at::Tensor& dc, - const at::Tensor& y, - const at::Tensor& h, - const at::Tensor& c, - const at::Tensor& i, - const at::Tensor& j, - const at::Tensor& f, - const at::Tensor& o, - const at::Tensor& tanhc) { - - at::Tensor seq_length = at::zeros({}, x.options()); - at::Tensor mask = at::zeros({}, x.options().dtype(at::kByte)); - at::Tensor wci = at::zeros({}, x.options()); - at::Tensor wcf = at::zeros({}, x.options()); - at::Tensor wco = at::zeros({}, x.options()); - - OpCommand cmd; - cmd.Name("DynamicRNNGrad") - .Input(x) - .Input(w) - .Input(b) - .Input(y) - .Input(init_h) - .Input(init_c) - .Input(h) - .Input(c) - .Input(dy) - .Input(dh) - .Input(dc) - .Input(i) - .Input(j) - .Input(f) - .Input(o) - .Input(tanhc) - .Input(seq_length) - .Input(mask) - .Input(wci) - .Input(wcf) - .Input(wco) - .Output(dw) - .Output(db) - .Output(dx) - .Output(dht) - .Output(dct) - .Attr("cell_type", "LSTM") - .Attr("direction", "UNIDIRECTIONAL") - .Attr("cell_depth", (int64_t)0) - .Attr("use_peephole", (bool)false) - .Attr("keep_prob", (float)-1.0) - .Attr("cell_clip", (float)-1.0) - .Attr("num_proj", (int64_t)0) - .Attr("time_major", (bool)true) - .Attr("forget_bias", (float)0.0) - .Run(); - - return std::tuple< at::Tensor&, at::Tensor&, at::Tensor&, at::Tensor&, at::Tensor&> {dx, dw, db, dht, dct}; -} - -std::tuple NPUNativeFunctions::npu_lstm_backward( - const c10::optional& grady_opt, - const c10::optional& gradh_opt, - const c10::optional& gradc_opt, - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& bias, - const at::Tensor& init_h, - const at::Tensor& init_c, - const at::Tensor& y, - const at::Tensor& h, - const at::Tensor& c, - const at::Tensor& i, - const at::Tensor& j, - const at::Tensor& f, - const at::Tensor& o, - const at::Tensor& tanhc) { - const at::Tensor& grady = c10::value_or_else(grady_opt, [] {return at::Tensor();}); - const at::Tensor& gradh = c10::value_or_else(gradh_opt, [] {return at::Tensor();}); - const at::Tensor& gradc = c10::value_or_else(gradc_opt, [] {return at::Tensor();}); - - at::Tensor inh = at::squeeze(init_h, 0); - at::Tensor inc = at::squeeze(init_c, 0); - - at::Tensor grad_input = OpPreparation::ApplyTensor(input); - at::Tensor grad_weight = OpPreparation::ApplyTensor(weight); - at::Tensor grad_bias = OpPreparation::ApplyTensor(bias); - at::Tensor grad_ht = OpPreparation::ApplyTensor(init_h); - at::Tensor grad_ct = OpPreparation::ApplyTensor(init_c); - - auto grad_y = grady.defined() ? grady : at::zeros(y.sizes(), y.options()); - auto grad_h = gradh.defined() ? gradh[input.size(0)-1] : at::zeros(inh.sizes(), h.options()); - auto grad_c = gradc.defined() ? gradc[input.size(0)-1] : at::zeros(inc.sizes(), c.options()); - - lstm_backward_out_npu(grad_weight, grad_bias, grad_input, grad_ht, grad_ct, input, weight, - bias, inh, inc, grad_y, grad_h, grad_c, y, h, c, i, j, f, o, tanhc); - - return std::tuple {grad_input, grad_weight, grad_bias, grad_ht, grad_ct}; -} - -class NPULstmFunction : public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& bias, - const at::Tensor& seqMask, - const at::Tensor& h, - const at::Tensor& c, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first, - bool flagSeq, - bool flagDirection) { - at::AutoNonVariableTypeMode g; - auto result = npu_lstm_npu( - input, - weight, - bias, - seqMask, - h, - c, - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first, - flagSeq, - flagDirection); - auto result0 = result[0]; - auto result1 = result[1]; - auto result2 = result[2]; - auto result3 = result[3]; - auto result4 = result[4]; - auto result5 = result[5]; - auto result6 = result[6]; - auto result7 = result[7]; - ctx->save_for_backward({input, - weight, - bias, - h, - c, - result0, - result1, - result2, - result3, - result4, - result5, - result6, - result7}); - return result; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto saved = ctx->get_saved_variables(); - auto input = saved[0]; - auto weight = saved[1]; - auto bias = saved[2]; - auto h = saved[3]; - auto c = saved[4]; - auto result0 = saved[5]; - auto result1 = saved[6]; - auto result2 = saved[7]; - auto result3 = saved[8]; - auto result4 = saved[9]; - auto result5 = saved[10]; - auto result6 = saved[11]; - auto result7 = saved[12]; - - std::tuple result = NPUNativeFunctions::npu_lstm_backward( - grad_outputs[0], - grad_outputs[1], - grad_outputs[2], - input, - weight, - bias, - h, - c, - result0, - result1, - result2, - result3, - result4, - result5, - result6, - result7); - tensor_list output = {std::get<0>(result), - std::get<1>(result), - std::get<2>(result), - at::Tensor(), - std::get<3>(result), - std::get<4>(result), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -std::vector NPUNativeFunctions::npu_lstm( - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& bias, - const at::Tensor& seqMask, - const at::Tensor& h, - const at::Tensor& c, - bool has_biases, - int64_t num_layers, - double dropout, - bool train, - bool bidirectional, - bool batch_first, - bool flagSeq, - bool flagDirection){ - return NPULstmFunction::apply( - input, - weight, - bias, - seqMask, - h, - c, - has_biases, - num_layers, - dropout, - train, - bidirectional, - batch_first, - flagSeq, - flagDirection); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/LtKernelNpu.cpp b/torch_npu/csrc/aten/ops/LtKernelNpu.cpp index 7e93ed3179..438554a9d2 100644 --- a/torch_npu/csrc/aten/ops/LtKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/LtKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -27,8 +27,7 @@ at::Tensor <_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, const at::Tensor selfCast = self; at::Tensor otherCast = other; if (self.dtype() == at::ScalarType::Int || other.dtype() == at::ScalarType::Int || - self.dtype() == at::ScalarType::Bool || other.dtype() == at::ScalarType::Bool || - self.dtype() == at::ScalarType::Long || other.dtype() == at::ScalarType::Long) + self.dtype() == at::ScalarType::Bool || other.dtype() == at::ScalarType::Bool) { selfCast = self.to(at::ScalarType::Float); otherCast = other.to(at::ScalarType::Float); @@ -45,7 +44,7 @@ at::Tensor <_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, const return result; } -at::Tensor &NPUNativeFunctions::lt_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) +at::Tensor &XLANativeFunctions::lt_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -65,8 +64,7 @@ at::Tensor &NPUNativeFunctions::lt_out(const at::Tensor &self, const at::Tensor at::Tensor <_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, at::Scalar other) { at::Tensor selfCast = self; - if (self.dtype() == at::ScalarType::Int || - self.dtype() == at::ScalarType::Long || self.dtype() == at::ScalarType::Bool) + if (self.dtype() == at::ScalarType::Int || self.dtype() == at::ScalarType::Bool) { selfCast = self.to(at::ScalarType::Float); } @@ -80,7 +78,7 @@ at::Tensor <_out_npu_nocheck(at::Tensor &result, const at::Tensor &self, at::S return result; } -at::Tensor &NPUNativeFunctions::lt_out(const at::Tensor &self, at::Scalar other, at::Tensor &result) +at::Tensor &XLANativeFunctions::lt_out(const at::Tensor &self, const at::Scalar& other, at::Tensor &result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); auto outputSize = formatCastOfSelf.sizes(); @@ -95,7 +93,7 @@ at::Tensor &NPUNativeFunctions::lt_out(const at::Tensor &self, at::Scalar other, return result; } -at::Tensor NPUNativeFunctions::lt(const at::Tensor &self, const at::Tensor &other) +at::Tensor XLANativeFunctions::lt(const at::Tensor &self, const at::Tensor &other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -112,7 +110,7 @@ at::Tensor NPUNativeFunctions::lt(const at::Tensor &self, const at::Tensor &othe return result; } -at::Tensor NPUNativeFunctions::lt(const at::Tensor &self, at::Scalar other) +at::Tensor XLANativeFunctions::lt(const at::Tensor &self, const at::Scalar &other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); // calculate the output size @@ -128,7 +126,7 @@ at::Tensor NPUNativeFunctions::lt(const at::Tensor &self, at::Scalar other) return result; } -at::Tensor &NPUNativeFunctions::lt_(at::Tensor &self, const at::Tensor &other) +at::Tensor &XLANativeFunctions::lt_(at::Tensor &self, const at::Tensor &other) { OpPreparation::CastBackToOriFormat(self); OpPreparation::CastBackToOriFormat(other); @@ -157,7 +155,7 @@ at::Tensor &NPUNativeFunctions::lt_(at::Tensor &self, const at::Tensor &other) return self; } -at::Tensor &NPUNativeFunctions::lt_(at::Tensor &self, at::Scalar other) +at::Tensor &XLANativeFunctions::lt_(at::Tensor &self, const at::Scalar &other) { OpPreparation::CastBackToOriFormat(self); c10::SmallVector inputs = {self}; diff --git a/torch_npu/csrc/aten/ops/MaskedFillKernelNpu.cpp b/torch_npu/csrc/aten/ops/MaskedFillKernelNpu.cpp deleted file mode 100644 index 1e714a5a1b..0000000000 --- a/torch_npu/csrc/aten/ops/MaskedFillKernelNpu.cpp +++ /dev/null @@ -1,107 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& masked_fill_out_npu_nocheck(const at::Tensor& self, const at::Tensor& mask, const at::Tensor& value, at::Tensor& result) { - at::Tensor maskBool = mask; - int64_t dimOfSelf = self.dim(); - - /* Avoid the problem that the TBE operator does not support 0-dimensional tensor input */ - if (dimOfSelf == 0) { - self.unsqueeze_(0); - } - - if ((mask.dtype() != at::kBool)) { - maskBool = mask.to(at::kBool); - } - at::Tensor valueTensor = value; - if (value.dtype() != self.dtype()) { - valueTensor = valueTensor.to(self.dtype()); - } - - OpCommand cmd; - cmd.Name("MaskedFill") - .Input(self) - .Input(maskBool) - .Input(valueTensor) - .Output(result) - .Run(); - - if (dimOfSelf == 0) { - result.squeeze_(0); - } - - return result; -} - -at::Tensor& masked_fill_out_npu_nocheck(const at::Tensor& self, const at::Tensor& mask, at::Scalar value, at::Tensor& result) { - at::Tensor maskBool = mask; - int64_t dimOfSelf = self.dim(); - - /* Avoid the problem that the TBE operator does not support 0-dimensional tensor input */ - if (dimOfSelf == 0) { - self.unsqueeze_(0); - } - - if (!(mask.dtype() == at::kBool)) { - maskBool = mask.to(at::kBool); - } - - OpCommand cmd; - cmd.Name("MaskedFill") - .Input(self) - .Input(maskBool) - .Input(value, self.scalar_type()) - .Output(result) - .Run(); - - if (dimOfSelf == 0) { - result.squeeze_(0); - } - return result; -} - -at::Tensor& NPUNativeFunctions::masked_fill_(at::Tensor& self, const at::Tensor& mask, const at::Tensor& value) { - // OpPreparation::CheckMemory({self, mask, value}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = masked_fill_out_npu_nocheck(contiguousSelf, mask, value, contiguousSelf); - self.copy_(result); - } else { - masked_fill_out_npu_nocheck(self, mask, value, self); - } - return self; -} - -at::Tensor& NPUNativeFunctions::masked_fill_(at::Tensor& self, const at::Tensor& mask, at::Scalar value) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = masked_fill_out_npu_nocheck(contiguousSelf, mask, value, contiguousSelf); - self.copy_(result); - } else { - masked_fill_out_npu_nocheck(self, mask, value, self); - } - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/MaskedFillRangeKernelNpu.cpp b/torch_npu/csrc/aten/ops/MaskedFillRangeKernelNpu.cpp deleted file mode 100644 index 4ba56bab85..0000000000 --- a/torch_npu/csrc/aten/ops/MaskedFillRangeKernelNpu.cpp +++ /dev/null @@ -1,74 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -void mask_fill_range_nocheck( - const at::Tensor& self, - const at::Tensor& start, - const at::Tensor& end, - const at::Tensor& value, - int64_t axis){ - int64_t x_dim = self.dim(); - int64_t min = -x_dim; - int64_t max = x_dim - 1; - TORCH_CHECK( - !(axis < min || axis > max), - "axis overfloaw the range, expected in range [", - -x_dim, - " ", - x_dim - 1, - "] "); - TORCH_CHECK( - start.ndimension() == 2 && start.sizes() == end.sizes(), - "Expected noempty 2D start tensor and start' sizes() should be equal end's sizes() "); - TORCH_CHECK( - start.size(0) == value.size(0), - "Expected value.length equal start loop num "); - TORCH_CHECK( - self.scalar_type() == value.scalar_type(), - "value dtype should be equal self dtype !, but value dtype is ", - value.scalar_type(), - " and self dtype is ", - self.scalar_type()); -} - -at::Tensor NPUNativeFunctions::npu_masked_fill_range( - const at::Tensor& self, - const at::Tensor& start, - const at::Tensor& end, - const at::Tensor& value, - int64_t axis){ - mask_fill_range_nocheck(self, start, end, value, axis); - at::Tensor result = OpPreparation::ApplyTensor(self); - OpCommand cmd; - cmd.Name("MaskedFillRange") - .Input(self) - .Input(start) - .Input(end) - .Input(value) - .Output(result) - .Attr("axis", axis) - .Run(); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/MaskedScatterKernelNpu.cpp b/torch_npu/csrc/aten/ops/MaskedScatterKernelNpu.cpp deleted file mode 100644 index 24931b3f56..0000000000 --- a/torch_npu/csrc/aten/ops/MaskedScatterKernelNpu.cpp +++ /dev/null @@ -1,73 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& masked_scatter_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& mask, - const at::Tensor& source) { - at::Tensor maskBool = mask; - if (!(mask.dtype() == at::kBool)) { - maskBool = NPUNativeFunctions::npu_dtype_cast(maskBool, at::kBool); - } - - OpCommand cmd; - cmd.Name("MaskedScatter") - .Input(self) - .Input(maskBool) - .Input(source) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::masked_scatter_( - at::Tensor& self, - const at::Tensor& mask, - const at::Tensor& source) { - c10::SmallVector inputs = {self, mask, source}; - c10::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - - at::Tensor selfFp32 = self; - at::Tensor sourceFp32 = source; - at::ScalarType selfType = self.scalar_type(); - if (selfType == at::ScalarType::Half) { - selfFp32 = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - sourceFp32 = NPUNativeFunctions::npu_dtype_cast(source, at::ScalarType::Float); - } - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfFp32); - at::Tensor result = masked_scatter_out_npu_nocheck(contiguousSelf, contiguousSelf, mask, sourceFp32); - NpuUtils::format_fresh_view(self, result); - } else { - masked_scatter_out_npu_nocheck(selfFp32, selfFp32, mask, sourceFp32); - self.copy_(selfFp32); - } - - return (self.scalar_type() != selfType) ? self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Half) : self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/MaskedSelectKernelNpu.cpp b/torch_npu/csrc/aten/ops/MaskedSelectKernelNpu.cpp index 6952fb2b12..bb90c5ea9e 100644 --- a/torch_npu/csrc/aten/ops/MaskedSelectKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MaskedSelectKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -34,7 +34,7 @@ at::Tensor& masked_select_out_npu_nocheck( const at::Tensor& mask) { at::Tensor maskBool = mask; if (!(mask.dtype() == at::kBool)) { - maskBool = NPUNativeFunctions::npu_dtype_cast(mask, at::kBool); + maskBool = XLANativeFunctions::npu_dtype_cast(mask, at::kBool); } OpCommand cmd; @@ -47,18 +47,18 @@ at::Tensor& masked_select_out_npu_nocheck( return result; } -at::Tensor& NPUNativeFunctions::masked_select_out( +at::Tensor& XLANativeFunctions::masked_select_out( const at::Tensor& self, const at::Tensor& mask, at::Tensor& result) { at::Tensor dtypeCastOfSelf = self; at::Tensor maskCast = mask; if (maskCast.sizes() != dtypeCastOfSelf.sizes()) { - maskCast = NPUNativeFunctions::npu_broadcast(mask, dtypeCastOfSelf.sizes()); + maskCast = XLANativeFunctions::npu_broadcast(mask, dtypeCastOfSelf.sizes()); } if (dtypeCastOfSelf.scalar_type() == at::ScalarType::Half) { - dtypeCastOfSelf = NPUNativeFunctions::npu_dtype_cast(dtypeCastOfSelf, at::ScalarType::Float); - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Float); + dtypeCastOfSelf = XLANativeFunctions::npu_dtype_cast(dtypeCastOfSelf, at::ScalarType::Float); + result = XLANativeFunctions::npu_dtype_cast(result, at::ScalarType::Float); } auto outputSize = masked_select_npu_output_size(dtypeCastOfSelf, maskCast); @@ -75,7 +75,7 @@ at::Tensor& NPUNativeFunctions::masked_select_out( .Call(result); if (result.scalar_type() != self.scalar_type()) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); + result = XLANativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); } if (!NpuUtils::check_match(&result)) { at::Tensor contiguousResult = NpuUtils::format_contiguous(result); @@ -87,16 +87,16 @@ at::Tensor& NPUNativeFunctions::masked_select_out( return result; } -at::Tensor NPUNativeFunctions::masked_select( +at::Tensor XLANativeFunctions::masked_select( const at::Tensor& self, const at::Tensor& mask) { at::Tensor dtypeCastOfSelf = self; at::Tensor maskCast = mask; if (maskCast.sizes() != dtypeCastOfSelf.sizes()) { - maskCast = NPUNativeFunctions::npu_broadcast(mask, dtypeCastOfSelf.sizes()); + maskCast = XLANativeFunctions::npu_broadcast(mask, dtypeCastOfSelf.sizes()); } if (dtypeCastOfSelf.scalar_type() == at::ScalarType::Half) { - dtypeCastOfSelf = NPUNativeFunctions::npu_dtype_cast(dtypeCastOfSelf, at::ScalarType::Float); + dtypeCastOfSelf = XLANativeFunctions::npu_dtype_cast(dtypeCastOfSelf, at::ScalarType::Float); } auto outputSize = masked_select_npu_output_size(dtypeCastOfSelf, maskCast); @@ -105,7 +105,7 @@ at::Tensor NPUNativeFunctions::masked_select( masked_select_out_npu_nocheck(result, dtypeCastOfSelf, maskCast); if (result.scalar_type() != self.scalar_type()) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); + result = XLANativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); } return result; } diff --git a/torch_npu/csrc/aten/ops/MatmulKernelNpu.cpp b/torch_npu/csrc/aten/ops/MatmulKernelNpu.cpp index 59b1c376e5..0429d8077c 100644 --- a/torch_npu/csrc/aten/ops/MatmulKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MatmulKernelNpu.cpp @@ -19,7 +19,7 @@ #include "torch_npu/csrc/framework/interface/EnvVariables.h" #include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -30,14 +30,14 @@ at::Tensor matmul_opt_npu( at::NoNamesGuard guard; auto has_out = out_opt.has_value(); at::Tensor out = out_opt.value_or(at::Tensor()); - if (at_npu::key::isDeviceTensor(tensor1) && - at_npu::key::isDeviceTensor(tensor2) && - tensor1.scalar_type() == at::kHalf && - tensor2.scalar_type() == at::kHalf && - at_npu::native::env::CheckBmmV2Enable()) { - auto res = matmul_by_bmmV2(tensor1, tensor2); - return has_out ? out.set_(res) : res; - } + // if (at_npu::key::isDeviceTensor(tensor1) && + // at_npu::key::isDeviceTensor(tensor2) && + // tensor1.scalar_type() == at::kHalf && + // tensor2.scalar_type() == at::kHalf && + // at_npu::native::env::CheckBmmV2Enable()) { + // auto res = matmul_by_bmmV2(tensor1, tensor2); + // return has_out ? out.set_(res) : res; + // } auto dim_tensor1 = tensor1.dim(); auto dim_tensor2 = tensor2.dim(); @@ -142,18 +142,18 @@ at::Tensor matmul_opt_npu( dim_tensor1, "D and ", dim_tensor2, "D"); } -at::Tensor NPUNativeFunctions::matmul(const at::Tensor & tensor1, const at::Tensor & tensor2) { - auto maybe_outnames = at::namedinference::compute_matmul_outnames(tensor1, tensor2); - auto result = matmul_opt_npu(c10::nullopt, tensor1, tensor2); - at::namedinference::propagate_names_if_nonempty(result, maybe_outnames); - return result; -} +// at::Tensor XLANativeFunctions::matmul(const at::Tensor & tensor1, const at::Tensor & tensor2) { +// auto maybe_outnames = at::namedinference::compute_matmul_outnames(tensor1, tensor2); +// auto result = matmul_opt_npu(c10::nullopt, tensor1, tensor2); +// at::namedinference::propagate_names_if_nonempty(result, maybe_outnames); +// return result; +// } -at::Tensor& NPUNativeFunctions::matmul_out(const at::Tensor & tensor1, const at::Tensor & tensor2, at::Tensor &result) { - auto maybe_outnames = at::namedinference::compute_matmul_outnames(tensor1, tensor2); - matmul_opt_npu(c10::optional(result), tensor1, tensor2); - at::namedinference::propagate_names_if_nonempty(result, maybe_outnames); - return result; -} +// at::Tensor& XLANativeFunctions::matmul_out(const at::Tensor & tensor1, const at::Tensor & tensor2, at::Tensor &result) { +// auto maybe_outnames = at::namedinference::compute_matmul_outnames(tensor1, tensor2); +// matmul_opt_npu(c10::optional(result), tensor1, tensor2); +// at::namedinference::propagate_names_if_nonempty(result, maybe_outnames); +// return result; +// } } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/MaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/MaxKernelNpu.cpp index a9d60d793f..6fe2bd3fc5 100644 --- a/torch_npu/csrc/aten/ops/MaxKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MaxKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -38,7 +38,7 @@ tuple max_out_npu_nocheck( return std::tie(output, indices); } -tuple NPUNativeFunctions::max_out( +tuple XLANativeFunctions::max_out( const at::Tensor& self, int64_t dim, bool keepdim, @@ -78,7 +78,7 @@ tuple NPUNativeFunctions::max_out( .ReturnRef(); } -tuple NPUNativeFunctions::max_out( +tuple XLANativeFunctions::max_out( const at::Tensor& self, at::Dimname dim, bool keepdim, @@ -87,7 +87,7 @@ tuple NPUNativeFunctions::max_out( return max_out(self, dimname_to_position(self, dim), keepdim, output, indices); } -tuple NPUNativeFunctions::max( +tuple XLANativeFunctions::max( const at::Tensor& self, int64_t dim, bool keepdim) { @@ -115,7 +115,7 @@ tuple NPUNativeFunctions::max( return std::tie(outputs, indices); } -tuple NPUNativeFunctions::max( +tuple XLANativeFunctions::max( const at::Tensor& self, at::Dimname dim, bool keepdim) { @@ -135,19 +135,21 @@ at::Tensor& max_out_npu_nocheck( return result; } -at::Tensor& NPUNativeFunctions::max_out( +at::Tensor& XLANativeFunctions::max_out( const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { OpPreparation::CheckOut( {self}, result, - self); + ACL_FORMAT_ND, + self.scalar_type(), + self.sizes()); max_out_npu_nocheck(self, other, result); return result; } -at::Tensor NPUNativeFunctions::maximum( +at::Tensor XLANativeFunctions::max( const at::Tensor& self, const at::Tensor& other) { auto outputSize = broadcast_ops_npu_output_size(self, other); @@ -171,7 +173,7 @@ at::Tensor& max_out_npu_nocheck( return result; } -at::Tensor NPUNativeFunctions::amax( +at::Tensor XLANativeFunctions::amax( const at::Tensor& self, at::IntArrayRef dims, bool keepdim) { @@ -185,13 +187,13 @@ at::Tensor NPUNativeFunctions::amax( return result; } -at::Tensor NPUNativeFunctions::max( +at::Tensor XLANativeFunctions::max( const at::Tensor& self) { at::SmallVector dims = CalcuOpUtil::get_dimlist_for_tensor(self); return amax(self, dims, false); } -at::Tensor& NPUNativeFunctions::amax_out( +at::Tensor& XLANativeFunctions::amax_out( const at::Tensor& self, at::IntArrayRef dims, bool keepdim, diff --git a/torch_npu/csrc/aten/ops/MaxV1KernelNpu.cpp b/torch_npu/csrc/aten/ops/MaxV1KernelNpu.cpp deleted file mode 100644 index c323af6d55..0000000000 --- a/torch_npu/csrc/aten/ops/MaxV1KernelNpu.cpp +++ /dev/null @@ -1,125 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -std::tuple max_v1_out_npu_nocheck( - const at::Tensor& self, - int64_t dim, - bool keepdim, - at::Tensor& output, - at::Tensor& indices) { - OpCommand cmd; - cmd.Name("ArgMaxWithValue") - .Input(self) - .Output(indices) - .Output(output) - .Attr("dimension", dim) - .Attr("keep_dims", keepdim) - .Run(); - return std::tie(output, indices); -} - -std::tuple npu_max_npu(const at::Tensor& self, int64_t dim, bool keepdim) { - c10::SmallVector dims = {dim}; - c10::SmallVector outputSize = - reduce_ops_npu_output_size(self, dims, keepdim); - c10::SmallVector indicesSize = - reduce_ops_npu_output_size(self, dims, keepdim); - int64_t npu_format = CalcuOpUtil::get_tensor_npu_format(self); - if (outputSize.empty()) { - npu_format = ACL_FORMAT_NCHW; - } - at::Tensor outputs = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options(), npu_format); - at::Tensor indices = OpPreparation::ApplyTensorWithFormat( - indicesSize, self.options().dtype(at::kInt), ACL_FORMAT_NCHW); - max_v1_out_npu_nocheck(self, dim, keepdim, outputs, indices); - return std::tie(outputs, indices); -} - -at::Tensor NPUNativeFunctions::npu_max_backward( - const at::Tensor& grad, - int64_t dim, - const at::Tensor& indices, - at::IntArrayRef sizes, bool keepdim) { - at::Tensor new_grad = grad; - at::Tensor new_indices = indices; - if (keepdim && sizes.size() > 0) { - new_grad = grad.squeeze(dim); - new_indices = indices.squeeze(dim); - } - if (new_indices.dtype() == at::kLong) { - new_indices = NPUNativeFunctions::npu_dtype_cast(new_indices, at::kInt); - } - auto grad_input = NPUNativeFunctions::npu_scatter(at::zeros(sizes, new_grad.options()), new_indices, new_grad, dim); - return grad_input; -} - -class NPUMaxFunction : public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& self, - int64_t dim, - bool keepdim) { - ctx->saved_data["dim"] = dim; - ctx->saved_data["shape"] = self.sizes(); - ctx->saved_data["keepdim"] = keepdim; - at::AutoNonVariableTypeMode g; - auto result = npu_max_npu(self, dim, keepdim); - auto indices = std::get<1>(result); - ctx->save_for_backward({indices}); - tensor_list result_list = {std::get<0>(result), indices}; - return result_list; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto dim = ctx->saved_data["dim"].toInt(); - auto sizes = ctx->saved_data["shape"].toIntVector(); - auto keepdim = ctx->saved_data["keepdim"].toBool(); - auto saved = ctx->get_saved_variables(); - auto indices = saved[0]; - at::Tensor result = NPUNativeFunctions::npu_max_backward(grad_outputs[0], dim, indices, sizes, keepdim); - - tensor_list output = {result, - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -std::tuple NPUNativeFunctions::npu_max(const at::Tensor& self, int64_t dim, bool keepdim) { - auto output = NPUMaxFunction::apply(self, dim, keepdim); - std::tuple result(output[0], output[1]); - return result; -} - -std::tuple NPUNativeFunctions::npu_max(const at::Tensor& self, at::Dimname dim, bool keepdim) { - return npu_max(self, dimname_to_position(self, dim), keepdim); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/MeanKernelNpu.cpp b/torch_npu/csrc/aten/ops/MeanKernelNpu.cpp index 8ca851a36d..aae50908b0 100644 --- a/torch_npu/csrc/aten/ops/MeanKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MeanKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -81,7 +81,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::mean_out( + at::Tensor &XLANativeFunctions::mean_out( const at::Tensor &self, at::IntArrayRef dim, bool keepdim, @@ -113,17 +113,17 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::mean_out( + at::Tensor &XLANativeFunctions::mean_out( const at::Tensor &self, at::DimnameList dim, bool keepdim, c10::optional dtype, at::Tensor &result) { - return NPUNativeFunctions::mean_out(self, dimnames_to_positions(self, dim), keepdim, dtype, result); + return XLANativeFunctions::mean_out(self, dimnames_to_positions(self, dim), keepdim, dtype, result); } - at::Tensor NPUNativeFunctions::mean( + at::Tensor XLANativeFunctions::mean( const at::Tensor &self, at::IntArrayRef dim, bool keepdim, @@ -146,22 +146,22 @@ namespace at_npu outputSize, self.options().dtype(dstType), npu_format); // calculate the output result of the NPU - NPUNativeFunctions::mean_out(self, dim, keepdim, dtype, result); + XLANativeFunctions::mean_out(self, dim, keepdim, dtype, result); return result; } - at::Tensor NPUNativeFunctions::mean( + at::Tensor XLANativeFunctions::mean( const at::Tensor &self, at::DimnameList dim, bool keepdim, c10::optional dtype) { - return NPUNativeFunctions::mean(self, dimnames_to_positions(self, dim), keepdim, dtype); + return XLANativeFunctions::mean(self, dimnames_to_positions(self, dim), keepdim, dtype); } - at::Tensor NPUNativeFunctions::mean(const at::Tensor &self, c10::optional dtype) + at::Tensor XLANativeFunctions::mean(const at::Tensor &self, c10::optional dtype) { - return NPUNativeFunctions::mean(self, c10::SmallVector{}, false, dtype); + return XLANativeFunctions::mean(self, c10::SmallVector{}, false, dtype); } } // namespace native diff --git a/torch_npu/csrc/aten/ops/MedianKernelNpu.cpp b/torch_npu/csrc/aten/ops/MedianKernelNpu.cpp deleted file mode 100644 index 62a79690a4..0000000000 --- a/torch_npu/csrc/aten/ops/MedianKernelNpu.cpp +++ /dev/null @@ -1,157 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector median_npu_output_size( - const at::Tensor& self, - int64_t dim, - bool keepdim) { - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - at::IntArrayRef dims(dim); - return reduce_ops_npu_output_size(self, dims, keepdim); -} - -at::Tensor& median_out_nocheck( - at::Tensor& result, - const at::Tensor& self) { - at::Tensor input = self.has_names() ? - self.rename(c10::nullopt).reshape({-1}) : self.reshape({-1}); - int64_t k = input.size(0) / 2; - - auto ret = topk(input, k + 1); - at::Tensor topkValues = std::get<0>(ret); - at::Tensor value = topkValues[k]; - - result.fill_(value); - return result; -} - -std::tuple median_out_value_nocheck( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim, - bool keepdim) { - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - int64_t k = self.dim() > 0 ? (self.size(dim) + 1) / 2 : 1; - - at::Tensor _self = self.has_names() ? self.rename(c10::nullopt) : self; - auto ret = topk(_self, k, dim, false, true); - at::Tensor topkValues = std::get<0>(ret); - at::Tensor topkIndices = std::get<1>(ret); - - if (topkIndices.dtype() == at::ScalarType::Long) { - topkIndices = topkIndices.to(at::kInt); - } - - //NCHW -> reflush base format - at::Tensor index = OpPreparation::ApplyTensorWithFormat( - {1}, _self.options().dtype(at::kInt), ACL_FORMAT_NCHW); - index.fill_(k - 1); - at::Tensor _values = index_select(topkValues, dim, index); - at::Tensor _indices = index_select(topkIndices, dim, index); - if (!keepdim) { - _values.squeeze_(dim); - _indices.squeeze_(dim); - } - at::namedinference::propagate_names_for_reduction(_values, self, dim, keepdim); - at::namedinference::propagate_names_for_reduction(_indices, self, dim, keepdim); - values.copy_(_values); - indices.copy_(_indices); - return tuple(values, indices); -} - -std::tuple median_out_npu_nocheck( - at::Tensor& values, - at::Tensor& indices, - const at::Tensor& self, - at::Dimname dim, - bool keepdim) { - return median_out_value_nocheck(values, indices, self, dimname_to_position(self, dim), keepdim); -} - -std::tuple NPUNativeFunctions::median_out( - const at::Tensor& self, - int64_t dim, - bool keepdim, - at::Tensor& values, - at::Tensor& indices) { - auto outputSize = median_npu_output_size(self, dim, keepdim); - OpPreparation::CheckOut( - {self}, - values, - ACL_FORMAT_ND, - self.scalar_type(), - outputSize); - - OpPreparation::CheckOut( - {self}, - indices, - ACL_FORMAT_ND, - at::ScalarType::Int, - outputSize); - - median_out_value_nocheck(values, indices, self, dim, keepdim); - return tuple(values, indices); -} - -std::tuple NPUNativeFunctions::median_out( - const at::Tensor& self, - at::Dimname dim, - bool keepdim, - at::Tensor& values, - at::Tensor& indices) { - return at::median_out(values, indices, self, dimname_to_position(self, dim), keepdim); -} - -at::Tensor NPUNativeFunctions::median(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - {}, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - - median_out_nocheck(result, self); - return result; -} - -std::tuple NPUNativeFunctions::median( - const at::Tensor& self, - int64_t dim, - bool keepdim) { - auto outputSize = median_npu_output_size(self, dim, keepdim); - at::Tensor values = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - //NCHW -> reflush base format - at::Tensor indices = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options().dtype(at::kInt), ACL_FORMAT_NCHW); - - median_out_value_nocheck(values, indices, self, dim, keepdim); - return tuple(values, indices); -} - -std::tuple NPUNativeFunctions::median( - const at::Tensor& self, - at::Dimname dim, - bool keepdim) { - return median(self, dimname_to_position(self, dim), keepdim); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/MinKernelNpu.cpp b/torch_npu/csrc/aten/ops/MinKernelNpu.cpp index 9996a704b0..8804632d73 100644 --- a/torch_npu/csrc/aten/ops/MinKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MinKernelNpu.cpp @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" @@ -38,7 +38,7 @@ tuple min_out_npu_nocheck( return std::tie(output, indices); } -tuple NPUNativeFunctions::min_out( +tuple XLANativeFunctions::min_out( const at::Tensor& self, int64_t dim, bool keepdim, @@ -62,7 +62,7 @@ tuple NPUNativeFunctions::min_out( .ReturnRef(); } -tuple NPUNativeFunctions::min(const at::Tensor& self, int64_t dim, bool keepdim) { +tuple XLANativeFunctions::min(const at::Tensor& self, int64_t dim, bool keepdim) { at::Tensor selfCast = self; if(self.dtype() == at::ScalarType::Bool){ selfCast = self.to(at::ScalarType::Float); @@ -88,7 +88,7 @@ tuple NPUNativeFunctions::min(const at::Tensor& self, in return std::tie(outputs, indices); } -tuple NPUNativeFunctions::min_out( +tuple XLANativeFunctions::min_out( const at::Tensor& self, at::Dimname dim, bool keepdim, @@ -97,7 +97,7 @@ tuple NPUNativeFunctions::min_out( return min_out(self, dimname_to_position(self, dim), keepdim, output, indices); } -tuple NPUNativeFunctions::min(const at::Tensor& self, at::Dimname dim, bool keepdim) { +tuple XLANativeFunctions::min(const at::Tensor& self, at::Dimname dim, bool keepdim) { return min(self, dimname_to_position(self, dim), keepdim); } @@ -114,7 +114,7 @@ at::Tensor& min_out_npu_nocheck( return result; } -at::Tensor& NPUNativeFunctions::min_out( +at::Tensor& XLANativeFunctions::min_out( const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { @@ -128,7 +128,7 @@ at::Tensor& NPUNativeFunctions::min_out( return result; } -at::Tensor NPUNativeFunctions::minimum(const at::Tensor& self, const at::Tensor& other) { +at::Tensor XLANativeFunctions::minimum(const at::Tensor& self, const at::Tensor& other) { auto outputSize = broadcast_ops_npu_output_size(self, other); at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); min_out_npu_nocheck(self, other, result); @@ -150,7 +150,7 @@ at::Tensor& min_out_npu_nocheck( return result; } -at::Tensor NPUNativeFunctions::amin(const at::Tensor& self, at::IntArrayRef dims, bool keepdim) { +at::Tensor XLANativeFunctions::amin(const at::Tensor& self, at::IntArrayRef dims, bool keepdim) { auto outputSize = reduce_ops_npu_output_size(self, dims, keepdim); int64_t npu_format = CalcuOpUtil::get_tensor_npu_format(self); if (outputSize.empty()) { @@ -161,12 +161,12 @@ at::Tensor NPUNativeFunctions::amin(const at::Tensor& self, at::IntArrayRef dims return result; } -at::Tensor NPUNativeFunctions::min(const at::Tensor& self) { +at::Tensor XLANativeFunctions::min(const at::Tensor& self) { c10::SmallVector dims = CalcuOpUtil::get_dimlist_for_tensor(self); return amin(self, dims, false); } -at::Tensor& NPUNativeFunctions::amin_out( +at::Tensor& XLANativeFunctions::amin_out( const at::Tensor& self, at::IntArrayRef dims, bool keepdim, diff --git a/torch_npu/csrc/aten/ops/MinV1KernelNpu.cpp b/torch_npu/csrc/aten/ops/MinV1KernelNpu.cpp deleted file mode 100644 index ea271eee4e..0000000000 --- a/torch_npu/csrc/aten/ops/MinV1KernelNpu.cpp +++ /dev/null @@ -1,125 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -tuple min_v1_out_npu_nocheck( - at::Tensor& output, - at::Tensor& indices, - const at::Tensor& self, - int64_t dim, - bool keepdim) { - OpCommand cmd; - cmd.Name("ArgMinWithValue") - .Input(self) - .Output(indices) - .Output(output) - .Attr("dimension", dim) - .Attr("keep_dims", keepdim) - .Run(); - - return std::tie(output, indices); -} - -tuple min_v1_npu(const at::Tensor& self, int64_t dim, bool keepdim) { - c10::SmallVector dims = {dim}; - c10::SmallVector outputSize = - reduce_ops_npu_output_size(self, dims, keepdim); - c10::SmallVector indicesSize = - reduce_ops_npu_output_size(self, dims, keepdim); - - int64_t npuFormat = CalcuOpUtil::get_tensor_npu_format(self); - if (outputSize.empty()) { - npuFormat = ACL_FORMAT_NCHW; - } - - at::Tensor outputs = OpPreparation::ApplyTensorWithFormat(outputSize, self.options(), npuFormat); - at::Tensor indices = OpPreparation::ApplyTensorWithFormat(indicesSize, self.options().dtype(at::kInt), npuFormat); - - min_v1_out_npu_nocheck(outputs, indices, self, dim, keepdim); - return std::tie(outputs, indices); -} - -tuple NPUNativeFunctions::npu_min(const at::Tensor& self, at::Dimname dim, bool keepdim) { - return min_v1_npu(self, dimname_to_position(self, dim), keepdim); -} - -at::Tensor NPUNativeFunctions::npu_min_backward( - const at::Tensor& grad, - int64_t dim, - const at::Tensor& indices, - at::IntArrayRef sizes, - bool keepdim) { - at::Tensor newGrad = grad; - at::Tensor newIndices = indices; - if (keepdim && sizes.size() > 0) { - newGrad = grad.squeeze(dim); - newIndices = indices.squeeze(dim); - } - auto gradInput = NPUNativeFunctions::npu_scatter( - at::native::zeros(sizes, newGrad.options()), newIndices, newGrad, dim); - return gradInput; -} - -class NPUMinFunction : public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& self, - int64_t dim, - bool keepdim) { - ctx->saved_data["dim"] = dim; - ctx->saved_data["keepdim"] = keepdim; - ctx->saved_data["size"] = self.sizes(); - at::AutoNonVariableTypeMode g; - auto result = min_v1_npu(self, dim, keepdim); - auto indices = std::get<1>(result); - ctx->save_for_backward({indices}); - tensor_list result_list = {std::get<0>(result), indices}; - return result_list; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto dim = ctx->saved_data["dim"].toInt(); - auto keepdim = ctx->saved_data["keepdim"].toBool(); - auto size = ctx->saved_data["size"].toIntVector(); - auto saved = ctx->get_saved_variables(); - auto indices = saved[0]; - at::Tensor result = NPUNativeFunctions::npu_min_backward( - grad_outputs[0], dim, indices, size, keepdim); - tensor_list output = {result, at::Tensor(), at::Tensor()}; - return output; - } -}; - -tuple NPUNativeFunctions::npu_min(const at::Tensor& self, int64_t dim, bool keepdim) { - auto result = NPUMinFunction::apply(self, dim, keepdim); - std::tuple output(result[0], result[1]); - return output; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/MishKernelNpu.cpp b/torch_npu/csrc/aten/ops/MishKernelNpu.cpp deleted file mode 100644 index 76a9b22421..0000000000 --- a/torch_npu/csrc/aten/ops/MishKernelNpu.cpp +++ /dev/null @@ -1,77 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -at::Tensor mish_npu(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - OpCommand cmd; - cmd.Name("Mish") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::npu_mish_backward(const at::Tensor& grad, const at::Tensor& input) { - at::Tensor result = OpPreparation::ApplyTensor(input); - OpCommand cmd; - cmd.Name("MishGrad") - .Input(grad) - .Input(input) - .Output(result) - .Run(); - - return result; -} - -class NPUMishFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self) { - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({self}); - return mish_npu(self); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto saved = ctx->get_saved_variables(); - auto input = saved[0]; - - at::Tensor result = NPUNativeFunctions::npu_mish_backward(grad_outputs[0], input); - tensor_list output = {result}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_mish(const at::Tensor& self) { - return NPUMishFunction::apply(self); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/MmKernelNpu.cpp b/torch_npu/csrc/aten/ops/MmKernelNpu.cpp index d397d99138..3ed60608df 100644 --- a/torch_npu/csrc/aten/ops/MmKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MmKernelNpu.cpp @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/framework/StorageDescHelper.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" @@ -37,9 +37,6 @@ Matmul: [1] 2-2-t(strict transpose); [2] 2-n-view+t(view transpose). False--Tensor is not transposed, proceed to format_contiguous. *****************************************/ bool is_transpose_last_two_dims_flex(const at::Tensor &tensor) { - if (c10_npu::NpuRunMode::IsGraphMode()) { - return false; - } if (tensor.dim() != 2) { return false; } @@ -57,9 +54,6 @@ bool is_transpose_last_two_dims_flex(const at::Tensor &tensor) { // Pick out strict-transpose tensors from flex-transpose tensors. bool is_transpose_last_two_dims_strict(const at::Tensor &tensor, bool is_transpose_flex) { - if (c10_npu::NpuRunMode::IsGraphMode()) { - return false; - } auto base_sizes = torch_npu::NPUBridge::GetNpuStorageImpl(tensor) ->get_npu_desc() .base_sizes_; @@ -78,7 +72,7 @@ void set_transposed_npu_desc(at::Tensor &tensor) { temp_transpose_Tensor.strides()); } -at::Tensor &NPUNativeFunctions::mm_out(const at::Tensor &self, +at::Tensor &XLANativeFunctions::mm_out(const at::Tensor &self, const at::Tensor &mat2, at::Tensor &result) { at::Tensor contiguousResult = @@ -144,7 +138,7 @@ at::Tensor &NPUNativeFunctions::mm_out(const at::Tensor &self, return result; } -at::Tensor NPUNativeFunctions::mm(const at::Tensor &self, +at::Tensor XLANativeFunctions::mm(const at::Tensor &self, const at::Tensor &mat2) { // calculate the output size auto outputSize = {self.size(0), mat2.size(1)}; @@ -168,25 +162,25 @@ at::Tensor NPUNativeFunctions::mm(const at::Tensor &self, static auto mm_bmm_nd = env::CheckMmBmmNDEnable(); if (FormatHelper::IsBaseFormatType(self) && FormatHelper::IsBaseFormatType(mat2) && mm_bmm_nd && isAligin()) { - result = NPUNativeFunctions::empty_with_format( + result = XLANativeFunctions::empty_with_format( outputSize, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), ACL_FORMAT_ND); } else { - result = NPUNativeFunctions::empty_with_format( + result = XLANativeFunctions::empty_with_format( outputSize, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), ACL_FORMAT_FRACTAL_NZ); } } else { - result = NPUNativeFunctions::empty_with_format( + result = XLANativeFunctions::empty_with_format( outputSize, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), ACL_FORMAT_ND); } // calculate the output result of the NPU - NPUNativeFunctions::mm_out(self, mat2, result); + XLANativeFunctions::mm_out(self, mat2, result); return result; } diff --git a/torch_npu/csrc/aten/ops/MseLossBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/MseLossBackwardKernelNpu.cpp index 43da192f29..dcb81a8f12 100644 --- a/torch_npu/csrc/aten/ops/MseLossBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MseLossBackwardKernelNpu.cpp @@ -16,12 +16,12 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::mse_loss_backward_out( +at::Tensor& XLANativeFunctions::mse_loss_backward_out( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -46,7 +46,7 @@ at::Tensor& NPUNativeFunctions::mse_loss_backward_out( return grad_input; } -at::Tensor NPUNativeFunctions::mse_loss_backward( +at::Tensor XLANativeFunctions::mse_loss_backward( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -57,7 +57,7 @@ at::Tensor NPUNativeFunctions::mse_loss_backward( } at::Tensor grad_input = OpPreparation::ApplyTensor(self); - NPUNativeFunctions::mse_loss_backward_out( + XLANativeFunctions::mse_loss_backward_out( grad_out, self, target, diff --git a/torch_npu/csrc/aten/ops/MseLossKernelNpu.cpp b/torch_npu/csrc/aten/ops/MseLossKernelNpu.cpp index 2b91cf28b6..9e8e33d55e 100644 --- a/torch_npu/csrc/aten/ops/MseLossKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MseLossKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -45,7 +45,7 @@ at::Tensor& mse_loss_out_npu_nocheck( return result; } -at::Tensor& NPUNativeFunctions::mse_loss_out( +at::Tensor& XLANativeFunctions::mse_loss_out( const at::Tensor& self, const at::Tensor& target, int64_t reduction, @@ -65,7 +65,7 @@ at::Tensor& NPUNativeFunctions::mse_loss_out( return result; } -at::Tensor NPUNativeFunctions::mse_loss( +at::Tensor XLANativeFunctions::mse_loss( const at::Tensor& self, const at::Tensor& target, int64_t reduction) { @@ -73,10 +73,7 @@ at::Tensor NPUNativeFunctions::mse_loss( if (reduction == at::Reduction::None) { outputSize = input_same_output_size(self); } - at::Tensor result = - reduction == at::Reduction::None ? - OpPreparation::ApplyTensor(self, outputSize) : - OpPreparation::ApplyTensorWithFormat(self, outputSize, ACL_FORMAT_ND); + at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); mse_loss_out_npu_nocheck(result, self, target, reduction); return result; diff --git a/torch_npu/csrc/aten/ops/MulKernelNpu.cpp b/torch_npu/csrc/aten/ops/MulKernelNpu.cpp index 42786f41cc..064d1b7272 100644 --- a/torch_npu/csrc/aten/ops/MulKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/MulKernelNpu.cpp @@ -18,7 +18,7 @@ #include "torch_npu/csrc/core/npu/register/OptionsManager.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -70,7 +70,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::mul_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) + at::Tensor &XLANativeFunctions::mul_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) { // calculate the output size at::Tensor outputTensor = mul_dest_output(self, other); @@ -86,7 +86,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::mul(const at::Tensor &self, const at::Tensor &other) + at::Tensor XLANativeFunctions::mul(const at::Tensor &self, const at::Tensor &other) { at::Tensor selfCast = self; at::Tensor otherCast = other; @@ -117,7 +117,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::mul(const at::Tensor &self, at::Scalar other) + at::Tensor XLANativeFunctions::mul(const at::Tensor &self, const at::Scalar& other) { // calculate the output size auto outputSize = input_same_output_size(self); @@ -132,7 +132,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::mul_(at::Tensor &self, const at::Tensor &other) + at::Tensor &XLANativeFunctions::mul_(at::Tensor &self, const at::Tensor &other) { TORCH_CHECK(at_npu::key::isDeviceTensor(self), "Input1 must be NPU-Tensor"); @@ -141,9 +141,9 @@ namespace at_npu CalcuOpUtil::check_memory_over_laps(inputs, outputs); at::Tensor selfDtypeCast = - (self.scalar_type() == at::kBool) ? NPUNativeFunctions::npu_dtype_cast(self, at::kFloat) : self; + (self.scalar_type() == at::kBool) ? XLANativeFunctions::npu_dtype_cast(self, at::kFloat) : self; at::Tensor otherDtypeCast = - (other.scalar_type() == at::kBool) ? NPUNativeFunctions::npu_dtype_cast(other, at::kFloat) : other; + (other.scalar_type() == at::kBool) ? XLANativeFunctions::npu_dtype_cast(other, at::kFloat) : other; if (!NpuUtils::check_match(&selfDtypeCast)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfDtypeCast); at::Tensor result = mul_out_npu_nocheck(contiguousSelf, contiguousSelf, otherDtypeCast); @@ -152,14 +152,14 @@ namespace at_npu mul_out_npu_nocheck(selfDtypeCast, selfDtypeCast, otherDtypeCast); } if (self.scalar_type() == at::kBool) { - selfDtypeCast = NPUNativeFunctions::npu_dtype_cast(selfDtypeCast, at::kBool); + selfDtypeCast = XLANativeFunctions::npu_dtype_cast(selfDtypeCast, at::kBool); } self.copy_(selfDtypeCast); return self; } - at::Tensor &NPUNativeFunctions::mul_(at::Tensor &self, at::Scalar other) + at::Tensor &XLANativeFunctions::mul_(at::Tensor &self, const at::Scalar& other) { if (!NpuUtils::check_match(&self)) { diff --git a/torch_npu/csrc/aten/ops/MultiHeadAttentionKernelNpu.cpp b/torch_npu/csrc/aten/ops/MultiHeadAttentionKernelNpu.cpp deleted file mode 100644 index 3d91aaaa5f..0000000000 --- a/torch_npu/csrc/aten/ops/MultiHeadAttentionKernelNpu.cpp +++ /dev/null @@ -1,313 +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. - -#include - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -static const int64_t FZ_ALIGN_NUM = 16; -std::vector multi_head_attention_npu( - const at::Tensor& query, const at::Tensor& key, const at::Tensor& value, - const at::Tensor& query_weight, const at::Tensor& key_weight, const at::Tensor& value_weight, - const at::Tensor& attn_mask, const at::Tensor& out_proj_weight, - const at::Tensor& query_bias, const at::Tensor& key_bias, const at::Tensor& value_bias, - const at::Tensor& out_proj_bias, const at::Tensor& mask, - int64_t attn_head_num, int64_t attn_dim_per_head, - int64_t src_len, int64_t tgt_len, - double dropout_prob, bool softmax_use_float) { - TORCH_CHECK(tgt_len > 0 && src_len > 0 && attn_head_num > 0 && attn_dim_per_head > 0, - "tgt_len, src_len, attn_head_num, attn_dim_per_head should not equal zero."); - TORCH_CHECK(tgt_len % FZ_ALIGN_NUM == 0 && src_len % FZ_ALIGN_NUM == 0 && - attn_head_num % FZ_ALIGN_NUM == 0 && attn_dim_per_head % FZ_ALIGN_NUM == 0, - "tgt_len, src_len, attn_head_num, attn_dim_per_head should align to 16."); - auto query_shape = query.sizes(); - int64_t batch = query_shape[0] / tgt_len; - auto weight_col = attn_head_num * attn_dim_per_head; - - auto query_options = query.options(); - auto query_format = CalcuOpUtil::get_tensor_npu_format(query); - - at::Tensor y = OpPreparation::ApplyTensorWithFormat( - {query_shape[0], weight_col}, query_options, query_format); - at::Tensor dropout_mask = OpPreparation::ApplyTensorWithFormat( - {batch * attn_head_num * tgt_len * src_len / 8}, query.options().dtype(at::kByte), ACL_FORMAT_ND); - at::Tensor query_res = OpPreparation::ApplyTensorWithFormat( - {batch, attn_head_num, tgt_len, attn_dim_per_head}, query_options, query_format); - at::Tensor key_res = OpPreparation::ApplyTensorWithFormat( - {batch, attn_head_num, src_len, attn_dim_per_head}, query_options, query_format); - at::Tensor value_res = OpPreparation::ApplyTensorWithFormat( - {batch, attn_head_num, src_len, attn_dim_per_head}, query_options, query_format); - at::Tensor attn_scores; - if (softmax_use_float) { - attn_scores = OpPreparation::ApplyTensorWithFormat( - {batch, attn_head_num, tgt_len, src_len}, query.options().dtype(at::kFloat), query_format); - } else { - attn_scores = OpPreparation::ApplyTensorWithFormat( - {batch, attn_head_num, tgt_len, src_len}, query_options, query_format); - } - at::Tensor attn_res = OpPreparation::ApplyTensorWithFormat( - {batch, attn_head_num, tgt_len, src_len}, query_options, query_format); - at::Tensor context = OpPreparation::ApplyTensorWithFormat( - {query_shape[0], weight_col}, query_options, query_format); - - OpCommand cmd; - cmd.Name("MultiHeadAttention") - .Input(query).Input(key).Input(value) - .Input(query_weight).Input(key_weight).Input(value_weight) - .Input(attn_mask).Input(out_proj_weight); - if (query_bias.defined()) { - cmd.Input(query_bias); - } - if (key_bias.defined()) { - cmd.Input(key_bias); - } - if (value_bias.defined()) { - cmd.Input(value_bias); - } - if (out_proj_bias.defined()) { - cmd.Input(out_proj_bias); - } - if (mask.defined()) { - cmd.Input(mask); - } - - cmd.Output(y).Output(dropout_mask).Output(query_res).Output(key_res).Output(value_res) - .Output(attn_scores).Output(attn_res).Output(context) - .Attr("attn_head_num", attn_head_num).Attr("attn_dim_per_head", attn_dim_per_head) - .Attr("src_len", src_len).Attr("tgt_len", tgt_len) - .Attr("keep_prob", static_cast(1 - dropout_prob)).Attr("softmax_use_float", softmax_use_float) - .Run(); - - tensor_list result1 = {y, dropout_mask, query_res, key_res, value_res, attn_scores, attn_res, context}; - - return result1; -} - -static const int64_t FZ_ALIGN_NUM1 = 16; -static const size_t BIAS_BUM1 = 4; -std::vector NPUNativeFunctions::npu_multi_head_attention_backward( - const at::Tensor& query, const at::Tensor& key, const at::Tensor& value, - const at::Tensor& query_weight, const at::Tensor& key_weight, const at::Tensor& value_weight, - const at::Tensor& out_proj_weight, const c10::optional& query_bias_opt, - const c10::optional& key_bias_opt, const c10::optional& value_bias_opt, - const c10::optional& out_proj_bias_opt, const at::Tensor& query_res, - const at::Tensor& key_res, const at::Tensor& value_res, - const at::Tensor& attn_scores, const at::Tensor& attn_res, const at::Tensor& context, - const at::Tensor& y_grad, const at::Tensor& dropout_mask, - int64_t attn_head_num, int64_t attn_dim_per_head, - int64_t src_len, int64_t tgt_len, - double dropout_prob, bool softmax_use_float -) { - const at::Tensor& query_bias = c10::value_or_else(query_bias_opt, [] {return at::Tensor();}); - const at::Tensor& key_bias = c10::value_or_else(key_bias_opt, [] {return at::Tensor();}); - const at::Tensor& value_bias = c10::value_or_else(value_bias_opt, [] {return at::Tensor();}); - const at::Tensor& out_proj_bias = c10::value_or_else(out_proj_bias_opt, [] {return at::Tensor();}); - - TORCH_CHECK(tgt_len > 0 && src_len > 0 && attn_head_num > 0 && attn_dim_per_head > 0, - "tgt_len, src_len, attn_head_num, attn_dim_per_head should not equal zero."); - TORCH_CHECK(tgt_len % FZ_ALIGN_NUM1 == 0 && src_len % FZ_ALIGN_NUM1 == 0 && - attn_head_num % FZ_ALIGN_NUM1 == 0 && attn_dim_per_head % FZ_ALIGN_NUM1 == 0, - "tgt_len, src_len, attn_head_num, attn_dim_per_head should align to 16."); - auto query_shape = query.sizes(); - int64_t batch = query_shape[0] / tgt_len; - auto weight_col = attn_head_num * attn_dim_per_head; - at::Tensor query_weight_grad = OpPreparation::ApplyTensor(query_weight, {weight_col, weight_col}); - at::Tensor key_weight_grad = OpPreparation::ApplyTensor(key_weight, {weight_col, weight_col}); - at::Tensor value_weight_grad = OpPreparation::ApplyTensor(value_weight, {weight_col, weight_col}); - at::Tensor out_proj_weight_grad = OpPreparation::ApplyTensor(out_proj_weight, {weight_col, weight_col}); - at::Tensor query_grad = OpPreparation::ApplyTensor(query, {query_shape[0], weight_col}); - at::Tensor key_grad = OpPreparation::ApplyTensor(key, {batch * src_len, weight_col}); - at::Tensor value_grad = OpPreparation::ApplyTensor(value, {batch * src_len, weight_col}); - at::Tensor query_bias_grad = OpPreparation::ApplyTensor(query_bias, {1, weight_col}); - at::Tensor key_bias_grad = OpPreparation::ApplyTensor(key_bias, {1, weight_col}); - at::Tensor value_bias_grad = OpPreparation::ApplyTensor(value_bias, {1, weight_col}); - at::Tensor out_proj_bias_grad = OpPreparation::ApplyTensor(out_proj_bias, {1, weight_col}); - vector grad_mask(BIAS_BUM1); - grad_mask.clear(); - grad_mask.push_back(query_bias.defined()); - grad_mask.push_back(key_bias.defined()); - grad_mask.push_back(value_bias.defined()); - grad_mask.push_back(out_proj_bias.defined()); - at::ArrayRef bias_grad_mask(grad_mask); - - OpCommand cmd; - cmd.Name("MultiHeadAttentionGrad") - .Input(query).Input(key).Input(value) - .Input(query_weight).Input(key_weight).Input(value_weight) - .Input(out_proj_weight).Input(query_res).Input(key_res).Input(value_res) - .Input(attn_scores).Input(attn_res).Input(context).Input(y_grad); - if (dropout_prob>0) { - cmd.Input(dropout_mask); - } - cmd.Output(query_weight_grad).Output(key_weight_grad).Output(value_weight_grad).Output(out_proj_weight_grad) - .Output(query_grad).Output(key_grad).Output(value_grad) - .Output(query_bias_grad).Output(key_bias_grad).Output(value_bias_grad).Output(out_proj_bias_grad) - .Attr("attn_head_num", attn_head_num).Attr("attn_dim_per_head", attn_dim_per_head) - .Attr("src_len", src_len).Attr("tgt_len", tgt_len) - .Attr("keep_prob", static_cast(1 - dropout_prob)).Attr("softmax_use_float", softmax_use_float) - .Attr("bias_grad_mask", bias_grad_mask) - .Run(); - - tensor_list result1 = {query_grad, key_grad, value_grad, query_weight_grad, key_weight_grad, value_weight_grad, - out_proj_weight_grad, query_bias_grad, key_bias_grad, value_bias_grad, out_proj_bias_grad}; - - return result1; -} - -class NPUMultiHeadAttentionFunction: public torch::autograd::Function { -public: - static tensor_list forward(AutogradContext *ctx, - const at::Tensor& query, const at::Tensor& key, const at::Tensor& value, - const at::Tensor& query_weight, const at::Tensor& key_weight, const at::Tensor& value_weight, - const at::Tensor& attn_mask, const at::Tensor& out_proj_weight, - const c10::optional& query_bias_opt, const c10::optional& key_bias_opt, - const c10::optional& value_bias_opt, - const c10::optional& out_proj_bias_opt, const c10::optional& dropout_mask_opt, - int64_t attn_head_num, int64_t attn_dim_per_head, - int64_t src_len, int64_t tgt_len, - double dropout_prob, bool softmax_use_float -) { - const at::Tensor& query_bias = c10::value_or_else(query_bias_opt, [] {return at::Tensor();}); - const at::Tensor& key_bias = c10::value_or_else(key_bias_opt, [] {return at::Tensor();}); - const at::Tensor& value_bias = c10::value_or_else(value_bias_opt, [] {return at::Tensor();}); - const at::Tensor& out_proj_bias = c10::value_or_else(out_proj_bias_opt, [] {return at::Tensor();}); - const at::Tensor& mask = c10::value_or_else(dropout_mask_opt, [] {return at::Tensor();}); - - auto result = multi_head_attention_npu(query, key, value, query_weight, key_weight, value_weight, - attn_mask, out_proj_weight, query_bias, key_bias, value_bias, out_proj_bias, mask, attn_head_num, - attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float); - - ctx->saved_data["attn_head_num"] = attn_head_num; - ctx->saved_data["attn_dim_per_head"] = attn_dim_per_head; - ctx->saved_data["src_len"] = src_len; - ctx->saved_data["tgt_len"] = tgt_len; - ctx->saved_data["dropout_prob"] = dropout_prob; - ctx->saved_data["softmax_use_float"] = softmax_use_float; - - at::AutoNonVariableTypeMode g; - - ctx->save_for_backward({query, key, value, query_weight, key_weight, value_weight, attn_mask, - out_proj_weight, query_bias, key_bias, value_bias, out_proj_bias, result[1], result[2], result[3], - result[4], result[5], result[6], result[7]}); - - return result; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto attn_head_num = ctx->saved_data["attn_head_num"].toInt(); - auto attn_dim_per_head = ctx->saved_data["attn_dim_per_head"].toInt(); - auto src_len = ctx->saved_data["src_len"].toInt(); - auto tgt_len = ctx->saved_data["tgt_len"].toInt(); - auto dropout_prob = ctx->saved_data["dropout_prob"].toDouble(); - auto softmax_use_float = ctx->saved_data["softmax_use_float"].toBool(); - - auto saved = ctx->get_saved_variables(); - auto query = saved[0]; - auto key = saved[1]; - auto value = saved[2]; - auto query_weight = saved[3]; - auto key_weight = saved[4]; - auto value_weight = saved[5]; - auto attn_mask = saved[6]; - auto out_proj_weight = saved[7]; - auto query_bias = saved[8]; - auto key_bias = saved[9]; - auto value_bias = saved[10]; - - auto out_proj_bias = saved[11]; - auto result1 = saved[12]; - auto result2 = saved[13]; - auto result3 = saved[14]; - auto result4 = saved[15]; - auto result5 = saved[16]; - auto result6 = saved[17]; - auto result7 = saved[18]; - auto result = NPUNativeFunctions::npu_multi_head_attention_backward( - query, - key, - value, - query_weight, - key_weight, - value_weight, - out_proj_weight, - query_bias, - key_bias, - value_bias, - out_proj_bias, - result2, - result3, - result4, - result5, - result6, - result7, - grad_outputs[0], - result1, - attn_head_num, - attn_dim_per_head, - src_len, - tgt_len, - dropout_prob, - softmax_use_float); - - tensor_list output = { - result[0], - result[1], - result[2], - result[3], - result[4], - result[5], - at::Tensor(), - result[6], - result[7], - result[8], - result[9], - result[10], - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor() - }; - return output; - } -}; - -std::vector NPUNativeFunctions::npu_multi_head_attention(const at::Tensor& query, const at::Tensor& key, - const at::Tensor& value, const at::Tensor& query_weight, const at::Tensor& key_weight, - const at::Tensor& value_weight, const at::Tensor& attn_mask, const at::Tensor& out_proj_weight, - const c10::optional& query_bias_opt, const c10::optional& key_bias_opt, - const c10::optional& value_bias_opt, - const c10::optional& out_proj_bias_opt, const c10::optional& dropout_mask_opt, - int64_t attn_head_num, int64_t attn_dim_per_head, - int64_t src_len, int64_t tgt_len, - double dropout_prob, bool softmax_use_float) { - return NPUMultiHeadAttentionFunction::apply(query, key, value, query_weight, key_weight, value_weight, - attn_mask, out_proj_weight, query_bias_opt, key_bias_opt, value_bias_opt, out_proj_bias_opt, - dropout_mask_opt, attn_head_num, attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float); -} - -}} // namespace at::native \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/MultinomialKernelNpu.cpp b/torch_npu/csrc/aten/ops/MultinomialKernelNpu.cpp deleted file mode 100644 index 0e5bc0bd10..0000000000 --- a/torch_npu/csrc/aten/ops/MultinomialKernelNpu.cpp +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& multinomial_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - int64_t num_samples, - bool replacement, - c10::optional gen) { - - OpCommand cmd; - cmd.Name("MultinomialWithReplacementD") - .Input(self) - .Output(result) - .Attr("num_samples", num_samples) - .Attr("replacement", replacement) - .Run(); - - return result; -} - - -at::Tensor& NPUNativeFunctions::multinomial_out( - const at::Tensor& self, - int64_t num_samples, - bool replacement, - c10::optional gen, - at::Tensor& result){ - - auto input_dim = self.dim(); - TORCH_CHECK(input_dim==1 || input_dim==2, "dim of input tensor only can be 1 or 2."); - - auto output_dim = result.dim(); - TORCH_CHECK(input_dim==output_dim, "dim of output tensor must equal to input tensor."); - - auto num = result.size(output_dim-1); - TORCH_CHECK(num == num_samples, "column of output tensor must equal num_samples."); - - multinomial_out_npu_nocheck(result, self, num_samples, replacement, gen); - - return result; -} - -at::Tensor NPUNativeFunctions::multinomial( - const at::Tensor& self, - int64_t num_samples, - bool replacement, - c10::optional gen){ - - auto dim = self.dim(); - TORCH_CHECK(dim==1 || dim==2, "dim of input tensor only can be 1 or 2."); - - auto shape = array_to_small_vector(self.sizes()); - shape[dim-1] = num_samples; - - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - shape, self.options().dtype(at::kLong), CalcuOpUtil::get_tensor_npu_format(self)); - multinomial_out_npu_nocheck(result, self, num_samples, replacement, gen); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/MvKernelNpu.cpp b/torch_npu/csrc/aten/ops/MvKernelNpu.cpp deleted file mode 100644 index 9050e114e6..0000000000 --- a/torch_npu/csrc/aten/ops/MvKernelNpu.cpp +++ /dev/null @@ -1,76 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu -{ - namespace native - { - - at::Tensor &mv_out_npu_nocheck(const at::Tensor &self, const at::Tensor &vec, at::Tensor &result) - { - bool isSelfT = CalcuOpUtil::is_transpose_last_two_dims(self); - at::Tensor contiguousSelf; - contiguousSelf = isSelfT ? self : NpuUtils::format_contiguous(self); - at::Tensor vecT = at::unsqueeze(vec, 1); - - OpCommand cmd; - cmd.Name("MatMul") - .InputWithoutContiguous(contiguousSelf) - .Input(vecT) - .Attr("transpose_x1", isSelfT) - .Attr("transpose_x2", false) - .Output(result) - .Run(); - - result = at::squeeze(result, 1); - npu_fast_reshape_(result); - return result; - } - - at::Tensor &NPUNativeFunctions::mv_out(const at::Tensor &self, const at::Tensor &vec, at::Tensor &result) - { - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - {self.size(0)}); - - result = at::unsqueeze(result, 1); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self, vec}, {result}) - .Func([&self, &vec](at::Tensor &result) - { mv_out_npu_nocheck(self, vec, result); }) - .Call(result); - } - - at::Tensor NPUNativeFunctions::mv(const at::Tensor &self, const at::Tensor &vec) - { - - at::Tensor result = OpPreparation::ApplyTensor(self, {self.size(0), 1}); - - mv_out_npu_nocheck(self, vec, result); - - return result; - } - - } // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/NeKernelNpu.cpp b/torch_npu/csrc/aten/ops/NeKernelNpu.cpp index adbb7587b3..68b046e12d 100644 --- a/torch_npu/csrc/aten/ops/NeKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/NeKernelNpu.cpp @@ -15,13 +15,19 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { at::Tensor& ne_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, const at::Tensor& other) { - auto unified_result = OpPreparation::comparison_op_check(result, self, other, true); + at::Tensor selfCast = self; + at::Tensor otherCast = other; + if(self.dtype() == at::ScalarType::Int || other.dtype() == at::ScalarType::Int){ + selfCast = self.to(at::ScalarType::Float); + otherCast = other.to(at::ScalarType::Float); + } + auto unified_result = OpPreparation::comparison_op_check(result, selfCast, otherCast, true); if(self.scalar_type() == at::kLong) { TORCH_WARN_ONCE("The oprator of ne is executed, Currently High Accuracy but Low Performance OP with 64-bit has been used," "Please Do Some Cast at Python Functions with 32-bit for Better Performance!"); @@ -29,30 +35,34 @@ at::Tensor& ne_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, const OpCommand cmd; cmd.Name("NotEqual") .Expect(unified_result) - .Input(self) - .Input(other) + .Input(selfCast) + .Input(otherCast) .Output(result) .Run(); return result; } -at::Tensor& ne_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, at::Scalar other) { +at::Tensor& ne_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, const at::Scalar& other) { + at::Tensor selfCast = self; + if(self.dtype() == at::ScalarType::Int){ + selfCast = self.to(at::ScalarType::Float); + } if(self.scalar_type() == at::kLong) { TORCH_WARN_ONCE("The oprator of ne is executed, Currently High Accuracy but Low Performance OP with 64-bit has been used," "Please Do Some Cast at Python Functions with 32-bit for Better Performance!"); } OpCommand cmd; cmd.Name("NotEqual") - .Input(self) - .Input(other, self.scalar_type()) + .Input(selfCast) + .Input(other, selfCast.scalar_type()) .Output(result) .Run(); return result; } -at::Tensor& NPUNativeFunctions::ne_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { +at::Tensor& XLANativeFunctions::ne_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); auto outputSize = broadcast_ops_npu_output_size(self, other); @@ -66,7 +76,7 @@ at::Tensor& NPUNativeFunctions::ne_out(const at::Tensor& self, const at::Tensor& return result; } -at::Tensor& NPUNativeFunctions::ne_out(const at::Tensor& self, at::Scalar other, at::Tensor& result) { +at::Tensor& XLANativeFunctions::ne_out(const at::Tensor& self, const at::Scalar& other, at::Tensor& result) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); OpPreparation::CheckOut( {self}, @@ -78,7 +88,7 @@ at::Tensor& NPUNativeFunctions::ne_out(const at::Tensor& self, at::Scalar other, return result; } -at::Tensor NPUNativeFunctions::ne(const at::Tensor& self, const at::Tensor& other) { +at::Tensor XLANativeFunctions::ne(const at::Tensor& self, const at::Tensor& other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); @@ -92,7 +102,7 @@ at::Tensor NPUNativeFunctions::ne(const at::Tensor& self, const at::Tensor& othe return result; } -at::Tensor NPUNativeFunctions::ne(const at::Tensor& self, at::Scalar other) { +at::Tensor XLANativeFunctions::ne(const at::Tensor& self, const at::Scalar& other) { at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); at::Tensor result = OpPreparation::ApplyTensor( @@ -103,7 +113,7 @@ at::Tensor NPUNativeFunctions::ne(const at::Tensor& self, at::Scalar other) { return result; } -at::Tensor& NPUNativeFunctions::ne_(at::Tensor& self, const at::Tensor& other) { +at::Tensor& XLANativeFunctions::ne_(at::Tensor& self, const at::Tensor& other) { OpPreparation::CastBackToOriFormat(self); OpPreparation::CastBackToOriFormat(other); OpPreparation::CheckMemory({self, other}, {self}); @@ -124,7 +134,7 @@ at::Tensor& NPUNativeFunctions::ne_(at::Tensor& self, const at::Tensor& other) { return self; } -at::Tensor& NPUNativeFunctions::ne_(at::Tensor& self, at::Scalar other) { +at::Tensor& XLANativeFunctions::ne_(at::Tensor& self, const at::Scalar& other) { OpPreparation::CastBackToOriFormat(self); OpPreparation::CheckMemory({self}, {self}); at::Tensor result = OpPreparation::ApplyTensor( diff --git a/torch_npu/csrc/aten/ops/NegKernelNpu.cpp b/torch_npu/csrc/aten/ops/NegKernelNpu.cpp index a3ae15a640..e073efe616 100644 --- a/torch_npu/csrc/aten/ops/NegKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/NegKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -34,7 +34,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::neg_out(const at::Tensor &self, at::Tensor &result) + at::Tensor &XLANativeFunctions::neg_out(const at::Tensor &self, at::Tensor &result) { OpPreparation::CheckOut( {self}, @@ -47,7 +47,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::neg(const at::Tensor &self) + at::Tensor XLANativeFunctions::neg(const at::Tensor &self) { // construct the output tensor of the NPU at::Tensor result = OpPreparation::ApplyTensorWithFormat( @@ -59,7 +59,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::neg_(at::Tensor &self) + at::Tensor &XLANativeFunctions::neg_(at::Tensor &self) { c10::SmallVector inputs = {self}; c10::SmallVector outputs = {self}; diff --git a/torch_npu/csrc/aten/ops/NmsRotatedKernelNpu.cpp b/torch_npu/csrc/aten/ops/NmsRotatedKernelNpu.cpp deleted file mode 100644 index 046a6d4192..0000000000 --- a/torch_npu/csrc/aten/ops/NmsRotatedKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple NPUNativeFunctions::npu_nms_rotated( - const at::Tensor& dets, - const at::Tensor& scores, - double iouThreshold, - double scoreThreshold, - int64_t maxOutputSize, - int64_t mode) { - c10::SmallVector selectedIndexSize = {dets.size(0)}; - c10::SmallVector selectedNumSize = {1}; - - at::Tensor selectedIndex = OpPreparation::ApplyTensor(selectedIndexSize, dets.options().dtype(at::kInt), dets); - at::Tensor selectedNum = OpPreparation::ApplyTensor(selectedNumSize, dets.options().dtype(at::kInt), dets); - - // the Op only support fp32 currently! - auto originDtype = dets.scalar_type(); - at::Tensor detsCast = dets; - at::Tensor scoresCast = scores; - if(originDtype != at::ScalarType::Float){ - detsCast = NPUNativeFunctions::npu_dtype_cast(dets, at::kFloat); - scoresCast = NPUNativeFunctions::npu_dtype_cast(scores, at::kFloat); - } - - OpCommand cmd; - cmd.Name("PolyNMS") - .Input(detsCast) - .Input(scoresCast) - .Output(selectedIndex) - .Output(selectedNum) - .Attr("iou_threshold", (float)iouThreshold) - .Attr("score_threshold", (float)scoreThreshold) - .Attr("max_output_size", maxOutputSize) - .Attr("mode", mode) - .Run(); - - at::Tensor selectedInd = selectedIndex.slice(0, 0, selectedNum.item().toLong()); - return std::tie(selectedInd, selectedNum); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/NmsV4KernelNpu.cpp b/torch_npu/csrc/aten/ops/NmsV4KernelNpu.cpp deleted file mode 100644 index ac777eaf97..0000000000 --- a/torch_npu/csrc/aten/ops/NmsV4KernelNpu.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple nms_v4_npu_nocheck( - const at::Tensor& self, - const at::Tensor& scores, - at::Scalar max_output_size, - const at::Tensor& iou_threshold, - const at::Tensor& scores_threshold, - bool pad_to_max_output_size, - at::Tensor& selected_indices, - at::Tensor& valid_outputs) { - at::Tensor max_output_size_tensor = OpPreparation::ApplyTensor( - {}, self.options().dtype(at::kInt), self).fill_(max_output_size); - OpCommand cmd; - cmd.Name("NonMaxSuppressionV4") - .Input(self) - .Input(scores) - .Input(max_output_size_tensor) - .Input(iou_threshold) - .Input(scores_threshold) - .Output(selected_indices) - .Output(valid_outputs) - .Attr("pad_to_max_output_size", pad_to_max_output_size) - .Run(); - - return std::tuple(selected_indices, valid_outputs); -} - -tuple NPUNativeFunctions::npu_nms_v4( - const at::Tensor& self, - const at::Tensor& scores, - at::Scalar max_output_size, - const at::Tensor& iou_threshold, - const at::Tensor& scores_threshold, - bool pad_to_max_output_size) { - auto outputSizes = nms_v4_npu_output_size(max_output_size); - - at::Tensor selected_indices = OpPreparation::ApplyTensor( - std::get<0>(outputSizes), - self.options().dtype(at::kInt), - self); - at::Tensor valid_outputs = OpPreparation::ApplyTensor( - std::get<1>(outputSizes), - self.options().dtype(at::kInt), - self); - - nms_v4_npu_nocheck( - self, - scores, - max_output_size, - iou_threshold, - scores_threshold, - pad_to_max_output_size, - selected_indices, - valid_outputs); - - return std::tuple(selected_indices, valid_outputs); -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/NmsWithMaskKernelNpu.cpp b/torch_npu/csrc/aten/ops/NmsWithMaskKernelNpu.cpp deleted file mode 100644 index 1870a286d7..0000000000 --- a/torch_npu/csrc/aten/ops/NmsWithMaskKernelNpu.cpp +++ /dev/null @@ -1,54 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple nms_with_mask_npu_nocheck( - const at::Tensor& input, - at::Scalar iou_threshold, - at::Tensor& boxes, - at::Tensor& idx, - at::Tensor& mask) { - float iouThresholdValue = CalcuOpUtil::get_scalar_float_value(iou_threshold); - OpCommand cmd; - cmd.Name("NMSWithMask") - .Input(input) - .Output(boxes) - .Output(idx) - .Output(mask) - .Attr("iou_threshold", iouThresholdValue) - .Run(); - return std::tuple(boxes, idx, mask); -} - -tuple NPUNativeFunctions::npu_nms_with_mask( - const at::Tensor& input, - at::Scalar iou_threshold) { - auto outputSizes = nms_with_mask_npu_output_size(input); - at::Tensor boxes = OpPreparation::ApplyTensor(input, std::get<0>(outputSizes)); - at::Tensor idx = OpPreparation::ApplyTensor(std::get<1>(outputSizes), input.options().dtype(at::kInt), input); - at::Tensor mask = OpPreparation::ApplyTensor(std::get<2>(outputSizes), input.options().dtype(at::kByte), input); - nms_with_mask_npu_nocheck(input, iou_threshold, boxes, idx, mask); - return std::tuple(boxes, idx, mask); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/NnpackSpatialConvolutionKernelNpu.cpp b/torch_npu/csrc/aten/ops/NnpackSpatialConvolutionKernelNpu.cpp deleted file mode 100644 index 688c8ebbab..0000000000 --- a/torch_npu/csrc/aten/ops/NnpackSpatialConvolutionKernelNpu.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector _nnpack_spatial_convolution_input( - const c10::SmallVector& input_tensor) { - c10::SmallVector inputTensors; - for (int i = 0; i < input_tensor.size(); i++) { - if (input_tensor[i].defined()) { - inputTensors.emplace_back(input_tensor[i]); - } - } - return CalcuOpUtil::create_npu_input_tensor_desc(inputTensors); -} - -c10::SmallVector _nnpack_spatial_convolution_output( - const c10::SmallVector& result) { - return CalcuOpUtil::create_npu_output_tensor_desc({result}); -} - -c10::SmallVector _nnpack_spatial_convolution_attr( - at::IntArrayRef padding, - at::IntArrayRef stride) { - c10::SmallVector paddings = { - padding[0], padding[0], padding[0], padding[0]}; - c10::SmallVector stridesSize = {1, 1, stride[0], stride[0]}; - - if (padding.size() != 1) { - paddings[2] = padding[1]; - paddings[3] = padding[1]; - } - if (stride.size() != 1) { - stridesSize[3] = stride[1]; - } - - c10::SmallVector dilations = {1, 1, 1, 1}; - string dataFormat = "NCHW"; - int64_t groups = 1; - - NPUAttrDesc npuAttrStrides = NPUAttrDesc("strides", stridesSize); - NPUAttrDesc npuAttrPads = NPUAttrDesc("pads", paddings); - NPUAttrDesc npuAttrDilations = NPUAttrDesc("dilations", dilations); - NPUAttrDesc npuAttrGroups = NPUAttrDesc("groups", groups); - NPUAttrDesc npuAttrDataFormat = NPUAttrDesc("data_format", dataFormat); - - c10::SmallVector attrs = { - npuAttrStrides, - npuAttrPads, - npuAttrDilations, - npuAttrGroups, - npuAttrDataFormat}; - - return attrs; -} - -at::Tensor _nnpack_spatial_convolution_output_npu( - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& bias, - at::IntArrayRef padding, - at::IntArrayRef stride, - at::Tensor& result) { - auto inputs = _nnpack_spatial_convolution_input({input, weight, bias}); - auto outputs = _nnpack_spatial_convolution_output({result}); - - // constructs the attr of the NPUAttrDesc - auto attrs = _nnpack_spatial_convolution_attr(stride, padding); - - // executing the NPU operator - CalcuOpUtil::execute_npu_operate("Conv2D", inputs, outputs, attrs); - return result; -} - -at::Tensor NPUNativeFunctions::_nnpack_spatial_convolution( - const at::Tensor& input, - const at::Tensor& weight, - const c10::optional& bias_opt, - at::IntArrayRef padding, - at::IntArrayRef stride) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = nnpack_spatial_convolution_npu_output_size( - input, weight, padding, stride); - at::Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, input.options(), ACL_FORMAT_NC1HWC0); - _nnpack_spatial_convolution_output_npu( - input, weight, bias, padding, stride, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/NonzeroKernelNpu.cpp b/torch_npu/csrc/aten/ops/NonzeroKernelNpu.cpp deleted file mode 100644 index 640564e8dd..0000000000 --- a/torch_npu/csrc/aten/ops/NonzeroKernelNpu.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies. -// 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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& nonzero_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("NonZero") - .Input(self) - .Output(result) - .Attr("transpose", false) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::nonzero_out(const at::Tensor& self, at::Tensor& result) { - auto outputSize = nonzero_npu_output_size(self); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - at::ScalarType::Long, - outputSize); - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){nonzero_out_npu_nocheck(result, self);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::nonzero(const at::Tensor& self) { - // calculate the output size - auto outputSize = nonzero_npu_output_size(self); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor( - outputSize, self.options().dtype(at::kLong), self); - - // calculate the output result of the NPU - nonzero_out_npu_nocheck(result, self); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/NormKernelNpu.cpp b/torch_npu/csrc/aten/ops/NormKernelNpu.cpp deleted file mode 100644 index fa42b6cd1d..0000000000 --- a/torch_npu/csrc/aten/ops/NormKernelNpu.cpp +++ /dev/null @@ -1,164 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "climits" - -namespace at_npu { -namespace native { - -int64_t calculate_p(c10::optional p) { - if (p.has_value()) { - float val = CalcuOpUtil::get_scalar_float_value(p.value()); - if (val == INFINITY) { - return static_cast(INT_MAX); // p = inf - } else if (val == -INFINITY) { - return static_cast(INT_MIN); // p = -inf - } else { - return static_cast(val); - } - } else { - return static_cast(2); // default: p = 2 - } -} - -// norm.dtype_out -at::Tensor &norm_out_npu_nocheck( - at::Tensor &out, - const at::Tensor &self, - c10::optional p, - at::IntArrayRef dim, - bool keepdim, - at::ScalarType dtype) { - at::Tensor fp32Self(self); - if (self.scalar_type() != at::ScalarType::Float) { - fp32Self = fp32Self.to(at::ScalarType::Float); - } - auto outputSize = reduce_ops_npu_output_size(fp32Self, dim, keepdim); - if (outputSize.empty()){ - outputSize.push_back(1); - } - at::Tensor resultTemp = OpPreparation::ApplyTensorWithSizes(outputSize, fp32Self.options()); - at::Tensor result = OpPreparation::ApplyTensorWithSizes(outputSize, fp32Self.options()); - auto pvalue = calculate_p(p); - OpCommand cmd1; - cmd1.Name("LpNormReduce") - .Input(fp32Self) - .Output(resultTemp) - .Attr("p", pvalue) - .Attr("axes", dim) - .Attr("keepdim", keepdim) - .Attr("epsilon", static_cast(0)) - .Run(); - - OpCommand cmd2; - cmd2.Name("LpNormUpdate") - .Input(resultTemp) - .Output(result) - .Attr("p", pvalue) - .Attr("epsilon", static_cast(0)) - .Run(); - // trans dtype for output - if (result.scalar_type() != dtype) { - result = result.to(dtype); - } - // until now, can not support resize shape of out correctly, - // so the shape of out must be equal to outputSize - out = out.copy_(result); - return out; -} - -// norm.out -at::Tensor &NPUNativeFunctions::norm_out( - const at::Tensor &self, - c10::optional p, - at::IntArrayRef dim, - bool keepdim, - at::Tensor &out) { - auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim); - OpPreparation::CheckOut( - {self}, - out, - ACL_FORMAT_ND, - self.scalar_type(), - outputSize); - norm_out_npu_nocheck(out, self, p, dim, keepdim, self.scalar_type()); - return out; -} - -// norm.dtype_out -at::Tensor &NPUNativeFunctions::norm_out( - const at::Tensor &self, - c10::optional p, - at::IntArrayRef dim, - bool keepdim, - at::ScalarType dtype, - at::Tensor &out) { - auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim); - OpPreparation::CheckOut( - {self}, - out, - ACL_FORMAT_ND, - self.scalar_type(), - outputSize); - - norm_out_npu_nocheck(out, self, p, dim, keepdim, dtype); - return out; -} -// norm.ScalarOpt_dim_dtype -at::Tensor NPUNativeFunctions::norm( - const at::Tensor &self, - c10::optional p, - at::IntArrayRef dim, - bool keepdim, - at::ScalarType dtype) -{ - auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim); - at::Tensor out = OpPreparation::ApplyTensorWithSizes(outputSize, self.options().dtype(dtype)); - norm_out_npu_nocheck(out, self, p, dim, keepdim, dtype); - return out; -} - -// norm.ScalarOpt_dtype -at::Tensor NPUNativeFunctions::norm( - const at::Tensor &self, - c10::optional p, - at::ScalarType dtype) -{ - return NPUNativeFunctions::norm(self, p, {}, false, dtype); -} - -// norm.Scalar -at::Tensor NPUNativeFunctions::norm( - const at::Tensor &self, - at::Scalar p) -{ - return NPUNativeFunctions::norm(self, p, {}, false, self.scalar_type()); -} - -// norm.ScalarOpt_dim -at::Tensor NPUNativeFunctions::norm( - const at::Tensor &self, - c10::optional p, - at::IntArrayRef dim, - bool keepdim) -{ - return NPUNativeFunctions::norm(self, p, dim, keepdim, self.scalar_type()); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/NormalKernelNpu.cpp b/torch_npu/csrc/aten/ops/NormalKernelNpu.cpp index 41ca2ace0e..ab537c482e 100644 --- a/torch_npu/csrc/aten/ops/NormalKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/NormalKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" namespace at_npu @@ -23,7 +23,7 @@ namespace at_npu namespace native { - at::Tensor &NPUNativeFunctions::normal_out( + at::Tensor &XLANativeFunctions::normal_out( const at::Tensor &mean, double std, c10::optional generator, @@ -51,7 +51,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::normal_out( + at::Tensor &XLANativeFunctions::normal_out( double mean, const at::Tensor &std, c10::optional generator, @@ -77,7 +77,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::normal_out( + at::Tensor &XLANativeFunctions::normal_out( const at::Tensor &mean, const at::Tensor &std, c10::optional generator, @@ -108,7 +108,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::normal_out( + at::Tensor &XLANativeFunctions::normal_out( double mean, double std, at::IntArrayRef size, @@ -118,7 +118,7 @@ namespace at_npu TORCH_CHECK(std > 0.0, "normal_ expects std > 0.0, but found std=", std); // the op of PTNormalFloatFloat only support format of ND - at::Tensor formatCastOfResult = NPUNativeFunctions::npu_format_cast(result, ACL_FORMAT_ND); + at::Tensor formatCastOfResult = XLANativeFunctions::npu_format_cast(result, ACL_FORMAT_ND); if (formatCastOfResult.scalar_type() == at::ScalarType::Half) { formatCastOfResult = formatCastOfResult.to(at::ScalarType::Float); @@ -138,40 +138,40 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::normal( + at::Tensor XLANativeFunctions::normal( const at::Tensor &mean, double std, c10::optional generator) { at::Tensor result = OpPreparation::ApplyTensor(mean); - NPUNativeFunctions::normal_out(mean, std, generator, result); + XLANativeFunctions::normal_out(mean, std, generator, result); return result; } - at::Tensor NPUNativeFunctions::normal( + at::Tensor XLANativeFunctions::normal( double mean, const at::Tensor &std, c10::optional generator) { at::Tensor result = OpPreparation::ApplyTensor(std); - NPUNativeFunctions::normal_out(mean, std, generator, result); + XLANativeFunctions::normal_out(mean, std, generator, result); return result; } - at::Tensor NPUNativeFunctions::normal( + at::Tensor XLANativeFunctions::normal( const at::Tensor &mean, const at::Tensor &std, c10::optional generator) { at::Tensor result = OpPreparation::ApplyTensor(mean); - NPUNativeFunctions::normal_out(mean, std, generator, result); + XLANativeFunctions::normal_out(mean, std, generator, result); return result; } - at::Tensor NPUNativeFunctions::normal( + at::Tensor XLANativeFunctions::normal( double mean, double std, at::IntArrayRef size, @@ -182,16 +182,16 @@ namespace at_npu c10::optional pin_memory_opt) { // construct the output tensor of the NPU - at::Tensor result = NPUNativeFunctions::empty_with_format( + at::Tensor result = XLANativeFunctions::empty_with_format( size, dtype_opt, layout_opt, device_opt, pin_memory_opt, ACL_FORMAT_ND); // calculate the output result of the NPU - NPUNativeFunctions::normal_out(mean, std, size, generator, result); + XLANativeFunctions::normal_out(mean, std, size, generator, result); return result; } - at::Tensor &NPUNativeFunctions::normal_( + at::Tensor &XLANativeFunctions::normal_( at::Tensor &self, double mean, double std, @@ -201,12 +201,12 @@ namespace at_npu if (!NpuUtils::check_match(&self)) { at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::normal_out(mean, std, contiguousSelf.sizes(), generator, contiguousSelf); + at::Tensor result = XLANativeFunctions::normal_out(mean, std, contiguousSelf.sizes(), generator, contiguousSelf); NpuUtils::format_fresh_view(self, result); } else { - NPUNativeFunctions::normal_out(mean, std, self.sizes(), generator, self); + XLANativeFunctions::normal_out(mean, std, self.sizes(), generator, self); } return self; diff --git a/torch_npu/csrc/aten/ops/NormalizeBatchKernelNpu.cpp b/torch_npu/csrc/aten/ops/NormalizeBatchKernelNpu.cpp deleted file mode 100644 index 2231fe96fe..0000000000 --- a/torch_npu/csrc/aten/ops/NormalizeBatchKernelNpu.cpp +++ /dev/null @@ -1,67 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -constexpr float_t EPSILON = 1e-5; - -namespace at_npu { -namespace native { - -static inline void normalize_batch_check( - const at::Tensor& self, - const at::Tensor& seq_len, - int64_t normalize_type){ - TORCH_CHECK( - seq_len.dim() == 1, - "Non-empty 1D seq_len tensor expected but got a tensor with sizes ", - seq_len.sizes()); - TORCH_CHECK( - seq_len.size(0) == self.size(0), - "seq_len's length should be equal self' num, but got seq_len length ", - seq_len.size(0), - "self num ", - self.size(0)); - TORCH_CHECK( - normalize_type >= 0 && normalize_type <= 1, - "normalize_type expected to be in range [0, 1], but got ", - normalize_type); -} - -at::Tensor NPUNativeFunctions::npu_normalize_batch( - const at::Tensor& self, - const at::Tensor& seq_len, - int64_t normalize_type){ - normalize_batch_check(self, seq_len, normalize_type); - // apply output tensor - at::Tensor result = OpPreparation::ApplyTensor(self); - string normalizeType = normalize_type == 0 ? "per_feature" : "all_features"; - - OpCommand cmd; - cmd.Name("NormalizeBatch") - .Input(self) - .Input(seq_len) - .Output(result) - .Attr("normalize_type", normalizeType) - .Attr("epsilon", EPSILON) - .Run(); - return result; -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/OneHotKernelNpu.cpp b/torch_npu/csrc/aten/ops/OneHotKernelNpu.cpp index 2381cc4cf8..8431fc8331 100644 --- a/torch_npu/csrc/aten/ops/OneHotKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/OneHotKernelNpu.cpp @@ -13,16 +13,16 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor NPUNativeFunctions::one_hot(const at::Tensor& self, int64_t num_classes) { +at::Tensor XLANativeFunctions::one_hot(const at::Tensor& self, int64_t num_classes) { at::Scalar on_value = 1; at::Scalar off_value = 0; int64_t axis = -1; - at::Scalar depth; + int64_t depth; auto self_temp = self.to(at::kFloat); TORCH_CHECK( @@ -48,16 +48,16 @@ at::Tensor NPUNativeFunctions::one_hot(const at::Tensor& self, int64_t num_class } auto outputSize = array_to_small_vector(self.sizes()); - outputSize.emplace_back(depth.toLong()); + outputSize.emplace_back(depth); at::Tensor result = OpPreparation::ApplyTensor( outputSize, self.options().dtype(at::ScalarType::Int), self); - + c10::SmallVector depthList = {depth}; OpCommand cmd; cmd.Name("OneHot") .Input(self) - .Input(depth, at::kInt) + .Input(depthList, at::kInt) .Input(on_value, at::ScalarType::Int) .Input(off_value, at::ScalarType::Int) .Output(result) diff --git a/torch_npu/csrc/aten/ops/OnehotNpu.cpp b/torch_npu/csrc/aten/ops/OnehotNpu.cpp index 88e1df181a..52dc2102b2 100644 --- a/torch_npu/csrc/aten/ops/OnehotNpu.cpp +++ b/torch_npu/csrc/aten/ops/OnehotNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -25,9 +25,9 @@ at::Tensor& one_hot_out_npu( const at::Tensor& self, int64_t axis, int64_t depth, - at::Scalar on_value, - at::Scalar off_value) { - at::Tensor selfCp = NPUNativeFunctions::npu_dtype_cast(self, at::kInt); + const at::Scalar& on_value, + const at::Scalar& off_value) { + at::Tensor selfCp = XLANativeFunctions::npu_dtype_cast(self, at::kInt); at::Tensor on_tmp = OpPreparation::ApplyTensor( {1}, selfCp.options().dtype(at::ScalarType::Float), @@ -50,12 +50,12 @@ at::Tensor& one_hot_out_npu( return result; } -at::Tensor NPUNativeFunctions::npu_one_hot( +at::Tensor XLANativeFunctions::npu_one_hot( const at::Tensor& self, int64_t axis, int64_t depth, - at::Scalar on_value, - at::Scalar off_value) { + const at::Scalar& on_value, + const at::Scalar& off_value) { auto outputSize = array_to_small_vector(self.sizes()); outputSize.emplace_back(depth); diff --git a/torch_npu/csrc/aten/ops/OnesKernelNpu.cpp b/torch_npu/csrc/aten/ops/OnesKernelNpu.cpp index 4ad26fbeba..31914c2a1d 100644 --- a/torch_npu/csrc/aten/ops/OnesKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/OnesKernelNpu.cpp @@ -17,16 +17,16 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::ones_out(at::IntArrayRef size, at::Tensor& result) { +at::Tensor& XLANativeFunctions::ones_out(at::IntArrayRef size, at::Tensor& result) { result.resize_(size); - return NPUNativeFunctions::one_(result); + return XLANativeFunctions::one_(result); } -at::Tensor NPUNativeFunctions::ones(at::IntArrayRef size, +at::Tensor XLANativeFunctions::ones(at::IntArrayRef size, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -41,10 +41,10 @@ at::Tensor NPUNativeFunctions::ones(at::IntArrayRef size, at::Tensor result = OpPreparation::ApplyTensorWithFormat(size, option, ACL_FORMAT_ND); // calculate the output result of the NPU - return NPUNativeFunctions::one_(result); + return XLANativeFunctions::one_(result); } -at::Tensor NPUNativeFunctions::ones( +at::Tensor XLANativeFunctions::ones( at::IntArrayRef size, c10::optional names, c10::optional dtype_opt, @@ -61,7 +61,7 @@ at::Tensor NPUNativeFunctions::ones( at::Tensor result = OpPreparation::ApplyTensorWithFormat(size, option, ACL_FORMAT_ND); // calculate the output result of the NPU - return NPUNativeFunctions::one_(result); + return XLANativeFunctions::one_(result); } } // namespace native diff --git a/torch_npu/csrc/aten/ops/OnesLikeKernelNpu.cpp b/torch_npu/csrc/aten/ops/OnesLikeKernelNpu.cpp index 64dca1ac41..a4f136fd95 100644 --- a/torch_npu/csrc/aten/ops/OnesLikeKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/OnesLikeKernelNpu.cpp @@ -16,14 +16,14 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" namespace at_npu { namespace native { - at::Tensor NPUNativeFunctions::ones_like(const at::Tensor &self, + at::Tensor XLANativeFunctions::ones_like(const at::Tensor &self, c10::optional dtype_opt, c10::optional layout_opt, c10::optional device_opt, @@ -45,14 +45,14 @@ namespace at_npu auto outputSize = input_same_output_size(self); // construct the output tensor of the NPU - at::Tensor result = NPUNativeFunctions::empty_with_format( + at::Tensor result = XLANativeFunctions::empty_with_format( outputSize, dtype_opt, layout_opt, device_opt, pin_memory_opt, CalcuOpUtil::get_tensor_npu_format(self)); // calculate the output result of the NPUc - return NPUNativeFunctions::one_(result); + return XLANativeFunctions::one_(result); } - at::Tensor &NPUNativeFunctions::one_(at::Tensor &self) + at::Tensor &XLANativeFunctions::one_(at::Tensor &self) { if (!NpuUtils::check_match(&self)) { diff --git a/torch_npu/csrc/aten/ops/PackPaddedSequenceKernelNpu.cpp b/torch_npu/csrc/aten/ops/PackPaddedSequenceKernelNpu.cpp deleted file mode 100644 index dc31470e25..0000000000 --- a/torch_npu/csrc/aten/ops/PackPaddedSequenceKernelNpu.cpp +++ /dev/null @@ -1,74 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::_pack_padded_sequence( - const at::Tensor& _input, - const at::Tensor& _lengths, - bool batch_first) { - auto input = batch_first ? _input.transpose(0, 1) : _input; - auto lengths_t = _lengths.contiguous(); - - int64_t batchSize = input.size(1); - int64_t * lengths = lengths_t.data_ptr(); - TORCH_CHECK(input.numel() > 0, "Cannot pack empty tensors."); - TORCH_CHECK(lengths_t.size(0) == batchSize, - "Expected `len(lengths)` to be equal to batch_size, but got ", lengths_t.size(0), - " (batch_size=", batchSize, ")"); - TORCH_CHECK(lengths[batchSize - 1] > 0, - "Length of all samples has to be greater than 0, but found an element " - "in 'lengths' that is <= 0"); - for(auto i = 0; i < batchSize - 1; i++) { - if (lengths[batchSize - 1 - i] > lengths[batchSize - 2 - i]) { - // NB: enforce_sorted is implemented at a Python level, but the sortedness - // check lives here. If enforce_sorted=False then this error should never - // get called. - AT_ERROR("`lengths` array must be sorted in decreasing order when " - "`enforce_sorted` is True. You can pass `enforce_sorted=False` " - "to pack_padded_sequence and/or pack_sequence to sidestep this " - "requirement if you do not need ONNX exportability."); - } - } - - at::Tensor batchSizesT = at::empty(lengths[0], _lengths.options()); - int64_t * batchSizes = batchSizesT.data_ptr(); - - int64_t prevL = 0; - for (int64_t i = 0; i < batchSize; ++i) { - int64_t l = lengths[batchSize - 1 - i]; - if (l > prevL) { - auto currentBatchSize = batchSize - i; - for (int64_t j = 0; j < (l - prevL); ++j) { - *batchSizes = currentBatchSize; - batchSizes++; - } - prevL = l; - } - TORCH_CHECK(l >= prevL); - } - - int64_t lastDim = _input.size(2); - at::Tensor inputDim2 = _input.contiguous().view({-1, lastDim}); - - return std::tie(inputDim2, batchSizesT); -} - -} -} \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PadKernelNpu.cpp b/torch_npu/csrc/aten/ops/PadKernelNpu.cpp deleted file mode 100644 index 43383b0ef2..0000000000 --- a/torch_npu/csrc/aten/ops/PadKernelNpu.cpp +++ /dev/null @@ -1,48 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& pad_npu_nocheck( - at::Tensor& output, - const at::Tensor& input, - at::IntArrayRef paddings) { - c10::SmallVector paddingsVector = array_to_small_vector(paddings); - paddingsVector.resize(2 * input.dim(), 0); - - OpCommand cmd; - cmd.Name("Pad") - .Input(input) - .Input(paddingsVector) - .Output(output) - .Run(); - return output; -} - -at::Tensor NPUNativeFunctions::npu_pad(const at::Tensor& input, at::IntArrayRef paddings) { - auto outputSize = pad_npu_output_size(input, paddings); - at::Tensor output = OpPreparation::ApplyTensor(input, outputSize); - pad_npu_nocheck(output, input, paddings); - return output; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PadPackedSequenceKernelNpu.cpp b/torch_npu/csrc/aten/ops/PadPackedSequenceKernelNpu.cpp deleted file mode 100644 index 6a25b00221..0000000000 --- a/torch_npu/csrc/aten/ops/PadPackedSequenceKernelNpu.cpp +++ /dev/null @@ -1,64 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::_pad_packed_sequence( - const at::Tensor& data, - const at::Tensor& _batchSizes, - bool batchFirst, - at::Scalar paddingValue, - int64_t totalLength) { - at::Tensor output = data; - auto batchSizesT = _batchSizes.contiguous().to("cpu"); - - int64_t * batchSizes = batchSizesT.data_ptr(); - int64_t maxBatchSize = batchSizes[0]; - int64_t maxRealSeqLength = batchSizesT.size(0); - int64_t maxSeqLength = maxRealSeqLength; - if (totalLength > 0) { - TORCH_CHECK(totalLength >= maxSeqLength, - "Expected total_length to be at least the length of the longest " - "sequence in input, but got total_length=", totalLength, " and " - "max sequence length being ", maxSeqLength); - maxSeqLength = totalLength; - } - - at::Tensor lengthsT = at::empty(maxBatchSize, batchSizesT.options().device(at::kCPU)); - int64_t * lengths = lengthsT.data_ptr() + maxBatchSize - 1; - int64_t prevBatchSize = maxBatchSize; - for (int64_t i = 0; i <= maxRealSeqLength; ++i) { - int64_t batchSize = i != maxRealSeqLength ? batchSizes[i] : 0; - int64_t dec = prevBatchSize - batchSize; - if (dec > 0) { - for (int64_t j = 0; j < dec; ++j) { - *lengths = i; - lengths--; - } - } - prevBatchSize = batchSize; - } - if (batchFirst) { - output = NPUNativeFunctions::npu_transpose(data, {0, 1}, true); - } - return std::tie(output, lengthsT); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PdistKernelNpu.cpp b/torch_npu/csrc/aten/ops/PdistKernelNpu.cpp deleted file mode 100644 index c6db543662..0000000000 --- a/torch_npu/csrc/aten/ops/PdistKernelNpu.cpp +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& pdist_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - float p) { - OpCommand cmd; - cmd.Name("Pdist") - .Input(self) - .Attr("p", p) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::_pdist_forward(const at::Tensor& self, double p) { - at::Tensor result; - if (self.size(0) <= 1) { - result = OpPreparation::ApplyTensor(self, {0}); - } else { - // double is not supported in NPU, type of P needs to be converted from double to float. - float p_float; - if (std::isinf(p)) { - p_float = std::numeric_limits::infinity(); - } else { - TORCH_CHECK(p <= std::numeric_limits::max(), "npu dose not support float64" ); - p_float = static_cast(p); - } - auto outputSize = pdist_npu_output_size(self, p_float); - result = OpPreparation::ApplyTensor(self, outputSize); - if(self.size(1) == 0){ - result.fill_(0); - } else { - pdist_out_npu_nocheck(result, self, p_float); - } - } - return result; -} - -at::Tensor NPUNativeFunctions::pdist(const at::Tensor& self, double p) { - TORCH_CHECK(self.dim() == 2, - "pdist only supports 2D tensors, got: ", self.dim(), "D"); - TORCH_CHECK(at::isFloatingType(self.scalar_type()), "pdist only supports floating-point dtypes"); - TORCH_CHECK(p >= 0, "pdist only supports non-negative p values"); - - return at::_pdist_forward(self, p); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PowKernelNpu.cpp b/torch_npu/csrc/aten/ops/PowKernelNpu.cpp index 1142184fee..4269d152e4 100644 --- a/torch_npu/csrc/aten/ops/PowKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/PowKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -63,7 +63,7 @@ namespace at_npu } // pow.Tensor_Tensor_out - at::Tensor &NPUNativeFunctions::pow_out(const at::Tensor &self, const at::Tensor &exp, at::Tensor &result) + at::Tensor &XLANativeFunctions::pow_out(const at::Tensor &self, const at::Tensor &exp, at::Tensor &result) { auto outputSize = broadcast_ops_npu_output_size(self, exp); OpPreparation::CheckOut( @@ -80,7 +80,7 @@ namespace at_npu } // pow.Tensor_Scalar_out - at::Tensor &NPUNativeFunctions::pow_out(const at::Tensor &self, at::Scalar exp, at::Tensor &result) + at::Tensor &XLANativeFunctions::pow_out(const at::Tensor &self, const at::Scalar &exp, at::Tensor &result) { OpPreparation::CheckOut( {self}, @@ -95,7 +95,7 @@ namespace at_npu } // pow.Scalar_out - at::Tensor &NPUNativeFunctions::pow_out(at::Scalar self, const at::Tensor &exp, at::Tensor &result) + at::Tensor &XLANativeFunctions::pow_out(const at::Scalar &self, const at::Tensor &exp, at::Tensor &result) { OpPreparation::CheckOut( {exp}, @@ -109,7 +109,7 @@ namespace at_npu .Call(result); } - at::Tensor NPUNativeFunctions::pow(const at::Tensor &self, const at::Tensor &exp) + at::Tensor XLANativeFunctions::pow(const at::Tensor &self, const at::Tensor &exp) { // calculate the output size auto outputSize = broadcast_ops_npu_output_size(self, exp); @@ -118,14 +118,14 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::pow(const at::Tensor &self, at::Scalar exp) + at::Tensor XLANativeFunctions::pow(const at::Tensor &self, const at::Scalar &exp) { at::Tensor result = OpPreparation::ApplyTensor(self); pow_tensor_scalar_out_npu_nocheck(self, exp, result); return result; } - at::Tensor NPUNativeFunctions::pow(at::Scalar self, const at::Tensor &exp) + at::Tensor XLANativeFunctions::pow(const at::Scalar &self, const at::Tensor &exp) { // calculate the output size auto outputSize = input_same_output_size(exp); @@ -138,15 +138,15 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::pow_(at::Tensor &self, const at::Tensor &exp) + at::Tensor &XLANativeFunctions::pow_(at::Tensor &self, const at::Tensor &exp) { - NPUNativeFunctions::pow_out(self, exp, self); + XLANativeFunctions::pow_out(self, exp, self); return self; } - at::Tensor &NPUNativeFunctions::pow_(at::Tensor &self, at::Scalar exp) + at::Tensor &XLANativeFunctions::pow_(at::Tensor &self, const at::Scalar &exp) { - NPUNativeFunctions::pow_out(self, exp, self); + XLANativeFunctions::pow_out(self, exp, self); return self; } diff --git a/torch_npu/csrc/aten/ops/PreluBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/PreluBackwardKernelNpu.cpp deleted file mode 100644 index 9d757ad378..0000000000 --- a/torch_npu/csrc/aten/ops/PreluBackwardKernelNpu.cpp +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple prelu_backward_out_npu_nocheck( - at::Tensor& grad_input, - at::Tensor& grad_weight, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight) { - OpCommand cmd; - cmd.Name("PReluGrad") - .Input(grad_output) - .Input(self) - .Input(weight) - .Output(grad_input) - .Output(grad_weight) - .Run(); - return tuple(grad_input, grad_weight); -} - -tuple prelu_backward_out_npu( - at::Tensor& grad_input, - at::Tensor& grad_weight, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight) { - prelu_backward_out_npu_nocheck(grad_input, grad_weight, grad_output, self, weight); - return tuple(grad_input, grad_weight); -} - -tuple NPUNativeFunctions::prelu_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight) { - // construct the output Tensor of the NPU - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - at::Tensor grad_weight = OpPreparation::ApplyTensor(weight); - // calculate the output result of the NPU - prelu_backward_out_npu_nocheck(grad_input, grad_weight, grad_output, self, weight); - return std::tie(grad_input, grad_weight); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PreluKernelNpu.cpp b/torch_npu/csrc/aten/ops/PreluKernelNpu.cpp deleted file mode 100644 index 2b9baa4be8..0000000000 --- a/torch_npu/csrc/aten/ops/PreluKernelNpu.cpp +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::prelu(const at::Tensor& self, const at::Tensor& weight_) { - auto input = self.contiguous(); - auto weight = weight_.contiguous(); - - // calculate the output size - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(input, outputSize); - - OpCommand cmd; - cmd.Name("PRelu") - .Input(self) - .Input(weight) - .Output(result) - .Run(); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ProdKernelNpu.cpp b/torch_npu/csrc/aten/ops/ProdKernelNpu.cpp deleted file mode 100644 index 4d697097d8..0000000000 --- a/torch_npu/csrc/aten/ops/ProdKernelNpu.cpp +++ /dev/null @@ -1,170 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -namespace { -static inline int64_t calculate_prod_output_format( - const at::Tensor& self, - at::IntArrayRef size) { - int64_t npu_format = CalcuOpUtil::get_tensor_npu_format(self); - // scalar scene no support nz - if (size.empty()) { - npu_format = ACL_FORMAT_ND; - } - return npu_format; -} -} - -at::Tensor& prod_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - c10::SmallVector dimList, - bool keepdim, - c10::optional dtype) { - OpCommand cmd; - cmd.Name("ReduceProd") - .Input(self) - .Input(dimList) - .Output(result) - .Attr("keep_dims", keepdim) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::prod_out( - const at::Tensor& self, - int64_t dim, - bool keepdim, - c10::optional dtype, - at::Tensor& result) { - at::Tensor self_tmp = self; - // fp16 transform:fp32 for precise - if (self.scalar_type() == at::ScalarType::Half) { - self_tmp = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - auto outputSize = prod_npu_output_size(self, dim, keepdim); - at::ScalarType dstType = dtype.has_value() ? dtype.value() : self.scalar_type(); - - OpPreparation::CheckOut( - {self_tmp}, - result, - ACL_FORMAT_ND, - dstType, - outputSize); - - at::Tensor result_tmp = result; - if (result_tmp.scalar_type() == at::ScalarType::Half) { - result_tmp = NPUNativeFunctions::npu_dtype_cast(result_tmp, at::ScalarType::Float); - } - - prod_out_npu_nocheck(result_tmp, self_tmp, {dim}, keepdim, dtype); - - if (result_tmp.scalar_type() != dstType) { - result_tmp = NPUNativeFunctions::npu_dtype_cast(result_tmp, dstType); - } - result.copy_(result_tmp); - - return result; -} - -at::Tensor& NPUNativeFunctions::prod_out( - const at::Tensor& self, - at::Dimname dim, - bool keepdim, - c10::optional dtype, - at::Tensor& result) { - return prod_out( - self, dimname_to_position(self, dim), keepdim, dtype, result); -} - -at::Tensor NPUNativeFunctions::prod( - const at::Tensor& self, - int64_t dim, - bool keepdim, - c10::optional dtype) { - at::Tensor self_tmp = self; - // Input transform:fp16 to fp32 - if (self.scalar_type() == at::ScalarType::Half) { - self_tmp = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - at::ScalarType dstType = dtype.has_value() ? dtype.value() : self.scalar_type(); - - // calculate the output size - auto outputSize = prod_npu_output_size(self_tmp, dim, keepdim); - - int64_t npu_format = calculate_prod_output_format(self_tmp, outputSize); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self_tmp.options(), npu_format); - - // calculate the output result of the NPU - prod_out_npu_nocheck(result, self_tmp, {dim}, keepdim, dtype); - - if (result.scalar_type() != dstType) { - result = NPUNativeFunctions::npu_dtype_cast(result, dstType); - } - - return result; -} - -at::Tensor NPUNativeFunctions::prod( - const at::Tensor& self, - at::Dimname dim, - bool keepdim, - c10::optional dtype) { - return prod(self, dimname_to_position(self, dim), keepdim, dtype); -} - -at::Tensor NPUNativeFunctions::prod(const at::Tensor& self, c10::optional dtype) { - at::Tensor self_tmp = self; - // Input transform:fp16 to fp32 - if (self.scalar_type() == at::ScalarType::Half) { - self_tmp = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - at::ScalarType dstType = dtype.has_value() ? dtype.value() : self.scalar_type(); - - // calculate the output size - auto outputSize = prod_npu_output_size(self, false); - - int64_t npu_format = calculate_prod_output_format(self, outputSize); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self_tmp.options(), npu_format); - - // calculate the output result of the NPU - prod_out_npu_nocheck( - result, self_tmp, CalcuOpUtil::get_dimlist_for_tensor(self), false, dtype); - - if (result.scalar_type() != dstType) { - result = npu_dtype_cast(result, dstType); - } - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PsRoiPoolingKernelNpu.cpp b/torch_npu/csrc/aten/ops/PsRoiPoolingKernelNpu.cpp deleted file mode 100644 index fffcf7a470..0000000000 --- a/torch_npu/csrc/aten/ops/PsRoiPoolingKernelNpu.cpp +++ /dev/null @@ -1,168 +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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; -at::Tensor& ps_roi_pooling_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& rois, - double spatial_scale, - int64_t group_size, - int64_t output_dim) { - OpCommand cmd; - cmd.Name("PSROIPoolingV2") - .Input(self) - .Input(rois) - .Output(result) - .Attr("spatial_scale", (float)spatial_scale) - .Attr("output_dim", output_dim) - .Attr("group_size", group_size) - .Run(); - - return result; -} - -at::Tensor ps_roi_pooling( - const at::Tensor& self, - const at::Tensor& rois, - double spatial_scale, - int64_t group_size, - int64_t output_dim) { - auto outputSize ={ - rois.size(0) * rois.size(2), output_dim, group_size, group_size}; - - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - ps_roi_pooling_npu_nocheck( - result, - self, - rois, - spatial_scale, - group_size, - output_dim); - - return result; -} - -at::Tensor& ps_roi_pooling_backward_npu_nocheck( - at::Tensor& input_grad, - const at::Tensor& output_grad, - const at::Tensor& rois, - double spatial_scale, - int64_t group_size, - int64_t output_dim, - at::IntArrayRef input_size) { - OpCommand cmd; - cmd.Name("PSROIPoolingGradV2D") - .Input(output_grad) - .Input(rois) - .Output(input_grad) - .Attr("spatial_scale", (float)spatial_scale) - .Attr("group_size", group_size) - .Attr("output_dim", output_dim) - .Attr("input_size", input_size) - .Run(); - - return input_grad; -} - -at::Tensor NPUNativeFunctions::npu_ps_roi_pooling_backward( - const at::Tensor& output_grad, - const at::Tensor& rois, - double spatial_scale, - int64_t group_size, - int64_t output_dim, - at::IntArrayRef input_size) { - auto outputSize ={ - rois.size(0), group_size * group_size * output_dim, input_size[0], input_size[1]}; - - at::Tensor input_grad = OpPreparation::ApplyTensor(output_grad, outputSize); - - ps_roi_pooling_backward_npu_nocheck( - input_grad, - output_grad, - rois, - spatial_scale, - group_size, - output_dim, - input_size); - - return input_grad; -} - -class NPUPsRoiPoolingFunction: public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - const at::Tensor& rois, - double spatial_scale, - int64_t group_size, - int64_t output_dim) { - ctx->saved_data["spatial_scale"] = spatial_scale; - ctx->saved_data["group_size"] = group_size; - ctx->saved_data["output_dim"] = output_dim; - c10::SmallVector input_size_vec = {self.size(2), self.size(3)}; - at::IntArrayRef input_size(input_size_vec); - ctx->saved_data["input_size"] = input_size; - at::AutoNonVariableTypeMode g; - ctx->save_for_backward({self, rois}); - return ps_roi_pooling(self, rois, spatial_scale, group_size, output_dim); - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto spatial_scale = ctx->saved_data["spatial_scale"].toDouble(); - auto group_size = ctx->saved_data["group_size"].toInt(); - auto output_dim = ctx->saved_data["output_dim"].toInt(); - auto input_size = ctx->saved_data["input_size"].toIntVector(); - auto saved = ctx->get_saved_variables(); - auto self = saved[0]; - auto rois = saved[1]; - - - at::Tensor result = NPUNativeFunctions::npu_ps_roi_pooling_backward(grad_outputs[0], - rois, - spatial_scale, - group_size, - output_dim, - input_size); - tensor_list output = {result, - at::Tensor(), - at::Tensor(), - at::Tensor(), - at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_ps_roi_pooling(const at::Tensor& self, - const at::Tensor& rois, - double spatial_scale, - int64_t group_size, - int64_t output_dim) { - return NPUPsRoiPoolingFunction::apply(self, rois, spatial_scale, group_size, output_dim); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/PutKernelNpu.cpp b/torch_npu/csrc/aten/ops/PutKernelNpu.cpp deleted file mode 100644 index 863e625549..0000000000 --- a/torch_npu/csrc/aten/ops/PutKernelNpu.cpp +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::put_( - at::Tensor& self, - const at::Tensor& index, - const at::Tensor& source, - bool accumulate) { - TORCH_CHECK(index.numel() == source.numel(), "source should have the same number of elements as index"); - if (source.numel() == 0) { - return self; - } - c10::SmallVector inputs = {self}; - c10::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - - at::Tensor selfFlatten = NpuUtils::format_contiguous(self.reshape(-1)); - at::Tensor indexFlatten = index.reshape({-1, 1}); - at::Tensor sourceFlatten = source.reshape(-1); - - OpCommand cmd; - accumulate ? cmd.Name("ScatterNdAdd") : cmd.Name("ScatterNdUpdate"); - cmd.Input(selfFlatten) - .Input(indexFlatten) - .Input(sourceFlatten) - .Output(selfFlatten) - .Attr("use_locking", false) - .Run(); - - self.copy_(selfFlatten); - return self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/QrKernelNpu.cpp b/torch_npu/csrc/aten/ops/QrKernelNpu.cpp deleted file mode 100644 index eca6a59b39..0000000000 --- a/torch_npu/csrc/aten/ops/QrKernelNpu.cpp +++ /dev/null @@ -1,99 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple, c10::SmallVector> qr_npu_output_size( - const at::Tensor& self, - bool some) { - int m = self.size(-2); - int n = self.size(-1); - auto k = std::min(m, n); - auto shape = array_to_small_vector(self.sizes()); - c10::SmallVector Qsize(shape.begin(), shape.end()-2); - c10::SmallVector Rsize(shape.begin(), shape.end()-2); - if(some){ - Qsize.insert(Qsize.end(), {m, k}); - Rsize.insert(Rsize.end(), {k, n}); - } else { - Qsize.insert(Qsize.end(), {m, m}); - Rsize.insert(Rsize.end(), {m, n}); - } - return std::tie(Qsize, Rsize); -} - -static inline void qr_check( - const at::Tensor& self) { - TORCH_CHECK( - self.ndimension() >= 2, - "Expected nonempty least 2D tensor, but got a tensor with sizes ", - self.dim()); -} - -std::tuple qr_out_npu_nocheck( - at::Tensor& Q, - at::Tensor& R, - const at::Tensor& self, - bool some) { - bool full_matrices = !some; - OpCommand cmd; - cmd.Name("Qr") - .Input(self) - .Output(Q) - .Output(R) - .Attr("full_matrices", full_matrices) - .Run(); - return std::tie(Q, R); -} - -std::tuple NPUNativeFunctions::qr_out( - const at::Tensor& self, - bool some, - at::Tensor& Q, - at::Tensor& R) { - qr_check(self); - auto sizes = qr_npu_output_size(self, some); - OpPreparation::CheckOut( - {self}, - Q, - self, - std::get<0>(sizes)); - OpPreparation::CheckOut( - {self}, - R, - self, - std::get<1>(sizes)); - return qr_out_npu_nocheck(Q, R, self, some); -} - -std::tuple NPUNativeFunctions::qr( - const at::Tensor& self, - bool some) { - qr_check(self); - auto sizes = qr_npu_output_size(self, some); - at::Tensor Q = OpPreparation::ApplyTensor(self, std::get<0>(sizes)); - at::Tensor R = OpPreparation::ApplyTensor(self, std::get<1>(sizes)); - - qr_out(self, some, Q, R); - return std::tie(Q, R); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/QuantizePerChannelKernelNpu.cpp b/torch_npu/csrc/aten/ops/QuantizePerChannelKernelNpu.cpp deleted file mode 100644 index 2ce7443def..0000000000 --- a/torch_npu/csrc/aten/ops/QuantizePerChannelKernelNpu.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector quantize_reshape_size( - const at::Tensor& self, - int64_t axis) { - c10::SmallVector outSize; - for(int64_t i=0; i < self.dim(); i++) { - if(i != axis) { - outSize.emplace_back(1); - } else { - outSize.emplace_back(self.sizes()[i]); - } - } - return outSize; -} - -at::Tensor& quantize_per_channel_out_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& scales, - const at::Tensor& zero_points, - int64_t axis, - at::ScalarType dtype) { - auto reshapeSize = quantize_reshape_size(self, axis); - at::Tensor scales_reshape = scales.reshape(reshapeSize); - at::Tensor zp_reshape = zero_points.reshape(reshapeSize); - at::Tensor scales_broadcast = NPUNativeFunctions::npu_broadcast(scales_reshape, self.sizes()); - at::Tensor zp_broadcast = NPUNativeFunctions::npu_broadcast(zp_reshape, self.sizes()); - string dtypeStr = "torch.qint8"; - if (dtype == at::ScalarType::QUInt8) { - dtypeStr = "torch.quint8"; - } else if (dtype == at::ScalarType::QInt32) { - dtypeStr = "torch.qint32"; - } - OpCommand cmd; - cmd.Name("Quantize") - .Input(self) - .Input(scales_broadcast) - .Input(zp_broadcast) - .Output(result) - .Attr("axis", axis) - .Attr("dtype", dtypeStr) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::quantize_per_channel( - const at::Tensor& self, - const at::Tensor& scales, - const at::Tensor& zero_points, - int64_t axis, - at::ScalarType dtype) { - axis = CalcuOpUtil::make_wrap_dim(axis, self.dim()); - TORCH_CHECK(scales.dim() == 1, "Scales' dim should be equal to 1."); - TORCH_CHECK(zero_points.dim() == 1, "Zero points' dim should be equal to 1."); - TORCH_CHECK(scales.sizes()[0] == zero_points.sizes()[0], "Scales' size should be equal to zero points' size."); - TORCH_CHECK(scales.sizes()[0] == self.sizes()[axis], "length of scales must equal to the specified dimension."); - auto outputSize = input_same_output_size(self); - auto outputDtype = at::kInt; - if (dtype == at::ScalarType::QInt8) { - outputDtype = at::kChar; - } else if (dtype == at::ScalarType::QUInt8) { - outputDtype = at::kByte; - } else if (dtype == at::ScalarType::QInt32) { - outputDtype = at::kInt; - } - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options().dtype(outputDtype), - CalcuOpUtil::get_tensor_npu_format(self)); - quantize_per_channel_out_nocheck(result, self, scales, zero_points, axis, dtype); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/QuantizePerTensorKernelNpu.cpp b/torch_npu/csrc/aten/ops/QuantizePerTensorKernelNpu.cpp deleted file mode 100644 index c2afae426b..0000000000 --- a/torch_npu/csrc/aten/ops/QuantizePerTensorKernelNpu.cpp +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& quantize_per_tensor_out_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& scales, - const at::Tensor& zero_points, - at::ScalarType dtype) { - string dtypeStr = "torch.qint8"; - if (dtype == at::ScalarType::QUInt8) { - dtypeStr = "torch.quint8"; - } else if (dtype == at::ScalarType::QInt32) { - dtypeStr = "torch.qint32"; - } - OpCommand cmd; - cmd.Name("Quantize") - .Input(self) - .Input(scales) - .Input(zero_points) - .Output(result) - .Attr("axis", (int64_t)1) - .Attr("dtype", dtypeStr) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::quantize_per_tensor( - const at::Tensor& self, - double scale, - int64_t zero_point, - at::ScalarType dtype) { - float scaleFloat = static_cast(scale); - auto outputSize = input_same_output_size(self); - auto outputDtype = at::kInt; - if (dtype == at::ScalarType::QInt8) { - outputDtype = at::kChar; - } else if (dtype == at::ScalarType::QUInt8) { - outputDtype = at::kByte; - } else if (dtype == at::ScalarType::QInt32) { - outputDtype = at::kInt; - } - at::Tensor scaleTensor = OpPreparation::ApplyTensorWithFormat( - {1}, - self.options().dtype(at::kFloat), - CalcuOpUtil::get_tensor_npu_format(self)); - scaleTensor[0] = scaleFloat; - at::Tensor zpTensor = OpPreparation::ApplyTensorWithFormat( - {1}, - self.options().dtype(at::kInt), - CalcuOpUtil::get_tensor_npu_format(self)); - zpTensor[0] = zero_point; - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options().dtype(outputDtype), - CalcuOpUtil::get_tensor_npu_format(self)); - quantize_per_tensor_out_nocheck(result, self, scaleTensor, zpTensor, dtype); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RandomChoiceWithMaskKernelNpu.cpp b/torch_npu/csrc/aten/ops/RandomChoiceWithMaskKernelNpu.cpp deleted file mode 100644 index 77d73f98de..0000000000 --- a/torch_npu/csrc/aten/ops/RandomChoiceWithMaskKernelNpu.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::npu_random_choice_with_mask( - const at::Tensor& self, - int64_t count, - int64_t seed, - int64_t seed2) { - TORCH_CHECK( - self.scalar_type() == at::ScalarType::Bool, - "The input.dtype should be bool, but get", - self.scalar_type()); - TORCH_CHECK( - self.dim() <= 5 && self.dim() >= 1, - "The input.dim should be in [1, 5], but get", - self.dim()); - TORCH_CHECK(count > 0, "The count must greater than 0, but get", count); - - at::Tensor result = OpPreparation::ApplyTensor({count, self.dim()}, self.options().dtype(at::kInt), self); - at::Tensor mask = OpPreparation::ApplyTensor(self, {count}); - OpCommand cmd; - cmd.Name("RandomChoiceWithMask") - .Input(self) - .Output(result) - .Output(mask) - .Attr("count", count) - .Attr("seed", seed) - .Attr("seed2", seed2) - .Run(); - - return std::tie(result, mask); -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RandomKernelNpu.cpp b/torch_npu/csrc/aten/ops/RandomKernelNpu.cpp deleted file mode 100644 index 5af28ca86d..0000000000 --- a/torch_npu/csrc/aten/ops/RandomKernelNpu.cpp +++ /dev/null @@ -1,108 +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. -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -namespace { - constexpr int MAX_ERROR_OF_FP32_TO_FP16 = 16; -} - -at::Tensor& random_out_npu(at::Tensor& result, at::Tensor& self, int64_t from, int64_t to, c10::optional gen_) { - OpCommand cmd; - cmd.Name("Random") - .Input(self) - .Output(result) - .Attr("from", from) - .Attr("to", to) - .Run(); - return result; -} - -at::Tensor& random_npu_(at::Tensor& self, int64_t from, int64_t to, c10::optional gen_) { - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - if (!NpuUtils::check_match(&selfCopy)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfCopy); - at::Tensor result = random_out_npu(contiguousSelf, contiguousSelf, from, to, gen_); - NpuUtils::format_fresh_view(selfCopy, result); - } else { - random_out_npu(selfCopy, selfCopy, from, to, gen_); - } - self.copy_(selfCopy); - return self; -} - -at::Tensor& NPUNativeFunctions::random_(at::Tensor& self, int64_t from, c10::optional to, c10::optional gen_) { - int64_t to_ = to.value(); - - random_npu_(self, from, to_, gen_); - - // fp32 casting to fp16 will introduce error, so needing to counteract it. - if (self.scalar_type() == at::ScalarType::Half) { - self = at::where(self == to_, self - MAX_ERROR_OF_FP32_TO_FP16, self); - } - - return self; -} - -at::Tensor& NPUNativeFunctions::random_(at::Tensor& self, int64_t to, c10::optional gen_) { - int64_t from = 0; - - random_npu_(self, from, to, gen_); - - // fp32 casting to fp16 will introduce error, so needing to counteract it. - if (self.scalar_type() == at::ScalarType::Half) { - self = at::where(self == to, self - MAX_ERROR_OF_FP32_TO_FP16, self); - } - - return self; -} - -at::Tensor& NPUNativeFunctions::random_(at::Tensor& self, c10::optional gen_) { - // Check the dtype of input - TORCH_CHECK( - self.dtype() == at::kHalf || - self.dtype() == at::kFloat || - self.dtype() == at::kInt || - self.dtype() == at::kLong, - "the dtype of input must be float16, float32, int32, int64"); - - int64_t from = 0; - int64_t to = 1; - - if (self.dtype() == at::kHalf) { - to = NPU_HALF_MAX; - } else if (self.dtype() == at::kInt) { - to = INT_MAX; - } else if (self.dtype() == at::kLong || self.dtype() == at::kFloat) { - // the max of 'to' is also LONG_MAX because to's dtype is int64 though self is of fp32 - to = LONG_MAX; - } - - random_npu_(self, from, to, gen_); - - return self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RandpermKernelNpu.cpp b/torch_npu/csrc/aten/ops/RandpermKernelNpu.cpp deleted file mode 100644 index 5a04b6048c..0000000000 --- a/torch_npu/csrc/aten/ops/RandpermKernelNpu.cpp +++ /dev/null @@ -1,67 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& NPUNativeFunctions::randperm_out(int64_t n, c10::optional generator, at::Tensor& result) { - TORCH_CHECK(n >= 0, "n must be non-negative, got", n); - - OpCommand cmd; - cmd.Name("Randperm") - .Output(result) - .Attr("n", n) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::randperm_out(int64_t n, at::Tensor& result) { - return NPUNativeFunctions::randperm_out(n, static_cast>(c10::nullopt), result); -} - -at::Tensor NPUNativeFunctions::randperm( - int64_t n, - c10::optional generator, - c10::optional dtype, - c10::optional layout, - c10::optional device, - c10::optional pin_memory) { - at::TensorOptions options; - options = options.dtype(dtype) - .layout(layout) - .device(device); - - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - {n}, - options, - ACL_FORMAT_NCHW); - - return NPUNativeFunctions::randperm_out(n, generator, result); -} - -at::Tensor NPUNativeFunctions::randperm( - int64_t n, - c10::optional dtype, - c10::optional layout, - c10::optional device, - c10::optional pin_memory) { - return NPUNativeFunctions::randperm(n, static_cast>(c10::nullopt), dtype, layout, device, pin_memory); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/RangeKernelNpu.cpp b/torch_npu/csrc/aten/ops/RangeKernelNpu.cpp deleted file mode 100644 index c8ea4f2e40..0000000000 --- a/torch_npu/csrc/aten/ops/RangeKernelNpu.cpp +++ /dev/null @@ -1,116 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& range_out_nocheck( - at::Scalar start, - at::Scalar end, - at::Scalar step, - at::Tensor& result) { - // generate x assistant tensor - int value = result.size(0); - vector tmp_vector = {}; - for (int i = 0; i < value; i++) { - tmp_vector.emplace_back(i); - } - at::Tensor assistDimInfo = at::from_blob(tmp_vector.data(), {value}, at::kInt); - at::Tensor assistTensor = CalcuOpUtil::copy_tensor_host_to_device(assistDimInfo); - assistTensor = NPUNativeFunctions::npu_dtype_cast(assistTensor, result.scalar_type()); - - OpCommand cmd; - cmd.Name("RangeD") - .Input(assistTensor) - .Output(result) - .Attr("start", start) - .Attr("limit", end) - .Attr("delta", step) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::range( - at::Scalar start, - at::Scalar end, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - c10::TensorOptions option = c10::TensorOptions().dtype(dtype_opt) - .device(device_opt) - .layout(layout_opt) - .pinned_memory(pin_memory_opt); - return at::range(start, end, 1, option); -} - -at::Tensor NPUNativeFunctions::range( - at::Scalar start, - at::Scalar end, - at::Scalar step, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - c10::TensorOptions option = c10::TensorOptions().dtype(dtype_opt) - .device(device_opt) - .layout(layout_opt) - .pinned_memory(pin_memory_opt); - - float start_value = CalcuOpUtil::get_scalar_float_value(start); - float end_value = CalcuOpUtil::get_scalar_float_value(end); - float step_value = CalcuOpUtil::get_scalar_float_value(step); - - TORCH_CHECK(step_value > 0 || step_value < 0, "step must be nonzero"); - TORCH_CHECK(((step_value > 0) && (end_value >= start_value)) || ((step_value < 0) && (end_value <= start_value)), - "upper bound and larger bound inconsistent with step sign"); - - auto outputSize = range_npu_output_size(start_value, end_value, step_value); - at::Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, option, ACL_FORMAT_NCHW); - return range_out_nocheck(start, end, step, result); -} - -at::Tensor& NPUNativeFunctions::range_out( - at::Scalar start, - at::Scalar end, - at::Scalar step, - at::Tensor& result) { - float start_value = CalcuOpUtil::get_scalar_float_value(start); - float end_value = CalcuOpUtil::get_scalar_float_value(end); - float step_value = CalcuOpUtil::get_scalar_float_value(step); - - TORCH_CHECK(step_value > 0 || step_value < 0, "step must be nonzero"); - TORCH_CHECK(((step_value > 0) && (end_value >= start_value)) || ((step_value < 0) && (end_value <= start_value)), - "upper bound and larger bound inconsistent with step sign"); - - auto outputSize = range_npu_output_size(start_value, end_value, step_value); - OpPreparation::CheckOut( - { }, - result, - ACL_FORMAT_NCHW, - result.scalar_type(), - outputSize); - - return range_out_nocheck(start, end, step, result); -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ReciprocalKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReciprocalKernelNpu.cpp index fab2584907..665b02de2e 100644 --- a/torch_npu/csrc/aten/ops/ReciprocalKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ReciprocalKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -30,7 +30,7 @@ at::Tensor& reciprocal_out_npu_nocheck(const at::Tensor& self, at::Tensor& resul return result; } -at::Tensor& NPUNativeFunctions::reciprocal_out(const at::Tensor& self, at::Tensor& result) { +at::Tensor& XLANativeFunctions::reciprocal_out(const at::Tensor& self, at::Tensor& result) { OpPreparation::CheckOut( {self}, result, @@ -42,7 +42,7 @@ at::Tensor& NPUNativeFunctions::reciprocal_out(const at::Tensor& self, at::Tenso .Call(result); } -at::Tensor NPUNativeFunctions::reciprocal(const at::Tensor& self) { +at::Tensor XLANativeFunctions::reciprocal(const at::Tensor& self) { // construct the output tensor of the NPU at::Tensor result = OpPreparation::ApplyTensor(self); // calculate the output result of the NPU @@ -51,8 +51,8 @@ at::Tensor NPUNativeFunctions::reciprocal(const at::Tensor& self) { return result; } -at::Tensor& NPUNativeFunctions::reciprocal_(at::Tensor& self) { - NPUNativeFunctions::reciprocal_out(self, self); +at::Tensor& XLANativeFunctions::reciprocal_(at::Tensor& self) { + XLANativeFunctions::reciprocal_out(self, self); return self; } diff --git a/torch_npu/csrc/aten/ops/ReflectionPad1dKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReflectionPad1dKernelNpu.cpp deleted file mode 100644 index 0e33c3b20e..0000000000 --- a/torch_npu/csrc/aten/ops/ReflectionPad1dKernelNpu.cpp +++ /dev/null @@ -1,109 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector reflection_pad1d_npu_output_size(const at::Tensor& self, at::IntArrayRef padding) { - int64_t N = self.size(0); - int64_t C = self.size(1); - int64_t H = self.size(2); - int64_t W = self.size(3); - int64_t padding_l = 0; - int64_t padding_r = 0; - int64_t padding_t = 0; - int64_t padding_b = 0; - - padding_l = padding[0]; - padding_r = padding[1]; - padding_t = padding[2]; - padding_b = padding[3]; - - int64_t Wo = W + padding_l + padding_r; - - c10::SmallVector outputSize = {N, C, H, Wo}; - return outputSize; -} - -at::Tensor& reflection_pad1d_out_npu_nocheck(at::Tensor& out, const at::Tensor& self, at::IntArrayRef padding) { - TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4"); - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * self.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 1; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - - c10::SmallVector value_tensor = {(int64_t)0}; - OpCommand cmd; - if(self.dtype() == at::kHalf) { - cmd.Name("PadV3") - .Input(self) - .Input(vectorInt, at::kInt) - .Input(value_tensor, self.scalar_type()) - .Output(out) - .Attr("mode", (string)"reflect") - .Attr("paddings_contiguous", true) - .Run(); - } else { - cmd.Name("MirrorPad") - .Input(self) - .Input(vectorInt, at::kInt) - .Output(out) - .Attr("mode", (string)"REFLECT") - .Run(); - } - return out; -} - -at::Tensor& NPUNativeFunctions::reflection_pad1d_out( - const at::Tensor& self, - at::IntArrayRef padding, - at::Tensor& result){ - c10::SmallVector paddings = {padding[0], padding[1], 0, 0}; - at::Tensor selfCopy = self; - selfCopy = selfCopy.unsqueeze(0); - - auto outputSize = reflection_pad1d_npu_output_size(selfCopy, paddings); - OpPreparation::CheckOut( - {selfCopy}, - result, - selfCopy, - outputSize); - reflection_pad1d_out_npu_nocheck(result, selfCopy, paddings); - result = result.squeeze(0); - return result; -} - -at::Tensor NPUNativeFunctions::reflection_pad1d(const at::Tensor& self, at::IntArrayRef padding) { - c10::SmallVector paddings = {padding[0], padding[1], 0, 0}; - at::Tensor selfCopy = self; - selfCopy = selfCopy.unsqueeze(0); - - auto outputSize = reflection_pad1d_npu_output_size(selfCopy, paddings); - at::Tensor out = OpPreparation::ApplyTensor(selfCopy, outputSize); - reflection_pad1d_out_npu_nocheck(out, selfCopy, paddings); - out = out.squeeze(0); - return out; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ReflectionPad2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReflectionPad2dBackwardKernelNpu.cpp deleted file mode 100644 index b0c2c3731c..0000000000 --- a/torch_npu/csrc/aten/ops/ReflectionPad2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,81 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& reflection_pad2d_backward_out_npu_nocheck( - const at::Tensor& gradOutput, - const at::Tensor& input, - at::IntArrayRef padding, - at::Tensor& gradInput) { - TORCH_CHECK(input.scalar_type() != at::ScalarType::Float, - "PadV3Grad don't supports torch.float!"); - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * input.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 0; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - OpCommand cmd; - cmd.Name("PadV3Grad") - .Input(gradOutput) - .Input(vectorInt, at::kInt) - .Output(gradInput) - .Attr("mode", (string)"reflect") - .Attr("paddings_contiguous", true) - .Run(); - return gradInput; -} - -at::Tensor& NPUNativeFunctions::reflection_pad2d_backward_out( - const at::Tensor& gradOutput, - const at::Tensor& input, - at::IntArrayRef padding, - at::Tensor& gradInput) { - OpPreparation::CheckOut( - {input, gradOutput}, - gradInput, - input); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({input, gradOutput}, {gradInput}) - .Func([&gradOutput, &input, &padding](at::Tensor& gradInput) - {reflection_pad2d_backward_out_npu_nocheck( - gradOutput, - input, - padding, - gradInput);}) - .Call(gradInput); -} - -at::Tensor NPUNativeFunctions::reflection_pad2d_backward( - const at::Tensor& gradOutput, - const at::Tensor& input, - at::IntArrayRef padding) { - at::Tensor gradInput = OpPreparation::ApplyTensor(input); - reflection_pad2d_backward_out_npu_nocheck( - gradOutput, - input, - padding, - gradInput); - return gradInput; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ReflectionPad2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReflectionPad2dKernelNpu.cpp deleted file mode 100644 index fedabd8fdc..0000000000 --- a/torch_npu/csrc/aten/ops/ReflectionPad2dKernelNpu.cpp +++ /dev/null @@ -1,94 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector reflection_pad2d_npu_output_size(const at::Tensor& self, at::IntArrayRef padding) { - int64_t N = self.size(0); - int64_t C = self.size(1); - int64_t H = self.size(2); - int64_t W = self.size(3); - int64_t padding_l = padding[0]; - int64_t padding_r = padding[1]; - int64_t padding_t = padding[2]; - int64_t padding_b = padding[3]; - int64_t Ho = H + padding_t + padding_b; - int64_t Wo = W + padding_l + padding_r; - c10::SmallVector outputSize = {N, C, Ho, Wo}; - return outputSize; -} - -at::Tensor& reflection_pad2d_out_npu_nocheck( - const at::Tensor& self, - at::IntArrayRef padding, - at::Tensor& out) { - TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4"); - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * self.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 1; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - c10::SmallVector value_tensor = {(int64_t)0}; - OpCommand cmd; - if(self.dtype() == at::kHalf) { - cmd.Name("PadV3") - .Input(self) - .Input(vectorInt, at::kInt) - .Input(value_tensor, self.scalar_type()) - .Output(out) - .Attr("mode", (string)"reflect") - .Attr("paddings_contiguous", true) - .Run(); - } else { - cmd.Name("MirrorPad") - .Input(self) - .Input(vectorInt, at::kInt) - .Output(out) - .Attr("mode", (string)"REFLECT") - .Run(); - } - return out; -} - -at::Tensor& NPUNativeFunctions::reflection_pad2d_out( - const at::Tensor& self, - at::IntArrayRef padding, - at::Tensor& result){ - auto outputSize = reflection_pad2d_npu_output_size(self, padding); - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - reflection_pad2d_out_npu_nocheck(self, padding, result); - return result; -} - -at::Tensor NPUNativeFunctions::reflection_pad2d(const at::Tensor& self, at::IntArrayRef padding) { - TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4"); - auto outputSize = reflection_pad2d_npu_output_size(self, padding); - at::Tensor out = OpPreparation::ApplyTensor(self, outputSize); - reflection_pad2d_out_npu_nocheck(self, padding, out); - return out; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ReluKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReluKernelNpu.cpp index 280167a892..557e412252 100644 --- a/torch_npu/csrc/aten/ops/ReluKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ReluKernelNpu.cpp @@ -18,53 +18,77 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" -namespace at_npu { -namespace native { - -at::Tensor& relu_out_npu(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Relu") - .Input(self) - .Output(result) - .Run(); - - return result; -} - - -at::Tensor NPUNativeFunctions::relu(const at::Tensor &self) +namespace at_npu { - // return at::threshold(self, 0, 0); - // calculate the output size - auto outputSize = input_same_output_size(self); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - - // calculate the output result of the NPU - relu_out_npu(self, result); - return result; -} - -at::Tensor &NPUNativeFunctions::relu_(at::Tensor &self) -{ - // return at::threshold_(self, 0, 0); - if (!NpuUtils::check_match(&self)) + namespace native { - at::Tensor selfContiguous = NpuUtils::format_contiguous(self); - at::Tensor result = relu_out_npu(selfContiguous, selfContiguous); - NpuUtils::format_fresh_view(self, result); - } - else - { - relu_out_npu(self, self); - } - return self; -} + c10::SmallVector relu_npu_input( + const c10::SmallVector &inputTensor) + { + return CalcuOpUtil::create_npu_input_tensor_desc(inputTensor); + } -} // namespace native + c10::SmallVector relu_npu_output( + const c10::SmallVector &outputTensor) + { + return CalcuOpUtil::create_npu_output_tensor_desc(outputTensor); + } + + c10::SmallVector relu_npu_attr(const at::Tensor &self) + { + c10::SmallVector attrs = {}; + return attrs; + } + + at::Tensor &relu_out_npu(const at::Tensor &self, at::Tensor &result) + { + // constructs the input and output NPUTensorDesc + auto inputs = relu_npu_input({self}); + auto outputs = relu_npu_output({result}); + + // constructs the attr of the NPUAttrDesc + auto attrs = relu_npu_attr(self); + + // executing the NPU operator + CalcuOpUtil::execute_npu_operate("Relu", inputs, outputs, attrs); + + return result; + } + + at::Tensor XLANativeFunctions::relu(const at::Tensor &self) + { + // return at::threshold(self, 0, 0); + // calculate the output size + auto outputSize = input_same_output_size(self); + + // construct the output tensor of the NPU + at::Tensor result = OpPreparation::ApplyTensorWithFormat( + outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); + + // calculate the output result of the NPU + relu_out_npu(self, result); + return result; + } + + at::Tensor &XLANativeFunctions::relu_(at::Tensor &self) + { + // return at::threshold_(self, 0, 0); + if (!NpuUtils::check_match(&self)) + { + at::Tensor selfContiguous = NpuUtils::format_contiguous(self); + at::Tensor result = relu_out_npu(selfContiguous, selfContiguous); + NpuUtils::format_fresh_view(self, result); + } + else + { + relu_out_npu(self, self); + } + + return self; + } + + } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RemainderKernelNpu.cpp b/torch_npu/csrc/aten/ops/RemainderKernelNpu.cpp deleted file mode 100644 index 257103b57e..0000000000 --- a/torch_npu/csrc/aten/ops/RemainderKernelNpu.cpp +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) 2022 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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& remainder_out_scalar_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Scalar other) { - OpCommand cmd; - cmd.Name("FloorMod") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::remainder_out( - const at::Tensor& self, - const at::Scalar other, - at::Tensor& result) { - OpPreparation::CheckOut({self}, result, self); - remainder_out_scalar_npu_nocheck(result, self, other); - return result; -} - -at::Tensor& remainder_out_tensor_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& other) { - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - if (other.dim() == 0) { - NPUNativeFunctions::remainder_out(self, other.item(), result); - } else { - OpCommand cmd; - cmd.Name("FloorMod") - .Expect(unified_result) - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - - return result; -} - -at::Tensor& NPUNativeFunctions::remainder_out( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - at::Tensor outputTensor = CalcuOpUtil::is_scalar_wrapped_to_tensor(self) ? other : self; - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(outputTensor), - self.scalar_type(), - outputSize); - remainder_out_tensor_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor NPUNativeFunctions::remainder(const at::Tensor& self, const at::Tensor& other) { - // calculate the output size - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - at::Tensor outputTensor = isSelfWrapped ? other : self; - - auto outputSize = broadcast_ops_npu_output_size(self, other); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - outputTensor.options(), - CalcuOpUtil::get_tensor_npu_format(outputTensor)); - - // calculate the output result of the NPU - remainder_out_tensor_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor NPUNativeFunctions::remainder(const at::Tensor& self, at::Scalar other) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - - // calculate the output result of the NPU - remainder_out_scalar_npu_nocheck(result, self, other); - - return result; -} - -at::Tensor& NPUNativeFunctions::remainder_(at::Tensor& self, const at::Tensor& other) { - at::SmallVector inputs = {other}; - at::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = remainder_out_tensor_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - remainder_out_tensor_npu_nocheck(self, self, other); - } - - return self; -} - - -at::Tensor& NPUNativeFunctions::remainder_(at::Tensor& self, at::Scalar other) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = remainder_out_scalar_npu_nocheck(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, result); - } else { - remainder_out_scalar_npu_nocheck(self, self, other); - } - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RenormKernelNpu.cpp b/torch_npu/csrc/aten/ops/RenormKernelNpu.cpp deleted file mode 100644 index 3ec5d26a4c..0000000000 --- a/torch_npu/csrc/aten/ops/RenormKernelNpu.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector renorm_npu_output_size( - const at::Tensor& self, - int64_t dim) { - c10::SmallVector outSize; - for(int64_t i=0; i < self.dim(); i++) { - if(i != dim) { - outSize.emplace_back(1); - } else { - outSize.emplace_back(self.sizes()[i]); - } - } - return outSize; -} - -at::Tensor& renorm_compute( - at::Tensor& result, - const at::Tensor& self, - at::Scalar p, - int64_t dim, - at::Scalar maxnorm) { - float p_value = CalcuOpUtil::get_scalar_float_value(p); - float maxnorm_value = CalcuOpUtil::get_scalar_float_value(maxnorm); - - OpCommand cmd; - cmd.Name("Renorm") - .Input(self) - .Output(result) - .Attr("p", p_value) - .Attr("maxnorm", maxnorm_value) - .Attr("dim", dim) - .Run(); - return result; -} - -at::Tensor& renorm_out_nocheck( - at::Tensor& result, - const at::Tensor& self, - at::Scalar p, - int64_t dim, - at::Scalar maxnorm) { - auto ori_type = self.scalar_type(); - if(ori_type != c10::ScalarType::Half && ori_type != c10::ScalarType::Float) { - AT_ERROR("Renorm only support float16 or float32 type."); - } - if(result.scalar_type() != ori_type) { - AT_ERROR("result's type must be equal to input's."); - } - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - auto outputSize = renorm_npu_output_size(self, dim); - at::Tensor result_bak = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options().dtype(at::kFloat), - CalcuOpUtil::get_tensor_npu_format(self)); - if(ori_type == c10::ScalarType::Half) { - at::Tensor self_no_name = self.rename(c10::nullopt); - at::Tensor result_no_name = result.rename(c10::nullopt); - self_no_name = NPUNativeFunctions::npu_dtype_cast(self_no_name, c10::ScalarType::Float); - result_no_name = NPUNativeFunctions::npu_dtype_cast(result_no_name, c10::ScalarType::Float); - renorm_compute( - result_bak, - self_no_name, - p, - dim, - maxnorm); - - at::Tensor result_broadcast = NPUNativeFunctions::npu_broadcast(result_bak, self.sizes()); - at::mul_out(result_no_name, result_broadcast, self_no_name); - NPUNativeFunctions::npu_dtype_cast_(result, result_no_name); - } else { - renorm_compute( - result_bak, - self, - p, - dim, - maxnorm); - - at::Tensor result_broadcast = NPUNativeFunctions::npu_broadcast(result_bak, self.sizes()); - at::mul_out(result, result_broadcast, self); - } - return result; -} - -at::Tensor& NPUNativeFunctions::renorm_out( - const at::Tensor& self, - at::Scalar p, - int64_t dim, - at::Scalar maxnorm, - at::Tensor& result) { - auto outputSize = input_same_output_size(self); - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - - c10::SmallVector inputs = {self}; - c10::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor checkresult = renorm_out_nocheck(contiguousSelf, contiguousSelf, p, dim, maxnorm); - NpuUtils::format_fresh_view(result, checkresult); - } else { - renorm_out_nocheck(result, self, p, dim, maxnorm); - } - - return result; -} - -at::Tensor NPUNativeFunctions::renorm(const at::Tensor& self, at::Scalar p, int64_t dim, at::Scalar maxnorm) { - // calculate the output size - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(self); - - return renorm_out_nocheck(result, self, p, dim, maxnorm); -} - -at::Tensor& NPUNativeFunctions::renorm_(at::Tensor& self, at::Scalar p, int64_t dim, at::Scalar maxnorm) { - - return renorm_out(self, p, dim, maxnorm, self); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RepeatInterLeaveKernelNpu.cpp b/torch_npu/csrc/aten/ops/RepeatInterLeaveKernelNpu.cpp deleted file mode 100644 index acb1e1494e..0000000000 --- a/torch_npu/csrc/aten/ops/RepeatInterLeaveKernelNpu.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& repeat_interleave_out_npu(at::Tensor& result, at::Tensor& self, int64_t repeats, int64_t dim) { - OpCommand cmd; - cmd.Name("TileWithAxis") - .Input(self) - .Output(result) - .Attr("tiles", repeats) - .Attr("axis", dim) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::repeat_interleave( - const at::Tensor &self, - int64_t repeats, - c10::optional dim) { - int64_t realDim = dim.value_or(0); - - int64_t self_dim = self.dim(); - if((realDim < -self_dim) || (realDim > self_dim - 1)){ - AT_ERROR("dim value should be in the range of [-x, x-1], x is the dimension number of input tensor."); - } - - at::Tensor selfTensor = self; - if(!dim.has_value()){ - selfTensor = at::flatten(selfTensor); - } - - auto outputSize = repeat_interleave_npu_output_size(selfTensor, repeats, realDim); - at::Tensor result = OpPreparation::ApplyTensor(selfTensor, outputSize); - repeat_interleave_out_npu(result, selfTensor, repeats, realDim); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RepeatKernelNpu.cpp b/torch_npu/csrc/aten/ops/RepeatKernelNpu.cpp deleted file mode 100644 index 6518f34c75..0000000000 --- a/torch_npu/csrc/aten/ops/RepeatKernelNpu.cpp +++ /dev/null @@ -1,61 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& repeat_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - at::IntArrayRef repeats) { - - OpCommand cmd; - cmd.Name("Tile") - .Input(self) - .Input(repeats) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::repeat(const at::Tensor& self, at::IntArrayRef repeats) { - TORCH_CHECK(repeats.size() >= self.ndimension(), - "Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor"); - at::Tensor selfCp = self; - if(repeats.size() > selfCp.ndimension()){ - auto diff = repeats.size() - selfCp.ndimension(); - for(int i=0;i vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * input.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 1; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - - OpCommand cmd; - cmd.Name("PadV3Grad") - .Input(gradOutput) - .Input(vectorInt, at::kInt) - .Output(gradInput) - .Attr("mode", (string)"edge") - .Attr("paddings_contiguous", true) - .Run(); - - return gradInput; - } - -at::Tensor& NPUNativeFunctions::replication_pad1d_backward_out(const at::Tensor& gradOutput, const at::Tensor& input, at::IntArrayRef padding, at::Tensor& gradInput) { - c10::SmallVector paddings = {padding[0], padding[1], 0, 0}; - at::Tensor inputCopy = input; - int dim_diff = 4 - inputCopy.dim(); - for (; dim_diff > 0; dim_diff--) { - inputCopy = inputCopy.unsqueeze(0); - } - - at::Tensor gradOutputCopy = gradOutput; - int dim_diff1 = 4 - gradOutputCopy.dim(); - for (; dim_diff1 > 0; dim_diff1--) { - gradOutputCopy = gradOutputCopy.unsqueeze(0); - } - - OpPreparation::CheckOut( - {input, gradOutput}, - gradInput, - inputCopy); - replication_pad1d_backward_out_npu_nocheck(gradInput, gradOutputCopy, inputCopy, padding); - for (; dim_diff > 0; dim_diff--) { - gradInput = gradInput.squeeze(0); - } - return gradInput; - } - -at::Tensor NPUNativeFunctions::replication_pad1d_backward(const at::Tensor& gradOutput, const at::Tensor& input, at::IntArrayRef padding) { - c10::SmallVector paddings = {padding[0], padding[1], 0, 0}; - at::Tensor inputCopy = input; - int dim_diff = 4 - inputCopy.dim(); - for (; dim_diff > 0; dim_diff--) { - inputCopy = inputCopy.unsqueeze(0); - } - - at::Tensor gradOutputCopy = gradOutput; - int dim_diff1 = 4 - gradOutputCopy.dim(); - for (; dim_diff1 > 0; dim_diff1--) { - gradOutputCopy = gradOutputCopy.unsqueeze(0); - } - - at::Tensor gradInput = OpPreparation::ApplyTensor(inputCopy); - - replication_pad1d_backward_out_npu_nocheck(gradInput, gradOutputCopy, inputCopy, paddings); - for (; dim_diff > 0; dim_diff--) { - gradInput = gradInput.squeeze(0); - } - return gradInput; - } - } // namespace native - } // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ReplicationPad1dKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReplicationPad1dKernelNpu.cpp deleted file mode 100644 index 250ed90630..0000000000 --- a/torch_npu/csrc/aten/ops/ReplicationPad1dKernelNpu.cpp +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -c10::SmallVector replication_pad1d_npu_output_size(const at::Tensor& self, at::IntArrayRef padding) { - int64_t N = self.size(0); - int64_t C = self.size(1); - int64_t H = self.size(2); - int64_t W = self.size(3); - int64_t padding_l = 0; - int64_t padding_r = 0; - int64_t padding_t = 0; - int64_t padding_b = 0; - - padding_l = padding[0]; - padding_r = padding[1]; - padding_t = padding[2]; - padding_b = padding[3]; - - int64_t Wo = W + padding_l + padding_r; - - c10::SmallVector outputSize = {N, C, H, Wo}; - return outputSize; -} - -at::Tensor& replication_pad1d_out_npu_nocheck(at::Tensor& out, const at::Tensor& self, at::IntArrayRef padding) { - TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4"); - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * self.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 1; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - c10::SmallVector value_tensor = {(int64_t)0}; - OpCommand cmd; - cmd.Name("PadV3") - .Input(self) - .Input(vectorInt, at::kInt) - .Input(value_tensor, self.scalar_type()) - .Output(out) - .Attr("mode", (string)"edge") - .Attr("paddings_contiguous", true) - .Run(); - return out; -} - -at::Tensor& NPUNativeFunctions::replication_pad1d_out( - const at::Tensor& self, - at::IntArrayRef padding, - at::Tensor& out) { - c10::SmallVector paddings = {padding[0], padding[1], 0, 0}; - at::Tensor selfCopy = self; - int diff = 4 - selfCopy.dim(); - int n = diff; - selfCopy = selfCopy.unsqueeze(0); - auto outputSize = replication_pad1d_npu_output_size(selfCopy, paddings); - OpPreparation::CheckOut( - {selfCopy}, - out, - selfCopy, - outputSize); - replication_pad1d_out_npu_nocheck(out, selfCopy, paddings); - out = out.squeeze(0); - return out; -} - -at::Tensor NPUNativeFunctions::replication_pad1d(const at::Tensor& self, at::IntArrayRef padding) { - c10::SmallVector paddings = {padding[0], padding[1], 0, 0}; - at::Tensor selfCopy = self; - int diff = 4 - selfCopy.dim(); - int n = diff; - selfCopy = selfCopy.unsqueeze(0); - - auto outputSize = replication_pad1d_npu_output_size(selfCopy, paddings); - at::Tensor out = OpPreparation::ApplyTensor(selfCopy, outputSize); - replication_pad1d_out_npu_nocheck(out, selfCopy, paddings); - out = out.squeeze(0); - return out; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ReplicationPad2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReplicationPad2dBackwardKernelNpu.cpp deleted file mode 100644 index bb495bdd6f..0000000000 --- a/torch_npu/csrc/aten/ops/ReplicationPad2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& replication_pad2d_backward_out_npu_nocheck( - at::Tensor& gradInput, - const at::Tensor& gradOutput, - const at::Tensor& input, - at::IntArrayRef padding) { - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * input.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 1; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - - OpCommand cmd; - cmd.Name("PadV3Grad") - .Input(gradOutput) - .Input(vectorInt, at::kInt) - .Output(gradInput) - .Attr("mode", (string)"edge") - .Attr("paddings_contiguous", true) - .Run(); - - return gradInput; -} - -at::Tensor& NPUNativeFunctions::replication_pad2d_backward_out( - const at::Tensor& gradOutput, - const at::Tensor& input, - at::IntArrayRef padding, - at::Tensor& gradInput) { - OpPreparation::CheckOut( - {input, gradOutput}, - gradInput, - input); - return replication_pad2d_backward_out_npu_nocheck(gradInput, gradOutput, input, padding); -} - -at::Tensor NPUNativeFunctions::replication_pad2d_backward( - const at::Tensor& gradOutput, - const at::Tensor& input, - at::IntArrayRef padding) { - at::Tensor gradInput = OpPreparation::ApplyTensor(input); - replication_pad2d_backward_out(gradOutput, input, padding, gradInput); - - return gradInput; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ReplicationPad2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReplicationPad2dKernelNpu.cpp deleted file mode 100644 index 8fd4273bca..0000000000 --- a/torch_npu/csrc/aten/ops/ReplicationPad2dKernelNpu.cpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& replication_pad2d_out_npu_nocheck(at::Tensor& out, const at::Tensor& self, at::IntArrayRef padding) { - TORCH_CHECK(padding.size() == 4, "padding size is expected to be 4"); - c10::SmallVector vectorInt; - c10::SmallVector paddingsVector = array_to_small_vector(padding); - paddingsVector.resize(2 * self.dim(), 0); - for (int64_t i = paddingsVector.size(); i > 1; i -= 2) { - vectorInt.emplace_back(paddingsVector[i - 2]); - vectorInt.emplace_back(paddingsVector[i - 1]); - } - // constructs the attr of the NPUAttrDesc - c10::SmallVector value_tensor = {(int64_t)0}; - OpCommand cmd; - cmd.Name("PadV3") - .Input(self) - .Input(vectorInt, at::kInt) - .Input(value_tensor, self.scalar_type()) - .Output(out) - .Attr("mode", (string)"edge") - .Attr("paddings_contiguous", true) - .Run(); - - return out; -} - -at::Tensor& NPUNativeFunctions::replication_pad2d_out( - const at::Tensor& self, - at::IntArrayRef padding, - at::Tensor& out) { - auto outputSize = replication_pad2d_npu_output_size(self, padding); - OpPreparation::CheckOut( - {self}, - out, - self, - outputSize); - return replication_pad2d_out_npu_nocheck(out, self, padding); -} - -at::Tensor NPUNativeFunctions::replication_pad2d(const at::Tensor& self, at::IntArrayRef padding) { - auto outputSize = replication_pad2d_npu_output_size(self, padding); - at::Tensor out = OpPreparation::ApplyTensor(self, outputSize); - replication_pad2d_out(self, padding, out); - - return out; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ReshapeKernelNpu.cpp b/torch_npu/csrc/aten/ops/ReshapeKernelNpu.cpp index 13391dbd16..dfe8a91f38 100644 --- a/torch_npu/csrc/aten/ops/ReshapeKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ReshapeKernelNpu.cpp @@ -17,35 +17,17 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/StorageDescHelper.h" #include "torch_npu/csrc/aten/common/InnerNpuNativeFunction.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/core/npu/NPURunMode.h" -#include +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::npu_reshape_out( - const at::Tensor& src, +at::Tensor& reshape_out_nocheck( + at::Tensor& result, + const at::Tensor& self, at::IntArrayRef shape, - bool can_refresh, - at::Tensor& result) { - if (c10_npu::NpuRunMode::IsGraphMode()) { - std::vector out_strides = at::detail::defaultStrides(shape); - if (result.sizes() != shape || result.strides() != out_strides) { - auto allow_flag = - result.unsafeGetTensorImpl()->allow_tensor_metadata_change(); - result.unsafeGetTensorImpl()->set_allow_tensor_metadata_change(true); - StorageDescHelper::SetDesc(result, shape, out_strides); - result.unsafeGetTensorImpl()->set_allow_tensor_metadata_change(allow_flag); - } - - OpCommand cmd; - cmd.Name("Reshape") - .InputWithoutContiguous(src) - .Input(shape, at::kLong) - .Output(result) - .Run(); - } else if (can_refresh) { + bool can_refresh) { + if (can_refresh) { StorageDescHelper::SetDesc( result, array_to_small_vector(result.sizes()), @@ -53,17 +35,30 @@ at::Tensor& NPUNativeFunctions::npu_reshape_out( } else { copy_d2d_by_memcpy( result, - src, - at::prod_intlist(torch_npu::NPUBridge::GetNpuStorageImpl(result)->get_npu_desc().storage_sizes_)); + self, + c10::multiply_integers(torch_npu::NPUBridge::GetNpuStorageImpl(result)->get_npu_desc().storage_sizes_)); } return result; } -at::Tensor NPUNativeFunctions::npu_reshape(const at::Tensor& self, at::IntArrayRef shape, bool can_refresh) { +at::Tensor& XLANativeFunctions::npu_reshape_out( + const at::Tensor& self, + at::IntArrayRef shape, + bool can_refresh, + at::Tensor& result) { + OpPreparation::CheckOut( + {self}, + result, + self, + shape); + return reshape_out_nocheck(result, self, shape, can_refresh); +} + +at::Tensor XLANativeFunctions::npu_reshape(const at::Tensor& self, at::IntArrayRef shape, bool can_refresh) { // construct the output tensor of the NPU at::Tensor result = OpPreparation::ApplyTensorWithFormat( shape, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - NPUNativeFunctions::npu_reshape_out(self, shape, can_refresh, result); + reshape_out_nocheck(result, self, shape, can_refresh); return result; } diff --git a/torch_npu/csrc/aten/ops/RoiAlignBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/RoiAlignBackwardKernelNpu.cpp deleted file mode 100644 index 2824500202..0000000000 --- a/torch_npu/csrc/aten/ops/RoiAlignBackwardKernelNpu.cpp +++ /dev/null @@ -1,84 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& roi_align_backward_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& rois, - at::IntArrayRef xdiff_shape, - int64_t pooled_width, - int64_t pooled_height, - double spatial_scale, - int64_t sample_num, - c10::optional roi_end_mode) { - OpCommand cmd; - cmd.Name("ROIAlignGrad") - .Input(self) - .Input(rois) - .Output(result) - .Attr("xdiff_shape", xdiff_shape) - .Attr("spatial_scale", (float)spatial_scale) - .Attr("pooled_height", pooled_height) - .Attr("pooled_width", pooled_width) - .Attr("sample_num", sample_num); - if (roi_end_mode.has_value()) { - cmd.Attr("roi_end_mode", roi_end_mode.value()); - } - cmd.Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::npu_roi_alignbk( - const at::Tensor& self, - const at::Tensor& rois, - at::IntArrayRef xdiff_shape, - int64_t pooled_width, - int64_t pooled_height, - double spatial_scale, - int64_t sample_num, - c10::optional roi_end_mode) { - at::Tensor result = - OpPreparation::ApplyTensorWithFormat(self, xdiff_shape, ACL_FORMAT_NC1HWC0); - - // Check the self empty - for (int i = 0; i < self.dim(); i++) { - if (self.size(i) == 0) { - result.fill_(0); - return result; - } - } - - roi_align_backward_npu_nocheck( - result, - self, - rois, - xdiff_shape, - pooled_width, - pooled_height, - spatial_scale, - sample_num, - roi_end_mode); - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RoiAlignKernelNpu.cpp b/torch_npu/csrc/aten/ops/RoiAlignKernelNpu.cpp deleted file mode 100644 index c6234d30b2..0000000000 --- a/torch_npu/csrc/aten/ops/RoiAlignKernelNpu.cpp +++ /dev/null @@ -1,97 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -c10::SmallVector roi_align_npu_output_size( - const at::Tensor& self, - const at::Tensor& rois, - int64_t pooled_height, - int64_t pooled_width) { - return { - rois.size(0), - self.size(1), - pooled_height, - pooled_width}; // {N, C, H1, W1} -} - -at::Tensor& roi_align_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& rois, - double spatial_scale, - int64_t pooled_height, - int64_t pooled_width, - int64_t sample_num, - int64_t roi_end_mode) { - OpCommand cmd; - cmd.Name("ROIAlign") - .Input(self) - .Input(rois) - .Output(result) - .Attr("spatial_scale", (float)spatial_scale) - .Attr("pooled_height", pooled_height) - .Attr("pooled_width", pooled_width) - .Attr("sample_num", sample_num) - .Attr("roi_end_mode", roi_end_mode) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::npu_roi_align( - const at::Tensor& self, - const at::Tensor& rois, - double spatial_scale, - int64_t pooled_height, - int64_t pooled_width, - int64_t sample_num, - int64_t roi_end_mode) { - at::Tensor selfCast = self; - at::Tensor roisCast = rois; - if (self.scalar_type() == at::kHalf || rois.scalar_type() == at::kHalf) { - selfCast = self.to(at::kFloat); - roisCast = rois.to(at::kFloat); - } - - auto outputSize = - roi_align_npu_output_size(self, rois, pooled_height, pooled_width); - - at::Tensor result = - OpPreparation::ApplyTensorWithFormat(self, outputSize, ACL_FORMAT_NC1HWC0); - - roi_align_npu_nocheck( - result, - self, - rois, - spatial_scale, - pooled_height, - pooled_width, - sample_num, - roi_end_mode); - - if (self.scalar_type() == at::kHalf || rois.scalar_type() == at::kHalf) { - result = result.to(at::kHalf); - } - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RollKernelNpu.cpp b/torch_npu/csrc/aten/ops/RollKernelNpu.cpp deleted file mode 100644 index 147041e321..0000000000 --- a/torch_npu/csrc/aten/ops/RollKernelNpu.cpp +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& roll_out_npu_no_transpose( - at::Tensor& result, - const at::Tensor& self, - at::IntArrayRef shifts, - at::IntArrayRef dims) { - - // executing the NPU operator - OpCommand cmd; - cmd.Name("Roll") - .Input(self) - .Output(result) - .Attr("shifts", shifts) - .Attr("dims", dims) - .Run(); - - return result; -} - -at::Tensor& roll_transpose( - at::Tensor& result, - const at::Tensor& self, - int64_t axis, - int64_t firstDim, - at::IntArrayRef shifts, - int64_t id) { - - c10::SmallVector perm; - for (int64_t i = 0; i < self.dim(); i++) { - perm.emplace_back(i); - } - std::swap(perm[axis], perm[firstDim]); - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); - auto outputSize = transpose_npu_output_size(result, perm); - at::Tensor transposeResult = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options(), - CalcuOpUtil::get_tensor_npu_format(self)); - c10::SmallVector dim = {firstDim}; - c10::SmallVector shift_bak = {shifts[id]}; - at::IntArrayRef dim_now = at::IntArrayRef(dim); - at::IntArrayRef shift_now = at::IntArrayRef(shift_bak); - roll_out_npu_no_transpose(transposeResult, transposeSelf, shift_now, dim_now); - NPUNativeFunctions::npu_transpose_out(transposeResult, perm, true, result); - return result; -} - -at::Tensor& roll_out_npu( - at::Tensor& result, - const at::Tensor& self, - at::IntArrayRef shifts, - at::IntArrayRef dims) { - - if (dims.size() == 0) { - roll_out_npu_no_transpose(result, self, shifts, dims); - } else { - TORCH_CHECK(dims.size() == shifts.size(), - "The size of shifts and dims should be the same when the size of dims is not 0."); - int64_t firstDim = CalcuOpUtil::make_wrap_dim(0, self.dim()); - for (int i = 0; i < dims.size(); i++) { - int64_t axis = CalcuOpUtil::make_wrap_dim(dims[i], self.dim()); - if (i == 0) { - if (axis == firstDim) { - c10::SmallVector dim = {firstDim}; - c10::SmallVector shift_bak = {shifts[i]}; - at::IntArrayRef dim_now = at::IntArrayRef(dim); - at::IntArrayRef shift_now = at::IntArrayRef(shift_bak); - roll_out_npu_no_transpose(result, self, shift_now, dim_now); - } else { - roll_transpose(result, self, axis, firstDim, shifts, i); - } - } else { - roll_transpose(result, result, axis, firstDim, shifts, i); - } - } - } - return result; -} - -at::Tensor NPUNativeFunctions::roll( - const at::Tensor& self, - at::IntArrayRef shifts, - at::IntArrayRef dims) { - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - - // calculate the output result of the NPU - roll_out_npu(result, self, shifts, dims); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RotatedBoxDecodeKernelNpu.cpp b/torch_npu/csrc/aten/ops/RotatedBoxDecodeKernelNpu.cpp deleted file mode 100644 index c189b5416f..0000000000 --- a/torch_npu/csrc/aten/ops/RotatedBoxDecodeKernelNpu.cpp +++ /dev/null @@ -1,41 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::npu_rotated_box_decode( - const at::Tensor& self, - const at::Tensor& deltas, - const at::Tensor& weight){ - at::Tensor result = OpPreparation::ApplyTensor(self); - at::Tensor weightContiguous = weight.to(at::Device(at::kCPU), at::kFloat); - at::ArrayRef weightList(weightContiguous.data_ptr(), weightContiguous.numel()); - - OpCommand cmd; - cmd.Name("RotatedBoxDecode") - .Input(self) - .Input(deltas) - .Output(result) - .Attr("weight", weightList) - .Run(); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RotatedBoxEncodeKernelNpu.cpp b/torch_npu/csrc/aten/ops/RotatedBoxEncodeKernelNpu.cpp deleted file mode 100644 index f4e6fec231..0000000000 --- a/torch_npu/csrc/aten/ops/RotatedBoxEncodeKernelNpu.cpp +++ /dev/null @@ -1,41 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::npu_rotated_box_encode( - const at::Tensor& self, - const at::Tensor& gtBox, - const at::Tensor& weight){ - at::Tensor result = OpPreparation::ApplyTensor(self); - at::Tensor weightContiguous = weight.to(at::Device(at::kCPU), at::kFloat); - at::ArrayRef weightList(weightContiguous.data_ptr(), weightContiguous.numel()); - - OpCommand cmd; - cmd.Name("RotatedBoxEncode") - .Input(self) - .Input(gtBox) - .Output(result) - .Attr("weight", weightList) - .Run(); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RotatedIouKernelNpu.cpp b/torch_npu/csrc/aten/ops/RotatedIouKernelNpu.cpp deleted file mode 100644 index 6338bf911b..0000000000 --- a/torch_npu/csrc/aten/ops/RotatedIouKernelNpu.cpp +++ /dev/null @@ -1,81 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& rotated_iou_npu_nocheck( - at::Tensor& iou, - const at::Tensor& boxes, - const at::Tensor& query_boxes, - bool trans, - int64_t mode, - bool is_cross, - double v_threshold, - double e_threshold) { - string mode_str = (mode == 0) ? "iou" : "iof"; - - OpCommand cmd; - cmd.Name("RotatedIou") - .Input(boxes) - .Input(query_boxes) - .Output(iou) - .Attr("trans", trans) - .Attr("mode", mode_str) - .Attr("is_cross", is_cross) - .Attr("value", static_cast(v_threshold)) - .Attr("value", static_cast(e_threshold)) - .Run(); - return iou; -} - -at::Tensor NPUNativeFunctions::npu_rotated_iou( - const at::Tensor& boxes, - const at::Tensor& query_boxes, - bool trans, - int64_t mode, - bool is_cross, - double v_threshold, - double e_threshold) { - TORCH_CHECK(boxes.ndimension() == 3 && query_boxes.ndimension() == 3); - - auto origin_dtype = boxes.scalar_type(); - - at::Tensor boxesOk = boxes.permute({0, 2, 1}); - if (boxesOk.scalar_type() == at::kHalf){ - boxesOk = NPUNativeFunctions::npu_dtype_cast(boxesOk, at::kFloat); - } - at::Tensor query_boxesOk = query_boxes.permute({0, 2, 1}); - if (query_boxesOk.scalar_type() == at::kHalf){ - query_boxesOk = NPUNativeFunctions::npu_dtype_cast(query_boxesOk, at::kFloat); - } - - int64_t B = boxesOk.size(0); - int64_t N = boxesOk.size(-1); - int64_t K = query_boxesOk.size(-1); - - c10::SmallVector output_size({B, N, K}); - at::Tensor iou = OpPreparation::ApplyTensor(boxesOk, output_size); - - rotated_iou_npu_nocheck(iou, boxesOk, query_boxesOk, trans, mode, is_cross, v_threshold, e_threshold); - iou = NPUNativeFunctions::npu_dtype_cast(iou, origin_dtype); - return iou; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RotatedOverlapsKernelNpu.cpp b/torch_npu/csrc/aten/ops/RotatedOverlapsKernelNpu.cpp deleted file mode 100644 index 7685cb1ddc..0000000000 --- a/torch_npu/csrc/aten/ops/RotatedOverlapsKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& rotated_overlaps_npu_nocheck( - at::Tensor& overlaps, - const at::Tensor& self, - const at::Tensor& query_boxes, - bool trans) { - OpCommand cmd; - cmd.Name("RotatedOverlaps") - .Input(self) - .Input(query_boxes) - .Output(overlaps) - .Attr("trans", trans) - .Run(); - return overlaps; -} - -at::Tensor NPUNativeFunctions::npu_rotated_overlaps( - const at::Tensor& self, - const at::Tensor& query_boxes, - bool trans) { - TORCH_CHECK(self.ndimension() == 3 && query_boxes.ndimension() == 3, - "boxes' dim should be equal to query_boxes' ndimension() ", - "and equal to 3!"); - auto origin_dtype = self.scalar_type(); - // the Op only support fp32 currently! - at::Tensor selfCp = NPUNativeFunctions::npu_dtype_cast(self, at::kFloat).permute({0, 2, 1}); - at::Tensor queryBoxesCp = NPUNativeFunctions::npu_dtype_cast(query_boxes, at::kFloat).permute({0, 2, 1}); - - int64_t B = selfCp.size(0); - int64_t N = selfCp.size(-1); - int64_t K = queryBoxesCp.size(-1); - - c10::SmallVector output_size({B, N, K}); - at::Tensor overlaps = OpPreparation::ApplyTensor(selfCp, output_size); - - rotated_overlaps_npu_nocheck(overlaps, selfCp, queryBoxesCp, trans); - overlaps = NPUNativeFunctions::npu_dtype_cast(overlaps, origin_dtype); - return overlaps; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RoundKernelNpu.cpp b/torch_npu/csrc/aten/ops/RoundKernelNpu.cpp deleted file mode 100644 index cc25fbda5a..0000000000 --- a/torch_npu/csrc/aten/ops/RoundKernelNpu.cpp +++ /dev/null @@ -1,55 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& round_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Round") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::round_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut({self}, result, self); - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){round_out_npu_nocheck(self, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::round(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - round_out_npu_nocheck(self, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::round_(at::Tensor& self) { - NPUNativeFunctions::round_out(self, self); - - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/RreluWithNoiseBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/RreluWithNoiseBackwardKernelNpu.cpp deleted file mode 100644 index a76b10b15f..0000000000 --- a/torch_npu/csrc/aten/ops/RreluWithNoiseBackwardKernelNpu.cpp +++ /dev/null @@ -1,43 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::rrelu_with_noise_backward( - const at::Tensor& grad_output, - const at::Tensor& self_or_result, - const at::Tensor& noise, - at::Scalar lower, - at::Scalar upper, - bool training, - bool is_result) { - auto minimum = 1E-6; - auto folat_lower = lower.toFloat(); - auto float_upper = upper.toFloat(); - if (training && (float_upper - folat_lower > minimum)) { - return grad_output.mul(noise); - } else { - at::Scalar negative_slope = (folat_lower + float_upper) / 2; - return NPUNativeFunctions::leaky_relu_backward(grad_output, self_or_result, negative_slope, is_result); - } -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RreluWithNoiseKernelNpu.cpp b/torch_npu/csrc/aten/ops/RreluWithNoiseKernelNpu.cpp deleted file mode 100644 index 76ac2a4064..0000000000 --- a/torch_npu/csrc/aten/ops/RreluWithNoiseKernelNpu.cpp +++ /dev/null @@ -1,130 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -#include - -namespace at_npu { -namespace native { - -void _rrelu_with_noise_train( - at::Tensor& output, - const at::Tensor& input, - const at::Tensor& noise, - at::Scalar lower_, - at::Scalar upper_, - c10::optional generator) { - float lower = lower_.toFloat(); - float upper = upper_.toFloat(); - auto shape = output.sizes(); - auto noise_shape = noise.sizes(); - at::Tensor tmp_tensor = output.contiguous(); - at::Tensor output_data = tmp_tensor.reshape({output.numel()}); - at::Tensor input_data = input.reshape({input.numel()}); - at::Tensor tmp_noise = noise; - tmp_noise = tmp_noise.reshape({tmp_noise.numel()}); - auto gen = at::get_generator_or_default(generator, at::detail::getDefaultCPUGenerator()); - - for (int64_t i = 0; i < input.numel(); i++) { - if (input_data[i].item().toFloat() <= 0) { - at::uniform_real_distribution uniform(lower, upper); - const float r = uniform(gen); - output_data[i] = input_data[i] * r; - tmp_noise[i] = r; - } else { - tmp_noise[i] = 1; - output_data[i] = input_data[i]; - } - } - if (!output.is_contiguous()) { - output.copy_(tmp_tensor); - } - tmp_noise.reshape(noise_shape); - noise.copy_(tmp_noise); - output.reshape(shape); -} - -at::Tensor& rrelu_with_noise_out_nocheck( - const at::Tensor& self, - const at::Tensor& noise, - at::Scalar lower, - at::Scalar upper, - bool training, - c10::optional generator, - at::Tensor& output) { - - if (training) { - _rrelu_with_noise_train(output, self.contiguous(), noise, lower, upper, generator); - return output; - } else { - auto float_lower = lower.toFloat(); - auto float_upper = upper.toFloat(); - at::Scalar negative_slope = (float_lower + float_upper) / 2; - return NPUNativeFunctions::leaky_relu_out(self, negative_slope, output); - } -} - -at::Tensor NPUNativeFunctions::rrelu_with_noise( - const at::Tensor& self, - const at::Tensor& noise, - at::Scalar lower, - at::Scalar upper, - bool training, - c10::optional generator) { - auto output = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); - return rrelu_with_noise_out_nocheck(self, noise, lower, upper, training, generator, output); -} - -at::Tensor& NPUNativeFunctions::rrelu_with_noise_( - at::Tensor& self, - const at::Tensor& noise, - at::Scalar lower, - at::Scalar upper, - bool training, - c10::optional generator) { - return NPUNativeFunctions::rrelu_with_noise_out(self, noise, lower, upper, training, generator, self); -} - -at::Tensor& NPUNativeFunctions::rrelu_with_noise_out( - const at::Tensor& self, - const at::Tensor& noise, - at::Scalar lower, - at::Scalar upper, - bool training, - c10::optional generator, - at::Tensor& output) { - - OpPreparation::CheckOut( - {self}, - output, - ACL_FORMAT_ND, - self.scalar_type(), - self.sizes()); - - if (!NpuUtils::check_match(&output)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(output); - at::Tensor newResult = rrelu_with_noise_out_nocheck(self, noise, lower, upper, training, generator, contiguousResult); - NpuUtils::format_fresh_view(output, newResult); - } else { - rrelu_with_noise_out_nocheck(self, noise, lower, upper, training, generator, output); - } - - return output; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/RsqrtKernelNpu.cpp b/torch_npu/csrc/aten/ops/RsqrtKernelNpu.cpp deleted file mode 100644 index 782814108e..0000000000 --- a/torch_npu/csrc/aten/ops/RsqrtKernelNpu.cpp +++ /dev/null @@ -1,52 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& rsqrt_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Rsqrt") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::rsqrt_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut({self}, result, self); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){rsqrt_out_npu_nocheck(self, result);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::rsqrt(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - rsqrt_out_npu_nocheck(self, result); - return result; -} - -at::Tensor& NPUNativeFunctions::rsqrt_(at::Tensor& self) { - rsqrt_out(self, self); - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/RsubKernelNpu.cpp b/torch_npu/csrc/aten/ops/RsubKernelNpu.cpp index 4c8200b577..36e12cf0e1 100644 --- a/torch_npu/csrc/aten/ops/RsubKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/RsubKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -58,8 +58,8 @@ at::Tensor& rsub_out_npu_nocheck( at::Tensor& rsub_out_npu_nocheck( at::Tensor& result, const at::Tensor& self, - at::Scalar other, - at::Scalar alpha) { + const at::Scalar& other, + const at::Scalar& alpha) { // other*alpha at::Tensor scalarValue(at::mul(self, alpha)); @@ -73,7 +73,7 @@ at::Tensor& rsub_out_npu_nocheck( return result; } -at::Tensor NPUNativeFunctions::rsub(const at::Tensor& self, const at::Tensor& other, at::Scalar alpha) { +at::Tensor XLANativeFunctions::rsub(const at::Tensor& self, const at::Tensor& other, const at::Scalar& alpha) { at::Tensor outputTensor = rsub_dest_output(self, other); auto outputSize = broadcast_ops_npu_output_size(self, other); @@ -84,7 +84,7 @@ at::Tensor NPUNativeFunctions::rsub(const at::Tensor& self, const at::Tensor& ot return result; } -at::Tensor NPUNativeFunctions::rsub(const at::Tensor& self, at::Scalar other, at::Scalar alpha) { +at::Tensor XLANativeFunctions::rsub(const at::Tensor& self, const at::Scalar& other, const at::Scalar& alpha) { at::Tensor result = OpPreparation::ApplyTensor(self); rsub_out_npu_nocheck(result, self, other, alpha); diff --git a/torch_npu/csrc/aten/ops/ScaledMaskedSoftmaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/ScaledMaskedSoftmaxKernelNpu.cpp deleted file mode 100644 index 38ea7584ee..0000000000 --- a/torch_npu/csrc/aten/ops/ScaledMaskedSoftmaxKernelNpu.cpp +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) 2022 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. - -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -at::Tensor npu_scaled_masked_softmax_forward( - const at::Tensor& self, - const at::Tensor& mask, - at::Scalar scale, - bool fixed_triu_mask){ - at::Tensor result = OpPreparation::ApplyTensor(self, self.options().dtype(at::kHalf)); - OpCommand cmd; - cmd.Name("ScaledMaskedSoftmax") - .Input(self) - .Input(mask) - .Output(result) - .Attr("scale", scale) - .Attr("fixed_triu_mask", fixed_triu_mask) - .Run(); - return result; -} - -at::Tensor npu_scaled_masked_softmax_backward( - const at::Tensor& y_grad, - const at::Tensor& y, - const at::Tensor& mask, - at::Scalar scale, - bool fixed_triu_mask){ - at::Tensor result = OpPreparation::ApplyTensor(y_grad, y_grad.options().dtype(at::kHalf)); - OpCommand cmd; - cmd.Name("ScaledMaskedSoftmaxGrad") - .Input(y_grad) - .Input(y) - .Input(mask) - .Output(result) - .Attr("scale", scale) - .Attr("fixed_triu_mask", fixed_triu_mask) - .Run(); - return result; -} - -class NPUscalemsFunction: public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self, - const at::Tensor& mask, - at::Scalar scale, - bool fixed_triu_mask) { - ctx->saved_data["scale"] = scale; - ctx->saved_data["fixed_triu_mask"] = fixed_triu_mask; - auto result = npu_scaled_masked_softmax_forward(self, mask, scale, fixed_triu_mask); - ctx->save_for_backward({result, mask}); - return result; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto scale = ctx->saved_data["scale"].toScalar(); - auto fixed_triu_mask = ctx->saved_data["fixed_triu_mask"].toBool(); - auto saved = ctx->get_saved_variables(); - auto result0 = saved[0]; - auto mask = saved[1]; - auto result = npu_scaled_masked_softmax_backward( - grad_outputs[0], result0, mask, scale, fixed_triu_mask); - tensor_list output = {result, at::Tensor(), at::Tensor(), at::Tensor()}; - return output; - } -}; - -at::Tensor NPUNativeFunctions::npu_scaled_masked_softmax( - const at::Tensor& self, - const at::Tensor& mask, - at::Scalar scale, - bool fixed_triu_mask){ - auto result = NPUscalemsFunction::apply(self, mask, scale, fixed_triu_mask); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ScatterAddKernelNpu.cpp b/torch_npu/csrc/aten/ops/ScatterAddKernelNpu.cpp deleted file mode 100644 index 9854f712ba..0000000000 --- a/torch_npu/csrc/aten/ops/ScatterAddKernelNpu.cpp +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& scatter_add_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& src) { - OpCommand cmd; - cmd.Name("ScatterAddWithAxis") - .Input(self) - .Input(index) - .Input(src) - .Output(result) - .Attr("axis", dim) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::scatter_add( - const at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& src) { - return self.clone(at::MemoryFormat::Contiguous).scatter_add_(dim, index, src); -} - -at::Tensor& NPUNativeFunctions::scatter_add_( - at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& src) { - OpPreparation::CheckMemory({self, index, src}, {self}); - - at::ScalarType selfType = self.scalar_type(); - at::Tensor selfFp32 = self; - at::Tensor srcFp32 = src; - if (selfType == at::ScalarType::Half) { - selfFp32 = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - srcFp32 = NPUNativeFunctions::npu_dtype_cast(src, at::ScalarType::Float); - } - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfFp32); - at::Tensor result = - scatter_add_out_npu_nocheck(contiguousSelf, contiguousSelf, dim, index, srcFp32); - self.copy_(result); - } else { - scatter_add_out_npu_nocheck(selfFp32, selfFp32, dim, index, srcFp32); - self.copy_(selfFp32); - } - - if(self.scalar_type() != selfType) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Half); - } - - return self; -} - -at::Tensor NPUNativeFunctions::scatter_add( - const at::Tensor& self, - at::Dimname dim, - const at::Tensor& index, - const at::Tensor& src) { - return scatter_add(self, dimname_to_position(self, dim), index, src); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ScatterKernelNpu.cpp b/torch_npu/csrc/aten/ops/ScatterKernelNpu.cpp deleted file mode 100644 index 8a32d4da90..0000000000 --- a/torch_npu/csrc/aten/ops/ScatterKernelNpu.cpp +++ /dev/null @@ -1,97 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& scatter_npu_src_nocheck( - at::Tensor& self, - int64_t dim, - const at::Tensor& index, - const at::Tensor& src) { - OpCommand cmd; - cmd.Name("ScatterElements") - .Input(self) - .Input(index) - .Input(src) - .Output(self) - .Attr("axis", dim) - .Run(); - return self; -} - -at::Tensor& scatter_npu_src_impl( - at::Tensor& self, - int64_t dim, - const at::Tensor& index_ex, - const at::Tensor& src_ex) { - at::ScalarType selfType = self.scalar_type(); - if (selfType == at::ScalarType::Half) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - at::Tensor index(index_ex); - if (index.scalar_type() == at::ScalarType::Half) { - index = NPUNativeFunctions::npu_dtype_cast(index, at::ScalarType::Float); - } - - at::Tensor src(src_ex); - if (src.scalar_type() != self.scalar_type()) { - src = NPUNativeFunctions::npu_dtype_cast(src, self.scalar_type()); - } - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - - scatter_npu_src_nocheck(contiguousSelf, dim, index, src); - NpuUtils::format_fresh_view(self, contiguousSelf); - } else { - scatter_npu_src_nocheck(self, dim, index, src); - } - - if(self.scalar_type() != selfType){ - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Half); - } - return self; -} - -at::Tensor& NPUNativeFunctions::scatter_( - at::Tensor& self, - int64_t dim, - const at::Tensor& index_ex, - const at::Tensor& src_ex) { - at::Tensor src(src_ex); - scatter_npu_src_impl(self, dim, index_ex, src); - return self; -} - -at::Tensor& NPUNativeFunctions::scatter_( - at::Tensor& self, - int64_t dim, - const at::Tensor& index_ex, - at::Scalar src) { - at::Tensor srcTensor = scalar_to_tensor(src).to(at::ScalarType::Float); - srcTensor = CalcuOpUtil::copy_tensor_host_to_device(srcTensor); - at::Tensor srcTensor_broadcast = NPUNativeFunctions::npu_broadcast(srcTensor, array_to_small_vector(index_ex.sizes())); - scatter_npu_src_impl(self, dim, index_ex, srcTensor_broadcast); - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ScatterV1KernelNpu.cpp b/torch_npu/csrc/aten/ops/ScatterV1KernelNpu.cpp deleted file mode 100644 index f142a37884..0000000000 --- a/torch_npu/csrc/aten/ops/ScatterV1KernelNpu.cpp +++ /dev/null @@ -1,48 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& scatter_out_npu( - at::Tensor& output, - const at::Tensor& self, - const at::Tensor& indices, - const at::Tensor& updates, - int64_t dim) { - OpCommand cmd; - cmd.Name("ArgMaxGrad") - .Input(self) - .Input(indices) - .Input(updates) - .Output(output) - .Attr("dimension", dim) - .Run(); - - return output; -} - -at::Tensor NPUNativeFunctions::npu_scatter(const at::Tensor& self, const at::Tensor& indices, const at::Tensor& updates, int64_t dim) { - at::Tensor outputs = OpPreparation::ApplyTensor(self); - scatter_out_npu(outputs, self, indices, updates, dim); - - return outputs; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SeluKernelNpu.cpp b/torch_npu/csrc/aten/ops/SeluKernelNpu.cpp deleted file mode 100644 index 88406b5766..0000000000 --- a/torch_npu/csrc/aten/ops/SeluKernelNpu.cpp +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& selu_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Selu") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::selu(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - - selu_out_npu_nocheck(result, self); - - return result; -} - -at::Tensor& NPUNativeFunctions::selu_(at::Tensor& self) { - OpPreparation::CheckMemory({self}, {self}); - - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = selu_out_npu_nocheck(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - selu_out_npu_nocheck(self, self); - } - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SigmoidBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/SigmoidBackwardKernelNpu.cpp deleted file mode 100644 index fdd644c05b..0000000000 --- a/torch_npu/csrc/aten/ops/SigmoidBackwardKernelNpu.cpp +++ /dev/null @@ -1,56 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& sigmoid_backward_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& grad_output, - const at::Tensor& output) { - auto unified_result = OpPreparation::binary_op_check(result, output, grad_output, true); - OpCommand cmd; - cmd.Name("SigmoidGrad") - .Expect(unified_result) - .Input(output) - .Input(grad_output) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::sigmoid_backward_out( - const at::Tensor& grad_output, - const at::Tensor& output, - at::Tensor& result) { - OpPreparation::CheckOut({grad_output, output}, result, grad_output); - sigmoid_backward_out_npu_nocheck(result, grad_output, output); - return result; -} - -at::Tensor NPUNativeFunctions::sigmoid_backward(const at::Tensor& grad_output, const at::Tensor& output) { - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output); - sigmoid_backward_out_npu_nocheck(grad_input, grad_output, output); - - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SigmoidKernelNpu.cpp b/torch_npu/csrc/aten/ops/SigmoidKernelNpu.cpp deleted file mode 100644 index 19f6ffb5e1..0000000000 --- a/torch_npu/csrc/aten/ops/SigmoidKernelNpu.cpp +++ /dev/null @@ -1,57 +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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& sigmoid_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Sigmoid") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::sigmoid_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self}, {result}) - .Func([&self](at::Tensor& result){sigmoid_out_npu_nocheck(result, self);}) - .Call(result); -} - -at::Tensor& NPUNativeFunctions::sigmoid_(at::Tensor& self) { - NPUNativeFunctions::sigmoid_out(self, self); - - return self; -} - -at::Tensor NPUNativeFunctions::sigmoid(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - sigmoid_out_npu_nocheck(result, self); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SignBitsPackKernelNpu.cpp b/torch_npu/csrc/aten/ops/SignBitsPackKernelNpu.cpp deleted file mode 100644 index 7fe4904e1a..0000000000 --- a/torch_npu/csrc/aten/ops/SignBitsPackKernelNpu.cpp +++ /dev/null @@ -1,52 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& sign_bits_pack_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - int64_t size) { - OpCommand cmd; - cmd.Name("SignBitsPack") - .Input(self) - .Output(result) - .Attr("size", size) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::npu_sign_bits_pack(const at::Tensor& self, int64_t size) { - TORCH_CHECK(self.dim() == 1, "input must be one-dimensional"); - TORCH_CHECK(self.scalar_type() == at::ScalarType::Half || self.scalar_type() == at::ScalarType::Float, - "all only supports torch.float16 and torch.float32 dtypes"); - auto ysize = (self.numel() + 7) / 8; - TORCH_CHECK(size != 0 && ysize % size == 0, "all must be divisible by size"); - at::Tensor result = OpPreparation::ApplyTensor({size, ysize / size}, self.options().dtype(at::kByte), self); - - // calculate the output result of the NPU - sign_bits_pack_npu_nocheck(result, self, size); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SignBitsUnpackKernelNpu.cpp b/torch_npu/csrc/aten/ops/SignBitsUnpackKernelNpu.cpp deleted file mode 100644 index a7b4b6f358..0000000000 --- a/torch_npu/csrc/aten/ops/SignBitsUnpackKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu{ -namespace native{ - -at::Tensor& sign_bits_unpack_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& x, - int64_t size, - c10::ScalarType dtype) { - int64_t typeEnum = dtype == at::ScalarType::Half ? 1 : 0; - OpCommand cmd; - cmd.Name("SignBitsUnpack") - .Input(x) - .Output(result) - .Attr("dtype", typeEnum) - .Attr("size", size) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::npu_sign_bits_unpack( - const at::Tensor& input, - int64_t size, - c10::ScalarType dtype) { - int64_t dim = input.dim(); - TORCH_CHECK(dim == 1, "input value should be a 1-dimensional tensor"); - - TORCH_CHECK(input.scalar_type() == at::ScalarType::Byte, "sign_bits_unpack input only supports torch.uint8 "); - - TORCH_CHECK(size > 0, "The argument 'size' is not valid because it is less than or equal to zero"); - - int64_t input_size = input.numel(); - TORCH_CHECK((input_size * 8) % size == 0, "input value length*8 must be multiple of size"); - - TORCH_CHECK(dtype == at::ScalarType::Float || dtype == at::ScalarType::Half, "The argument 'dtype' must be torch.float32 or torch.float16"); - - int64_t m = input_size * 8 / size; - at::Tensor result = OpPreparation::ApplyTensor({size, m}, input.options().dtype(dtype), input); - - sign_bits_unpack_out_npu_nocheck(result, input, size, dtype); - return result; - } -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SignKernelNpu.cpp b/torch_npu/csrc/aten/ops/SignKernelNpu.cpp deleted file mode 100644 index 4fd0ab516e..0000000000 --- a/torch_npu/csrc/aten/ops/SignKernelNpu.cpp +++ /dev/null @@ -1,69 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& sign_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Sign") - .Input(self) - .Output(result) - .Run(); - - return result; -} - - -at::Tensor& NPUNativeFunctions::sign_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - sign_out_npu_nocheck(result, self); - - return result; -} - -at::Tensor& NPUNativeFunctions::sgn_out(const at::Tensor& self, at::Tensor& result) { - return NPUNativeFunctions::sign_out(self, result); -} - -at::Tensor NPUNativeFunctions::sign(const at::Tensor& self) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - sign_out_npu_nocheck(result, self); - - return result; -} - -at::Tensor& NPUNativeFunctions::sign_(at::Tensor& self) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = sign_out_npu_nocheck(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - sign_out_npu_nocheck(self, self); - } - - return self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SiluKernelNpu.cpp b/torch_npu/csrc/aten/ops/SiluKernelNpu.cpp deleted file mode 100644 index 0b4c07bba4..0000000000 --- a/torch_npu/csrc/aten/ops/SiluKernelNpu.cpp +++ /dev/null @@ -1,136 +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. - -#include -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -using torch::autograd::Function; -using torch::autograd::AutogradContext; -using tensor_list = std::vector; - -at::Tensor& silu_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Swish") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& silu_out_npu(const at::Tensor& self, at::Tensor& out){ - OpPreparation::CheckOut( - {self}, - out, - self); - - if (!NpuUtils::check_match(&out)) { - at::Tensor contiguousOut = NpuUtils::format_contiguous(out); - at::Tensor newOut = silu_out_npu_nocheck(contiguousOut, self); - NpuUtils::format_fresh_view(out, newOut); - } else { - silu_out_npu_nocheck(out, self); - } - - return out; -} - -at::Tensor silu_kerner_npu(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - - silu_out_npu_nocheck(result, self); - - return result; -} - -at::Tensor& NPUNativeFunctions::npu_silu_(at::Tensor& self) { - silu_out_npu(self, self); - return self; -} - -at::Tensor& silu_backward_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& grad_output, - const at::Tensor& x0, - const at::Tensor& x1) { - - OpCommand cmd; - cmd.Name("SwishGrad") - .Input(grad_output) - .Input(x0) - .Input(x1) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::npu_silu_backward(const at::Tensor& grad_output, const at::Tensor& x0, const at::Tensor& x1) { - // construct the output tensor of the NPU - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output); - - // calculate the output result of the NPU - silu_backward_out_npu_nocheck(grad_input, grad_output, x0, x1); - - return grad_input; -} - -class NPUSiluFunction : public torch::autograd::Function { -public: - static at::Tensor forward(AutogradContext *ctx, - const at::Tensor& self) { - at::AutoNonVariableTypeMode g; - at::Tensor result = silu_kerner_npu(self); - ctx->save_for_backward({self, result}); - - return result; - } - - static tensor_list backward(AutogradContext *ctx, - tensor_list grad_outputs) { - auto saved = ctx->get_saved_variables(); - auto input = saved[0]; - auto result = saved[1]; - - at::Tensor output = NPUNativeFunctions::npu_silu_backward(grad_outputs[0], input, result); - tensor_list outputlist = {output}; - - return outputlist; - } -}; - -at::Tensor NPUNativeFunctions::npu_silu(const at::Tensor& self) { - return NPUSiluFunction::apply(self); -} - -at::Tensor& NPUNativeFunctions::silu_out(const at::Tensor& self, at::Tensor& result) { - silu_out_npu(self, result); - return result; -} - -at::Tensor NPUNativeFunctions::silu(const at::Tensor& self) { - return NPUSiluFunction::apply(self); -} - -at::Tensor& NPUNativeFunctions::silu_(at::Tensor& self) { - silu_out_npu(self, self); - return self; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SinKernelNpu.cpp b/torch_npu/csrc/aten/ops/SinKernelNpu.cpp deleted file mode 100644 index 0b21d6f00e..0000000000 --- a/torch_npu/csrc/aten/ops/SinKernelNpu.cpp +++ /dev/null @@ -1,63 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& sin_out_npu_nocheck(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("Sin") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::sin_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut({self}, result, self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor newResult = sin_out_npu_nocheck(contiguousResult, self); - NpuUtils::format_fresh_view(result, newResult); - } else { - sin_out_npu_nocheck(result, self); - } - - return result; -} - -at::Tensor NPUNativeFunctions::sin(const at::Tensor& self) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - self.sizes(), self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - - // calculate the output result of the NPU - sin_out_npu_nocheck(result, self); - - return result; -} - -at::Tensor& NPUNativeFunctions::sin_(at::Tensor& self) { - NPUNativeFunctions::sin_out(self, self); - return self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SinhKernelNpu.cpp b/torch_npu/csrc/aten/ops/SinhKernelNpu.cpp deleted file mode 100644 index bd0d2af415..0000000000 --- a/torch_npu/csrc/aten/ops/SinhKernelNpu.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& sinh_out_nocheck(const at::Tensor& self, at::Tensor& result) { - // executing the NPU operator - OpCommand cmd; - cmd.Name("Sinh") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::sinh_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - sinh_out_nocheck(self, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - sinh_out_nocheck(self, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::sinh(const at::Tensor& self) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - - // calculate the output result of the NPU - sinh_out_nocheck(self, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::sinh_(at::Tensor& self) { - NPUNativeFunctions::sinh_out(self, self); - - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SliceKernelNpu.cpp b/torch_npu/csrc/aten/ops/SliceKernelNpu.cpp index 68f883aeae..bf59c628b8 100644 --- a/torch_npu/csrc/aten/ops/SliceKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SliceKernelNpu.cpp @@ -16,14 +16,14 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - at::Tensor &NPUNativeFunctions::npu_slice_out( + at::Tensor &XLANativeFunctions::npu_slice_out( const at::Tensor &self, c10::IntArrayRef offsets, c10::IntArrayRef size, @@ -42,7 +42,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::npu_slice(const at::Tensor &self, c10::IntArrayRef offsets, c10::IntArrayRef size) + at::Tensor XLANativeFunctions::npu_slice(const at::Tensor &self, c10::IntArrayRef offsets, c10::IntArrayRef size) { // calculate the output size c10::SmallVector outputSize = diff --git a/torch_npu/csrc/aten/ops/SlogdetKernelNpu.cpp b/torch_npu/csrc/aten/ops/SlogdetKernelNpu.cpp deleted file mode 100644 index 6c8eb11ef1..0000000000 --- a/torch_npu/csrc/aten/ops/SlogdetKernelNpu.cpp +++ /dev/null @@ -1,55 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -namespace at_npu { -namespace native { - -tuple slogdet_out_nocheck_npu( - const at::Tensor& self, - at::Tensor& sign, - at::Tensor& y) { - OpCommand cmd; - cmd.Name("LogMatrixDeterminant") - .Input(self) - .Output(sign) - .Output(y) - .Run(); - - return std::tie(sign, y); -} - -tupleNPUNativeFunctions::slogdet(const at::Tensor& self) { - - TORCH_CHECK(self.dim() >= 2, "input must be at least 2 dimensions"); - - // calculate the output size - auto outputSize = array_to_small_vector(self.sizes()); - outputSize.erase(outputSize.end() - 2, outputSize.end()); - - // construct the output tensor of the NPU - at::Tensor sign = OpPreparation::ApplyTensor(self, outputSize); - at::Tensor y = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - slogdet_out_nocheck_npu(self, sign, y); - - return std::tie(sign, y); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SlowConvDilated2DKernelNpu.cpp b/torch_npu/csrc/aten/ops/SlowConvDilated2DKernelNpu.cpp deleted file mode 100644 index a3059712bd..0000000000 --- a/torch_npu/csrc/aten/ops/SlowConvDilated2DKernelNpu.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::slow_conv_dilated2d( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - - if (stride[0] == 0) { - AT_ERROR("slow_conv_dilated2d_npu_output_size: stride[0] can not be zero"); - } - if (padding[0] < 0 || padding[1] < 0){ - AT_ERROR("slow_conv_dilated2d_npu_output_size: padding can not be less than zero"); - } - auto outputSize = slow_conv_dilated2d_npu_output_size( - self, weight, stride, padding, dilation); - at::Tensor result = OpPreparation::ApplyTensorWithFormat(outputSize, self.options(), ACL_FORMAT_NC1HWC0); - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - int64_t groups = 1; - c10::SmallVector stridesSize = {1,1,stride[0],stride[1]}; - c10::SmallVector paddings = { - padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - - OpCommand cmd; - cmd.Name("Conv2D") - .Input(self) - .Input(weight); - if (bias.defined()){ - cmd.Input(bias); - } - cmd.Output(result) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups",groups) - .Attr("data_format","NCHW") - .Run(); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SlowConvDilated2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/SlowConvDilated2dBackwardKernelNpu.cpp deleted file mode 100644 index dd4e74f154..0000000000 --- a/torch_npu/csrc/aten/ops/SlowConvDilated2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor slow_conv_dilated2d_backward_input_out_npu( - at::Tensor grad_input, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - string dataFormat = "NCHW"; - int64_t groups = 1; - c10::SmallVector dimList = array_to_small_vector(self.sizes()); - OpCommand cmd; - cmd.Name("Conv2DBackpropInput") - .Input(dimList, at::kInt) - .Input(weight) - .Input(grad_output) - .Output(grad_input) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - - return grad_input; -} - -at::Tensor slow_conv_dilated2d_backward_weight_out_npu( - at::Tensor grad_weight, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - string dataFormat = "NCHW"; - int64_t groups = 1; - c10::SmallVector dimList = array_to_small_vector(weight.sizes()); - // executing the NPU operator - OpCommand cmd; - cmd.Name("Conv2DBackpropFilter") - .Input(self) - .Input(dimList, at::kInt) - .Input(grad_output) - .Output(grad_weight) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - - return grad_weight; -} - -at::Tensor slow_conv_dilated2d_backward_bias_out_npu( - at::Tensor grad_bias, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - string dataFormat = "NCHW"; - // executing the NPU operator - OpCommand cmd; - cmd.Name("BiasAddGrad") - .Input(self) - .Output(grad_bias) - .Attr("data_format", dataFormat) - .Run(); - - return grad_bias; -} - -tuple slow_conv_dilated2d_backward_out_npu( - at::Tensor grad_input, - at::Tensor grad_weight, - at::Tensor grad_bias, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - std::array output_mask) { - // calculate the output result of the NPU - - if (output_mask[0]) { - slow_conv_dilated2d_backward_input_out_npu( - grad_input, grad_output, self, weight, kernel_size, stride, padding, dilation); - } - - if (output_mask[1]) { - slow_conv_dilated2d_backward_weight_out_npu( - grad_weight, grad_output, self, weight, kernel_size, stride, padding, dilation); - } - - if (output_mask[2]) { - slow_conv_dilated2d_backward_bias_out_npu( - grad_bias, grad_output, self, weight, kernel_size, stride, padding, dilation); - } - - return tuple(grad_input, grad_weight, grad_bias); -} - -tuple NPUNativeFunctions::slow_conv_dilated2d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - std::array output_mask) { - - auto outputSizes = slow_conv_dilated2d_backward_npu_output_size( - grad_output,self,weight,kernel_size,stride,padding, dilation); - - at::Tensor undefined; - - at::Tensor grad_input = - (output_mask[0] ? OpPreparation::ApplyTensor(grad_output, self.sizes()) : undefined); - - at::Tensor grad_weight = - (output_mask[1] ? OpPreparation::ApplyTensor(grad_output, weight.sizes()) : undefined); - - at::Tensor grad_bias = - (output_mask[2] ? OpPreparation::ApplyTensor(grad_output, weight.size(0)) : undefined); - - slow_conv_dilated2d_backward_out_npu( - grad_input, - grad_weight, - grad_bias, - grad_output, - self, - weight, - kernel_size, - stride, - padding, - dilation, - output_mask); - - return std::tie(grad_input, grad_weight, grad_bias); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SlowConvTranspose2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/SlowConvTranspose2dBackwardKernelNpu.cpp deleted file mode 100644 index fcb9ce5fdf..0000000000 --- a/torch_npu/csrc/aten/ops/SlowConvTranspose2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,260 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor slow_conv_transpose2d_backward_grad_output_out_npu( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - const at::Tensor& columns, - const at::Tensor& ones) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - string dataFormat = "NCHW"; - int64_t groups = 1; - // executing the NPU operator - OpCommand cmd; - cmd.Name("Conv2D") - .Input(grad_output) - .Input(weight) - .Output(grad_input) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - - return grad_input; -} - -at::Tensor slow_conv_transpose2d_backward_weight_out_npu( - at::Tensor& grad_weight, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - const at::Tensor& columns, - const at::Tensor& ones) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - string dataFormat = "NCHW"; - int64_t groups = 1; - c10::SmallVector dimList = array_to_small_vector(weight.sizes()); - // executing the NPU operator - OpCommand cmd; - cmd.Name("Conv2DBackpropFilter") - .Input(grad_output) - .Input(dimList, at::kInt) - .Input(self) - .Output(grad_weight) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - - return grad_weight; -} - -at::Tensor slow_conv_transpose2d_backward_bias_out_npu( - at::Tensor& grad_bias, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - const at::Tensor& columns, - const at::Tensor& ones) { - at::Tensor gradView = grad_output.contiguous().view({grad_output.size(0), grad_output.size(1), -1}); - at::sum_out(grad_bias, gradView, c10::SmallVector {0, 2}); - - return grad_bias; -} - -tuple slow_conv_transpose2d_backward_npu_nocheck( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - const at::Tensor& columns, - const at::Tensor& ones, - at::Tensor& grad_input, - at::Tensor& grad_weight, - at::Tensor& grad_bias) { - slow_conv_transpose2d_backward_grad_output_out_npu( - grad_input, - grad_output, - self, - weight, - kernel_size, - stride, - padding, - output_padding, - dilation, - columns, - ones); - - slow_conv_transpose2d_backward_weight_out_npu( - grad_weight, - grad_output, - self, - weight, - kernel_size, - stride, - padding, - output_padding, - dilation, - columns, - ones); - slow_conv_transpose2d_backward_bias_out_npu( - grad_bias, - grad_output, - self, - weight, - kernel_size, - stride, - padding, - output_padding, - dilation, - columns, - ones); - - return tuple(grad_input, grad_weight, grad_bias); -} - -tuple NPUNativeFunctions::slow_conv_transpose2d_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - const at::Tensor& columns, - const at::Tensor& ones, - at::Tensor& grad_input, - at::Tensor& grad_weight, - at::Tensor& grad_bias) { - auto outputSizes = slow_conv_transpose2d_backward_npu_output_size( - grad_output, self, weight, kernel_size, stride, padding, output_padding, dilation, columns, ones); - - OpPreparation::CheckOut( - {grad_output, self, weight}, - grad_input, - ACL_FORMAT_NC1HWC0, - self.scalar_type(), - std::get<0>(outputSizes)); - OpPreparation::CheckOut( - {grad_output, self, weight}, - grad_weight, - ACL_FORMAT_FRACTAL_Z, - at::kFloat, - std::get<1>(outputSizes)); - OpPreparation::CheckOut( - {grad_output, self, weight}, - grad_bias, - ACL_FORMAT_NCHW, - grad_output.scalar_type(), - {grad_output.size(1)}); - - return slow_conv_transpose2d_backward_npu_nocheck( - grad_output, - self, - weight, - kernel_size, - stride, - padding, - output_padding, - dilation, - columns, - ones, - grad_input, - grad_weight, - grad_bias); -} - -tuple NPUNativeFunctions::slow_conv_transpose2d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - const at::Tensor& columns, - const at::Tensor& ones, - std::array output_mask) { - auto flag = 2; - auto outputSizes = slow_conv_transpose2d_backward_npu_output_size( - grad_output, self, weight, kernel_size, stride, padding, output_padding, dilation, columns, ones); - at::Tensor grad_input; - at::Tensor grad_weight; - at::Tensor grad_bias; - - if (output_mask[0]) { - grad_input = OpPreparation::ApplyTensorWithFormat(self, std::get<0>(outputSizes), ACL_FORMAT_NC1HWC0); - } - - if (output_mask[1]) { - grad_weight = OpPreparation::ApplyTensorWithFormat(std::get<1>(outputSizes), weight.options().dtype(at::kFloat), ACL_FORMAT_FRACTAL_Z); - } - - if (output_mask[flag]) { - grad_bias = OpPreparation::ApplyTensorWithFormat(grad_output, {grad_output.size(1)}, ACL_FORMAT_NCHW); - } - - return slow_conv_transpose2d_backward_npu_nocheck( - grad_output, - self, - weight, - kernel_size, - stride, - padding, - output_padding, - dilation, - columns, - ones, - grad_input, - grad_weight, - grad_bias); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SlowConvTranspose2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/SlowConvTranspose2dKernelNpu.cpp deleted file mode 100644 index c4997f1736..0000000000 --- a/torch_npu/csrc/aten/ops/SlowConvTranspose2dKernelNpu.cpp +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -c10::SmallVector slow_conv_transpose2d_npu_output_size( - const at::Tensor & self, - const at::Tensor & weight, - at::IntArrayRef kernel_size, - const at::Tensor & bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation) { - int ndim = self.dim(); - int dimh = 1; - int dimw = 2; - auto flag = 4; - auto flag_a = 3; - - if (ndim == flag) { - dimh++; - dimw++; - } - - TORCH_CHECK( - self.numel() != 0 && (ndim == flag_a || ndim == flag), - "non-empty 3D or 4D input tensor expected but got a tensor with size ", - self.sizes()); - int64_t N = self.size(0); - int64_t Co = weight.size(1); - int64_t H = self.size(dimh); - int64_t W = self.size(dimw); - - int64_t Ho = (H - 1) * stride[0] - 2 * padding[0] + - dilation[0] * (kernel_size[0] - 1) + output_padding[0] + 1; - int64_t Wo = (W - 1) * stride[1] - 2 * padding[1] + - dilation[1] * (kernel_size[1] - 1) + output_padding[1] + 1; - - c10::SmallVector outputSize = {N, Co, Ho, Wo}; - - return outputSize; -} - -static inline void slow_conv_transpose2d_shape_check_npu( - const at::Tensor & self, - const at::Tensor & weight, - at::IntArrayRef kernel_size, - const at::Tensor & bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation) { - TORCH_CHECK( - kernel_size[0] > 0 && kernel_size[1] > 0, - "kernel size should be greater than zero, but got kernel_height: ", - kernel_size[0], - " kernel_width: ", - kernel_size[1]); - TORCH_CHECK( - stride[0] > 0 && stride[1] > 0, - "stride should be greater than zero, but got stride_height: ", - stride[0], - " stride_width: ", - stride[1]); - TORCH_CHECK( - dilation[0] > 0 && dilation[1] > 0, - "dilation should be greater than zero, but got dilation_height: ", - dilation[0], - ", dilation_width: ", - dilation[1]); - TORCH_CHECK( - (output_padding[1] < stride[1] || - output_padding[1] < dilation[1]) && - (output_padding[0] < stride[0] || - output_padding[0] < dilation[0]), - "output padding must be smaller than either stride or dilation, but got output_padding_height: ", - output_padding[0], - " output_padding_width: ", - output_padding[1], - " stride_height: ", - stride[0], - " stride_width: ", - stride[1], - " dilation_height: ", - dilation[0], - " dilation_width: ", - dilation[1]); - - auto flag_a = 2; - auto flag_b = 4; - - TORCH_CHECK( - weight.numel() != 0 && (weight.dim() == flag_a || weight.dim() == flag_b), - "non-empty 2D or 4D weight tensor expected, but got: ", - weight.sizes()); - if (bias.defined()) { - check_dim_size(bias, 1, 0, weight.size(1)); - } - - TORCH_CHECK( - kernel_size.size() == flag_a, - "It is expected kernel_size equals to 2, but got size ", - kernel_size.size()); - - TORCH_CHECK( - dilation.size() == flag_a, - "It is expected dilation equals to 2, but got size ", - dilation.size()); - - TORCH_CHECK( - padding.size() == flag_a, - "It is expected padding equals to 2, but got size ", - padding.size()); - - TORCH_CHECK( - stride.size() == flag_a, - "It is expected stride equals to 2, but got size ", - stride.size()); - - TORCH_CHECK( - output_padding.size() == flag_a, - "It is expected stride equals to 2, but got size ", - output_padding.size()); -} - -at::Tensor& slow_conv_transpose2d_npu_nocheck( - const at::Tensor & self, - const at::Tensor & weight, - at::IntArrayRef kernel_size, - const c10::optional & bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - at::Tensor& out) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - slow_conv_transpose2d_shape_check_npu( - self, weight, kernel_size, bias, stride, padding, output_padding, dilation); - - auto outputSize = slow_conv_transpose2d_npu_output_size( - self, weight, kernel_size, bias, stride, padding, output_padding, dilation); - if (!out.sizes().equals(outputSize)) { - out.resize_(outputSize); - } - - c10::SmallVector paddings = { - padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - c10::SmallVector outputpadding = { - output_padding[0], output_padding[0], output_padding[1], output_padding[1]}; - string dataFormat = "NCHW"; - int64_t groups = 1; - c10::SmallVector sizeVec = array_to_small_vector(out.sizes()); - OpCommand cmd; - cmd.Name("Conv2DTranspose") - .Input(sizeVec, at::kInt) - .Input(self) - .Input(weight); - if (bias.defined()) { - cmd.Input(bias); - } - cmd.Output(out) - .Attr("pads", paddings) - .Attr("output_padding", outputpadding) - .Attr("strides", stridesSize) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - return out; -} - -at::Tensor& NPUNativeFunctions::slow_conv_transpose2d_out( - const at::Tensor & self, - const at::Tensor & weight, - at::IntArrayRef kernel_size, - const c10::optional & bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation, - at::Tensor& out) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = slow_conv_transpose2d_npu_output_size( - self, weight, kernel_size, bias, stride, padding, output_padding, dilation); - - if (bias.defined()) { - OpPreparation::CheckOut( - {self, weight, bias}, - {out}, - ACL_FORMAT_NC1HWC0, - self.scalar_type(), - outputSize); - } else { - OpPreparation::CheckOut( - {self, weight}, - {out}, - ACL_FORMAT_NC1HWC0, - self.scalar_type(), - outputSize); - } - - return slow_conv_transpose2d_npu_nocheck( - self, weight, kernel_size, bias_opt, stride, padding, output_padding, dilation, out); -} - -at::Tensor NPUNativeFunctions::slow_conv_transpose2d( - const at::Tensor & self, - const at::Tensor & weight, - at::IntArrayRef kernel_size, - const c10::optional & bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef dilation) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = slow_conv_transpose2d_npu_output_size( - self, weight, kernel_size, bias, stride, padding, output_padding, dilation); - - at::Tensor result = OpPreparation::ApplyTensorWithFormat(self, outputSize, ACL_FORMAT_NC1HWC0); - slow_conv_transpose2d_npu_nocheck( - self, weight, kernel_size, bias_opt, stride, padding, output_padding, dilation, result); - - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SoftShrinkBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftShrinkBackwardKernelNpu.cpp deleted file mode 100644 index 227e098c73..0000000000 --- a/torch_npu/csrc/aten/ops/SoftShrinkBackwardKernelNpu.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& softshrink_backward_out_nocheck( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar lambd, - at::Tensor& grad_input) { - OpPreparation::CheckMemory({grad_output, self}, {grad_input}); - OpCommand cmd; - cmd.Name("SoftShrinkGrad") - .Input(grad_output) - .Input(self) - .Output(grad_input) - .Attr("lambd", lambd) - .Run(); - - return grad_input; -} - -at::Tensor& NPUNativeFunctions::softshrink_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar lambd, - at::Tensor& grad_input) { - - OpPreparation::CheckOut( - {self, grad_output}, - grad_input, - self); - - if (!NpuUtils::check_match(&grad_input)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(grad_input); - softshrink_backward_out_nocheck(grad_output, self, lambd, contiguousResult); - NpuUtils::format_fresh_view(grad_input, contiguousResult); - } else { - softshrink_backward_out_nocheck(grad_output, self, lambd, grad_input); - } - - return grad_input; -} - -at::Tensor NPUNativeFunctions::softshrink_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar lambd) { - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - - softshrink_backward_out_nocheck( - grad_output, self, lambd, grad_input); - - return grad_input; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SoftShrinkKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftShrinkKernelNpu.cpp deleted file mode 100644 index e59c33971a..0000000000 --- a/torch_npu/csrc/aten/ops/SoftShrinkKernelNpu.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& softshrink_out_nocheck( - const at::Tensor& self, - at::Scalar lambd, - at::Tensor& result) { - - OpPreparation::CheckMemory({self}, {result}); - OpCommand cmd; - cmd.Name("SoftShrink") - .Input(self) - .Output(result) - .Attr("lambd", lambd) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::softshrink_out( - const at::Tensor& self, - at::Scalar lambd, - at::Tensor& result) { - TORCH_CHECK(lambd.toFloat() > 0, "lambd should be greater than 0"); - OpPreparation::CheckOut( - {self}, - result, - self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - softshrink_out_nocheck(self, lambd, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - softshrink_out_nocheck(self, lambd, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::softshrink(const at::Tensor& self, at::Scalar lambd) { - TORCH_CHECK(lambd.toFloat() > 0, "lambd should be greater than 0"); - at::Tensor result = OpPreparation::ApplyTensor(self); - - softshrink_out_nocheck(self, lambd, result); - - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SoftmaxBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftmaxBackwardKernelNpu.cpp index aef7ee2aa6..5c04267a91 100644 --- a/torch_npu/csrc/aten/ops/SoftmaxBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SoftmaxBackwardKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -28,7 +28,7 @@ namespace at_npu const at::Tensor &grad_output, const at::Tensor &output, int64_t dim, - const at::Tensor &self) + at::ScalarType input_dtype) { c10::SmallVector dimList = {dim}; // executing the NPU operator @@ -43,27 +43,27 @@ namespace at_npu return grad_input; } - at::Tensor NPUNativeFunctions::_softmax_backward_data( + at::Tensor XLANativeFunctions::_softmax_backward_data( const at::Tensor &grad_output, const at::Tensor &output, int64_t dim, - const at::Tensor &self) + at::ScalarType input_dtype) { // calculate the output size auto outputSize = input_same_output_size(grad_output); + at::Tensor tmp_output = output; // output'format must be same with grad_output - at::Tensor temp_output = output; - if (CalcuOpUtil::get_tensor_npu_format(temp_output) == ACL_FORMAT_NC1HWC0) + if (CalcuOpUtil::get_tensor_npu_format(tmp_output) != CalcuOpUtil::get_tensor_npu_format(grad_output)) { - NPUNativeFunctions::npu_format_cast_(temp_output, CalcuOpUtil::get_tensor_npu_format(grad_output)); + XLANativeFunctions::npu_format_cast_(tmp_output, CalcuOpUtil::get_tensor_npu_format(grad_output)); } // construct the output tensor of the NPU - at::Tensor grad_input = OpPreparation::ApplyTensor(temp_output, outputSize); + at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output, outputSize); // calculate the output result of the NPU - softmax_backward_out_npu(grad_input, grad_output, temp_output, dim, self); + softmax_backward_out_npu(grad_input, grad_output, tmp_output, dim, input_dtype); return grad_input; } diff --git a/torch_npu/csrc/aten/ops/SoftmaxCrossEntropyWithLogitsKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftmaxCrossEntropyWithLogitsKernelNpu.cpp index 889c39b6cb..06dde499f9 100644 --- a/torch_npu/csrc/aten/ops/SoftmaxCrossEntropyWithLogitsKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SoftmaxCrossEntropyWithLogitsKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include namespace at_npu { @@ -60,7 +60,7 @@ at::Tensor softmax_cross_entropy_with_logits_npu( return std::get<0>(softmax_cross_entropy_with_logits_impl_npu(self, labels)); } -at::Tensor NPUNativeFunctions::npu_softmax_cross_entropy_with_logits_backward( +at::Tensor XLANativeFunctions::npu_softmax_cross_entropy_with_logits_backward( const at::Tensor& grad, const at::Tensor& self, const at::Tensor& labels) { @@ -84,7 +84,7 @@ public: auto self = saved[0]; auto labels = saved[1]; - at::Tensor result = NPUNativeFunctions::npu_softmax_cross_entropy_with_logits_backward(grad_outputs[0], + at::Tensor result = XLANativeFunctions::npu_softmax_cross_entropy_with_logits_backward(grad_outputs[0], self, labels); tensor_list output = {result, at::Tensor()}; @@ -92,7 +92,7 @@ public: } }; -at::Tensor NPUNativeFunctions::npu_softmax_cross_entropy_with_logits(const at::Tensor& self, +at::Tensor XLANativeFunctions::npu_softmax_cross_entropy_with_logits(const at::Tensor& self, const at::Tensor& labels) { return NPUSoftmaxCrossEntropyWithLogitsFunction::apply(self, labels); } diff --git a/torch_npu/csrc/aten/ops/SoftmaxKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftmaxKernelNpu.cpp index 03b4bab9ef..a4807a7221 100644 --- a/torch_npu/csrc/aten/ops/SoftmaxKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SoftmaxKernelNpu.cpp @@ -16,14 +16,14 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - at::Tensor NPUNativeFunctions::softmax( + at::Tensor XLANativeFunctions::softmax( const at::Tensor &self, int64_t dim, c10::optional dtype) @@ -39,15 +39,15 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::softmax( + at::Tensor XLANativeFunctions::softmax( const at::Tensor &self, at::Dimname dim, c10::optional dtype) { - return NPUNativeFunctions::softmax(self, dimname_to_position(self, dim), dtype); + return XLANativeFunctions::softmax(self, dimname_to_position(self, dim), dtype); } - at::Tensor NPUNativeFunctions::_softmax(const at::Tensor &self, int64_t dim, bool half_to_float) + at::Tensor XLANativeFunctions::_softmax(const at::Tensor &self, int64_t dim, bool half_to_float) { // construct the output tensor of the NPU diff --git a/torch_npu/csrc/aten/ops/SoftplusBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftplusBackwardKernelNpu.cpp deleted file mode 100644 index 4dc10af959..0000000000 --- a/torch_npu/csrc/aten/ops/SoftplusBackwardKernelNpu.cpp +++ /dev/null @@ -1,71 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& softplus_backward_out_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar beta, - at::Scalar threshold, - const at::Tensor& output) { - OpCommand cmd; - cmd.Name("SoftplusV2Grad") - .Input(grad_output) - .Input(self) - .Output(grad_input) - .Attr("beta", beta) - .Attr("threshold", threshold) - .Run(); - - return grad_input; -} - -at::Tensor& NPUNativeFunctions::softplus_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar beta, - at::Scalar threshold, - const at::Tensor& output, - at::Tensor& grad_input) { - OpPreparation::CheckOut( - {self}, - grad_input, - self); - return softplus_backward_out_nocheck(grad_input, grad_output, self, beta, threshold, output); -} - -at::Tensor NPUNativeFunctions::softplus_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Scalar beta, - at::Scalar threshold, - const at::Tensor& output) { - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor( - outputSize, self.options(), self); - softplus_backward_out_nocheck(result, grad_output, self, beta, threshold, output); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SoftplusKernelNpu.cpp b/torch_npu/csrc/aten/ops/SoftplusKernelNpu.cpp deleted file mode 100644 index 0400a34ac3..0000000000 --- a/torch_npu/csrc/aten/ops/SoftplusKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& softplus_out_nocheck( - const at::Tensor& self, - at::Scalar beta, - at::Scalar threshold, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("SoftplusV2") - .Input(self) - .Output(result) - .Attr("beta", beta) - .Attr("threshold", threshold) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::softplus_out( - const at::Tensor& self, - at::Scalar beta, - at::Scalar threshold, - at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - return softplus_out_nocheck(self, beta, threshold, result); -} - -at::Tensor NPUNativeFunctions::softplus( - const at::Tensor& self, - at::Scalar beta, - at::Scalar threshold) { - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor( - outputSize, self.options(), self); - softplus_out_nocheck(self, beta, threshold, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SortKernelNpu.cpp b/torch_npu/csrc/aten/ops/SortKernelNpu.cpp deleted file mode 100644 index 496316d389..0000000000 --- a/torch_npu/csrc/aten/ops/SortKernelNpu.cpp +++ /dev/null @@ -1,110 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple sort_out_npu_no_transpose( - const at::Tensor& self, - int64_t dim, - bool descending, - at::Tensor& values, - at::Tensor& indices) { - OpCommand cmd; - cmd.Name("Sort") - .Input(self) - .Output(values) - .Output(indices) - .Attr("axis", dim) - .Attr("descending", descending) - .Run(); - - return std::tie(values, indices); -} - -tuple NPUNativeFunctions::sort_out( - const at::Tensor& self, - int64_t dim, - bool descending, - at::Tensor& values, - at::Tensor& indices) { - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - int64_t lastDim = CalcuOpUtil::make_wrap_dim(-1, self.dim()); - - if (dim != lastDim) { - at::SmallVector perm; - for (int64_t i = 0; i < self.dim(); i++) { - perm.emplace_back(i); - } - std::swap(perm[dim], perm[lastDim]); - - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); - auto outputSize = transpose_npu_output_size(values, perm); - at::Tensor transposeValues = OpPreparation::ApplyTensor(values, outputSize); - at::Tensor transposeIndices =OpPreparation::ApplyTensor(indices, outputSize); - - sort_out_npu_no_transpose( - transposeSelf, lastDim, descending, transposeValues, transposeIndices); - - NPUNativeFunctions::npu_transpose_out(transposeValues, perm, true, values); - NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, true, indices); - } else { - sort_out_npu_no_transpose( - self, lastDim, descending, values, indices); - } - - // indices dtype transform Int64 - indices = indices.to(at::kLong); - - return std::tie(values, indices); -} - -tuple NPUNativeFunctions::sort_out( - const at::Tensor& self, - at::Dimname dim, - bool descending, - at::Tensor& values, - at::Tensor& indices) { - return NPUNativeFunctions::sort_out(self, dimname_to_position(self, dim), descending, values, indices); -} - -tuple NPUNativeFunctions::sort( - const at::Tensor& self, - int64_t dim, - bool descending) { - auto outputSize = input_same_output_size(self); - - at::Tensor values = OpPreparation::ApplyTensor(self); - at::Tensor indices = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options().dtype(at::kInt), ACL_FORMAT_NCHW); - - NPUNativeFunctions::sort_out(self, dim, descending, values, indices); - - return std::tie(values, indices); -} - -tuple NPUNativeFunctions::sort( - const at::Tensor& self, - at::Dimname dim, - bool descending) { - return NPUNativeFunctions::sort(self, dimname_to_position(self, dim), descending); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SortWithoutIndicesKernelNpu.cpp b/torch_npu/csrc/aten/ops/SortWithoutIndicesKernelNpu.cpp deleted file mode 100644 index a376c1faa7..0000000000 --- a/torch_npu/csrc/aten/ops/SortWithoutIndicesKernelNpu.cpp +++ /dev/null @@ -1,111 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" - -namespace at_npu { -namespace native { - -at::Tensor& sort_without_indices_no_transpose( - at::Tensor& result, - const at::Tensor& self, - int64_t dim, - bool descending) { - OpCommand cmd; - cmd.Name("SortV2") - .Input(self) - .Output(result) - .Attr("axis", dim) - .Attr("descending", descending) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::npu_sort_v2_out( - const at::Tensor& self, - int64_t dim, - bool descending, - at::Tensor& result) { - auto outputSize = input_same_output_size(self); - - OpPreparation::CheckOut( - {self}, - result, - self); - - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - int64_t lastDim = CalcuOpUtil::make_wrap_dim(-1, self.dim()); - - if (dim != lastDim) { - c10::SmallVector perm; - for (int64_t i = 0; i < self.dim(); i++) { - perm.emplace_back(i); - } - std::swap(perm[dim], perm[lastDim]); - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); - - auto outputSize = transpose_npu_output_size(result, perm); - at::Tensor transposeResult = OpPreparation::ApplyTensor(result, outputSize); - - sort_without_indices_no_transpose(transposeResult, transposeSelf, lastDim, descending); - NPUNativeFunctions::npu_transpose_out(transposeResult, perm, true, result); - } else { - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - sort_without_indices_no_transpose(contiguousResult, self, dim, descending); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - sort_without_indices_no_transpose(result, self, dim, descending); - } - } - - return result; -} - -at::Tensor NPUNativeFunctions::npu_sort_v2( - const at::Tensor& self, - int64_t dim, - bool descending) { - auto outputSize = input_same_output_size(self); - at::Tensor result = OpPreparation::ApplyTensor(self); - - dim = CalcuOpUtil::make_wrap_dim(dim, self.dim()); - int64_t lastDim = CalcuOpUtil::make_wrap_dim(-1, self.dim()); - - if (dim != lastDim) { - c10::SmallVector perm; - for (int64_t i = 0; i < self.dim(); i++) { - perm.emplace_back(i); - } - std::swap(perm[dim], perm[lastDim]); - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); - - auto outputSize = transpose_npu_output_size(result, perm); - at::Tensor transposeResult = OpPreparation::ApplyTensor(result, outputSize); - - sort_without_indices_no_transpose(transposeResult, transposeSelf, lastDim, descending); - NPUNativeFunctions::npu_transpose_out(transposeResult, perm, true, result); - } else { - sort_without_indices_no_transpose(result, self, dim, descending); - } - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SqrtKernelNpu.cpp b/torch_npu/csrc/aten/ops/SqrtKernelNpu.cpp index ff96d5d69c..cb33a2e6f3 100644 --- a/torch_npu/csrc/aten/ops/SqrtKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SqrtKernelNpu.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -30,7 +30,7 @@ at::Tensor& sqrt_out_npu_nocheck(const at::Tensor& self, at::Tensor& result) { return result; } -at::Tensor& NPUNativeFunctions::sqrt_out(const at::Tensor& self, at::Tensor& result) { +at::Tensor& XLANativeFunctions::sqrt_out(const at::Tensor& self, at::Tensor& result) { OpPreparation::CheckOut({self}, result, self); OpPipeWithDefinedOut pipe; @@ -39,15 +39,15 @@ at::Tensor& NPUNativeFunctions::sqrt_out(const at::Tensor& self, at::Tensor& res .Call(result); } -at::Tensor NPUNativeFunctions::sqrt(const at::Tensor& self) { +at::Tensor XLANativeFunctions::sqrt(const at::Tensor& self) { at::Tensor result = OpPreparation::ApplyTensor(self); sqrt_out_npu_nocheck(self, result); return result; } -at::Tensor& NPUNativeFunctions::sqrt_(at::Tensor& self) { - NPUNativeFunctions::sqrt_out(self, self); +at::Tensor& XLANativeFunctions::sqrt_(at::Tensor& self) { + XLANativeFunctions::sqrt_out(self, self); return self; } diff --git a/torch_npu/csrc/aten/ops/StackKernelNpu.cpp b/torch_npu/csrc/aten/ops/StackKernelNpu.cpp deleted file mode 100644 index 60fe439744..0000000000 --- a/torch_npu/csrc/aten/ops/StackKernelNpu.cpp +++ /dev/null @@ -1,98 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include - -namespace at_npu { -namespace native { - -namespace { -at_npu::native::DynamicInputRegFunc stack_func = - [](DyNumAndIndex num_and_index, std::string op_name) -> ge::OperatorPtr { - auto ge_op = std::make_shared(op_name.c_str()); - ge_op->create_dynamic_input_byindex_x( - num_and_index.front().first, num_and_index.front().second); - return ge_op; - }; -} - -at::SmallVector stack_npu_output_size( - at::TensorList tensors, - int64_t dim) { - dim = CalcuOpUtil::make_wrap_dim(dim, tensors[0].dim() + 1); - at::SmallVector shape; - for (int i = 0; i < dim; i++) { - shape.emplace_back(tensors[0].size(i)); - } - shape.emplace_back(tensors.size()); - for (int i = dim; i < tensors[0].dim(); i++) { - shape.emplace_back(tensors[0].size(i)); - } - - return shape; -} - -at::Tensor& stack_out_npu_nocheck(at::TensorList tensors, int64_t dim, at::Tensor& result) { - auto inputTensors = CalcuOpUtil::ConvertTensorListToSmallVector(tensors); - auto dynamic_num = inputTensors.size(); - - OpCommand cmd; - cmd.Name("Pack") - .DynamicInputReg(stack_func, {{dynamic_num, 0}}); - for (int i = 0; i < dynamic_num; i++) { - string inputName = "x" + std::to_string(i); - cmd.Input(inputTensors[i],inputName); - } - cmd.Output(result) - .Attr("N", (int64_t)tensors.size()) - .Attr("axis", dim) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::stack_out(at::TensorList tensors, int64_t dim, at::Tensor& result) { - auto outputSize = stack_npu_output_size(tensors, dim); - - OpPreparation::CheckOut( - {tensors[0]}, - result, - ACL_FORMAT_ND, - tensors[0].scalar_type(), - outputSize); - - stack_out_npu_nocheck(tensors, dim, result); - - return result; -} - -at::Tensor NPUNativeFunctions::stack(at::TensorList tensors, int64_t dim) { - auto outputSize = stack_npu_output_size(tensors, dim); - - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - tensors[0].options(), - ACL_FORMAT_ND); - - stack_out_npu_nocheck(tensors, dim, result); - - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/StdKernelNpu.cpp b/torch_npu/csrc/aten/ops/StdKernelNpu.cpp deleted file mode 100644 index dee968daba..0000000000 --- a/torch_npu/csrc/aten/ops/StdKernelNpu.cpp +++ /dev/null @@ -1,150 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -tuple std_mean_out_npu_nocheck( - at::Tensor& resultStd, - at::Tensor& resultMean, - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - OpCommand cmd1; - cmd1.Name("ReduceMeanD") - .Input(self) - .Output(resultMean) - .Attr("axes", dim) - .Attr("keep_dims", keepdim) - .Run(); - - at::Tensor resultMeanCopy = resultMean; - if (resultMean.dim() != 0 && keepdim == false) { - auto dimVector = array_to_small_vector(dim); - std::sort(dimVector.begin(), dimVector.end()); - for (int64_t i = 0; i < dimVector.size(); i++) { - resultMeanCopy = resultMeanCopy.unsqueeze(dimVector[i]); - } - } - resultMeanCopy = resultMeanCopy.expand(self.sizes()); - OpCommand cmd2; - cmd2.Name("ReduceStdWithMean") - .Input(self) - .Input(resultMeanCopy) - .Output(resultStd) - .Attr("dim", dim) - .Attr("unbiased", unbiased) - .Attr("keepdim", keepdim) - .Run(); - - return std::tie(resultStd, resultMean); -} - -at::Tensor& NPUNativeFunctions::std_out( - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim, - at::Tensor& result) { - auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim); - at::Tensor meanResult = OpPreparation::ApplyTensor(self, outputSize); - - OpPreparation::CheckOut( - {self}, - result, - ACL_FORMAT_ND, - self.scalar_type(), - outputSize); - - std_mean_out_npu_nocheck(result, meanResult, self, dim, unbiased, keepdim); - - return result; -} - -at::Tensor& NPUNativeFunctions::std_out( - const at::Tensor& self, - at::DimnameList dim, - bool unbiased, - bool keepdim, - at::Tensor& result) { - return NPUNativeFunctions::std_out(self, dimnames_to_positions(self, dim), unbiased, keepdim, result); -} - -at::Tensor NPUNativeFunctions::std( - const at::Tensor & self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim); - - at::Tensor result1 = OpPreparation::ApplyTensor(self, outputSize); - at::Tensor result2 = OpPreparation::ApplyTensor(self, outputSize); - - std_mean_out_npu_nocheck(result1, result2, self, dim, unbiased, keepdim); - return result1; -} - -at::Tensor NPUNativeFunctions::std( - const at::Tensor & self, - bool unbiased) { - c10::SmallVector dims = CalcuOpUtil::get_dimlist_for_tensor(self); - return NPUNativeFunctions::std(self, dims, unbiased, false); -} - -tuple NPUNativeFunctions::std_mean( - const at::Tensor & self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - auto outputSize = reduce_ops_npu_output_size(self, dim, keepdim); - - at::Tensor result1 = OpPreparation::ApplyTensor(self, outputSize); - at::Tensor result2 = OpPreparation::ApplyTensor(self, outputSize); - - std_mean_out_npu_nocheck(result1, result2, self, dim, unbiased, keepdim); - - return std::tie(result1, result2); -} - -tuple NPUNativeFunctions::std_mean( - const at::Tensor & self, - bool unbiased) { - c10::SmallVector dims = CalcuOpUtil::get_dimlist_for_tensor(self); - return NPUNativeFunctions::std_mean(self, dims, unbiased, false); -} - -tuple NPUNativeFunctions::std_mean( - const at::Tensor & self, - at::DimnameList dim, - bool unbiased, - bool keepdim) { - return NPUNativeFunctions::std_mean(self, dimnames_to_positions(self, dim), unbiased, keepdim); -} - -at::Tensor NPUNativeFunctions::std( - const at::Tensor & self, - at::DimnameList dim, - bool unbiased, - bool keepdim) { - return NPUNativeFunctions::std(self, dimnames_to_positions(self, dim), unbiased, keepdim); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/StrideAddKernelNpu.cpp b/torch_npu/csrc/aten/ops/StrideAddKernelNpu.cpp index eb85dfefab..80fc76d49d 100644 --- a/torch_npu/csrc/aten/ops/StrideAddKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/StrideAddKernelNpu.cpp @@ -18,7 +18,7 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -108,12 +108,12 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::npu_stride_add( + at::Tensor XLANativeFunctions::npu_stride_add( const at::Tensor &self, const at::Tensor &other, - c10::Scalar offset1, - c10::Scalar offset2, - c10::Scalar c1_len) + const c10::Scalar &offset1, + const c10::Scalar &offset2, + const c10::Scalar &c1_len) { // calculate the output size auto outputSize = deprecated_broadcast_ops_npu_output_size(self.sizes(), other.sizes()); diff --git a/torch_npu/csrc/aten/ops/SubKernelNpu.cpp b/torch_npu/csrc/aten/ops/SubKernelNpu.cpp index 33ac4018ee..31a6bf46e9 100644 --- a/torch_npu/csrc/aten/ops/SubKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SubKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -26,8 +26,8 @@ namespace at_npu at::Tensor &sub_scalar_out_npu( at::Tensor &result, const at::Tensor &self, - at::Scalar other, - at::Scalar alpha) + const at::Scalar &other, + const at::Scalar &alpha) { // other*alpha float otherValue = CalcuOpUtil::get_scalar_float_value(other); @@ -75,10 +75,10 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::sub_out( + at::Tensor &XLANativeFunctions::sub_out( const at::Tensor &self, const at::Tensor &other, - at::Scalar alpha, + const at::Scalar &alpha, at::Tensor &result) { at::Tensor outputTensor = CalcuOpUtil::is_scalar_wrapped_to_tensor(self) ? other : self; @@ -94,7 +94,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::sub(const at::Tensor &self, const at::Tensor &other, at::Scalar alpha) + at::Tensor XLANativeFunctions::sub(const at::Tensor &self, const at::Tensor &other, const at::Scalar &alpha) { bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); at::Tensor outputTensor = isSelfWrapped ? other : self; @@ -114,7 +114,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::sub(const at::Tensor &self, at::Scalar other, at::Scalar alpha) + at::Tensor XLANativeFunctions::sub(const at::Tensor &self, const at::Scalar &other, const at::Scalar &alpha) { // calculate the output size auto outputSize = input_same_output_size(self); @@ -129,7 +129,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::sub_(at::Tensor &self, const at::Tensor &other, at::Scalar alpha) + at::Tensor &XLANativeFunctions::sub_(at::Tensor &self, const at::Tensor &other, const at::Scalar &alpha) { c10::SmallVector inputs = {self, other}; c10::SmallVector outputs = {self}; @@ -149,7 +149,7 @@ namespace at_npu return self; } - at::Tensor &NPUNativeFunctions::sub_(at::Tensor &self, at::Scalar other, at::Scalar alpha) + at::Tensor &XLANativeFunctions::sub_(at::Tensor &self, const at::Scalar &other, const at::Scalar &alpha) { if (!NpuUtils::check_match(&self)) { diff --git a/torch_npu/csrc/aten/ops/SubSampleKernelNpu.cpp b/torch_npu/csrc/aten/ops/SubSampleKernelNpu.cpp deleted file mode 100644 index adf201614d..0000000000 --- a/torch_npu/csrc/aten/ops/SubSampleKernelNpu.cpp +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::npu_sub_sample( - const at::Tensor &self, - int64_t per_images, - double positive_fraction) { - - at::Tensor result = OpPreparation::ApplyTensor(self); - OpCommand cmd; - cmd.Name("SubSample") - .Input(self) - .Output(result) - .Attr("batch_size_per_images", per_images) - .Attr("positive_fraction", (float)positive_fraction) - .Run(); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/SumKernelNpu.cpp b/torch_npu/csrc/aten/ops/SumKernelNpu.cpp index 1de3eb006e..7fd224c90a 100644 --- a/torch_npu/csrc/aten/ops/SumKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/SumKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -53,19 +53,11 @@ namespace at_npu at::Tensor &result, const at::Tensor &self, at::IntArrayRef dim, - bool keepdim, - c10::ScalarType dtype) - { - at::Tensor selfs = self; - if(self.scalar_type() != c10::ScalarType::Float){ - selfs = NPUNativeFunctions::npu_dtype_cast(self, c10::ScalarType::Float); - } + bool keepdim) + { + at::Tensor selfs = XLANativeFunctions::npu_dtype_cast(self, c10::ScalarType::Float); sum_out_npu_no_dtype(result, selfs, dim, keepdim); - if(dtype == c10::ScalarType::Long){ - result = NPUNativeFunctions::npu_dtype_cast(result, c10::ScalarType::Long); - return result; - } - result = NPUNativeFunctions::npu_dtype_cast(result, c10::ScalarType::Int); + result = XLANativeFunctions::npu_dtype_cast(result, c10::ScalarType::Int); return result; } @@ -79,8 +71,10 @@ namespace at_npu c10::ScalarType dstType; if (dtype.has_value()) { - if(dtype.value() == c10::ScalarType::Int || dtype.value() == c10::ScalarType::Long){ - return sum_out_npu_int_dtype(result, self, dim, keepdim, dtype.value()); + if (dtype.value() == c10::ScalarType::Int) + { + at::Tensor selfs = XLANativeFunctions::npu_dtype_cast(self, c10::ScalarType::Int); + return sum_out_npu_int_dtype(result, selfs, dim, keepdim); } else { @@ -89,13 +83,13 @@ namespace at_npu } else if (isIntegralType(self.scalar_type(), true)) { - return sum_out_npu_int_dtype(result, self, dim, keepdim, self.scalar_type()); + return sum_out_npu_int_dtype(result, self, dim, keepdim); } else if (result.defined()) { if (isIntegralType(result.scalar_type(), true)) { - return sum_out_npu_int_dtype(result, self, dim, keepdim, self.scalar_type()); + return sum_out_npu_int_dtype(result, self, dim, keepdim); } else { @@ -117,7 +111,7 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::sum_out( + at::Tensor &XLANativeFunctions::sum_out( const at::Tensor &self, at::IntArrayRef dim, bool keepdim, @@ -145,18 +139,18 @@ namespace at_npu return result; } - at::Tensor &NPUNativeFunctions::sum_out( + at::Tensor &XLANativeFunctions::sum_out( const at::Tensor &self, at::DimnameList dim, bool keepdim, c10::optional dtype, at::Tensor &result) { - return NPUNativeFunctions::sum_out(self, + return XLANativeFunctions::sum_out(self, dimnames_to_positions(self, dim), keepdim, dtype, result); } - at::Tensor NPUNativeFunctions::sum( + at::Tensor XLANativeFunctions::sum( const at::Tensor &self, at::IntArrayRef dim, bool keepdim, @@ -165,7 +159,7 @@ namespace at_npu c10::ScalarType dstType; if (dtype.has_value()) { - if (isIntegralType(dtype.value(), true)) + if (dtype.value() == c10::ScalarType::Int) { dstType = c10::ScalarType::Float; } @@ -211,18 +205,18 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::sum( + at::Tensor XLANativeFunctions::sum( const at::Tensor &self, at::DimnameList dim, bool keepdim, c10::optional dtype) { - return NPUNativeFunctions::sum(self, dimnames_to_positions(self, dim), keepdim, dtype); + return XLANativeFunctions::sum(self, dimnames_to_positions(self, dim), keepdim, dtype); } - at::Tensor NPUNativeFunctions::sum(const at::Tensor &self, c10::optional dtype) + at::Tensor XLANativeFunctions::sum(const at::Tensor &self, c10::optional dtype) { - return NPUNativeFunctions::sum(self, c10::SmallVector{}, false, dtype); + return XLANativeFunctions::sum(self, c10::SmallVector{}, false, dtype); } } // namespace native diff --git a/torch_npu/csrc/aten/ops/SvdHelperKernelNpu.cpp b/torch_npu/csrc/aten/ops/SvdHelperKernelNpu.cpp deleted file mode 100644 index 0c1194a5d8..0000000000 --- a/torch_npu/csrc/aten/ops/SvdHelperKernelNpu.cpp +++ /dev/null @@ -1,109 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -int64_t batch_count(const at::Tensor& batched_matrices) { - int64_t result = 1; - auto number = 2; - for (int64_t i = 0; i < batched_matrices.ndimension() - number; i++) { - result *= batched_matrices.size(i); - } - return result; -} - -void single_check_errors(int64_t info, const char* name, bool allow_singular = false, int64_t batch_idx = -1) { - std::string batch_info = ""; - if (batch_idx >= 0) { - batch_info = ": For batch " + std::to_string(batch_idx); - } - if (info < 0) { - AT_ERROR(name, batch_info, ": Argument ", -info, " has illegal value"); - } else if (info > 0) { - if (strstr(name, "svd")) { - AT_ERROR(name, ": the updating process of SBDSDC did not converge (error: ", info, ")"); - } else if (strstr(name, "symeig")) { - AT_ERROR(name, batch_info, ": the algorithm failed to converge; ", info, - " off-diagonal elements of an intermediate tridiagonal form did not converge to zero."); - } else if (!allow_singular) { - AT_ERROR(name, batch_info, ": U(", info, ",", info, ") is zero, singular U."); - } - } -} - -void batch_check_errors(std::vector& infos, const char* name, bool allow_singular = false) { - for (size_t i = 0; i < infos.size(); i++) { - auto info = infos[i]; - single_check_errors(info, name, allow_singular, i); - } -} - -std::tuple NPUNativeFunctions::_svd_helper(const at::Tensor& self, bool some, bool compute_uv) { - TORCH_CHECK(self.dtype() == at::kFloat, "svd_npu only supported Float, but get", self.dtype()); - std::vector infos(batch_count(self), 0); - int64_t m = self.size(-2); - int64_t n = self.size(-1); - int64_t k = std::min(m, n); - - at::Tensor U_working_copy, S_working_copy, VT_working_copy; - auto sizes = self.sizes().vec(); - - auto number_a = 2; - auto number_b = 1; - sizes[self.dim() - number_b] = (compute_uv && some) ? std::min(m, n) : m; - U_working_copy = OpPreparation::ApplyTensor(self, sizes); - - sizes[self.dim() - number_a] = n; - sizes[self.dim() - number_b] = (compute_uv && some) ? k : n; - VT_working_copy = OpPreparation::ApplyTensor(self, sizes); - - sizes.pop_back(); - sizes[self.dim() - number_a] = std::min(m, n); - S_working_copy = OpPreparation::ApplyTensor(self, sizes); - - if (self.numel() > 0) { - OpCommand cmd; - cmd.Name("Svd") - .Input(self) - .Output(S_working_copy) - .Output(U_working_copy) - .Output(VT_working_copy) - .Attr("compute_uv", compute_uv) - .Attr("full_matrices", !some) - .Run(); - - if (self.dim() > number_a) { - batch_check_errors(infos, "svd_npu"); - } else { - single_check_errors(infos[0], "svd_npu"); - } - - if (!compute_uv) { - VT_working_copy.zero_(); - U_working_copy.zero_(); - } - } else { - U_working_copy.zero_(); - VT_working_copy.zero_(); - } - - return std::make_tuple(U_working_copy, S_working_copy, VT_working_copy); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/SymeigKernelNpu.cpp b/torch_npu/csrc/aten/ops/SymeigKernelNpu.cpp deleted file mode 100644 index a104fe448c..0000000000 --- a/torch_npu/csrc/aten/ops/SymeigKernelNpu.cpp +++ /dev/null @@ -1,48 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::_symeig_helper(const at::Tensor& self, bool eigenvectors, bool upper) { - auto self_sizes = self.sizes().vec(); - self_sizes.pop_back(); - auto eigvals = at::empty(self_sizes, self.options()); - - if (self.numel() == 0) { - return std::tuple(eigvals, at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT)); - } - - auto self_working_copy = self.clone(); - OpCommand cmd; - cmd.Name("SelfAdjointEig") - .Input(self) - .Output(eigvals) - .Output(self_working_copy) - .Attr("compute_v", true) - .Run(); - - if (eigenvectors) { - return std::tuple(eigvals, self_working_copy); - } else { - return std::tuple(eigvals, at::empty({0}, self.options())); - } -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TakeKernelNpu.cpp b/torch_npu/csrc/aten/ops/TakeKernelNpu.cpp deleted file mode 100644 index b645a231a1..0000000000 --- a/torch_npu/csrc/aten/ops/TakeKernelNpu.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& take_out_nocheck(const at::Tensor& self, const at::Tensor& index, at::Tensor& result) { - at::Tensor input_tensor = self.reshape(-1); - at::Tensor contiguousSelf = NpuUtils::format_contiguous(input_tensor); - at::Tensor contiguousIndex = NpuUtils::format_contiguous(index); - - OpCommand cmd; - cmd.Name("Gather") - .Input(contiguousSelf) - .Input(contiguousIndex) - .Output(result) - .Attr("validate_indices", false) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::take_out(const at::Tensor& self, const at::Tensor& index, at::Tensor& result) { - // calculate the output size - auto outputSize = input_same_output_size(index); - - OpPreparation::CheckOut( - {self, index}, - result, - self, - outputSize); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - take_out_nocheck(self, index, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - take_out_nocheck(self, index, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::take(const at::Tensor& self, const at::Tensor& index) { - at::Tensor result = OpPreparation::ApplyTensor(self, index.sizes()); - take_out_nocheck(self, index, result); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TanKernelNpu.cpp b/torch_npu/csrc/aten/ops/TanKernelNpu.cpp deleted file mode 100644 index 629c5f11bd..0000000000 --- a/torch_npu/csrc/aten/ops/TanKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& tan_out_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Tan") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::tan_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - tan_out_nocheck(self, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - tan_out_nocheck(self, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::tan(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - tan_out_nocheck(self, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::tan_(at::Tensor& self) { - NPUNativeFunctions::tan_out(self, self); - - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TanhBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/TanhBackwardKernelNpu.cpp deleted file mode 100644 index e0abc60d25..0000000000 --- a/torch_npu/csrc/aten/ops/TanhBackwardKernelNpu.cpp +++ /dev/null @@ -1,54 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& tanh_backward_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& grad_output, - const at::Tensor& self) { - OpCommand cmd; - cmd.Name("TanhGrad") - .Input(self) - .Input(grad_output) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::tanh_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Tensor& result) { - OpPreparation::CheckOut({grad_output, self}, result, self); - tanh_backward_out_npu_nocheck(result, grad_output, self); - return result; -} - -at::Tensor NPUNativeFunctions::tanh_backward(const at::Tensor& grad_output, const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - tanh_backward_out_npu_nocheck(result, grad_output, self); - - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TanhKernelNpu.cpp b/torch_npu/csrc/aten/ops/TanhKernelNpu.cpp deleted file mode 100644 index 5ec2311735..0000000000 --- a/torch_npu/csrc/aten/ops/TanhKernelNpu.cpp +++ /dev/null @@ -1,55 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::tanh_out(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Tanh") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::tanh(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - // calculate the output result of the NPU - NPUNativeFunctions::tanh_out(self, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::tanh_(at::Tensor& self) { - OpPreparation::CheckMemory({self}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = NPUNativeFunctions::tanh_out(contiguousSelf, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - NPUNativeFunctions::tanh_out(self, self); - } - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/ThresholdBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/ThresholdBackwardKernelNpu.cpp index 3f837dc552..0043340a38 100644 --- a/torch_npu/csrc/aten/ops/ThresholdBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ThresholdBackwardKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" namespace at_npu @@ -54,10 +54,10 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::threshold_backward( + at::Tensor XLANativeFunctions::threshold_backward( const at::Tensor &grad_output, const at::Tensor &self, - at::Scalar threshold) + const at::Scalar &threshold) { // calculate the output size auto outputSize = input_same_output_size(self); @@ -73,7 +73,7 @@ namespace at_npu ACL_FORMAT_NC1HWC0)) { at::Tensor grad_output_5HD = - NPUNativeFunctions::npu_format_cast(grad_output, ACL_FORMAT_NC1HWC0); + XLANativeFunctions::npu_format_cast(grad_output, ACL_FORMAT_NC1HWC0); threshold_backward_out_npu(result, grad_output_5HD, self, threshold); return result; } diff --git a/torch_npu/csrc/aten/ops/ThresholdKernelNpu.cpp b/torch_npu/csrc/aten/ops/ThresholdKernelNpu.cpp index 609d40a2e0..2c7ee4be30 100644 --- a/torch_npu/csrc/aten/ops/ThresholdKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ThresholdKernelNpu.cpp @@ -15,14 +15,14 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::threshold_out( +at::Tensor& XLANativeFunctions::threshold_out( const at::Tensor& self, - at::Scalar threshold, - at::Scalar value, + const at::Scalar& threshold, + const at::Scalar& value, at::Tensor& result) { OpCommand cmd; cmd.Name("ThresholdV2D") @@ -35,20 +35,20 @@ at::Tensor& NPUNativeFunctions::threshold_out( return result; } -at::Tensor NPUNativeFunctions::threshold(const at::Tensor& self, at::Scalar threshold, at::Scalar value) { +at::Tensor XLANativeFunctions::threshold(const at::Tensor& self, const at::Scalar& threshold, const at::Scalar& value) { at::Tensor result = OpPreparation::ApplyTensor(self); - NPUNativeFunctions::threshold_out(self, threshold, value, result); + XLANativeFunctions::threshold_out(self, threshold, value, result); return result; } -at::Tensor& NPUNativeFunctions::threshold_(at::Tensor& self, at::Scalar threshold, at::Scalar value) { +at::Tensor& XLANativeFunctions::threshold_(at::Tensor& self, const at::Scalar& threshold, const at::Scalar& value) { if (!NpuUtils::check_match(&self)) { at::Tensor selfContiguous = NpuUtils::format_contiguous(self); at::Tensor result = - NPUNativeFunctions::threshold_out(selfContiguous, threshold, value, selfContiguous); + XLANativeFunctions::threshold_out(selfContiguous, threshold, value, selfContiguous); NpuUtils::format_fresh_view(self, result); } else { - NPUNativeFunctions::threshold_out(self, threshold, value, self); + XLANativeFunctions::threshold_out(self, threshold, value, self); } return self; diff --git a/torch_npu/csrc/aten/ops/TopKKernelNpu.cpp b/torch_npu/csrc/aten/ops/TopKKernelNpu.cpp index 7b8df57292..5d518df1a4 100644 --- a/torch_npu/csrc/aten/ops/TopKKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/TopKKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -63,7 +63,7 @@ tuple topk_out_npu_nocheck( std::swap(perm[dim], perm[lastDim]); // construct the output tensor of the NPU - at::Tensor transposeSelf = NPUNativeFunctions::npu_transpose(self, perm, true); + at::Tensor transposeSelf = XLANativeFunctions::npu_transpose(self, perm); auto outputSize = transpose_npu_output_size(values, perm); at::Tensor transposeValue = OpPreparation::ApplyTensor(values, outputSize); at::Tensor transposeIndices = OpPreparation::ApplyTensor(indices, outputSize); @@ -75,8 +75,8 @@ tuple topk_out_npu_nocheck( lastDim, largest, sorted); - NPUNativeFunctions::npu_transpose_out(transposeValue, perm, true, values); - NPUNativeFunctions::npu_transpose_out(transposeIndices, perm, true, indices); + XLANativeFunctions::npu_transpose_out(transposeValue, perm, values); + XLANativeFunctions::npu_transpose_out(transposeIndices, perm, indices); } else { topk_out_npu_no_transpose( values, indices, self, k, lastDim, largest, sorted); @@ -85,7 +85,7 @@ tuple topk_out_npu_nocheck( return tuple(values, indices); } -tuple NPUNativeFunctions::topk_out( +tuple XLANativeFunctions::topk_out( const at::Tensor& self, int64_t k, int64_t dim, @@ -126,7 +126,7 @@ tuple NPUNativeFunctions::topk_out( .ReturnRef(); } -tuple NPUNativeFunctions::topk( +tuple XLANativeFunctions::topk( const at::Tensor& self, int64_t k, int64_t dim, @@ -143,7 +143,7 @@ tuple NPUNativeFunctions::topk( topk_out_npu_nocheck(values, indices, selfCp, k, dim, largest, sorted); // indices dtype transform Int64 - indices = NPUNativeFunctions::npu_dtype_cast(indices, at::kLong); + indices = XLANativeFunctions::npu_dtype_cast(indices, at::kLong); return tuple(values, indices); } diff --git a/torch_npu/csrc/aten/ops/TransposeKernelNpu.cpp b/torch_npu/csrc/aten/ops/TransposeKernelNpu.cpp index 09f1b56a17..0d063989df 100644 --- a/torch_npu/csrc/aten/ops/TransposeKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/TransposeKernelNpu.cpp @@ -18,47 +18,91 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - at::Tensor &NPUNativeFunctions::npu_transpose_out( + at::Tensor &XLANativeFunctions::npu_transpose_out( const at::Tensor &self, at::IntArrayRef perm, - bool require_contiguous, - at::Tensor &result - ) + at::Tensor &result) { + c10::SmallVector permVec = array_to_small_vector(perm); OpCommand cmd; - if (require_contiguous) { - // Any tensor-view(discontiguous) Input Tensor from users should be transformed to be contiguous here. - cmd.Name("Transpose") - .Input(self) - .Input(perm) - .Output(result) - .Run(); - } else { - // For permute-opt in trans-contiguous, it accepts transposed(discontiguous) Input Tensor. cmd.Name("Transpose") .InputWithoutContiguous(self) .Input(perm) .Output(result) .Run(); - } return result; } - at::Tensor NPUNativeFunctions::npu_transpose(const at::Tensor &self, at::IntArrayRef perm, bool require_contiguous) + at::Tensor XLANativeFunctions::npu_transpose(const at::Tensor &self, at::IntArrayRef perm) { auto outputSize = transpose_npu_output_size(self, perm); at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - NPUNativeFunctions::npu_transpose_out(self, perm, require_contiguous, result); + XLANativeFunctions::npu_transpose_out(self, perm, result); return result; } + c10::SmallVector transpose_to_contiguous_npu_input( + const c10::SmallVector &src) + { + + c10::SmallVector inputs; + for (int i = 0; i < src.size(); i++) + { + inputs.emplace_back( + NPUTensorDesc(src[i])); + + if (src[i].dim() == 0) + { + inputs[i].tensorDescType = NPUTensorDesc::TensorDescType::TENSOR_SCALAR; + } + } + return inputs; + } + + c10::SmallVector transpose_to_contiguous_npu_output( + const c10::SmallVector &result) + { + return CalcuOpUtil::create_npu_output_tensor_desc(result); + } + + at::Tensor XLANativeFunctions::npu_transpose_to_contiguous(const at::Tensor &self) + { + RECORD_FUNCTION("transpose_to_contiguous", vector({self})); + int64_t self_format = CalcuOpUtil::get_tensor_npu_format(self); + at::Tensor result = OpPreparation::ApplyTensorWithFormat(self.sizes(), self.options(), self_format); + + // obtain the transpose axises + at::IntArrayRef dim; + if ((self.dim() == 2) && (self.stride(self.dim() - 2) == 1)) + { + dim = at::IntArrayRef({1, 0}); + } + else if ((self.dim() == 3) && (self.stride(self.dim() - 2) == 1)) + { + dim = at::IntArrayRef({0, 2, 1}); + } + else if ((self.dim() == 3) && (self.stride(0) <= self.stride(1))) + { + dim = at::IntArrayRef({1, 0, 2}); + } + // constructs the input and output NPUTensorDesc + auto inputs = transpose_to_contiguous_npu_input({self}); + auto outputs = transpose_to_contiguous_npu_output({result}); + + // constructs the attr of the NPUAttrDesc + NPUAttrDesc npuAttrTranspose = NPUAttrDesc("perm", dim); + c10::SmallVector attrs = {npuAttrTranspose}; + + CalcuOpUtil::execute_npu_operate("TransposeD", inputs, outputs, attrs); + return result; + } } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/TriangularSolveHelperKernelNpu.cpp b/torch_npu/csrc/aten/ops/TriangularSolveHelperKernelNpu.cpp deleted file mode 100644 index bb06f2f8d5..0000000000 --- a/torch_npu/csrc/aten/ops/TriangularSolveHelperKernelNpu.cpp +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) 2021 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include - -namespace at_npu { -namespace native { -std::tuple NPUNativeFunctions::_triangular_solve_helper( - const at::Tensor& self, - const at::Tensor& A, - bool upper, - bool transpose, - bool unitriangular) { - - at::Tensor self_broadcasted, A_broadcasted; - std::tie(self_broadcasted, A_broadcasted) = at::native::_linalg_broadcast_batch_dims(self, A, "triangular_solve"); - TORCH_CHECK(self_broadcasted.dtype() == at::kFloat && A_broadcasted.dtype() == at::kFloat, - "_triangular_solve_helper_npu only supported Float, but get ", self_broadcasted.dtype(), ' ', A_broadcasted.dtype()); - auto self_working_copy = OpPreparation::ApplyTensor(self_broadcasted); - auto A_working_copy = A_broadcasted.clone(); - at::Tensor A_tensor = A_broadcasted; - if (unitriangular) { - auto diagonal_tensor = at::eye(A_tensor.size(-2), A_tensor.size(-1), A_tensor.options()); - A_tensor = A_tensor * (1 - diagonal_tensor) + diagonal_tensor; - } - OpCommand cmd; - cmd.Name("MatrixTriangularSolve") - .Input(A_tensor) - .Input(self_broadcasted) - .Output(self_working_copy) - .Attr("lower", !upper) - .Attr("adjoint", transpose) - .Run(); - - return std::tuple(self_working_copy, A_working_copy); -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TrilKernelNpu.cpp b/torch_npu/csrc/aten/ops/TrilKernelNpu.cpp deleted file mode 100644 index e154a88c1d..0000000000 --- a/torch_npu/csrc/aten/ops/TrilKernelNpu.cpp +++ /dev/null @@ -1,71 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& tril_out_nocheck(const at::Tensor& self, int64_t diagonal, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Tril") - .Input(self) - .Output(result) - .Attr("diagonal", diagonal) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::tril_out(const at::Tensor& self, int64_t diagonal, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - tril_out_nocheck(self, diagonal, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - tril_out_nocheck(self, diagonal, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::tril(const at::Tensor& self, int64_t diagonal) { - auto is_last_two_dims = [&self]() { - auto selfStorage = torch_npu::NPUBridge::GetNpuStorageImpl(self)->get_npu_desc().storage_sizes_; - if (selfStorage.size() <= 1) { - return false; - } - - return true; - }; - TORCH_CHECK(is_last_two_dims(), "tril require tensor should be last two dims"); - at::Tensor result = OpPreparation::ApplyTensor(self); - tril_out_nocheck(self, diagonal, result); - - return result; -} - -at::Tensor& NPUNativeFunctions::tril_(at::Tensor& self, int64_t diagonal) { - NPUNativeFunctions::tril_out(self, diagonal, self); - - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TriuKernelNpu.cpp b/torch_npu/csrc/aten/ops/TriuKernelNpu.cpp deleted file mode 100644 index 64344c0ac8..0000000000 --- a/torch_npu/csrc/aten/ops/TriuKernelNpu.cpp +++ /dev/null @@ -1,89 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& triu_out_npu_nocheck(const at::Tensor& self, int64_t k, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Triu") - .Input(self) - .Output(result) - .Attr("diagonal", k) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::triu_out(const at::Tensor& self, int64_t k, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - triu_out_npu_nocheck(selfCopy, k, result); - if (self.scalar_type() == at::ScalarType::Half) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); - } - return result; -} - -at::Tensor NPUNativeFunctions::triu(const at::Tensor& self, int64_t k) { - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - at::Tensor result = OpPreparation::ApplyTensor(selfCopy); - - triu_out_npu_nocheck(selfCopy, k, result); - if (self.scalar_type() == at::ScalarType::Half) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); - } - - return result; -} - -at::Tensor& NPUNativeFunctions::triu_(at::Tensor& self, int64_t k) { - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(selfCopy); - at::Tensor result = triu_out_npu_nocheck(contiguousSelf, k, contiguousSelf); - if (self.scalar_type() == at::ScalarType::Half) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); - } - self.copy_(result); - } else { - triu_out_npu_nocheck(selfCopy, k, selfCopy); - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(selfCopy, at::ScalarType::Half); - } - self.copy_(selfCopy); - } - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/TrueDivideKernelNpu.cpp b/torch_npu/csrc/aten/ops/TrueDivideKernelNpu.cpp deleted file mode 100644 index ea15df646a..0000000000 --- a/torch_npu/csrc/aten/ops/TrueDivideKernelNpu.cpp +++ /dev/null @@ -1,174 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor &true_div_scalar_out_npu(const at::Tensor &self, const at::Scalar other, at::Tensor &result) -{ - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - OpCommand cmd; - cmd.Name("Div") - .Expect(unified_result) - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor &true_div_out_npu_nocheck(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) -{ - - // executing the NPU operator - if (other.dim() == 0) - { - true_div_scalar_out_npu(self, other.item(), result); - } - else - { - auto unified_result = OpPreparation::binary_op_check(result, self, other, true); - OpCommand cmd; - cmd.Name("Div") - .Expect(unified_result) - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - - return result; -} - -at::Tensor &NPUNativeFunctions::true_divide_out(const at::Tensor &self, const at::Tensor &other, at::Tensor &result) -{ - at::Tensor selfTemp = self; - at::Tensor otherTemp = other; - if (result.scalar_type() != at::ScalarType::Float && result.scalar_type() != at::ScalarType::Half) { - TORCH_CHECK(false, "result type Float can't be cast to the desired output type ", result.scalar_type()); - } - - if (self.scalar_type() != result.scalar_type()) - { - selfTemp = NPUNativeFunctions::npu_dtype_cast(self, result.scalar_type()); - otherTemp = other.to(result.scalar_type()); - } - // calculate the output size - at::Tensor outputTensor = CalcuOpUtil::is_scalar_wrapped_to_tensor(selfTemp) ? otherTemp : selfTemp; - auto outputSize = broadcast_ops_npu_output_size(selfTemp, otherTemp); - OpPreparation::CheckOut( - {selfTemp}, - result, - CalcuOpUtil::get_tensor_npu_format(outputTensor), - outputTensor.scalar_type(), - outputSize); - - if (!NpuUtils::check_match(&result)) - { - at::Tensor contiguousResult = NpuUtils::format_contiguous(selfTemp); - true_div_out_npu_nocheck(selfTemp, otherTemp, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } - else - { - true_div_out_npu_nocheck(selfTemp, otherTemp, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::true_divide(const at::Tensor &self, const at::Tensor &other) -{ - at::Tensor selfTemp = self; - at::Tensor otherTemp = other; - if (self.scalar_type() == at::ScalarType::Int || self.scalar_type() == at::ScalarType::Bool) { - selfTemp = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - if (other.scalar_type() == at::ScalarType::Int) { - otherTemp = other.to(at::ScalarType::Float); - } - - // calculate the output size - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(selfTemp); - at::Tensor outputTensor = isSelfWrapped ? otherTemp : selfTemp; - - auto outputSize = broadcast_ops_npu_output_size(selfTemp, otherTemp); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - outputTensor.options(), - CalcuOpUtil::get_tensor_npu_format(outputTensor)); - - // calculate the output result of the NPU - true_div_out_npu_nocheck(selfTemp, otherTemp, result); - - return result; -} - -at::Tensor NPUNativeFunctions::true_divide(const at::Tensor &self, at::Scalar other) -{ - // calculate the output size - auto outputSize = input_same_output_size(self); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - self.options(), - CalcuOpUtil::get_tensor_npu_format(self)); - - // calculate the output result of the NPU - true_div_scalar_out_npu(self, other, result); - - return result; -} - -at::Tensor &NPUNativeFunctions::true_divide_(at::Tensor &self, const at::Tensor &other) -{ - at::Tensor otherTemp = other; - if (self.scalar_type() != other.scalar_type()) - { - otherTemp = other.to(self.scalar_type()); - } - - NPUNativeFunctions::true_divide_out(self, otherTemp, self); - - return self; -} - -at::Tensor &NPUNativeFunctions::true_divide_(at::Tensor &self, at::Scalar other) -{ - if (!NpuUtils::check_match(&self)) - { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - - true_div_scalar_out_npu(contiguousSelf, other, contiguousSelf); - - NpuUtils::format_fresh_view(self, contiguousSelf); - } - else - { - true_div_scalar_out_npu(self, other, self); - } - return self; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/TruncKernelNpu.cpp b/torch_npu/csrc/aten/ops/TruncKernelNpu.cpp deleted file mode 100644 index 96f887b8a4..0000000000 --- a/torch_npu/csrc/aten/ops/TruncKernelNpu.cpp +++ /dev/null @@ -1,60 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& trunc_nocheck(const at::Tensor& self, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Trunc") - .Input(self) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::trunc_out(const at::Tensor& self, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - self); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor checkResult = trunc_nocheck(self, contiguousResult); - NpuUtils::format_fresh_view(result, checkResult); - } else { - trunc_nocheck(self, result); - } - - return result; -} - -at::Tensor& NPUNativeFunctions::trunc_(at::Tensor& self) { - return trunc_out(self, self); -} - -at::Tensor NPUNativeFunctions::trunc(const at::Tensor& self) { - at::Tensor result = OpPreparation::ApplyTensor(self); - trunc_nocheck(self, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UniformKernelNpu.cpp b/torch_npu/csrc/aten/ops/UniformKernelNpu.cpp deleted file mode 100644 index 71a12cb5aa..0000000000 --- a/torch_npu/csrc/aten/ops/UniformKernelNpu.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2021 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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& uniform_out_npu( - const at::Tensor& self, - double from, - double to, - c10::optional gen_, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("Uniform") - .Input(self) - .Output(result) - .Attr("from", static_cast(from)) - .Attr("to", static_cast(to)) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::uniform_(at::Tensor& self, double from, double to, c10::optional gen_) { - // The operator needs to use fp32 for calculation. - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = self.to(at::ScalarType::Float); - } - - if (!NpuUtils::check_match(&selfCopy)) { - at::Tensor selfContiguous = NpuUtils::format_contiguous(selfCopy); - at::Tensor result = uniform_out_npu(selfContiguous, from, to, gen_, selfContiguous); - NpuUtils::format_fresh_view(selfCopy, result); - } else { - uniform_out_npu(selfCopy, from, to, gen_, selfCopy); - } - self.copy_(selfCopy); - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UniqueConsecutiveKernelNpu.cpp b/torch_npu/csrc/aten/ops/UniqueConsecutiveKernelNpu.cpp deleted file mode 100644 index de1eba533a..0000000000 --- a/torch_npu/csrc/aten/ops/UniqueConsecutiveKernelNpu.cpp +++ /dev/null @@ -1,74 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple unique_consecutive_out_npu( - at::Tensor& output, - at::Tensor& inverse_indices, - at::Tensor& counts, - const at::Tensor& self, - const bool return_inverse, - const bool return_counts, - c10::optional dim) { - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - output = NPUNativeFunctions::npu_dtype_cast(output, at::ScalarType::Float); - } - c10::SmallVector output_sync_idx = {0, 2}; - OpCommand cmd; - cmd.Sync(output_sync_idx) - .Name("UniqueConsecutive") - .Input(selfCopy) - .Output(output) - .Output(inverse_indices) - .Output(counts) - .Attr("return_idx", return_inverse) - .Attr("return_counts", return_counts); - if (dim.has_value()) { - cmd.Attr("axis", dim.value()); - } - cmd.Run(); - if (self.scalar_type() == at::ScalarType::Half) { - output = NPUNativeFunctions::npu_dtype_cast(output, at::ScalarType::Half); - } - return std::tie(output, inverse_indices, counts); -} - -std::tuple NPUNativeFunctions::unique_consecutive( - const at::Tensor& self, - const bool return_inverse, - const bool return_counts, - c10::optional dim) { - at::Tensor output = (dim.has_value()) ? - OpPreparation::ApplyTensor(self) : OpPreparation::ApplyTensor(self, {self.numel()}); - at::Tensor inverse_indices = (dim.has_value()) ? - OpPreparation::ApplyTensorWithFormat(self.size(dim.value()), self.options().dtype(at::kLong), ACL_FORMAT_ND) : - OpPreparation::ApplyTensorWithFormat(self.sizes(), self.options().dtype(at::kLong), ACL_FORMAT_ND); - at::Tensor counts = (dim.has_value()) ? - OpPreparation::ApplyTensorWithFormat(self.size(dim.value()), self.options().dtype(at::kLong), ACL_FORMAT_ND) : - OpPreparation::ApplyTensorWithFormat({self.numel()}, self.options().dtype(at::kLong), ACL_FORMAT_ND); - unique_consecutive_out_npu(output, inverse_indices, counts, self, return_inverse, return_counts, dim); - return std::tie(output, inverse_indices, counts); -} - - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpSampleBicubic2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpSampleBicubic2dBackwardKernelNpu.cpp deleted file mode 100644 index b8af96d8bb..0000000000 --- a/torch_npu/csrc/aten/ops/UpSampleBicubic2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies. -// 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& upsample_bicubic2d_backward_out_nocheck( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& grad_input) { - - TORCH_CHECK( - output_size.size() == 2, - "It is expected output_size equals to 2, but got size ", - output_size.size()); - - TORCH_CHECK( - input_size.size() == 4, - "It is expected input_size equals to 4, but got size ", - input_size.size()); - - float temp_h = 0.0; - float temp_w = 0.0; - if(scales_h.has_value()) { - temp_h = (float)scales_h.value(); - } - if(scales_w.has_value()) { - temp_w = (float)scales_w.value(); - } - c10::SmallVector scales = {temp_h, temp_w}; - c10::SmallVector roi = {}; - string coordinate_transformation_mode = - align_corners ? "align_corners" : "half_pixel"; - - float cu = -0.75; - int64_t ex = 0; - float ext = 0.0; - string mode = "cubic"; - string ne = "round_prefer_floor"; - - OpCommand cmd; - cmd.Name("ResizeGradD") - .Input(grad_output) - .Output(grad_input) - .Attr("scales", scales) - .Attr("roi", roi) - .Attr("original_size", input_size) - .Attr("coordinate_transformation_mode", coordinate_transformation_mode) - .Attr("cubic_coeff_a", cu) - .Attr("exclude_outside", ex) - .Attr("extrapolation_value", ext) - .Attr("mode", mode) - .Attr("nearest_mode", ne) - .Run(); - - return grad_input; -} - -at::Tensor& NPUNativeFunctions::upsample_bicubic2d_backward_out( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& grad_input) { - - auto outputSize = upsample_bicubic2d_backward_npu_output_size(input_size); - - OpPreparation::CheckOut( - {grad_output}, - grad_input, - CalcuOpUtil::get_tensor_npu_format(grad_output), - grad_output.scalar_type(), - outputSize); - - if (!NpuUtils::check_match(&grad_input)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(grad_input); - upsample_bicubic2d_backward_out_nocheck(grad_output, output_size, input_size, align_corners, scales_h, scales_w, contiguousResult); - NpuUtils::format_fresh_view(grad_input, contiguousResult); - } else { - upsample_bicubic2d_backward_out_nocheck(grad_output, output_size, input_size, align_corners, scales_h, scales_w, grad_input); - } - - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_bicubic2d_backward( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - // construct the output tensor of the NPU - auto outputSize = upsample_bicubic2d_backward_npu_output_size(input_size); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, grad_output.options(), CalcuOpUtil::get_tensor_npu_format(grad_output)); - // calculate the output result of the NPU - return upsample_bicubic2d_backward_out_nocheck(grad_output, output_size, input_size, align_corners, scales_h, scales_w, result); -} - -at::Tensor NPUNativeFunctions::upsample_bicubic2d_backward( - const at::Tensor& grad_output, - c10::optional output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 1); - // construct the output tensor of the NPU - auto outputSize = upsample_bicubic2d_backward_npu_output_size(input_size); - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, grad_output.options(), CalcuOpUtil::get_tensor_npu_format(grad_output)); - // calculate the output result of the NPU - return upsample_bicubic2d_backward_out_nocheck(grad_output, osize, input_size, align_corners, scales_h, scales_w, result); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpSampleNearest3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpSampleNearest3dKernelNpu.cpp deleted file mode 100644 index 77ca73fcaf..0000000000 --- a/torch_npu/csrc/aten/ops/UpSampleNearest3dKernelNpu.cpp +++ /dev/null @@ -1,135 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::SmallVector upsample_nearest3d_outputsize_npu( - const at::Tensor& input, - at::IntArrayRef output_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - TORCH_CHECK( - output_size.size() == 3, - "It is expected output_size equals to 3, but got size ", - output_size.size()); - - int64_t output_depth = output_size[0]; - int64_t output_height = output_size[1]; - int64_t output_width = output_size[2]; - - int64_t nbatch = input.size(0); - int64_t channels = input.size(1); - int64_t input_depth = input.size(2); - int64_t input_height = input.size(3); - int64_t input_width = input.size(4); - - at::SmallVector outputSize = - {nbatch, channels, output_depth, output_height, output_width}; - - return outputSize; -} - -at::Tensor& upsample_nearest3d_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& input, - at::IntArrayRef output_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - at::Tensor inputCopy = (input.scalar_type() == at::ScalarType::Half) ? - NPUNativeFunctions::npu_dtype_cast(input, at::ScalarType::Float) : input; - - OpCommand cmd; - cmd.Name("UpsampleNearest3d") - .Input(inputCopy) - .Output(result) - .Attr("output_size", output_size) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_nearest3d_out( - const at::Tensor& input, - at::IntArrayRef output_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& result) { - auto outputsize = upsample_nearest3d_outputsize_npu( - input, output_size, scales_d, scales_h, scales_w); - - at::Tensor tmp = (input.scalar_type() == at::ScalarType::Half) ? - OpPreparation::ApplyTensorWithSizes(outputsize, input.options().dtype(at::kFloat)) : - OpPreparation::ApplyTensor(input, outputsize); - - upsample_nearest3d_out_npu_nocheck( - tmp, input, output_size, scales_d, scales_h, scales_w); - - if (input.scalar_type() == at::ScalarType::Half) { - tmp = NPUNativeFunctions::npu_dtype_cast(tmp, input.scalar_type()); - } - - OpPreparation::CheckOut( - {tmp}, result, tmp); - - result.copy_(tmp); - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest3d( - const at::Tensor& input, - at::IntArrayRef output_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - auto outputsize = upsample_nearest3d_outputsize_npu( - input, output_size, scales_d, scales_h, scales_w); - - at::Tensor result = (input.scalar_type() == at::ScalarType::Half) ? - OpPreparation::ApplyTensorWithSizes(outputsize, input.options().dtype(at::kFloat)) : - OpPreparation::ApplyTensor(input, outputsize); - - upsample_nearest3d_out_npu_nocheck( - result, input, output_size, scales_d, scales_h, scales_w); - - if (input.scalar_type() == at::ScalarType::Half) { - result = NPUNativeFunctions::npu_dtype_cast(result, input.scalar_type()); - } - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest3d( - const at::Tensor& input, - c10::optional output_size, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input.sizes(), output_size, scale_factors); - auto scales_d = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 1); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 2); - at::Tensor result = NPUNativeFunctions::upsample_nearest3d( - input, osize, scales_d, scales_h, scales_w); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleBicubic2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleBicubic2dKernelNpu.cpp deleted file mode 100644 index 994d5ce7bf..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleBicubic2dKernelNpu.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& upsample_bicubic2d_out_nocheck( - at::Tensor& result, - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - - TORCH_CHECK( - output_size.size() == 2, - "It is expected output_size equals to 2, but got size ", - output_size.size()); - - float temp_h = 0.0; - float temp_w = 0.0; - if (scales_h.has_value()) { - temp_h = (float)scales_h.value(); - } - if (scales_w.has_value()) { - temp_w = (float)scales_w.value(); - } - c10::SmallVector scales = {temp_h, temp_w}; - c10::SmallVector roi = {}; - string coordinate_transformation_mode = "half_pixel"; - if (align_corners == true) { - coordinate_transformation_mode = "align_corners"; - } - - OpCommand cmd; - cmd.Name("ResizeD") - .Input(self) - .Output(result) - .Attr("sizes", output_size) - .Attr("scales", scales) - .Attr("roi", roi) - .Attr("coordinate_transformation_mode", coordinate_transformation_mode) - .Attr("cubic_coeff_a", (float)-0.75) - .Attr("exclude_outside", (int64_t)0) - .Attr("extrapolation_value", (float)0.0) - .Attr("mode", (string)"cubic") - .Attr("nearest_mode", (string)"round_prefer_floor") - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_bicubic2d_out( - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& result) { - - // calculate the output size - int64_t N = self.size(0); - int64_t C = self.size(1); - int64_t H = output_size[0]; - int64_t W = output_size[1]; - - c10::SmallVector outputSize = {N, C, H, W}; - - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - upsample_bicubic2d_out_nocheck(contiguousResult, self, output_size, align_corners, scales_h, scales_w); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - upsample_bicubic2d_out_nocheck(result, self, output_size, align_corners, scales_h, scales_w); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_bicubic2d( - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - - // calculate the output size - int64_t N = self.size(0); - int64_t C = self.size(1); - int64_t H = output_size[0]; - int64_t W = output_size[1]; - c10::SmallVector outputSize = {N, C, H, W}; - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - upsample_bicubic2d_out_nocheck(result, self, output_size, align_corners, scales_h, scales_w); - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_bicubic2d( - const at::Tensor& self, - c10::optional output_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(self.sizes(), output_size, scale_factors); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 1); - - // calculate the output size - int64_t N = self.size(0); - int64_t C = self.size(1); - int64_t H = osize[0]; - int64_t W = osize[1]; - c10::SmallVector outputSize = {N, C, H, W}; - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - upsample_bicubic2d_out_nocheck(result, self, osize, align_corners, scales_h, scales_w); - - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleBilinear2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleBilinear2dBackwardKernelNpu.cpp deleted file mode 100644 index 9493e00cf7..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleBilinear2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,181 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -bool upsample_bilinear2d_backward_check_is_aicore( - const at::Tensor& grad_output) { - int64_t H = grad_output.size(2); - int64_t W = grad_output.size(3); - // 判断H或W大于10000走ai_cpu算子 - if (H > 10000 || W > 10000) { - return false; - } - return true; -} - -at::Tensor& upsample_bilinear2d_backward_out_npu_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - bool isAicore = upsample_bilinear2d_backward_check_is_aicore(grad_output); - OpCommand cmd; - if (isAicore) { - at::Tensor original_image = OpPreparation::ApplyTensor(grad_output, input_size); - bool half_pixel_centers = !align_corners; - cmd.Name("ResizeBilinearV2Grad") - .Input(grad_output) - .Input(original_image) - .Output(grad_input) - .Attr("align_corners", align_corners) - .Attr("half_pixel_centers", half_pixel_centers) - .Run(); - } else { - cmd.Name("PTUpsampleBilinear2dGrad") - .Input(grad_output) - .Output(grad_input) - .Attr("output_size", output_size) - .Attr("input_size", input_size) - .Attr("align_corners", align_corners); - if (scales_h.has_value()) { - cmd.Attr("scales_h", static_cast(scales_h.value())); - } - if (scales_w.has_value()) { - cmd.Attr("scales_w", static_cast(scales_w.value())); - } - cmd.Run(); - } - return grad_input; -} - -at::Tensor& NPUNativeFunctions::upsample_bilinear2d_backward_out( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& grad_input) { - - OpPreparation::CheckOut( - {grad_output}, - grad_input, - grad_output, - input_size); - if (!NpuUtils::check_match(&grad_input)) { - at::Tensor result_contiguous = NpuUtils::format_contiguous(grad_input); - - upsample_bilinear2d_backward_out_npu_nocheck( - result_contiguous, - grad_output, - output_size, - input_size, - align_corners, - scales_h, - scales_w); - NpuUtils::format_fresh_view(grad_input, result_contiguous); - } else { - upsample_bilinear2d_backward_out_npu_nocheck( - grad_input, - grad_output, - output_size, - input_size, - align_corners, - scales_h, - scales_w); - } - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_bilinear2d_backward( - const at::Tensor& grad_output_ex, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - at::Tensor grad_output = grad_output_ex; - bool isAicore = upsample_bilinear2d_backward_check_is_aicore(grad_output); - if (!isAicore) { - if (grad_output.scalar_type() != at::ScalarType::Float) { - grad_output = NPUNativeFunctions::npu_dtype_cast(grad_output, at::ScalarType::Float); - } - } - auto outputSize = upsample_bilinear2d_backward_npu_output_size( - grad_output, output_size, input_size, align_corners, scales_h, scales_w); - aclFormat format = isAicore ? ACL_FORMAT_NC1HWC0 : (aclFormat)CalcuOpUtil::get_tensor_npu_format(grad_output); - at::Tensor grad_input = OpPreparation::ApplyTensorWithFormat(grad_output, outputSize, format); - - upsample_bilinear2d_backward_out_npu_nocheck( - grad_input, - grad_output, - output_size, - input_size, - align_corners, - scales_h, - scales_w); - if (grad_input.dtype() != grad_output_ex.dtype()) { - grad_input = grad_input.to(grad_output_ex.dtype()); - } - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_bilinear2d_backward( - const at::Tensor& grad_output_ex, - c10::optional output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 1); - - at::Tensor grad_output = grad_output_ex; - bool isAicore = upsample_bilinear2d_backward_check_is_aicore(grad_output); - if (!isAicore) { - if (grad_output.scalar_type() != at::ScalarType::Float) { - grad_output = NPUNativeFunctions::npu_dtype_cast(grad_output, at::ScalarType::Float); - } - } - auto outputSize = upsample_bilinear2d_backward_npu_output_size( - grad_output, osize, input_size, align_corners, scales_h, scales_w); - aclFormat format = isAicore ? ACL_FORMAT_NC1HWC0 : (aclFormat)CalcuOpUtil::get_tensor_npu_format(grad_output); - at::Tensor grad_input = OpPreparation::ApplyTensorWithFormat(grad_output, outputSize, format); - - upsample_bilinear2d_backward_out_npu_nocheck( - grad_input, - grad_output, - osize, - input_size, - align_corners, - scales_h, - scales_w); - if (grad_input.dtype() != grad_output_ex.dtype()) { - grad_input = grad_input.to(grad_output_ex.dtype()); - } - return grad_input; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleBilinear2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleBilinear2dKernelNpu.cpp deleted file mode 100644 index d97f47bbc0..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleBilinear2dKernelNpu.cpp +++ /dev/null @@ -1,126 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" - -namespace at_npu { -namespace native { - -at::Tensor& upsample_bilinear2d_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - OpCommand cmd; - bool half_pixel_centers = !align_corners; - int64_t H = output_size[0]; - int64_t W = output_size[1]; - at::SmallVector attr_size = {H, W}; - cmd.Name("ResizeBilinearV2") - .Input(self) - .Input(attr_size, at::kInt) - .Output(result) - .Attr("align_corners", align_corners) - .Attr("half_pixel_centers", half_pixel_centers) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_bilinear2d_out( - const at::Tensor& self_ex, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& result){ - at::Tensor self = self_ex; - if (self.scalar_type() != at::ScalarType::Float) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - auto outputSize = upsample_bilinear2d_npu_output_size( - self, output_size, align_corners, scales_h, scales_w); - - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - if (!NpuUtils::check_match(&result)) { - at::Tensor result_contiguous = NpuUtils::format_contiguous(result); - - upsample_bilinear2d_out_npu_nocheck( - result_contiguous, self, output_size, align_corners, scales_h, scales_w); - NpuUtils::format_fresh_view(result, result_contiguous); - } else { - upsample_bilinear2d_out_npu_nocheck( - result, self, output_size, align_corners, scales_h, scales_w); - } - return result; -} - -at::Tensor NPUNativeFunctions::upsample_bilinear2d( - const at::Tensor& self_ex, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_h, - c10::optional scales_w) { - at::Tensor self = self_ex; - if (self.scalar_type() != at::ScalarType::Float) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - auto outputSize = upsample_bilinear2d_npu_output_size( - self, output_size, align_corners, scales_h, scales_w); - at::Tensor result = OpPreparation::ApplyTensor(outputSize, self.options(), self); - - upsample_bilinear2d_out_npu_nocheck( - result, self, output_size, align_corners, scales_h, scales_w); - if (result.dtype() != self_ex.dtype()) { - result = NPUNativeFunctions::npu_dtype_cast(result, self_ex.scalar_type()); - } - return result; -} - -at::Tensor NPUNativeFunctions::upsample_bilinear2d( - const at::Tensor& self_ex, - c10::optional output_size, - bool align_corners, - c10::optional> scale_factors) { - at::Tensor self = self_ex; - auto osize = CalcuOpUtil::compute_output_size(self_ex.sizes(), output_size, scale_factors); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 1); - - if (self.scalar_type() != at::ScalarType::Float) { - self = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - auto outputSize = upsample_bilinear2d_npu_output_size( - self, osize, align_corners, scales_h, scales_w); - at::Tensor result = OpPreparation::ApplyTensor(outputSize, self.options(), self); - - upsample_bilinear2d_out_npu_nocheck( - result, self, osize, align_corners, scales_h, scales_w); - if (result.dtype() != self_ex.dtype()) { - result = NPUNativeFunctions::npu_dtype_cast(result, self_ex.scalar_type()); - } - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleLinear1dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleLinear1dBackwardKernelNpu.cpp deleted file mode 100644 index 8aaffddc08..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleLinear1dBackwardKernelNpu.cpp +++ /dev/null @@ -1,166 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" - -namespace at_npu { -namespace native { - -static inline void upsample_linear1d_backward_check( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size) { - - TORCH_CHECK( - output_size.size() == 1, - "It is expected output_size equals to 1, but got size ", - output_size.size()); - - TORCH_CHECK( - input_size.size() == 3, - "It is expected input_size equals to 3, but got size ", - input_size.size()); - - TORCH_CHECK( - (grad_output.size(1) != 0 && grad_output.size(2) != 0) && grad_output.dim() == 3, - "Non-empty 3D data tensor expected but got a tensor with sizes ", - grad_output.sizes()); - - int64_t output_width = grad_output.size(2); - int64_t input_width = input_size[2]; - - TORCH_CHECK( - output_width > 0 && input_width > 0, - "Input and output sizes should be greater than 0, but got input (W: ", - input_width, - ") and output (W: ", - output_width, - ")"); -} - -at::Tensor& upsample_linear1d_backward_out( - at::Tensor& result, - const at::Tensor& grad_output, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales) { - - c10::SmallVector sc = {}; - if (scales.has_value()) { - sc.push_back(scales.value()); - } else { - float temp = float(grad_output.size(3)) / float(input_size[2]); - sc.push_back(temp); - } - string coordinate_transformation_mode = - align_corners ? "align_corners" : "half_pixel"; - - // executing the NPU operator - OpCommand cmd; - cmd.Name("ResizeGradD") - .Input(grad_output) - .Output(result) - .Attr("original_size", input_size) - .Attr("scales", sc) - .Attr("coordinate_transformation_mode", coordinate_transformation_mode) - .Attr("mode", (string)"linear") - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::upsample_linear1d_backward( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales) { - upsample_linear1d_backward_check(grad_output, output_size, input_size); - at::Tensor _grad_output = grad_output; - if(grad_output.scalar_type() != at::ScalarType::Float) - { - _grad_output = NPUNativeFunctions::npu_dtype_cast(_grad_output, at::ScalarType::Float); - } - - // calculate the output size - int64_t N = _grad_output.size(0); - int64_t C = _grad_output.size(1); - int64_t W = input_size[2]; - - c10::SmallVector outputSize = {N, C, W}; - - // Since only NCHW format input is currently supported, first convert the - // input grad_output (3 dimensions) to 4 dimensions as the input of npu - auto grad_output_4dim = _grad_output.unsqueeze(2); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(_grad_output, outputSize); - - // calculate the output result of the NPU - upsample_linear1d_backward_out( - result, grad_output_4dim, input_size, align_corners, scales); - - if (result.dtype() != grad_output.dtype()) { - result = result.to(grad_output.dtype()); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_linear1d_backward( - const at::Tensor& grad_output, - c10::optional output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 0); - - upsample_linear1d_backward_check(grad_output, osize, input_size); - at::Tensor _grad_output = grad_output; - if(grad_output.scalar_type() != at::ScalarType::Float) - { - _grad_output = NPUNativeFunctions::npu_dtype_cast(_grad_output, at::ScalarType::Float); - } - - // calculate the output size - int64_t N = _grad_output.size(0); - int64_t C = _grad_output.size(1); - int64_t W = input_size[2]; - - c10::SmallVector outputSize = {N, C, W}; - - // Since only NCHW format input is currently supported, first convert the - // input grad_output (3 dimensions) to 4 dimensions as the input of npu - auto grad_output_4dim = _grad_output.unsqueeze(2); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(_grad_output, outputSize); - - // calculate the output result of the NPU - upsample_linear1d_backward_out( - result, grad_output_4dim, input_size, align_corners, scales_w); - - if (result.dtype() != grad_output.dtype()) { - result = result.to(grad_output.dtype()); - } - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpsampleLinear1dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleLinear1dKernelNpu.cpp deleted file mode 100644 index 9693d981fc..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleLinear1dKernelNpu.cpp +++ /dev/null @@ -1,158 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -static inline void upsample_linear1d_check( - const at::Tensor& self, - at::IntArrayRef output_size) { - TORCH_CHECK( - output_size.size() == 1, - "It is expected output_size equals to 1, but got size ", - output_size.size()); - - TORCH_CHECK( - (self.size(1) != 0 && self.size(2) != 0) && self.dim() == 3, - "Non-empty 3D data tensor expected but got a tensor with sizes ", - self.sizes()); - - int64_t input_width = self.size(2); - int64_t output_width = output_size[0]; - - TORCH_CHECK( - input_width > 0 && output_width > 0, - "Input and output sizes should be greater than 0, but got input (W: ", - input_width, - ") and output (W: ", - output_width, - ")"); -} - -at::Tensor& upsample_linear1d_out_nocheck( - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales, - at::Tensor& result) { - upsample_linear1d_check(self, output_size); - - // Since only NCHW format input is currently supported, first convert the - // input self (3 dimensions) to 4 dimensions as the input of npu - at::Tensor selfcp = self.unsqueeze(2); - - // to calculate the value of scale - c10::SmallVector sc = {}; - if (scales.has_value()) { - sc.push_back(scales.value()); - } else { - float temp = float(output_size[0]) / float(selfcp.size(3)); - sc.push_back(temp); - } - - string coordinate_transformation_mode = - align_corners ? "align_corners" : "half_pixel"; - - string mode = "linear"; - - OpCommand cmd; - cmd.Name("ResizeD") - .Input(selfcp) - .Output(result) - .Attr("sizes", output_size) - .Attr("coordinate_transformation_mode", coordinate_transformation_mode) - .Attr("mode", mode) - .Attr("scales", sc) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_linear1d_out( - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales, - at::Tensor& result) { - - // calculate the output size - auto outputSize = upsample_linear1d_npu_output_size( - self, output_size, align_corners, scales); - - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - at::Tensor newResult = upsample_linear1d_out_nocheck(self, output_size, align_corners, scales, contiguousResult); - NpuUtils::format_fresh_view(result, newResult); - } else { - upsample_linear1d_out_nocheck(self, output_size, align_corners, scales, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_linear1d( - const at::Tensor& self, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales) { - // calculate the output size - auto outputSize = upsample_linear1d_npu_output_size( - self, output_size, align_corners, scales); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - - // calculate the output result of the NPU - upsample_linear1d_out_nocheck(self, output_size, align_corners, scales, result); - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_linear1d( - const at::Tensor& self, - c10::optional output_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(self.sizes(), output_size, scale_factors); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 0); - // calculate the output size - auto outputSize = upsample_linear1d_npu_output_size( - self, osize, align_corners, scales_w); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); - - // calculate the output result of the NPU - upsample_linear1d_out_nocheck(self, osize, align_corners, scales_w, result); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpsampleNearest1dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleNearest1dBackwardKernelNpu.cpp deleted file mode 100644 index bdc1a5eb02..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleNearest1dBackwardKernelNpu.cpp +++ /dev/null @@ -1,105 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor& upsample_nearest1d_backward_out_nocheck( - const at::Tensor& grads, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales, - at::Tensor& y) { - OpCommand cmd; - cmd.Name("UpsampleNearest1dGrad") - .Input(grads) - .Output(y) - .Attr("output_size", output_size) - .Attr("input_size", input_size); - if (scales.has_value()) { - cmd.Attr("scales", static_cast(scales.value())); - } - cmd.Run(); - - return y; -} - -at::Tensor& NPUNativeFunctions::upsample_nearest1d_backward_out( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales, - at::Tensor& y) { - at::Tensor grads = grad_output; - if (grad_output.scalar_type() != at::ScalarType::Float) { - grads = grad_output.to(at::kFloat); - } - - OpPreparation::CheckOut( - {grad_output}, - y, - CalcuOpUtil::get_tensor_npu_format(grad_output), - grads.scalar_type(), - input_size); - - if (!NpuUtils::check_match(&y)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(y); - upsample_nearest1d_backward_out_nocheck(grads, output_size, input_size, scales, contiguousResult); - NpuUtils::format_fresh_view(y, contiguousResult); - } else { - upsample_nearest1d_backward_out_nocheck(grads, output_size, input_size, scales, y); - } - - return y; -} - -at::Tensor NPUNativeFunctions::upsample_nearest1d_backward( - const at::Tensor& grad_output, - c10::optional output_size, - at::IntArrayRef input_size, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 0); - at::Tensor grads = grad_output; - if (grad_output.scalar_type() != at::ScalarType::Float) { - grads = grad_output.to(at::kFloat); - } - at::Tensor grad_input = OpPreparation::ApplyTensor(input_size, grads.options(), grad_output); - upsample_nearest1d_backward_out_nocheck(grads, osize, input_size, scales_w, grad_input); - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_nearest1d_backward( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales) { - at::Tensor grads = grad_output; - if (grad_output.scalar_type() != at::ScalarType::Float) { - grads = grad_output.to(at::kFloat); - } - - at::Tensor grad_input = OpPreparation::ApplyTensor(input_size, grads.options(), grad_output); - - upsample_nearest1d_backward_out_nocheck( - grads, output_size, input_size, scales, grad_input); - return grad_input; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleNearest1dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleNearest1dKernelNpu.cpp deleted file mode 100644 index 88e4ad7705..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleNearest1dKernelNpu.cpp +++ /dev/null @@ -1,109 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -c10::SmallVector upsample_nearest1d_npu_output_size( - const at::Tensor& input, - at::IntArrayRef output_size, - c10::optional scales) { - c10::SmallVector outputSize; - int64_t N = input.size(0); - int64_t C = input.size(1); - int64_t W; - int64_t Z = input.size(2); - - if (output_size.size() != 0) { - W = output_size[0]; - } else { - float temp_scales = (float)scales.value(); - W = temp_scales * Z; - } - outputSize = {N, C, W}; - return outputSize; -} - -at::Tensor& upsample_nearest1d_out_nocheck( - const at::Tensor& self, - at::IntArrayRef output_size, - c10::optional scales, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("UpsampleNearest1d") - .Input(self) - .Output(result) - .Attr("output_size", output_size); - if (scales.has_value()) { - cmd.Attr("scales", static_cast(scales.value())); - } - cmd.Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_nearest1d_out( - const at::Tensor& self, - at::IntArrayRef output_size, - c10::optional scales, - at::Tensor& result) { - c10::SmallVector outputSize = upsample_nearest1d_npu_output_size(self, output_size, scales); - - OpPreparation::CheckOut( - {self}, - result, - self, - outputSize); - - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguousResult = NpuUtils::format_contiguous(result); - upsample_nearest1d_out_nocheck(self, output_size, scales, contiguousResult); - NpuUtils::format_fresh_view(result, contiguousResult); - } else { - upsample_nearest1d_out_nocheck(self, output_size, scales, result); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest1d( - const at::Tensor& input, - c10::optional output_size, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input.sizes(), output_size, scale_factors); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 0); - c10::SmallVector outputSize = upsample_nearest1d_npu_output_size(input, osize, scales_w); - at::Tensor result = OpPreparation::ApplyTensor(input, outputSize); - upsample_nearest1d_out_nocheck(input, osize, scales_w, result); - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest1d( - const at::Tensor& self, - at::IntArrayRef output_size, - c10::optional scales) { - c10::SmallVector outputSize = upsample_nearest1d_npu_output_size(self, output_size, scales); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - upsample_nearest1d_out_nocheck(self, output_size, scales, result); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleNearest2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleNearest2dBackwardKernelNpu.cpp deleted file mode 100644 index 0ffab86967..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleNearest2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,74 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::upsample_nearest2d_backward_out( - const at::Tensor& grads, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& y) { - at::SmallVector outputSize = {input_size[2], input_size[3]}; - OpCommand cmd; - cmd.Name("ResizeNearestNeighborV2Grad") - .Input(grads) - .Input(outputSize, at::kInt) - .Output(y) - .Attr("align_corners", false) - .Attr("half_pixel_centers", false) - .Run(); - - return y; -} - -at::Tensor NPUNativeFunctions::upsample_nearest2d_backward( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_h, - c10::optional scales_w) { - at::Tensor grads = grad_output; - if (grad_output.scalar_type() != at::ScalarType::Float) { - grads = grad_output.to(at::kFloat); - } - at::Tensor grad_input = OpPreparation::ApplyTensor( - input_size, grads.options(), grad_output); - NPUNativeFunctions::upsample_nearest2d_backward_out( - grads, output_size, input_size, scales_h, scales_w, grad_input); - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_nearest2d_backward( - const at::Tensor& grad_output, - c10::optional output_size, - at::IntArrayRef input_size, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 1); - at::Tensor grad_input = OpPreparation::ApplyTensor(grad_output, input_size); - NPUNativeFunctions::upsample_nearest2d_backward_out(grad_output, osize, input_size, scales_h, scales_w, grad_input); - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpsampleNearest2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleNearest2dKernelNpu.cpp deleted file mode 100644 index cb1fcfbbdb..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleNearest2dKernelNpu.cpp +++ /dev/null @@ -1,84 +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. -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::SmallVector upsample_nearest2d_npu_output_size( - const at::Tensor& input, - at::IntArrayRef output_size){ - int64_t N = input.size(0); - int64_t C = input.size(1); - int64_t H = output_size[0]; - int64_t W = output_size[1]; - at::SmallVector outputSize = {N, C, H, W}; - - return outputSize; -} - -at::Tensor& NPUNativeFunctions::upsample_nearest2d_out( - const at::Tensor& self, - at::IntArrayRef output_size, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& result) { - at::SmallVector outputSize = upsample_nearest2d_npu_output_size(self, output_size); - if (!result.sizes().equals(outputSize)){ - result.resize_(outputSize); - } - at::SmallVector outputSizeVec = array_to_small_vector(output_size); - OpCommand cmd; - cmd.Name("ResizeNearestNeighborV2") - .Input(self) - .Input(outputSizeVec, at::kInt) - .Output(result) - .Attr("align_corners", false) - .Attr("half_pixel_centers", false) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest2d( - const at::Tensor& self, - at::IntArrayRef output_size, - c10::optional scales_h, - c10::optional scales_w) { - at::SmallVector outputSize = upsample_nearest2d_npu_output_size(self, output_size); - - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - NPUNativeFunctions::upsample_nearest2d_out(self, output_size, scales_h, scales_w, result); - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest2d( - const at::Tensor& input, - c10::optional output_size, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input.sizes(), output_size, scale_factors); - auto scale_h = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scale_w = CalcuOpUtil::get_scale_value(scale_factors, 1); - at::Tensor result = OpPreparation::ApplyTensor(input, osize); - NPUNativeFunctions::upsample_nearest2d_out(input, osize, scale_h, scale_w, result); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpsampleNearest3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleNearest3dBackwardKernelNpu.cpp deleted file mode 100644 index e319236e90..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleNearest3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,157 +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. - - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::SmallVector upsample_nearest3d_backward_outputsize_npu( - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - TORCH_CHECK( - output_size.size() == 3, - "It is expected output_size equals to 3, but got size ", - output_size.size()); - - TORCH_CHECK( - input_size.size() == 5, - "It is expected input_size equals to 5, but got size ", - input_size.size()); - - int64_t output_depth = output_size[0]; - int64_t output_height = output_size[1]; - int64_t output_width = output_size[2]; - - int64_t nbatch = input_size[0]; - int64_t channels = input_size[1]; - int64_t input_depth = input_size[2]; - int64_t input_height = input_size[3]; - int64_t input_width = input_size[4]; - - at::SmallVector outputSize = - {nbatch, channels, input_depth, input_height, input_width}; - - return outputSize; -} - -at::Tensor& upsample_nearest3d_backward_npu_nocheck( - at::Tensor& result, - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - at::Tensor grad_output_copy = grad_output; - if (grad_output.scalar_type() == at::ScalarType::Half) { - grad_output_copy = NPUNativeFunctions::npu_dtype_cast(grad_output, at::kFloat); - } - - OpCommand cmd; - cmd.Name("UpsampleNearest3dGrad") - .Input(grad_output_copy) - .Output(result) - .Attr("input_size", input_size) - .Attr("output_size", output_size) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_nearest3d_backward_out( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& grad_input) { - auto outputsize = upsample_nearest3d_backward_outputsize_npu( - output_size, input_size, scales_d, scales_h, scales_w); - - OpPreparation::CheckOut({grad_output}, grad_input, grad_output, outputsize); - - if (grad_output.scalar_type() == at::kHalf) { - auto out_copy = OpPreparation::ApplyTensorWithSizes( - outputsize, grad_output.options().dtype(at::kFloat)); - - upsample_nearest3d_backward_npu_nocheck( - out_copy, grad_output, output_size, input_size, scales_d, scales_h, scales_w); - - out_copy = NPUNativeFunctions::npu_dtype_cast(out_copy, at::kHalf); - NpuUtils::format_fresh_view(grad_input, out_copy); - } else if (!NpuUtils::check_match(&grad_input)) { - auto contiguous_out = NpuUtils::format_contiguous(grad_input); - - upsample_nearest3d_backward_npu_nocheck( - contiguous_out, grad_output, output_size, input_size, scales_d, scales_h, scales_w); - - NpuUtils::format_fresh_view(grad_input, contiguous_out); - } else { - upsample_nearest3d_backward_npu_nocheck( - grad_input, grad_output, output_size, input_size, scales_d, scales_h, scales_w); - } - - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_nearest3d_backward( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - auto outputsize = upsample_nearest3d_backward_outputsize_npu( - output_size, input_size, scales_d, scales_h, scales_w); - - at::Tensor result = (grad_output.scalar_type() == at::kHalf) ? - OpPreparation::ApplyTensorWithSizes(outputsize, grad_output.options().dtype(at::kFloat)) : - OpPreparation::ApplyTensor(grad_output, outputsize); - - upsample_nearest3d_backward_npu_nocheck( - result, grad_output, output_size, input_size, scales_d, scales_h, scales_w); - - if (grad_output.scalar_type() == at::kHalf) { - result = NPUNativeFunctions::npu_dtype_cast(result, grad_output.scalar_type()); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_nearest3d_backward( - const at::Tensor& grad_output, - c10::optional output_size, - at::IntArrayRef input_size, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_d = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 1); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 2); - at::Tensor grad_input = NPUNativeFunctions::upsample_nearest3d_backward( - grad_output, osize, input_size, scales_d, scales_h, scales_w); - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/UpsampleTrilinear3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleTrilinear3dBackwardKernelNpu.cpp deleted file mode 100644 index ab63f6da5c..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleTrilinear3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,159 +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. - - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::SmallVector upsample_trilinear3d_backward_outputsize_npu( - at::IntArrayRef output_size, - at::IntArrayRef input_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - TORCH_CHECK( - output_size.size() == 3, - "It is expected output_size equals to 3, but got size ", - output_size.size()); - - TORCH_CHECK( - input_size.size() == 5, - "It is expected input_size equals to 5, but got size ", - input_size.size()); - - int64_t output_depth = output_size[0]; - int64_t output_height = output_size[1]; - int64_t output_width = output_size[2]; - - int64_t nbatch = input_size[0]; - int64_t channels = input_size[1]; - int64_t input_depth = input_size[2]; - int64_t input_height = input_size[3]; - int64_t input_width = input_size[4]; - - at::SmallVector outputSize = - {nbatch, channels, input_depth, input_height, input_width}; - return outputSize; -} - -at::Tensor& upsample_trilinear3d_backward_npu_nocheck( - at::Tensor& out, - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - auto grad_output_copy = (grad_output.scalar_type() == at::kHalf) ? - NPUNativeFunctions::npu_dtype_cast(grad_output, at::kFloat) : grad_output; - - OpCommand cmd; - cmd.Name("UpsampleTrilinear3dGrad") - .Input(grad_output_copy) - .Output(out) - .Attr("input_size", input_size) - .Attr("output_size", output_size) - .Attr("align_corners", align_corners) - .Run(); - - return out; -} - -at::Tensor& NPUNativeFunctions::upsample_trilinear3d_backward_out( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& grad_input) { - auto outputsize = upsample_trilinear3d_backward_outputsize_npu( - output_size, input_size, scales_d, scales_h, scales_w); - - OpPreparation::CheckOut({grad_output}, grad_input, grad_output, outputsize); - - if (grad_output.scalar_type() == at::kHalf) { - at::Tensor out_copy = OpPreparation::ApplyTensorWithSizes( - outputsize, grad_output.options().dtype(at::kFloat)); - - upsample_trilinear3d_backward_npu_nocheck( - out_copy, grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w); - - out_copy = NPUNativeFunctions::npu_dtype_cast(out_copy, grad_output.scalar_type()); - NpuUtils::format_fresh_view(grad_input, out_copy); - } else if (!NpuUtils::check_match(&grad_input)) { - auto contiguous_out = NpuUtils::format_contiguous(grad_input); - - upsample_trilinear3d_backward_npu_nocheck( - grad_input, grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w); - - NpuUtils::format_fresh_view(grad_input, contiguous_out); - } else { - upsample_trilinear3d_backward_npu_nocheck( - grad_input, grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w); - } - - return grad_input; -} - -at::Tensor NPUNativeFunctions::upsample_trilinear3d_backward( - const at::Tensor& grad_output, - at::IntArrayRef output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - auto outputsize = upsample_trilinear3d_backward_outputsize_npu( - output_size, input_size, scales_d, scales_h, scales_w); - - at::Tensor result = (grad_output.scalar_type() == at::kHalf) ? - OpPreparation::ApplyTensorWithSizes(outputsize, grad_output.options().dtype(at::kFloat)) : - OpPreparation::ApplyTensor(grad_output, outputsize); - - upsample_trilinear3d_backward_npu_nocheck( - result, grad_output, output_size, input_size, align_corners, scales_d, scales_h, scales_w); - - if (grad_output.scalar_type() == at::kHalf) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::kHalf); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_trilinear3d_backward( - const at::Tensor& grad_output, - c10::optional output_size, - at::IntArrayRef input_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input_size, output_size, scale_factors); - auto scales_d = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 1); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 2); - at::Tensor grad_input = NPUNativeFunctions::upsample_trilinear3d_backward( - grad_output, osize, input_size, align_corners, scales_d, scales_h, scales_w); - return grad_input; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/UpsampleTrilinear3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/UpsampleTrilinear3dKernelNpu.cpp deleted file mode 100644 index deedd126e1..0000000000 --- a/torch_npu/csrc/aten/ops/UpsampleTrilinear3dKernelNpu.cpp +++ /dev/null @@ -1,149 +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. - - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::SmallVector upsample_trilinear3d_outputsize_npu( - const at::Tensor& input, - at::IntArrayRef output_size, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - TORCH_CHECK( - output_size.size() == 3, - "It is expected output_size equals to 3, but got size ", - output_size.size()); - - int64_t output_depth = output_size[0]; - int64_t output_height = output_size[1]; - int64_t output_width = output_size[2]; - - int64_t nbatch = input.size(0); - int64_t channels = input.size(1); - int64_t input_depth = input.size(2); - int64_t input_height = input.size(3); - int64_t input_width = input.size(4); - - at::SmallVector outputSize = - {nbatch, channels, output_depth, output_height, output_width}; - return outputSize; -} - -at::Tensor& upsample_trilinear3d_npu_nocheck( - at::Tensor& result, - const at::Tensor& input, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - at::Tensor input_copy = (input.scalar_type() == at::ScalarType::Half) ? - NPUNativeFunctions::npu_dtype_cast(input, at::kFloat) : input; - - OpCommand cmd; - cmd.Name("UpsampleTrilinear3d") - .Input(input_copy) - .Output(result) - .Attr("output_size", output_size) - .Attr("align_corners", align_corners) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::upsample_trilinear3d_out( - const at::Tensor& input, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w, - at::Tensor& result) { - auto outputsize = upsample_trilinear3d_outputsize_npu( - input, output_size, scales_d, scales_h, scales_w); - - OpPreparation::CheckOut({input}, result, input, outputsize); - - if (input.scalar_type() == at::kHalf) { - auto out_copy = OpPreparation::ApplyTensorWithSizes( - outputsize, input.options().dtype(at::kFloat)); - - upsample_trilinear3d_npu_nocheck( - out_copy, input, output_size, align_corners, scales_d, scales_h, scales_w); - - out_copy = NPUNativeFunctions::npu_dtype_cast(out_copy, input.scalar_type()); - NpuUtils::format_fresh_view(result, out_copy); - } else if (!NpuUtils::check_match(&result)) { - auto contiguous_out = NpuUtils::format_contiguous(result); - - upsample_trilinear3d_npu_nocheck( - contiguous_out, input, output_size, align_corners, scales_d, scales_h, scales_w); - - NpuUtils::format_fresh_view(result, contiguous_out); - } else { - upsample_trilinear3d_npu_nocheck( - result, input, output_size, align_corners, scales_d, scales_h, scales_w); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_trilinear3d( - const at::Tensor& input, - at::IntArrayRef output_size, - bool align_corners, - c10::optional scales_d, - c10::optional scales_h, - c10::optional scales_w) { - auto outputsize = upsample_trilinear3d_outputsize_npu( - input, output_size, scales_d, scales_h, scales_w); - - at::Tensor result = (input.scalar_type() == at::kHalf) ? - OpPreparation::ApplyTensorWithSizes(outputsize, input.options().dtype(at::kFloat)) : - OpPreparation::ApplyTensor(input, outputsize); - - upsample_trilinear3d_npu_nocheck( - result, input, output_size, align_corners, scales_d, scales_h, scales_w); - - if (input.scalar_type() == at::kHalf) { - result = NPUNativeFunctions::npu_dtype_cast(result, input.scalar_type()); - } - - return result; -} - -at::Tensor NPUNativeFunctions::upsample_trilinear3d( - const at::Tensor& input, - c10::optional output_size, - bool align_corners, - c10::optional> scale_factors) { - auto osize = CalcuOpUtil::compute_output_size(input.sizes(), output_size, scale_factors); - auto scales_d = CalcuOpUtil::get_scale_value(scale_factors, 0); - auto scales_h = CalcuOpUtil::get_scale_value(scale_factors, 1); - auto scales_w = CalcuOpUtil::get_scale_value(scale_factors, 2); - at::Tensor result = NPUNativeFunctions::upsample_trilinear3d( - input, osize, align_corners, scales_d, scales_h, scales_w); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/VarKernelNpu.cpp b/torch_npu/csrc/aten/ops/VarKernelNpu.cpp deleted file mode 100644 index 9c93fb023c..0000000000 --- a/torch_npu/csrc/aten/ops/VarKernelNpu.cpp +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -auto check_and_trans_dim(const at::Tensor& self, at::IntArrayRef dim) { - int64_t dim_size = self.dim(); - int64_t ne_dim_size = dim_size * -1; - std::vector result_dim; - for(int64_t i = 0; i < dim.size(); i++) { - if(dim[i] >= ne_dim_size && dim[i] <= (dim_size - 1)) { - int64_t tmp_dim = CalcuOpUtil::make_wrap_dim(dim[i], self.dim()); - result_dim.emplace_back(tmp_dim); - } else { - AT_ERROR("dim value should be in the range of [-n, n-1], n is the dimension number of input tensor."); - } - } - std::sort(result_dim.begin(), result_dim.end()); - return result_dim; -} - -auto get_result_names(const at::Tensor& self, at::IntArrayRef dim, bool keepdim){ - auto names = self.names(); - std::vector result_names; - for(int64_t i = 0; i < names.size(); i++){ - result_names.emplace_back(names[i]); - } - if(!keepdim){ - for(int64_t i = dim.size() - 1; i >= 0; i--){ - int64_t need_remove_dim = dim[i]; - result_names.erase(result_names.begin() + need_remove_dim); - } - } - return result_names; -} - -at::Tensor& var_after_npu_nocheckout( - at::Tensor& var, - const at::Tensor& self, - const at::Tensor& mean_broadcast, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - bool if_std = false; - OpCommand cmd; - cmd.Name("ReduceStdV2Update") - .Input(self) - .Input(mean_broadcast) - .Output(var) - .Attr("dim", dim) - .Attr("if_std", if_std) - .Attr("unbiased", unbiased) - .Attr("keepdim", keepdim) - .Run(); - return var; -} - -tuple var_mean_compute( - at::Tensor& variance, - at::Tensor& mean, - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - auto meanOutputSizeKeepDim = var_npu_output_size(self, dim, true); - auto meanOutputSizeNotKeepDim = var_npu_output_size(self, dim, false); - mean = at::mean(self, dim, false); - mean.resize_(meanOutputSizeKeepDim); - at::Tensor mean_broadcast = NPUNativeFunctions::npu_broadcast(mean, self.sizes()); - if(!keepdim){ - mean.resize_(meanOutputSizeNotKeepDim); - } - var_after_npu_nocheckout(variance, self, mean_broadcast, dim, unbiased, keepdim); - return tuple(variance, mean); -} - -tuple var_mean_out_npu( - at::Tensor& variance, - at::Tensor& mean, - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - auto dim_now = check_and_trans_dim(self, dim); - auto meanOutputSizeKeepDim = var_npu_output_size(self, dim_now, true); - auto meanOutputSizeNotKeepDim = var_npu_output_size(self, dim_now, false); - auto ori_type = self.scalar_type(); - if(ori_type != c10::ScalarType::Half && ori_type != c10::ScalarType::Float) { - AT_ERROR("Var Mean only support float16 or float32 type."); - } - if(variance.scalar_type() != mean.scalar_type() || variance.scalar_type() != ori_type) { - AT_ERROR("mean's type and variance' type must be equal to input's type."); - } - var_mean_compute( - variance, - mean, - self, - dim_now, - unbiased, - keepdim); - - return tuple(variance, mean); -} - -at::Tensor& NPUNativeFunctions::var_out( - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim, - at::Tensor& var) { - // check and trans dim - auto dim_now = check_and_trans_dim(self, dim); - auto outputSize = var_npu_output_size(self, dim_now, keepdim); - - // construct the output mean tensor of the NPU - at::Tensor mean = OpPreparation::ApplyTensor(self, outputSize); - at::Tensor var_ = OpPreparation::ApplyTensor(self, outputSize); - - var_mean_out_npu(var_, mean, self, dim, unbiased, keepdim); - OpPreparation::CheckOut( - {var_}, - var, - var_); - var.copy_(var_); - return var; -} - -at::Tensor& NPUNativeFunctions::var_out( - const at::Tensor& self, - at::DimnameList dim, - bool unbiased, - bool keepdim, - at::Tensor& var) { - return NPUNativeFunctions::var_out( - self, dimnames_to_positions(self, dim), unbiased, keepdim, var); -} - -at::Tensor NPUNativeFunctions::var(const at::Tensor& self, bool unbiased) { - bool keepdim = false; - c10::SmallVector dim = CalcuOpUtil::get_dimlist_for_tensor(self); - - return NPUNativeFunctions::var(self, dim, unbiased, keepdim); -} - -at::Tensor NPUNativeFunctions::var( - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - auto dim_now = check_and_trans_dim(self, dim); - // calculate the output size - auto outputSize = var_npu_output_size(self, dim_now, keepdim); - - // construct the output tensor of the NPU - at::Tensor variance = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - NPUNativeFunctions::var_out(self, dim, unbiased, keepdim, variance); - - return variance; -} - -at::Tensor NPUNativeFunctions::var( - const at::Tensor& self, - at::DimnameList dim, - bool unbiased, - bool keepdim) { - return NPUNativeFunctions::var(self, dimnames_to_positions(self, dim), unbiased, keepdim); -} - -at::Tensor _var_npu(const at::Tensor& self, bool unbiased) { - return at::var(self, unbiased); -} - -tuple NPUNativeFunctions::var_mean( - const at::Tensor& self, - at::DimnameList dim, - bool unbiased, - bool keepdim) { - return NPUNativeFunctions::var_mean(self, dimnames_to_positions(self, dim), unbiased, keepdim); -} - -tuple NPUNativeFunctions::var_mean( - const at::Tensor& self, - at::IntArrayRef dim, - bool unbiased, - bool keepdim) { - auto dim_now = check_and_trans_dim(self, dim); - // calculate the output size - auto outputSize = var_npu_output_size(self, dim_now, keepdim); - - // construct the output tensor of the NPU - at::Tensor variance = OpPreparation::ApplyTensor(self, outputSize); - - at::Tensor mean = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - var_mean_out_npu(variance, mean, self, dim, unbiased, keepdim); - - return tuple(variance, mean); -} - -tuple NPUNativeFunctions::var_mean(const at::Tensor& self, bool unbiased) { - c10::SmallVector dim = CalcuOpUtil::get_dimlist_for_tensor(self); - - return NPUNativeFunctions::var_mean(self, dim, unbiased, false); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/WhereKernelNpu.cpp b/torch_npu/csrc/aten/ops/WhereKernelNpu.cpp deleted file mode 100644 index 7218ac74fd..0000000000 --- a/torch_npu/csrc/aten/ops/WhereKernelNpu.cpp +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies. -// 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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" -#include "torch_npu/csrc/core/NPUBridge.h" - -namespace at_npu { -namespace native { - -std::tuple npu_expand_outplace( - const at::Tensor &to_expand1, - const at::Tensor &to_expand2, - const at::Tensor &to_expand3, - const char *api_name) { - for (auto& t : {to_expand1, to_expand2, to_expand3}) { - if (!t.defined()) { - AT_ERROR(api_name, "(...) called with an undefined Tensor"); - } - } - - if (to_expand1.sizes().equals(to_expand2.sizes()) && to_expand1.sizes().equals(to_expand3.sizes())) { - return std::make_tuple(to_expand1, to_expand2, to_expand3); - } - - auto expanded_size12 = broadcast_ops_npu_output_size(to_expand1, to_expand2); - auto expanded_size = broadcast_ops_npu_output_size(expanded_size12, to_expand3.sizes()); - - return std::make_tuple( - to_expand1.expand(expanded_size, true), - to_expand2.expand(expanded_size, true), - to_expand3.expand(expanded_size, true)); -} - -at::Tensor NPUNativeFunctions::_s_where( - const at::Tensor& condition, - const at::Tensor& self, - const at::Tensor& other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - - OpCommand cmd; - cmd.Name("Select") - .Input(condition) - .Input(self) - .Input(other) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::where( - const at::Tensor& condition, - const at::Tensor& self, - const at::Tensor& other) { - TORCH_CHECK(condition.device() == self.device() && self.device() == other.device(), - "expected condition, x and y to be on the same device, but condition is on ", - condition.device(), " and x and y are on ", self.device(), " and ", other.device(), - " respectively"); - if (condition.scalar_type() != at::ScalarType::Byte && condition.scalar_type() != at::ScalarType::Bool) { - AT_ERROR("Expected condition to have ScalarType Byte, but got ScalarType ", - toString(condition.scalar_type())); - } - at::Tensor b_condition, b_self, b_other; - std::tie(b_condition, b_self, b_other) = npu_expand_outplace(condition, self, other, "where_npu"); - return at::_s_where(b_condition, b_self, b_other); -} - -at::SmallVector where_npu_output_size(const at::Tensor& condition){ - int64_t dim = condition.dim(); - at::Tensor boolSelf = NPUNativeFunctions::npu_dtype_cast(condition, at::ScalarType::Bool); - at::Tensor intSelf = NPUNativeFunctions::npu_dtype_cast(boolSelf, at::ScalarType::Int); - at::Tensor coutNonzeroSelf = at::sum(intSelf, at::ScalarType::Int); - int64_t nonzeroNum = coutNonzeroSelf.item().toInt(); - at::SmallVector outputSize = {nonzeroNum, dim}; - return outputSize; -} - - -vector NPUNativeFunctions::where(const at::Tensor& condition) { - at::Tensor formatCastOfCondition = condition; - if (torch_npu::NPUBridge::GetNpuStorageImpl(condition)->npu_desc_.npu_format_ != - ACL_FORMAT_ND) { - formatCastOfCondition = NPUNativeFunctions::npu_format_cast(formatCastOfCondition, ACL_FORMAT_ND); - } - if (condition.scalar_type() == at::ScalarType::Half) { - formatCastOfCondition = NPUNativeFunctions::npu_dtype_cast(formatCastOfCondition, at::ScalarType::Float); - } - - // calculate the output size - auto outputSize = where_npu_output_size(formatCastOfCondition); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, formatCastOfCondition.options().dtype(at::kLong), ACL_FORMAT_ND); - - OpCommand cmd; - cmd.Name("NonZero") - .Input(formatCastOfCondition) - .Output(result) - .Run(); - result = result.transpose(1, 0); - std::vector chunkResult = result.chunk(result.size(0), 0); - std::vector squeezeResult; - for(int64_t i = 0; i < chunkResult.size(); i++){ - squeezeResult.push_back(chunkResult[i].squeeze(0)); - } - - return squeezeResult; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/XlogyKernelNpu.cpp b/torch_npu/csrc/aten/ops/XlogyKernelNpu.cpp deleted file mode 100644 index fabc0c1a54..0000000000 --- a/torch_npu/csrc/aten/ops/XlogyKernelNpu.cpp +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright (c) 2022 Huawei Technologies Co., Ltd -// Copyright (c) 2022, 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& xlogy_out_npu_nocheck(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Xlogy") - .Input(self) - .Input(other) - .Output(result) - .Run(); - return result; -} - -at::Tensor& xlogy_out_npu_nocheck(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Xlogy") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& xlogy_out_npu_nocheck(at::Scalar& self, const at::Tensor& other, at::Tensor& result) { - OpCommand cmd; - cmd.Name("Xlogy") - .Input(self, other.scalar_type()) - .Input(other) - .Output(result) - .Run(); - return result; -} - - -at::Tensor& NPUNativeFunctions::xlogy_out(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - at::Tensor formatCastOfSelf = OpPreparation::CastBackToOriFormat(self); - at::Tensor formatCastOfOther = OpPreparation::CastBackToOriFormat(other); - auto outputSize = broadcast_ops_npu_output_size(self, other); - OpPreparation::CheckOut( - {self, other}, - result, - CalcuOpUtil::get_tensor_npu_format(formatCastOfSelf), - result.scalar_type(), - outputSize); - xlogy_out_npu_nocheck(formatCastOfSelf, formatCastOfOther, result); - return result; -} - -at::Tensor& NPUNativeFunctions::xlogy_out(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - OpPreparation::CheckOut( - {self}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - self.sizes()); - xlogy_out_npu_nocheck(self, other, result); - return result; -} - -at::Tensor& NPUNativeFunctions::xlogy_out(at::Scalar self, const at::Tensor& other, at::Tensor& result) { - OpPreparation::CheckOut( - {other}, - result, - CalcuOpUtil::get_tensor_npu_format(other), - other.scalar_type(), - other.sizes()); - xlogy_out_npu_nocheck(self, other, result); - return result; -} - -at::Tensor NPUNativeFunctions::xlogy(const at::Tensor& self, const at::Tensor& other) { - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - at::Tensor outputTensor = isSelfWrapped ? other : self; - // calculate the output size - auto outputSize = broadcast_ops_npu_output_size(self, other); - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, - outputTensor.options(), - CalcuOpUtil::get_tensor_npu_format(outputTensor)); - // calculate the output result of the NPU - xlogy_out_npu_nocheck(self, other, result); - return result; -} - -at::Tensor NPUNativeFunctions::xlogy(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - xlogy_out_npu_nocheck(self, other, result); - return result; - -} - -at::Tensor NPUNativeFunctions::xlogy(at::Scalar self, const at::Tensor& other) { - at::Tensor result = OpPreparation::ApplyTensor(other); - xlogy_out_npu_nocheck(self, other, result); - return result; -} - - -at::Tensor& NPUNativeFunctions::xlogy_(at::Tensor& self, const at::Tensor& other) { - c10::SmallVector inputs = {self, other}; - c10::SmallVector outputs = {self}; - CalcuOpUtil::check_memory_over_laps(inputs, outputs); - if (!NpuUtils::check_match(&self)) - { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = xlogy_out_npu_nocheck(contiguousSelf, other, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } - else - { - xlogy_out_npu_nocheck(self, other, self); - } - return self; -} - -at::Tensor& NPUNativeFunctions::xlogy_(at::Tensor& self, at::Scalar other) { - if (!NpuUtils::check_match(&self)) - { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = xlogy_out_npu_nocheck(contiguousSelf, other, result); - NpuUtils::format_fresh_view(self, result); - } - else - { - xlogy_out_npu_nocheck(self, other, self); - } - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/YoloBoxesEncodeKernelNpu.cpp b/torch_npu/csrc/aten/ops/YoloBoxesEncodeKernelNpu.cpp deleted file mode 100644 index c3263a8190..0000000000 --- a/torch_npu/csrc/aten/ops/YoloBoxesEncodeKernelNpu.cpp +++ /dev/null @@ -1,76 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -static inline void yolo_boxes_encode_check( - const at::Tensor& anchor_boxes, - const at::Tensor& gt_bboxes, - const at::Tensor& stride){ - TORCH_CHECK( - anchor_boxes.dim() == 2 && anchor_boxes.size(1) == 4, - "Non-empty 2D anchor_boxes tensor expected but got a tensor with sizes ", - anchor_boxes.sizes()); - TORCH_CHECK( - anchor_boxes.size(0) <= 20480, - "anchor_boxes only support max [20480] num, but got num ", - anchor_boxes.size(0)); - TORCH_CHECK( - gt_bboxes.dim() == 2 && gt_bboxes.size(1) == 4, - "Non-empty 2D gt_bboxes tensor expected but got a tensor with sizes ", - gt_bboxes.sizes()); - TORCH_CHECK( - stride.dim() == 1, - "Non-empty 1D stride tensor expected but got a tensor with sizes ", - stride.sizes()); - TORCH_CHECK( - stride.size(0) == gt_bboxes.size(0), - "stride's length should be equal gt_bboxes' num, but got stride length ", - stride.size(0), - "gt_bboxes num ", - gt_bboxes.size(0)); - TORCH_CHECK( - at::isIntegralType(stride.scalar_type(), true) && stride.scalar_type() != at::ScalarType::Long, - "int32 strdie tensor expected but got a tensor with dtype: ", - stride.scalar_type()); -} - -at::Tensor NPUNativeFunctions::npu_yolo_boxes_encode( - const at::Tensor& anchor_boxes, - const at::Tensor& gt_bboxes, - const at::Tensor& stride, - bool performance_mode){ - yolo_boxes_encode_check(anchor_boxes, gt_bboxes, stride); - at::Tensor result = OpPreparation::ApplyTensor(gt_bboxes); - string implModeStr = performance_mode ? "high_performance" : "high_precision"; - at::Tensor strideCp = NPUNativeFunctions::npu_dtype_cast(stride, at::ScalarType::Int); - OpCommand cmd; - cmd.Name("YoloBoxesEncode") - .Input(anchor_boxes) - .Input(gt_bboxes) - .Input(strideCp) - .Output(result) - .Attr("performance_mode", implModeStr) - .Run(); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ZerosKernelNpu.cpp b/torch_npu/csrc/aten/ops/ZerosKernelNpu.cpp deleted file mode 100644 index 173ec56102..0000000000 --- a/torch_npu/csrc/aten/ops/ZerosKernelNpu.cpp +++ /dev/null @@ -1,52 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::zeros_out(at::IntArrayRef size, at::Tensor& result) { - result.resize_(size); - return result.zero_(); -} - -at::Tensor NPUNativeFunctions::zeros(at::IntArrayRef size, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - at::TensorOptions option = option.dtype(dtype_opt) - .layout(layout_opt) - .device(device_opt) - .pinned_memory(pin_memory_opt); - at::Tensor result = OpPreparation::ApplyTensorWithFormat(size, option, ACL_FORMAT_ND); - return result.zero_(); -} - -at::Tensor NPUNativeFunctions::zeros( - at::IntArrayRef size, - c10::optional names, - c10::optional dtype_opt, - c10::optional layout_opt, - c10::optional device_opt, - c10::optional pin_memory_opt) { - return NPUNativeFunctions::zeros(size, dtype_opt, layout_opt, device_opt, pin_memory_opt); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/ZerosLikeKernelNpu.cpp b/torch_npu/csrc/aten/ops/ZerosLikeKernelNpu.cpp index aa107b2d45..7f0c2fc60b 100644 --- a/torch_npu/csrc/aten/ops/ZerosLikeKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/ZerosLikeKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -34,7 +34,7 @@ namespace at_npu return result; } - at::Tensor NPUNativeFunctions::zeros_like( + at::Tensor XLANativeFunctions::zeros_like( const at::Tensor &self, c10::optional dtype_opt, c10::optional layout_opt, @@ -56,7 +56,7 @@ namespace at_npu auto outputSize = input_same_output_size(self); // construct the output tensor of the NPU - at::Tensor result = NPUNativeFunctions::empty_with_format( + at::Tensor result = XLANativeFunctions::empty_with_format( outputSize, dtype_opt, layout_opt, device_opt, pin_memory_opt, CalcuOpUtil::get_tensor_npu_format(self)); @@ -64,7 +64,7 @@ namespace at_npu return result.zero_(); } - at::Tensor &NPUNativeFunctions::zero_(at::Tensor &self) + at::Tensor &XLANativeFunctions::zero_(at::Tensor &self) { if (!NpuUtils::check_match(&self)) { diff --git a/torch_npu/csrc/aten/ops/_Unique2KernelNpu.cpp b/torch_npu/csrc/aten/ops/_Unique2KernelNpu.cpp deleted file mode 100644 index e8dedb6a52..0000000000 --- a/torch_npu/csrc/aten/ops/_Unique2KernelNpu.cpp +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple _unique2_out_npu( - at::Tensor& y, - at::Tensor& yOutputSize, - at::Tensor& yInverse, - at::Tensor& yCounts, - const at::Tensor& self, - bool sorted, - bool return_inverse, - bool return_counts) { - OpCommand cmd; - cmd.Name("UniqueWithCountsAndSorting") - .Input(self) - .Output(y) - .Output(yOutputSize) - .Output(yInverse) - .Output(yCounts) - .Attr("sorted", sorted) - .Attr("return_inverse", true) - .Attr("return_counts", true) - .Run(); - - return std::tuple(y, yOutputSize, yInverse, yCounts); -} - -tuple NPUNativeFunctions::_unique2( - const at::Tensor& self, - bool sorted, - bool return_inverse, - bool return_counts) { - if (self.numel() == 0) { - at::Tensor result= OpPreparation::ApplyTensor(self, {0}); - at::Tensor yInverse = OpPreparation::ApplyTensor({0}, self.options().dtype(at::kLong), self); - at::Tensor yCounts = OpPreparation::ApplyTensor({0}, self.options().dtype(at::kLong), self); - return std::tie(result, yInverse, yCounts); - } - - auto yInverseSize = input_same_output_size(self); - auto outputSizes = tuple, c10::SmallVector, at::IntArrayRef>( - {self.numel()}, {1}, yInverseSize); - - at::Tensor selfCopy = self; - if (self.scalar_type() == at::ScalarType::Half) { - selfCopy = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Float); - } - - at::Tensor y = OpPreparation::ApplyTensor(selfCopy, std::get<0>(outputSizes)); - at::Tensor yOutputSize = OpPreparation::ApplyTensorWithFormat(std::get<1>(outputSizes), self.options().dtype(at::kLong), ACL_FORMAT_ND); - at::Tensor yInverse = OpPreparation::ApplyTensorWithFormat(std::get<2>(outputSizes), self.options().dtype(at::kLong), ACL_FORMAT_ND); - at::Tensor yCounts = OpPreparation::ApplyTensorWithFormat(std::get<0>(outputSizes), self.options().dtype(at::kLong), ACL_FORMAT_ND); - - _unique2_out_npu(y, yOutputSize, yInverse, yCounts, selfCopy, sorted, return_inverse, return_counts); - - int64_t count = yOutputSize[0].item().toLong(); - at::Tensor result = y.slice(0, 0, count, 1); - result = NpuUtils::format_contiguous(result); - - if (self.scalar_type() == at::ScalarType::Half) { - result = NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Half); - } - - if (return_counts) { - yCounts = yCounts.slice(0, 0, count, 1); - yCounts = NpuUtils::format_contiguous(yCounts); - } else { - yCounts = at::empty({0}, self.options().dtype(at::kLong)); - } - - if (!(return_counts || return_inverse)) { - yInverse = at::empty({0}, self.options().dtype(at::kLong)); - } - - return std::tuple(result, yInverse, yCounts); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/__And__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__And__KernelNpu.cpp deleted file mode 100644 index 88313179e2..0000000000 --- a/torch_npu/csrc/aten/ops/__And__KernelNpu.cpp +++ /dev/null @@ -1,88 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor and_dest_output(const at::Tensor& self, const at::Tensor& other) { - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - - if (not isSelfWrapped) { - return self; - } else { - return other; - } -} - -at::Tensor& and_out_npu_nocheck( - const at::Tensor& self, - const at::Scalar other, - at::Tensor& result) { - OpCommand cmd; - cmd.Name((self.scalar_type() == at::ScalarType::Bool) ? "LogicalAnd" : "BitwiseAnd") - .Input(self) - .Input(other,self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& and_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) { - and_out_npu_nocheck(self, other.item(),result); - } else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) { - and_out_npu_nocheck(other, self.item(),result); - } else { - OpCommand cmd; - cmd.Name((self.scalar_type() == at::ScalarType::Bool) ? "LogicalAnd" : "BitwiseAnd") - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - - return result; -} - -at::Tensor NPUNativeFunctions::__and__(const at::Tensor& self, const at::Tensor& other) { - // calculate the output size - at::Tensor outputTensor = and_dest_output(self, other); - auto outputSize = broadcast_ops_npu_output_size(self, other); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(outputTensor, outputSize); - // calculate the output result of the NPU - and_out_npu_nocheck(self, other,result); - return result; -} - -at::Tensor NPUNativeFunctions::__and__(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - and_out_npu_nocheck(self, other,result); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/__Ior__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__Ior__KernelNpu.cpp deleted file mode 100644 index 978ec7e8c6..0000000000 --- a/torch_npu/csrc/aten/ops/__Ior__KernelNpu.cpp +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& ior_out_npu_nocheck(const at::Tensor& self, const at::Tensor& other, at::Tensor& result) { - string real_op_name = (self.dtype() == at::ScalarType::Bool) ? "LogicalOr" : "BitwiseOr"; - OpCommand cmd; - cmd.Name(real_op_name) - .Input(self) - .Input(other) - .Output(result) - .Run(); - return result; -} - -at::Tensor& ior_out_npu_nocheck(const at::Tensor& self, at::Scalar other, at::Tensor& result) { - string real_op_name = (self.dtype() == at::ScalarType::Bool) ? "LogicalOr" : "BitwiseOr"; - OpCommand cmd; - cmd.Name(real_op_name) - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::__ior__(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other}, {self}); - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = ior_out_npu_nocheck(contiguousSelf, other, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - ior_out_npu_nocheck(self, other, self); - } - return self; -} - -at::Tensor& NPUNativeFunctions::__ior__(at::Tensor& self, at::Scalar other) { - if (!NpuUtils::check_match(&self)) { - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - at::Tensor result = ior_out_npu_nocheck(contiguousSelf, other, contiguousSelf); - NpuUtils::format_fresh_view(self, result); - } else { - ior_out_npu_nocheck(self, other, self); - } - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/__Lshift__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__Lshift__KernelNpu.cpp deleted file mode 100644 index 02860791f8..0000000000 --- a/torch_npu/csrc/aten/ops/__Lshift__KernelNpu.cpp +++ /dev/null @@ -1,63 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& lshift_out_npu_nocheck( - const at::Tensor& self, - at::Scalar other, - at::Tensor& result) { - at::Tensor otherBroadcast = at::empty(self.sizes(), self.options()).fill_(other); - OpCommand cmd; - cmd.Name("LeftShift") - .Input(self) - .Input(otherBroadcast) - .Output(result) - .Run(); - return result; -} - -at::Tensor& lshift_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - at::Tensor otherBroadcast = other.expand(self.sizes()); - OpCommand cmd; - cmd.Name("LeftShift") - .Input(self) - .Input(otherBroadcast) - .Output(result) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::__lshift__(const at::Tensor& self, const at::Tensor& other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - lshift_out_npu_nocheck(self, other, result); - return result; -} - -at::Tensor NPUNativeFunctions::__lshift__(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - lshift_out_npu_nocheck(self, other, result); - return result; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/__Or__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__Or__KernelNpu.cpp deleted file mode 100644 index 686ebecd15..0000000000 --- a/torch_npu/csrc/aten/ops/__Or__KernelNpu.cpp +++ /dev/null @@ -1,87 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor or___dest_output(const at::Tensor& self, const at::Tensor& other) { - bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self); - - if (isSelfWrapped) { - return other; - } else { - return self; - } -} - -at::Tensor& or___out_scalar_npu(at::Tensor& result, const at::Tensor& self, at::Scalar other) { - string real_op_name = - (self.dtype() == at::ScalarType::Bool) ? "LogicalOr" : "BitwiseOr"; - OpCommand cmd; - cmd.Name(real_op_name) - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& or___out_tensor_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& other) { - if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) { - or___out_scalar_npu(result, self, other.item()); - } else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) { - or___out_scalar_npu(result, other, self.item()); - } else { - - string real_op_name = - (self.dtype() == at::ScalarType::Bool) ? "LogicalOr" : "BitwiseOr"; - OpCommand cmd; - cmd.Name(real_op_name) - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - - return result; -} - -at::Tensor NPUNativeFunctions::__or__(const at::Tensor& self, const at::Tensor& other) { - at::Tensor outputTensor = or___dest_output(self, other); - auto outputSize = broadcast_ops_npu_output_size(self, other); - at::Tensor result = OpPreparation::ApplyTensor(outputTensor, outputSize); - or___out_tensor_npu(result, self, other); - - return result; -} - -at::Tensor NPUNativeFunctions::__or__(const at::Tensor& self, at::Scalar other) { - at::Tensor result = OpPreparation::ApplyTensor(self); - or___out_scalar_npu(result, self, other); - - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/__Rshift__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__Rshift__KernelNpu.cpp deleted file mode 100644 index 954ac65d50..0000000000 --- a/torch_npu/csrc/aten/ops/__Rshift__KernelNpu.cpp +++ /dev/null @@ -1,69 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& rshift_out_npu_nocheck( - const at::Tensor& self, - at::Scalar other, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("RightShift") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& rshift_out_npu_nocheck( - const at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("RightShift") - .Input(self) - .Input(other) - .Output(result) - .Run(); - - return result; -} - -at::Tensor NPUNativeFunctions::__rshift__(const at::Tensor& self, const at::Tensor& other) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - rshift_out_npu_nocheck(self, other,result); - - return result; -} - -at::Tensor NPUNativeFunctions::__rshift__(const at::Tensor& self, at::Scalar other) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - - rshift_out_npu_nocheck(self, other, result); - - return result; -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/__Xor__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__Xor__KernelNpu.cpp deleted file mode 100644 index 0284884505..0000000000 --- a/torch_npu/csrc/aten/ops/__Xor__KernelNpu.cpp +++ /dev/null @@ -1,165 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& not_out_npu(at::Tensor& result, const at::Tensor& self) { - OpCommand cmd; - cmd.Name("LogicalNot") - .Input(self) - .Output(result) - .Run(); - return result; -} - -at::Tensor& not_out_npu(at::Tensor& result, const at::Scalar self) { - OpCommand cmd; - cmd.Name("LogicalNot") - .Input(self, self.type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& and_out_npu(at::Tensor& result, const at::Tensor& self, const at::Tensor& other) { - OpCommand cmd; - cmd.Name("LogicalAnd") - .Input(self) - .Input(other) - .Output(result) - .Run(); - return result; -} - -at::Tensor& and_out_npu(at::Tensor& result, const at::Tensor& self, const at::Scalar other) { - OpCommand cmd; - cmd.Name("LogicalAnd") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& or_out_npu(at::Tensor& result, const at::Tensor& self, const at::Scalar other) { - OpCommand cmd; - cmd.Name("LogicalOr") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& xor_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& other) { - auto outputSize = broadcast_ops_npu_output_size(self, other); - // executing the NPU operator - if (self.dtype() == at::ScalarType::Bool) { - auto not_self_result = OpPreparation::ApplyTensor(self, outputSize); - not_out_npu(not_self_result, self); - - auto not_other_result = OpPreparation::ApplyTensor(self, outputSize); - not_out_npu(not_other_result, other); - - auto not_self_and_other = OpPreparation::ApplyTensor(self, outputSize); - and_out_npu(not_self_and_other, not_self_result, other); - - auto self_and_not_other = OpPreparation::ApplyTensor(self, outputSize); - and_out_npu(self_and_not_other, self, not_other_result); - - OpCommand cmd; - cmd.Name("LogicalOr") - .Input(not_self_and_other) - .Input(self_and_not_other) - .Output(result) - .Run(); - } else { - OpCommand cmd; - cmd.Name("BitwiseXor") - .Input(self) - .Input(other) - .Output(result) - .Run(); - } - - return result; -} - -at::Tensor& xor_out_npu( - at::Tensor& result, - const at::Tensor& self, - const at::Scalar other) { - // executing the NPU operator - if (self.dtype() == at::ScalarType::Bool) { - auto not_self_result = OpPreparation::ApplyTensor(self); - not_out_npu(not_self_result, self); - - auto not_self_or_other = OpPreparation::ApplyTensor(self); - or_out_npu(not_self_or_other, not_self_result, other); - - auto not_not_self_or_other = OpPreparation::ApplyTensor(self); - not_out_npu(not_not_self_or_other, not_self_or_other); - - auto not_self_and_other = OpPreparation::ApplyTensor(self); - and_out_npu(not_self_and_other, not_self_result, other); - - OpCommand cmd; - cmd.Name("LogicalOr") - .Input(not_self_and_other) - .Input(not_not_self_or_other) - .Output(result) - .Run(); - - } else { - OpCommand cmd; - cmd.Name("BitwiseXor") - .Input(self) - .Input(other, self.scalar_type()) - .Output(result) - .Run(); - } - - return result; -} - -at::Tensor NPUNativeFunctions::__xor__(const at::Tensor& self, const at::Tensor& other) { - // calculate the output size - auto outputSize = broadcast_ops_npu_output_size(self, other); - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - // calculate the output result of the NPU - xor_out_npu(result, self, other); - return result; -} - -at::Tensor NPUNativeFunctions::__xor__(const at::Tensor& self, const at::Scalar other) { - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self); - - // calculate the output result of the NPU - xor_out_npu(result, self, other); - - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/__iLshift__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__iLshift__KernelNpu.cpp deleted file mode 100644 index baeb07553f..0000000000 --- a/torch_npu/csrc/aten/ops/__iLshift__KernelNpu.cpp +++ /dev/null @@ -1,78 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& ilshift_out_npu( - at::Tensor& result, - at::Tensor& self, - at::Scalar other) { - at::Tensor otherBroadcast = OpPreparation::ApplyTensor(self).fill_(other); - OpCommand cmd; - cmd.Name("LeftShift") - .Input(self) - .Input(otherBroadcast) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& ilshift_out_npu( - at::Tensor& result, - at::Tensor& self, - const at::Tensor& other) { - at::Tensor otherBroadcast = other.expand(self.sizes()); - OpCommand cmd; - cmd.Name("LeftShift") - .Input(self) - .Input(otherBroadcast) - .Output(result) - .Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::__ilshift__(at::Tensor& self, const at::Tensor& other) { - if(!NpuUtils::check_match(&self)){ - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - ilshift_out_npu(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, contiguousSelf); - } else { - ilshift_out_npu(self, self, other); - } - - return self; -} - -at::Tensor& NPUNativeFunctions::__ilshift__(at::Tensor& self, at::Scalar other) { - if(!NpuUtils::check_match(&self)){ - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - ilshift_out_npu(contiguousSelf, contiguousSelf, other); - NpuUtils::format_fresh_view(self, contiguousSelf); - } else { - ilshift_out_npu(self, self, other); - } - - return self; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/__iRshift__KernelNpu.cpp b/torch_npu/csrc/aten/ops/__iRshift__KernelNpu.cpp deleted file mode 100644 index 0dec63b5ff..0000000000 --- a/torch_npu/csrc/aten/ops/__iRshift__KernelNpu.cpp +++ /dev/null @@ -1,72 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& irshift_out_npu_nocheck( - at::Tensor& self, - at::Scalar other, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("RightShift") - .Input(self) - .Input(other,self.scalar_type()) - .Output(result) - .Run(); - return result; -} - -at::Tensor& irshift_out_npu_nocheck( - at::Tensor& self, - const at::Tensor& other, - at::Tensor& result) { - OpCommand cmd; - cmd.Name("RightShift") - .Input(self) - .Input(other) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::__irshift__(at::Tensor& self, const at::Tensor& other) { - OpPreparation::CheckMemory({self, other}, {self}); - if(!NpuUtils::check_match(&self)){ - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - irshift_out_npu_nocheck(contiguousSelf, other, contiguousSelf); - NpuUtils::format_fresh_view(self, contiguousSelf); - } else { - irshift_out_npu_nocheck(self, other, self); - } - return self; -} - -at::Tensor& NPUNativeFunctions::__irshift__(at::Tensor& self, at::Scalar other) { - if(!NpuUtils::check_match(&self)){ - at::Tensor contiguousSelf = NpuUtils::format_contiguous(self); - irshift_out_npu_nocheck(contiguousSelf, other, contiguousSelf); - NpuUtils::format_fresh_view(self, contiguousSelf); - } else { - irshift_out_npu_nocheck(self, other, self); - } - return self; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/convolution/Conv2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/Conv2dBackwardKernelNpu.cpp index d91782324a..82b6e68422 100644 --- a/torch_npu/csrc/aten/ops/convolution/Conv2dBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/convolution/Conv2dBackwardKernelNpu.cpp @@ -18,7 +18,7 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -79,9 +79,9 @@ at::Tensor conv2d_backward_input_out_npu( OpCommand cmd; cmd.Name("Conv2DBackpropInput") .Input(dimList, at::kInt) - .Input(weight, "filter", ACL_FORMAT_NCHW) - .Input(grad, "out_backprop", ACL_FORMAT_NCHW) - .Output(gradInput, "y", ACL_FORMAT_NCHW) + .Input(weight) + .Input(grad) + .Output(gradInput) .Attr("strides", stridesSize) .Attr("pads", paddings) .Attr("dilations", dilations) @@ -129,10 +129,10 @@ at::Tensor conv2d_backward_weight_out_npu( // executing the NPU operator OpCommand cmd; cmd.Name("Conv2DBackpropFilter") - .Input(input, "x", ACL_FORMAT_NCHW) + .Input(input) .Input(dimList, at::kInt) - .Input(grad, "out_backprop", ACL_FORMAT_NCHW) - .Output(gradWeight, "y", ACL_FORMAT_NCHW) + .Input(grad) + .Output(gradWeight) .Attr("strides", stridesSize) .Attr("pads", paddings) .Attr("dilations", dilations) @@ -195,7 +195,7 @@ tuple conv2d_backward_out_npu( return tuple(gradInput, gradWeight, gradBias); } -tuple NPUNativeFunctions::npu_conv2d_backward( +tuple XLANativeFunctions::npu_conv2d_backward( const at::Tensor& input, const at::Tensor& grad, const at::Tensor& weight, diff --git a/torch_npu/csrc/aten/ops/convolution/Conv2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/Conv2dKernelNpu.cpp index e178b4b4a7..5b5e75f1bd 100644 --- a/torch_npu/csrc/aten/ops/convolution/Conv2dKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/convolution/Conv2dKernelNpu.cpp @@ -18,7 +18,7 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -45,7 +45,7 @@ bool isSpecialConv1d( } // isSpecialConv1d } // namespace -at::Tensor& NPUNativeFunctions::npu_conv2d_out( +at::Tensor& XLANativeFunctions::npu_conv2d_out( const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias_opt, @@ -63,12 +63,12 @@ at::Tensor& NPUNativeFunctions::npu_conv2d_out( c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; OpCommand cmd; cmd.Name("Conv2D") - .Input(input, "x", ACL_FORMAT_NCHW) - .Input(weight, "filter", ACL_FORMAT_NCHW); + .Input(input) + .Input(weight); if (bias.defined()) { cmd.Input(bias); } - cmd.Output(result, "y", ACL_FORMAT_NCHW) + cmd.Output(result) .Attr("strides", stridesSize) .Attr("pads", paddings) .Attr("dilations", dilations) @@ -79,7 +79,7 @@ at::Tensor& NPUNativeFunctions::npu_conv2d_out( return result; } -at::Tensor NPUNativeFunctions::npu_conv2d( +at::Tensor XLANativeFunctions::npu_conv2d( const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias, @@ -115,7 +115,7 @@ at::Tensor NPUNativeFunctions::npu_conv2d( // construct the output tensor of the NPU at::Tensor result = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_NC1HWC0); // calculate the output result of the NPU - NPUNativeFunctions::npu_conv2d_out(input, weight, bias, stride, padding, dilation, groups, result); + XLANativeFunctions::npu_conv2d_out(input, weight, bias, stride, padding, dilation, groups, result); return result; } diff --git a/torch_npu/csrc/aten/ops/convolution/Conv3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/Conv3dBackwardKernelNpu.cpp deleted file mode 100644 index b38ef864a0..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/Conv3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,139 +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. - -#include -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -at::Tensor conv3d_backward_inputmask(at::Tensor &gradInput, const at::Tensor &input, - const at::Tensor &grad, const at::Tensor &weight, - at::IntArrayRef stride, at::IntArrayRef padding, - at::IntArrayRef dilation, int64_t groups) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1], stride[2]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], - padding[1], padding[2], padding[2]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1], dilation[2]}; - at::IntArrayRef inputSize = input.sizes(); - at::Tensor weightCast = weight.to(grad.dtype()); - - OpCommand cmd; - cmd.Name("Conv3DBackpropInput") - .Input(inputSize, at::kInt) - .Input(weightCast) - .Input(grad) - .Output(gradInput) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", (string) "NCDHW") - .Run(); - return gradInput; -} - -at::Tensor conv3d_backward_weightmask(at::Tensor &gradWeight, const at::Tensor &input, - const at::Tensor &grad, const at::Tensor &weight, - at::IntArrayRef stride, at::IntArrayRef padding, - at::IntArrayRef dilation, int64_t groups) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1], stride[2]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], - padding[1], padding[2], padding[2]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1], dilation[2]}; - at::IntArrayRef inputSize = weight.sizes(); - - OpCommand cmd; - cmd.Name("Conv3DBackpropFilter") - .Input(input) - .Input(inputSize, at::kInt) - .Input(grad) - .Output(gradWeight) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", (string) "NCDHW") - .Run(); - - return gradWeight; -} - -at::Tensor conv3d_backward_biasmask(at::Tensor &gradBias, const at::Tensor &input, - const at::Tensor &grad, const at::Tensor &weight, - at::IntArrayRef stride, at::IntArrayRef padding, - at::IntArrayRef dilation, int64_t groups) { - // constructs the input and output NPUTensorDesc - if (input.numel() == input.size(0) * input.size(1) * input.size(2)) { - at::Tensor gradView = - grad.contiguous().view({grad.size(0), grad.size(1), grad.size(2)}); - at::sum_out(gradBias, gradView, c10::SmallVector{0}); - } else { - at::Tensor gradView = - grad.contiguous().view({grad.size(0), grad.size(1), grad.size(2), -1}); - at::sum_out(gradBias, gradView, c10::SmallVector{0, 2, 3}); - } - - return gradBias; -} - -// interface -tuple NPUNativeFunctions::npu_conv3d_backward( - const at::Tensor &input, const at::Tensor &grad, - const at::Tensor &weight, at::IntArrayRef stride, - at::IntArrayRef padding, at::IntArrayRef dilation, - int64_t groups, std::array grad_input_mask) { - - at::Tensor gradInput; - at::Tensor gradWeight; - at::Tensor gradBias; - - if (grad_input_mask[0]) { - // format should be NDC1HWC0 - gradInput = OpPreparation::ApplyTensorWithFormat( - input.sizes(), input.options(), ACL_FORMAT_NDC1HWC0); - - conv3d_backward_inputmask( - gradInput, input, grad, weight, stride, padding, dilation, groups); - } - - if (grad_input_mask[1]) { - // format should be FRACTAL_Z_3D - gradWeight = OpPreparation::ApplyTensorWithFormat( - weight.sizes(), weight.options().dtype(at::kFloat), ACL_FRACTAL_Z_3D); - - conv3d_backward_weightmask( - gradWeight, input, grad, weight, stride, padding, dilation, groups); - } - - if (grad_input_mask[2]) { - // format should be NCHW, gradias.size = grad.size(1) - gradBias = OpPreparation::ApplyTensorWithFormat( - {grad.size(1)}, grad.options(), ACL_FORMAT_NCHW); - - conv3d_backward_biasmask( - gradBias, input, grad, weight, stride, padding, dilation, groups); - } - - return std::make_tuple(gradInput, gradWeight, gradBias); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/convolution/Conv3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/Conv3dKernelNpu.cpp deleted file mode 100644 index d793f3a46f..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/Conv3dKernelNpu.cpp +++ /dev/null @@ -1,278 +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. - -#include -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -c10::SmallVector conv3d_npu_output_size( - const at::Tensor &input, const at::Tensor &weight, - const at::Tensor &bias, at::IntArrayRef stride, - at::IntArrayRef padding, at::IntArrayRef dilation, - int64_t groups) { - int64_t N = input.size(0); - int64_t D = input.size(2); - int64_t H = input.size(3); - int64_t W = input.size(4); - int64_t Co = weight.size(0); - auto kernel_size = weight.sizes().slice(2); - int64_t Do = - (D + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) / stride[0] + 1; - int64_t Ho = - (H + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1) - 1) / stride[1] + 1; - int64_t Wo = - (W + 2 * padding[2] - dilation[2] * (kernel_size[2] - 1) - 1) / stride[2] + 1; - - c10::SmallVector outputSize = {N, Co, Do, Ho, Wo}; - - return outputSize; -} - -at::Tensor &conv3d_out_npu_nocheck(at::Tensor &result, const at::Tensor &input, - const at::Tensor &weight, const at::Tensor &bias, - at::IntArrayRef stride, at::IntArrayRef padding, - at::IntArrayRef dilation, int64_t groups) { - at::Tensor filter = weight.to(input.dtype()); - c10::SmallVector inputTensor = {input, filter, bias}; - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1], stride[2]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], - padding[1], padding[2], padding[2]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1], dilation[2]}; - - OpCommand cmd; - cmd.Name("Conv3D"); - cmd.Input(input); - cmd.Input(filter); - if (bias.defined()) { - cmd.Input(bias); - } - cmd.Output(result); - cmd.Attr("strides", stridesSize); - cmd.Attr("pads", paddings); - cmd.Attr("dilations", dilations); - cmd.Attr("groups", groups); - cmd.Attr("data_format", (string) "NCDHW"); - cmd.Run(); - - return result; -} - -at::Tensor& NPUNativeFunctions::npu_conv3d_out(const at::Tensor &input, - const at::Tensor &weight, - const c10::optional &bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups, - at::Tensor &result) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = conv3d_npu_output_size( - input, weight, bias, stride, padding, dilation, groups); - OpPreparation::CheckOut( - {input, weight, bias}, - result, - input, - outputSize); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({input, weight, bias}, {result}) - .Func([&input, &weight, &bias, stride, padding, dilation, groups](at::Tensor &result) { - conv3d_out_npu_nocheck( - result, input, weight, bias, stride, padding, dilation, groups); - }) - .Call(result); -} - -at::Tensor NPUNativeFunctions::npu_conv3d(const at::Tensor &input, - const at::Tensor &weight, const c10::optional &bias_opt, - at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, - int64_t groups) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - - auto outputSize = conv3d_npu_output_size( - input, weight, bias, stride, padding, dilation, groups); - - at::Tensor result = OpPreparation::ApplyTensor(input, outputSize); - conv3d_out_npu_nocheck(result, input, weight, bias, stride, padding, dilation, groups); - - return result; -} - -tuple, c10::SmallVector> slow_conv3d_npu_output_size( - const at::Tensor &input, - const at::Tensor &weight, - const at::Tensor &bias, - at::IntArrayRef stride, - at::IntArrayRef padding) { - int64_t N = input.size(0); - int64_t C = input.size(1); - int64_t D = input.size(2); - int64_t H = input.size(3); - int64_t W = input.size(4); - int64_t Co = weight.size(0); - auto kernel_size = weight.sizes().slice(2); - int64_t Do = - (D + 2 * padding[0] - (kernel_size[0])) / stride[0] + 1; - int64_t Ho = - (H + 2 * padding[1] - (kernel_size[1])) / stride[1] + 1; - int64_t Wo = - (W + 2 * padding[2] - (kernel_size[2])) / stride[2] + 1; - - c10::SmallVector outputSize = {N, Co, Do, Ho, Wo}; - c10::SmallVector finputSize = { - N, C * kernel_size[0] * kernel_size[1] * kernel_size[2], Do * Ho * Wo}; - - return tuple, c10::SmallVector>(outputSize, finputSize); -} - -std::tuple slow_conv3d_forward_npu_nocheck( - const at::Tensor& input, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional & bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& output, - at::Tensor& finput, - at::Tensor& fgrad_input) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - at::Tensor filter = weight.to(input.dtype()); - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1], stride[2]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], - padding[1], padding[2], padding[2]}; - c10::SmallVector dilations = {1, 1, 1, 1, 1}; - - OpCommand cmd; - cmd.Name("Conv3D"); - cmd.Input(input); - cmd.Input(filter); - if (bias.defined()) { - cmd.Input(bias); - } - cmd.Output(output); - cmd.Attr("strides", stridesSize); - cmd.Attr("pads", paddings); - cmd.Attr("dilations", dilations); - cmd.Attr("data_format", (string) "NCDHW"); - cmd.Run(); - - return std::tuple(output, finput, fgrad_input); -} - -std::tuple NPUNativeFunctions::slow_conv3d_forward_out( - const at::Tensor& input, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional & bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& output, - at::Tensor& finput, - at::Tensor& fgrad_input) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = slow_conv3d_npu_output_size( - input, weight, bias, stride, padding); - OpPreparation::CheckOut( - {input, weight, bias}, - output, - input, - std::get<0>(outputSize)); - slow_conv3d_forward_npu_nocheck( - input, - weight, - kernel_size, - bias_opt, - stride, - padding, - output, - finput, - fgrad_input); - return std::tuple(output, finput, fgrad_input); -} - -at::Tensor& NPUNativeFunctions::slow_conv3d_out( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional & bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& output) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = slow_conv3d_npu_output_size( - self, weight, bias, stride, padding); - at::Tensor finput = OpPreparation::ApplyTensor(self, std::get<1>(outputSize)); - at::Tensor fgrad_input = at::empty({0}, self.options()); - - return std::get<0>(slow_conv3d_forward_npu_nocheck( - self, - weight, - kernel_size, - bias, - stride, - padding, - output, - finput, - fgrad_input)); -} - -std::tuple NPUNativeFunctions::slow_conv3d_forward( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - auto outputSize = slow_conv3d_npu_output_size( - self, weight, bias, stride, padding); - auto output = OpPreparation::ApplyTensorWithFormat(self, std::get<0>(outputSize), ACL_FORMAT_NDC1HWC0); - auto finput = OpPreparation::ApplyTensorWithSizes({0}, self.options()); - auto fgrad_input = OpPreparation::ApplyTensorWithSizes({0}, self.options()); - - - slow_conv3d_forward_npu_nocheck( - self, - weight, - kernel_size, - bias_opt, - stride, - padding, - output, - finput, - fgrad_input); - - return std::tuple(output, finput, fgrad_input); -} - -at::Tensor NPUNativeFunctions::slow_conv3d( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional & bias, - at::IntArrayRef stride, - at::IntArrayRef padding) { - return std::get<0>(NPUNativeFunctions::slow_conv3d_forward( - self, weight, kernel_size, bias, stride, padding)); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/convolution/ConvTbcBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ConvTbcBackwardKernelNpu.cpp deleted file mode 100644 index efecebd87d..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/ConvTbcBackwardKernelNpu.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -tuple NPUNativeFunctions::conv_tbc_backward( - const at::Tensor& self, - const at::Tensor& input, - const at::Tensor& weight, - const at::Tensor& bias, - int64_t pad) { - // construct the output tensor of the NPU - auto output = NPUNativeFunctions::npu_conv2d_backward( - input.permute({1, 2, 0}).unsqueeze(2), - self.permute({1, 2, 0}).unsqueeze(2), - weight.permute({2, 1, 0}).unsqueeze(2), - {1, 1}, - {0, pad}, - {1, 1}, - 1, - {1, 1, 1}); - - return std::make_tuple( - std::move((std::get<0>(output)).squeeze(2).permute({2, 0, 1})), - std::move((std::get<1>(output)).squeeze(2).permute({2, 1, 0})), - std::move(std::get<2>(output))); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dBackwardKernelNpu.cpp index 95782c6bd8..f55b34b785 100644 --- a/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dBackwardKernelNpu.cpp @@ -19,7 +19,7 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -140,7 +140,7 @@ tuple conv_transpose2d_backward_out_npu( return std::tie(gradInput, gradWeight, gradBias); } -tuple NPUNativeFunctions::npu_conv_transpose2d_backward( +tuple XLANativeFunctions::npu_conv_transpose2d_backward( const at::Tensor& input, const at::Tensor& grad_output, const at::Tensor& weight, @@ -177,7 +177,7 @@ tuple NPUNativeFunctions::npu_conv_transpose return std::tie(gradInput, gradWeight, gradBias); } - +/* c10::SmallVector convolution_transpose3d_npu_output_size( const at::Tensor& input, const at::Tensor& weight, @@ -270,7 +270,7 @@ at::Tensor convolution_transpose3d_npu( return result; } - +*/ at::Tensor convolution_transpose_kernel_npu( const at::Tensor& input, const at::Tensor& weight, @@ -284,13 +284,13 @@ at::Tensor convolution_transpose_kernel_npu( at::Tensor output; if (dim == 4) { - output = NPUNativeFunctions::npu_conv_transpose2d( + output = XLANativeFunctions::npu_conv_transpose2d( input, weight, bias, padding, output_padding, stride, dilation, groups); } if (dim == 5) { - output = convolution_transpose3d_npu( - input, weight, bias, padding, output_padding, stride, dilation, groups); + // output = convolution_transpose3d_npu( + // input, weight, bias, padding, output_padding, stride, dilation, groups); } return output; @@ -311,7 +311,7 @@ tuple convolution_transpose_backward_npu( tuple output; if (dim == 4) { - output = NPUNativeFunctions::npu_conv_transpose2d_backward( + output = XLANativeFunctions::npu_conv_transpose2d_backward( input, grad, weight, @@ -324,20 +324,20 @@ tuple convolution_transpose_backward_npu( } if (dim == 5) { - output = NPUNativeFunctions::npu_conv_transpose3d_backward( - input, - grad, - weight, - padding, - output_padding, - stride, - dilation, - groups, - grad_input_mask); + // output = XLANativeFunctions::npu_conv_transpose3d_backward( + // input, + // grad, + // weight, + // padding, + // output_padding, + // stride, + // dilation, + // groups, + // grad_input_mask); } // Note:weight.grad should be equal weight if (std::get<1>(output).defined()) { - std::get<1>(output) = NPUNativeFunctions::npu_dtype_cast(std::get<1>(output), weight.scalar_type()); + std::get<1>(output) = XLANativeFunctions::npu_dtype_cast(std::get<1>(output), weight.scalar_type()); } return output; } @@ -413,7 +413,7 @@ public: } }; -at::Tensor NPUNativeFunctions::npu_convolution_transpose(const at::Tensor& input, +at::Tensor XLANativeFunctions::npu_convolution_transpose(const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias_opt, at::IntArrayRef padding, diff --git a/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dKernelNpu.cpp index a0a32368fb..78e62f3b05 100644 --- a/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/convolution/ConvTranspose2dKernelNpu.cpp @@ -18,7 +18,7 @@ #include #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -63,7 +63,7 @@ at::Tensor& conv_transpose2d_out_npu( return result; } -at::Tensor NPUNativeFunctions::npu_conv_transpose2d( +at::Tensor XLANativeFunctions::npu_conv_transpose2d( const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias_opt, diff --git a/torch_npu/csrc/aten/ops/convolution/ConvTranspose3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ConvTranspose3dBackwardKernelNpu.cpp deleted file mode 100644 index c008bb243f..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/ConvTranspose3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,219 +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. - - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -at::Tensor conv_transpose3d_backward_input_out_npu( - at::Tensor& gradInput, - const at::Tensor& input, - const at::Tensor& grad_output, - const at::Tensor& weight, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef stride, - at::IntArrayRef dilation, - int64_t groups) { - // constructs the input and output NPUat::TensorDesc - c10::SmallVector stridesSize = { - 1, 1, stride[0], stride[1], stride[2]}; - c10::SmallVector paddings = { - padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]}; - c10::SmallVector dilations = { - 1, 1, dilation[0], dilation[1], dilation[2]}; - string dataFormat = "NCDHW"; - - OpCommand cmd; - cmd.Name("Conv3D") - .Input(grad_output) - .Input(weight) - .Output(gradInput) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - return gradInput; -} - -at::Tensor conv_transpose3d_backward_weight_out_npu( - at::Tensor& gradWeight, - const at::Tensor& input, - const at::Tensor& grad_output, - const at::Tensor& weight, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef stride, - at::IntArrayRef dilation, - int64_t groups) { - c10::SmallVector dimList = array_to_small_vector(weight.sizes()); - c10::SmallVector stridesSize = { - 1, 1, stride[0], stride[1], stride[2]}; - c10::SmallVector paddings = { - padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]}; - c10::SmallVector dilations = { - 1, 1, dilation[0], dilation[1], dilation[2]}; - string sizeName = "filter_size"; - string dataFormat = "NCDHW"; - - // executing the NPU operator - OpCommand cmd; - cmd.Name("Conv3DBackpropFilterD") - .Input(grad_output) - .Input(input) - .Output(gradWeight) - .Attr(sizeName, dimList) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("groups", groups) - .Attr("data_format", dataFormat) - .Run(); - - return gradWeight; -} - -at::Tensor conv_transpose3d_backward_bias_out_npu( - at::Tensor& gradBias, - const at::Tensor& input, - const at::Tensor& grad_output, - const at::Tensor& weight, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef stride, - at::IntArrayRef dilation, - int64_t groups) { - at::Tensor gradView = grad_output.contiguous().view({ - grad_output.size(0), - grad_output.size(1), - grad_output.size(2), - -1}); - at::sum_out(gradBias, gradView, c10::SmallVector{0, 2, 3}); - - return gradBias; -} -tuple conv_transpose3d_backward_out_npu( - at::Tensor& gradInput, - at::Tensor& gradWeight, - at::Tensor& gradBias, - const at::Tensor& input, - const at::Tensor& grad_output, - const at::Tensor& weight, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef stride, - at::IntArrayRef dilation, - int64_t groups, - std::array output_mask) { - // calculate the output result of the NPU - if (output_mask[0]) { - conv_transpose3d_backward_input_out_npu( - gradInput, - input, - grad_output, - weight, - padding, - output_padding, - stride, - dilation, - groups); - } - - if (output_mask[1]) { - conv_transpose3d_backward_weight_out_npu( - gradWeight, - input, - grad_output, - weight, - padding, - output_padding, - stride, - dilation, - groups); - } - - if (output_mask[2]) { - conv_transpose3d_backward_bias_out_npu( - gradBias, - input, - grad_output, - weight, - padding, - output_padding, - stride, - dilation, - groups); - } - - return std::tie(gradInput, gradWeight, gradBias); -} - -tuple NPUNativeFunctions::npu_conv_transpose3d_backward( - const at::Tensor& input, - const at::Tensor& grad_output, - const at::Tensor& weight, - at::IntArrayRef padding, - at::IntArrayRef output_padding, - at::IntArrayRef stride, - at::IntArrayRef dilation, - int64_t groups, - std::array output_mask) { - at::Tensor gradInput; - at::Tensor gradWeight; - at::Tensor gradBias; - - // construct the output tensor of the NPU - if (output_mask[0]) { - gradInput = OpPreparation::ApplyTensorWithFormat( - input, ACL_FORMAT_NDC1HWC0); - } - - if (output_mask[1]) { - gradWeight = OpPreparation::ApplyTensorWithFormat( - weight.sizes(), weight.options().dtype(at::kFloat), ACL_FRACTAL_Z_3D); - } - - if (output_mask[2]) { - gradBias = OpPreparation::ApplyTensorWithFormat( - {grad_output.size(1)}, grad_output.options(), ACL_FORMAT_NCDHW); - } - - // calculate the output result of the NPU - conv_transpose3d_backward_out_npu( - gradInput, - gradWeight, - gradBias, - input, - grad_output, - weight, - padding, - output_padding, - stride, - dilation, - groups, - output_mask); - - return std::tie(gradInput, gradWeight, gradBias); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/convolution/ConvolutionKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ConvolutionKernelNpu.cpp index 54ef6d0a67..84d81b4623 100644 --- a/torch_npu/csrc/aten/ops/convolution/ConvolutionKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/convolution/ConvolutionKernelNpu.cpp @@ -22,7 +22,7 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -128,41 +128,7 @@ at::Tensor view3d(const at::Tensor& tensor) { return tensor.squeeze(2); } -at::Tensor NPUNativeFunctions::conv2d( - const at::Tensor& input, - const at::Tensor& weight, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups) { - return at::convolution( - input, weight, bias, stride, padding, dilation, false, {{0, 0}}, groups); -} - -at::Tensor _conv3d_npu( - const at::Tensor& input, - const at::Tensor& weight, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - int64_t groups) { - TORCH_CHECK(input.ndimension() == 5, - "The dim of input shoould be 5 but here is ", input.ndimension()); - return at::convolution( - input, - weight, - bias, - stride, - padding, - dilation, - false, - {{0, 0, 0}}, - groups); -} - -at::Tensor NPUNativeFunctions::conv_transpose2d( +at::Tensor XLANativeFunctions::conv_transpose2d( const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias, @@ -183,7 +149,7 @@ at::Tensor NPUNativeFunctions::conv_transpose2d( groups); } -at::Tensor NPUNativeFunctions::conv_transpose3d( +at::Tensor XLANativeFunctions::conv_transpose3d( const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias, @@ -204,109 +170,6 @@ at::Tensor NPUNativeFunctions::conv_transpose3d( groups); } -at::Tensor NPUNativeFunctions::convolution( - const at::Tensor& input, - const at::Tensor& weight, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - bool transposed, - at::IntArrayRef output_padding, - int64_t groups) { - return at::_convolution( - input, - weight, - bias, - stride, - padding, - dilation, - transposed, - output_padding, - groups, - false, - false, - false); -} - -at::Tensor _convolution_npu( - const at::Tensor& input_, - const at::Tensor& weight_, - const c10::optional& bias_opt_, - at::IntArrayRef stride_, - at::IntArrayRef padding_, - at::IntArrayRef dilation_, - bool transposed_, - at::IntArrayRef output_padding_, - int64_t groups_, - bool benchmark, - bool deterministic, - bool cudnn_enabled) { - at::Tensor input = input_; - at::Tensor weight = weight_; - - const at::Tensor& bias_ = c10::value_or_else(bias_opt_, [] {return at::Tensor();}); - at::Tensor bias = bias_; - - int64_t k = weight.ndimension(); - int64_t dim = k - 2; - - auto stride = expand_dim_if_needed(stride_, "stride", dim); - auto padding = expand_dim_if_needed(padding_, "padding", dim); - auto dilation = expand_dim_if_needed(dilation_, "dilation", dim); - bool transposed = transposed_; - auto output_padding = - expand_dim_if_needed(output_padding_, "output_padding", dim); - int64_t groups = groups_; - - if (input.size(0) == 0) { - // don't send empty inputs through backends - // but need to compute correct output size first and set up history for - // params - c10::SmallVector o; - if (!transposed) { - o = conv_output_size( - input.sizes(), weight.sizes(), padding, stride, dilation); - } else { - o = conv_input_size( - input.sizes(), - weight.sizes(), - padding, - output_padding, - stride, - dilation, - groups); - } - at::Tensor weight_view = at::_unsafe_view(weight, -1); - at::Tensor out = input * weight_view[0]; - if (bias.defined()) { - out = out + bias[0]; - } - return out.view(o); - } - - if (k == 3) { - view1d_as_2d(stride, padding, dilation, output_padding); - input = view4d(input); - weight = view4d(weight); - } - - at::Tensor output; - if (!transposed) { - output = NPUNativeFunctions::npu_convolution( - input, weight, bias_opt_, stride, padding, dilation, groups); - } else { - output = NPUNativeFunctions::npu_convolution_transpose( - input, weight, bias_opt_, padding, output_padding, stride, dilation, groups); - } - - if (k == 3) { - output = view3d(output); - } - - return output; -} - at::Tensor convolution_kernel_npu( const at::Tensor& input, const at::Tensor& weight, @@ -321,7 +184,7 @@ at::Tensor convolution_kernel_npu( at::Tensor output; if (dim == 4) { output = - NPUNativeFunctions::npu_conv2d(input, weight, bias_opt, stride, padding, dilation, groups); + XLANativeFunctions::npu_conv2d(input, weight, bias_opt, stride, padding, dilation, groups); } if (dim == 5) { @@ -330,18 +193,18 @@ at::Tensor convolution_kernel_npu( is_dilated |= (d != 1); } if (groups == 1 && !is_dilated) { - output = at::slow_conv3d( - input, weight, kernel_size, bias_opt, stride, padding); + // output = at::slow_conv3d( + // input, weight, kernel_size, bias_opt, stride, padding); } else { - output = NPUNativeFunctions::npu_conv3d( - input, weight, bias_opt, stride, padding, dilation, groups); + // output = XLANativeFunctions::npu_conv3d( + // input, weight, bias_opt, stride, padding, dilation, groups); } } return output; } -tuple NPUNativeFunctions::npu_convolution_backward( +tuple XLANativeFunctions::npu_convolution_backward( const at::Tensor& input, const at::Tensor& grad, const at::Tensor& weight, @@ -354,7 +217,7 @@ tuple NPUNativeFunctions::npu_convolution_ba tuple output; if (dim == 4) { - output = NPUNativeFunctions::npu_conv2d_backward( + output = XLANativeFunctions::npu_conv2d_backward( input, grad, weight, @@ -366,7 +229,7 @@ tuple NPUNativeFunctions::npu_convolution_ba } if (dim == 5) { - output = NPUNativeFunctions::npu_conv3d_backward( + /* output = XLANativeFunctions::npu_conv3d_backward( input, grad, weight, @@ -374,182 +237,15 @@ tuple NPUNativeFunctions::npu_convolution_ba padding, dilation, groups, - grad_input_mask); + grad_input_mask);*/ } // Note:weight.grad should be equal weight if (std::get<1>(output).defined()) { - std::get<1>(output) = NPUNativeFunctions::npu_dtype_cast(std::get<1>(output), weight.scalar_type()); + std::get<1>(output) = XLANativeFunctions::npu_dtype_cast(std::get<1>(output), weight.scalar_type()); } return output; } -std::tuple npu_convolution_double_backward( - const c10::optional& ggI, const c10::optional& ggW, const c10::optional& ggb, - const at::Tensor& input, const at::Tensor& gO_r, const at::Tensor& weight_r, - at::IntArrayRef stride_, at::IntArrayRef padding_, at::IntArrayRef dilation_, - int64_t groups_, std::array grad_input_mask) { - int64_t dim = input.ndimension(); - at::Tensor ggO; - at::Tensor gI; - at::Tensor gW; - if (dim == 4) { - std::tie(ggO, gI, gW) = at::_convolution_double_backward(ggI, ggW, ggb, gO_r, weight_r, input, stride_, padding_, - {{1, 1}}, false, {{0, 0}}, 1, false, false, false, false, grad_input_mask); - } - if (dim == 5) { - std::tie(ggO, gI, gW) = at::_convolution_double_backward(ggI, ggW, ggb, gO_r, weight_r, input, stride_, padding_, - {{1, 1, 1}}, false, {{0, 0, 0}}, 1, false, false, false, false, grad_input_mask); - } - return std::tie(ggO, gI, gW); -} - -at::Tensor NPUNativeFunctions::_convolution_nogroup( - const at::Tensor& input, - const at::Tensor& weight, - const c10::optional& bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - bool transposed, - at::IntArrayRef output_padding) { - at::Tensor output; - if (!transposed) { - output = - NPUNativeFunctions::npu_convolution(input, weight, bias_opt, stride, padding, dilation, 1); - } - - return output; -} - -at::Tensor NPUNativeFunctions::thnn_conv2d( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding) { - return std::get<0>(at::thnn_conv2d_forward( - self, weight, kernel_size, bias, stride, padding)); -} - -at::Tensor& NPUNativeFunctions::thnn_conv2d_out( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& output) { - at::Tensor finput = at::empty({0}, self.options()); - at::Tensor fgrad_input = at::empty({0}, self.options()); - return std::get<0>(at::thnn_conv2d_forward_out( - output, - finput, - fgrad_input, - self, - weight, - kernel_size, - bias, - stride, - padding)); -} - -tuple NPUNativeFunctions::thnn_conv2d_forward( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding) { - at::Tensor finput = at::empty({0}, self.options()); - at::Tensor fgrad_input = at::empty({0}, self.options()); - at::Tensor output = - NPUNativeFunctions::npu_convolution(self, weight, bias, stride, padding, {1, 1}, 1); - return tuple(output, finput, fgrad_input); -} - -tuple NPUNativeFunctions::thnn_conv2d_forward_out( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& output, - at::Tensor& finput, - at::Tensor& fgrad_input) { - NPUNativeFunctions::npu_conv2d_out(self, weight, bias, stride, padding, {1, 1}, 1, output); - return tuple(output, finput, fgrad_input); -} - -tuple NPUNativeFunctions::thnn_conv2d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - const at::Tensor& finput, - const at::Tensor& fgrad_input, - std::array output_mask) { - return NPUNativeFunctions::npu_convolution_backward( - self, grad_output, weight, stride, padding, {1, 1}, 1, output_mask); -} - -at::Tensor& NPUNativeFunctions::thnn_conv_depthwise2d_out( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - at::Tensor& out) { - return at::thnn_conv_depthwise2d_forward_out( - out, self, weight, kernel_size, bias, stride, padding, dilation); -} - -at::Tensor NPUNativeFunctions::thnn_conv_depthwise2d( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - return at::thnn_conv_depthwise2d_forward( - self, weight, kernel_size, bias, stride, padding, dilation); -} - -at::Tensor NPUNativeFunctions::_convolution( - const at::Tensor& input_, - const at::Tensor& weight_, - const c10::optional& bias_, - at::IntArrayRef stride_, - at::IntArrayRef padding_, - at::IntArrayRef dilation_, - bool transposed_, - at::IntArrayRef output_padding_, - int64_t groups_, - bool benchmark, - bool deterministic, - bool cudnn_enabled, - bool allow_tf32) { - - return _convolution_npu(input_, - weight_, - bias_, - stride_, - padding_, - dilation_, - transposed_, - output_padding_, - groups_, - benchmark, - deterministic, - cudnn_enabled); -} - class NPUConvlutionFunction : public torch::autograd::Function { public: static at::Tensor forward(AutogradContext *ctx, @@ -589,7 +285,7 @@ public: grad_input_mask[1] = weight.requires_grad(); grad_input_mask[2] = bias_has_value; - tuple result = NPUNativeFunctions::npu_convolution_backward(input, + tuple result = XLANativeFunctions::npu_convolution_backward(input, grad_outputs[0], weight, stride, @@ -608,7 +304,7 @@ public: } }; -at::Tensor NPUNativeFunctions::npu_convolution(const at::Tensor& input, +at::Tensor XLANativeFunctions::npu_convolution(const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias_opt, at::IntArrayRef stride, @@ -625,5 +321,29 @@ at::Tensor NPUNativeFunctions::npu_convolution(const at::Tensor& input, return NPUConvlutionFunction::apply(input, weight, bias, stride, padding, dilation, groups); } +at::Tensor XLANativeFunctions::convolution_overrideable( + const at::Tensor& input, const at::Tensor& weight, const c10::optional& bias_opt, + c10::IntArrayRef stride, c10::IntArrayRef padding, c10::IntArrayRef dilation, + bool transposed, c10::IntArrayRef output_padding, int64_t groups) { + + return XLANativeFunctions::npu_conv2d(input, weight, bias_opt, stride, padding, dilation, groups); +} + +std::tuple XLANativeFunctions::convolution_backward_overrideable( + const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight, + c10::IntArrayRef stride, c10::IntArrayRef padding, + c10::IntArrayRef dilation, bool transposed, c10::IntArrayRef output_padding, + int64_t groups, std::array output_mask) { + + return XLANativeFunctions::npu_convolution_backward(input, + grad_output, + weight, + stride, + padding, + dilation, + groups, + output_mask); +} + } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/convolution/ConvtbcKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ConvtbcKernelNpu.cpp deleted file mode 100644 index b68a837382..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/ConvtbcKernelNpu.cpp +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { -at::Tensor NPUNativeFunctions::conv_tbc( - const at::Tensor& self, - const at::Tensor& weight, - const at::Tensor& bias, - int64_t pad) { - // check the shape of input tensors - TORCH_CHECK( - self.dim() == 3, "Input must have 3 dims: time, batch, in_channel."); - TORCH_CHECK( - weight.dim() == 3, - "Weight tensor must have 3 dims: kernel_width," - " in_channels, out_channels."); - TORCH_CHECK(bias.dim() == 1, "Bias must be 1-D."); - TORCH_CHECK( - self.size(2) == weight.size(1), - "Input dim 2 (input channels) " - "is not == dim 1 in the weight tenso."); - TORCH_CHECK( - weight.size(2) == bias.size(0), - "Bias size must equal dim 2 in " - "the weight tensor (output channels)."); - - // calculate the output size - int64_t Co = weight.size(2); - int64_t Wo = (self.size(0) + 2 * pad - (weight.size(0) - 1) - 1) + 1; - - c10::SmallVector outputSize = {self.size(1), Co, 1, Wo}; - - // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensorWithFormat(self, outputSize, ACL_FORMAT_NCHW); - - c10::SmallVector paddings = {0, 0, pad, pad}; - c10::SmallVector stridesSize = {1, 1, 1, 1}; - c10::SmallVector dilations = {1, 1, 1, 1}; - - at::Tensor self_tensor = self.transpose(0, 2).transpose(0, 1).unsqueeze(2); - at::Tensor weight_tensor = weight.transpose(0, 2).unsqueeze(2); - - OpCommand cmd; - cmd.Name("Conv2D") - .Input(self_tensor) - .Input(weight_tensor) - .Input(bias) - .Output(result) - .Attr("pads", paddings) - .Attr("strides", stridesSize) - .Attr("dilations", dilations) - .Attr("data_format", (string)"NCHW") - .Run(); - - result = result.squeeze(2).transpose(0, 2).transpose(1, 2); - return result; -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/convolution/ThnnConvDepthwise2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ThnnConvDepthwise2dBackwardKernelNpu.cpp deleted file mode 100644 index b0a03f9725..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/ThnnConvDepthwise2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,150 +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. - -#include -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -void thnn_conv_depthwise2d_backward_input_out_npu( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - auto inputSize = self.sizes(); - OpCommand cmd; - cmd.Name("DepthwiseConv2DBackpropInput") - .Input(inputSize, at::kInt) - .Input(weight) - .Input(grad_output) - .Output(grad_input) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("data_format", (string)"NCHW") - .Run(); -} - -void thnn_conv_depthwise2d_backward_weight_out_npu( - at::Tensor& grad_weight, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - auto inputSize = weight.sizes(); - OpCommand cmd; - cmd.Name("DepthwiseConv2DBackpropFilter") - .Input(self) - .Input(inputSize, at::kInt) - .Input(grad_output) - .Output(grad_weight) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("data_format", (string)"NCHW") - .Run(); -} - -tuple NPUNativeFunctions::thnn_conv_depthwise2d_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - at::Tensor& grad_input, - at::Tensor& grad_weight) { - at::Tensor weight_ex = weight.permute({1, 0, 2, 3}); - if (grad_input.defined()) { - thnn_conv_depthwise2d_backward_input_out_npu( - grad_input, - grad_output, - self, - weight_ex, - kernel_size, - stride, - padding, - dilation); - } - if (grad_weight.defined()) { - thnn_conv_depthwise2d_backward_weight_out_npu( - grad_weight, - grad_output, - self, - weight_ex, - kernel_size, - stride, - padding, - dilation); - } - - return tuple(grad_input, grad_weight); -} - -tuple NPUNativeFunctions::thnn_conv_depthwise2d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - std::array output_mask) { - // calculate the output size - at::Tensor grad_input; - at::Tensor grad_weight; - // construct the output tensor of - if (output_mask[0]) { - grad_input = OpPreparation::ApplyTensorWithFormat(self, ACL_FORMAT_NC1HWC0); - } - - if (output_mask[1]) { - grad_weight = OpPreparation::ApplyTensorWithFormat(weight, ACL_FORMAT_NCHW); - } - - return NPUNativeFunctions::thnn_conv_depthwise2d_backward_out( - grad_output, - self, - weight, - kernel_size, - stride, - padding, - dilation, - grad_input, - grad_weight); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/convolution/ThnnConvDepthwise2dForwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/convolution/ThnnConvDepthwise2dForwardKernelNpu.cpp deleted file mode 100644 index d60ef99cb5..0000000000 --- a/torch_npu/csrc/aten/ops/convolution/ThnnConvDepthwise2dForwardKernelNpu.cpp +++ /dev/null @@ -1,86 +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. - -#include -#include - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -at::Tensor& NPUNativeFunctions::thnn_conv_depthwise2d_forward_out( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - at::Tensor& out) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - const at::Tensor& weightModify = weight.permute({1, 0, 2, 3}); - - // constructs the input and output NPUTensorDesc - c10::SmallVector stridesSize = {1, 1, stride[0], stride[1]}; - c10::SmallVector paddings = {padding[0], padding[0], padding[1], padding[1]}; - c10::SmallVector dilations = {1, 1, dilation[0], dilation[1]}; - - OpCommand cmd; - cmd.Name("DepthwiseConv2D") - .Input(self) - .Input(weightModify); - if (bias.defined()) { - cmd.Input(bias); - } - cmd.Output(out) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("data_format", (string)"NCHW") - .Run(); - return out; -} - -at::Tensor NPUNativeFunctions::thnn_conv_depthwise2d_forward( - const at::Tensor& self, - const at::Tensor& weight, - at::IntArrayRef kernel_size, - const c10::optional& bias_opt, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation) { - // calculate the output size - int64_t N = self.size(0); - int64_t Co = weight.size(0); - int64_t H = self.size(2); - int64_t W = self.size(3); - int64_t Ho = (H + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) - 1) / - stride[0] + 1; - int64_t Wo = (W + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1) - 1) / - stride[1] + 1; - c10::SmallVector outputSize = {N, Co, Ho, Wo}; - at::Tensor result = OpPreparation::ApplyTensorWithFormat(self, outputSize, ACL_FORMAT_NC1HWC0); - - NPUNativeFunctions::thnn_conv_depthwise2d_forward_out( - self, weight, kernel_size, bias_opt, stride, padding, dilation, result); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/loss/L1LossBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/L1LossBackwardKernelNpu.cpp deleted file mode 100644 index 84b0971802..0000000000 --- a/torch_npu/csrc/aten/ops/loss/L1LossBackwardKernelNpu.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& l1_loss_backward_out_npu_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - string reductionStr) { - OpCommand cmd; - cmd.Name("L1LossGrad") - .Input(grad_output) - .Input(self) - .Input(target) - .Attr("reduction", reductionStr) - .Output(grad_input) - .Run(); - return grad_input; -} - -at::Tensor& NPUNativeFunctions::l1_loss_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - at::Tensor& grad_input) { - at::Tensor gradOutputBroadcast = grad_output; - at::Tensor targetBroadcast = target; - if (grad_output.sizes() != self.sizes()) { - gradOutputBroadcast = NPUNativeFunctions::npu_broadcast(grad_output, self.sizes()); - } - if (target.sizes() != self.sizes()) { - targetBroadcast = NPUNativeFunctions::npu_broadcast(target, self.sizes()); - } - - OpPreparation::CheckOut( - {grad_output, self, target}, - grad_input, - self); - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - return l1_loss_backward_out_npu_nocheck( - grad_input, - gradOutputBroadcast, - self, - targetBroadcast, - reductionStr); -} - -at::Tensor NPUNativeFunctions::l1_loss_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction) { - at::Tensor gradOutputBroadcast = grad_output; - at::Tensor targetBroadcast = target; - if (grad_output.sizes() != self.sizes()) { - gradOutputBroadcast = NPUNativeFunctions::npu_broadcast(grad_output, self.sizes()); - } - if (target.sizes() != self.sizes()) { - targetBroadcast = NPUNativeFunctions::npu_broadcast(target, self.sizes()); - } - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - OpPipeWithApplyOut pipe; - return pipe.ApplyOutputSameAs(self) - .Func([&gradOutputBroadcast, &self, &targetBroadcast, &reductionStr](at::Tensor& result) { - l1_loss_backward_out_npu_nocheck(result, gradOutputBroadcast, self, targetBroadcast, reductionStr); - }) - .Call(); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/loss/L1LossKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/L1LossKernelNpu.cpp deleted file mode 100644 index 89cee90f37..0000000000 --- a/torch_npu/csrc/aten/ops/loss/L1LossKernelNpu.cpp +++ /dev/null @@ -1,69 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& l1_loss_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& target, - string reductionStr) { - OpCommand cmd; - cmd.Name("LpLoss") - .Input(self) - .Input(target) - .Attr("reduction", reductionStr) - .Attr("p", (int64_t)1) - .Output(result) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::l1_loss_out( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - at::Tensor& result) { - OpPreparation::CheckOut( - {self, target}, - result, - self); - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - return l1_loss_out_npu_nocheck(result, self, target, reductionStr); -} - -at::Tensor NPUNativeFunctions::l1_loss( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction) { - at::IntArrayRef outputSize; - if (reduction == at::Reduction::None) { - outputSize = input_same_output_size(self); - } - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - - l1_loss_out_npu_nocheck(result, self, target, reductionStr); - return result; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/loss/LossKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/LossKernelNpu.cpp deleted file mode 100644 index 2f616f41fd..0000000000 --- a/torch_npu/csrc/aten/ops/loss/LossKernelNpu.cpp +++ /dev/null @@ -1,97 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor NPUNativeFunctions::nll_loss( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight, - int64_t reduction, - int64_t ignore_index) { - return std::get<0>( - at::nll_loss_forward(self, target, weight, reduction, ignore_index)); -} - -at::Tensor& NPUNativeFunctions::nll_loss_out( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight, - int64_t reduction, - int64_t ignore_index, - at::Tensor& output) { - at::Tensor total_weight = OpPreparation::ApplyTensor({}, self.options(), self); - return std::get<0>(at::nll_loss_forward_out( - output, total_weight, self, target, weight, reduction, ignore_index)); -} - -at::Tensor NPUNativeFunctions::nll_loss2d( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight, - int64_t reduction, - int64_t ignore_index) { - return std::get<0>( - at::nll_loss2d_forward(self, target, weight, reduction, ignore_index)); -} - -at::Tensor& NPUNativeFunctions::nll_loss2d_out( - const at::Tensor& self, - const at::Tensor& target, - const c10::optional& weight, - int64_t reduction, - int64_t ignore_index, - at::Tensor& output) { - at::Tensor total_weight = OpPreparation::ApplyTensor({}, self.options(), self); - return std::get<0>(at::nll_loss2d_forward_out( - output, total_weight, self, target, weight, reduction, ignore_index)); -} - -at::Tensor & NPUNativeFunctions::multilabel_margin_loss_out( - const at::Tensor & self, - const at::Tensor & target, - int64_t reduction, - at::Tensor & output) { - c10::SmallVector outputSize; - const auto ndims = self.dim(); - int64_t nframe; - if (ndims <= 1) { - nframe = 1; - } else { - nframe = self.size(0); - } - - if (reduction == at::Reduction::None) { - outputSize = {nframe}; - } - output = OpPreparation::ApplyTensor(outputSize, self.options(), self); - at::Tensor is_target = OpPreparation::ApplyTensor(target); - return std::get<0>(at::multilabel_margin_loss_forward_out(output, is_target, self, target, reduction)); -} - -at::Tensor NPUNativeFunctions::multilabel_margin_loss( - const at::Tensor & self, - const at::Tensor & target, - int64_t reduction) { - return std::get<0>(at::multilabel_margin_loss_forward(self, target, reduction)); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/loss/MultilabelMarginLossKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/MultilabelMarginLossKernelNpu.cpp deleted file mode 100644 index efdbee9729..0000000000 --- a/torch_npu/csrc/aten/ops/loss/MultilabelMarginLossKernelNpu.cpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple NPUNativeFunctions::multilabel_margin_loss_forward_out( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - at::Tensor& output, - at::Tensor& is_target) { - - OpPreparation::CheckMemory({self, target}, {output, is_target}); - string reductionStr = CalcuOpUtil::get_reduction_str(reduction); - OpCommand cmd; - cmd.Name("MultilabelMarginLoss") - .Input(self) - .Input(target) - .Output(output) - .Output(is_target) - .Attr("reduction", reductionStr) - .Run(); - return std::tuple(output, is_target); -} - -std::tuple NPUNativeFunctions::multilabel_margin_loss_forward( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction) { - c10::SmallVector outputSize; - int64_t nframe; - if (self.dim() <= 1) { - nframe = 1; - } else { - nframe = self.size(0); - } - if (reduction == at::Reduction::None) { - outputSize = {nframe}; - } - auto output = OpPreparation::ApplyTensor(self, outputSize); - auto is_target = OpPreparation::ApplyTensor(target); - - NPUNativeFunctions::multilabel_margin_loss_forward_out( - self, target, reduction, output, is_target); - return std::make_tuple(output, is_target); -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/loss/NLLLoss2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/NLLLoss2dBackwardKernelNpu.cpp index f437396368..c0fc993238 100644 --- a/torch_npu/csrc/aten/ops/loss/NLLLoss2dBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/loss/NLLLoss2dBackwardKernelNpu.cpp @@ -14,12 +14,12 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::nll_loss2d_backward_out( +at::Tensor& XLANativeFunctions::nll_loss2d_backward_out( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -38,10 +38,12 @@ at::Tensor& NPUNativeFunctions::nll_loss2d_backward_out( if (ignore_index >= 0) { at::Tensor zero = at::zeros(1, self.options()); + void* ignore_ptr = reinterpret_cast(weight_tensor.data_ptr()) + + ignore_index * weight_tensor.itemsize(); CalcuOpUtil::AclrtMemcpyAsync( - {weight_tensor, ignore_index}, + ignore_ptr, weight_tensor.itemsize(), - {zero, 0}, + reinterpret_cast(zero.data_ptr()), weight_tensor.itemsize(), ACL_MEMCPY_DEVICE_TO_DEVICE); } @@ -62,7 +64,7 @@ at::Tensor& NPUNativeFunctions::nll_loss2d_backward_out( return grad_input; } -at::Tensor NPUNativeFunctions::nll_loss2d_backward( +at::Tensor XLANativeFunctions::nll_loss2d_backward( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -93,7 +95,7 @@ at::Tensor NPUNativeFunctions::nll_loss2d_backward( at::Tensor grad_input = OpPreparation::ApplyTensorWithFormat( outputSize, self_input.options(), CalcuOpUtil::get_tensor_npu_format(self_input)); // calculate the output result of the NPU - NPUNativeFunctions::nll_loss2d_backward_out( + XLANativeFunctions::nll_loss2d_backward_out( grad_output_reshape, self_input, target_input, diff --git a/torch_npu/csrc/aten/ops/loss/NLLLoss2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/NLLLoss2dKernelNpu.cpp index 75116f8eeb..4fa92bf8ff 100644 --- a/torch_npu/csrc/aten/ops/loss/NLLLoss2dKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/loss/NLLLoss2dKernelNpu.cpp @@ -14,7 +14,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -38,7 +38,7 @@ tuple, c10::SmallVector> nll_loss } } // namespace -tuple NPUNativeFunctions::nll_loss2d_forward_out( +tuple XLANativeFunctions::nll_loss2d_forward_out( const at::Tensor& self, const at::Tensor& target, const c10::optional& weight_opt, @@ -56,10 +56,12 @@ tuple NPUNativeFunctions::nll_loss2d_forward_out( if (ignore_index >= 0) { at::Tensor zero = at::zeros(1, self.options()); + void* ignore_ptr = reinterpret_cast(weight_tensor.data_ptr()) + + ignore_index * weight_tensor.itemsize(); CalcuOpUtil::AclrtMemcpyAsync( - {weight_tensor, ignore_index}, + ignore_ptr, weight_tensor.itemsize(), - {zero, 0}, + reinterpret_cast(zero.data_ptr()), weight_tensor.itemsize(), ACL_MEMCPY_DEVICE_TO_DEVICE); } @@ -81,7 +83,7 @@ tuple NPUNativeFunctions::nll_loss2d_forward_out( return tuple(result, total_weight); } -tuple NPUNativeFunctions::nll_loss2d_forward( +tuple XLANativeFunctions::nll_loss2d_forward( const at::Tensor& self, const at::Tensor& target, const c10::optional& weight_opt, @@ -112,7 +114,7 @@ tuple NPUNativeFunctions::nll_loss2d_forward( OpPreparation::ApplyTensor(self_input, std::get<1>(outputSizes)); // calculate the output result of the NPU - NPUNativeFunctions::nll_loss2d_forward_out( + XLANativeFunctions::nll_loss2d_forward_out( self_input, target_input, weight_opt, diff --git a/torch_npu/csrc/aten/ops/loss/NLLLossBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/NLLLossBackwardKernelNpu.cpp index 178f72820a..017df9e23b 100644 --- a/torch_npu/csrc/aten/ops/loss/NLLLossBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/loss/NLLLossBackwardKernelNpu.cpp @@ -16,12 +16,12 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::nll_loss_backward_out( +at::Tensor& XLANativeFunctions::nll_loss_backward_out( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -40,10 +40,12 @@ at::Tensor& NPUNativeFunctions::nll_loss_backward_out( if (ignore_index >= 0 && ignore_index < self.size(-1)) { at::Tensor zero = at::zeros(1, self.options()); + void* ignore_ptr = reinterpret_cast(weight_tensor.data_ptr()) + + ignore_index * weight_tensor.itemsize(); CalcuOpUtil::AclrtMemcpyAsync( - {weight_tensor, ignore_index}, + ignore_ptr, weight_tensor.itemsize(), - {zero, 0}, + reinterpret_cast(zero.data_ptr()), weight_tensor.itemsize(), ACL_MEMCPY_DEVICE_TO_DEVICE); } @@ -77,7 +79,7 @@ at::Tensor& NPUNativeFunctions::nll_loss_backward_out( return grad_input; } -at::Tensor NPUNativeFunctions::nll_loss_backward( +at::Tensor XLANativeFunctions::nll_loss_backward( const at::Tensor& grad_output, const at::Tensor& self, const at::Tensor& target, @@ -93,7 +95,7 @@ at::Tensor NPUNativeFunctions::nll_loss_backward( outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self)); // calculate the output result of the NPU - NPUNativeFunctions::nll_loss_backward_out( + XLANativeFunctions::nll_loss_backward_out( grad_output, self, target, diff --git a/torch_npu/csrc/aten/ops/loss/NLLLossKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/NLLLossKernelNpu.cpp index 42bc4962f4..7cd6820f5e 100644 --- a/torch_npu/csrc/aten/ops/loss/NLLLossKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/loss/NLLLossKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -38,10 +38,12 @@ tuple nll_loss_forward_npu_nocheck( if (ignore_index >= 0 && ignore_index < self.size(-1)) { at::Tensor zero = at::zeros(1, self.options()); + void* ignore_ptr = reinterpret_cast(weight_tensor.data_ptr()) + + ignore_index * weight_tensor.itemsize(); CalcuOpUtil::AclrtMemcpyAsync( - {weight_tensor, ignore_index}, + ignore_ptr, weight_tensor.itemsize(), - {zero, 0}, + reinterpret_cast(zero.data_ptr()), weight_tensor.itemsize(), ACL_MEMCPY_DEVICE_TO_DEVICE); } @@ -51,7 +53,7 @@ tuple nll_loss_forward_npu_nocheck( at::Tensor targetCast = target; auto scalar_type = target.scalar_type(); if (scalar_type == at::kLong) { - targetCast = NPUNativeFunctions::npu_dtype_cast(target, at::kInt); + targetCast = XLANativeFunctions::npu_dtype_cast(target, at::kInt); } else if (scalar_type == at::kInt) { ; } @@ -74,7 +76,7 @@ tuple nll_loss_forward_npu_nocheck( return tuple(result, total_weight); } -tuple NPUNativeFunctions::nll_loss_forward_out( +tuple XLANativeFunctions::nll_loss_forward_out( const at::Tensor& self, const at::Tensor& target, const c10::optional& weight_opt, @@ -88,7 +90,7 @@ tuple NPUNativeFunctions::nll_loss_forward_out( weight_tensor = NpuUtils::format_contiguous(weight); } else { auto options = self.options(); - weight_tensor = NPUNativeFunctions::ones( + weight_tensor = XLANativeFunctions::ones( self.size(1), optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); @@ -105,7 +107,7 @@ tuple NPUNativeFunctions::nll_loss_forward_out( .ReturnRef(); } -tuple NPUNativeFunctions::nll_loss_forward( +tuple XLANativeFunctions::nll_loss_forward( const at::Tensor& self, const at::Tensor& target, const c10::optional& weight_opt, diff --git a/torch_npu/csrc/aten/ops/loss/SmoothL1LossBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/SmoothL1LossBackwardKernelNpu.cpp deleted file mode 100644 index 74ca2f6764..0000000000 --- a/torch_npu/csrc/aten/ops/loss/SmoothL1LossBackwardKernelNpu.cpp +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) 2020 Huawei Technologies Co., Ltd -// -// 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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::smooth_l1_loss_backward_out( - const at::Tensor& grad_out, - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - double beta, - at::Tensor& grad_input) { - string reductionStr(CalcuOpUtil::get_reduction_str(reduction)); - - OpPreparation::CheckMemory({self, grad_out, target}, {grad_input}); - OpCommand cmd; - cmd.Name("SmoothL1LossGradV2") - .Input(self) - .Input(target) - .Input(grad_out) - .Output(grad_input) - .Attr("reduction", reductionStr) - .Attr("sigma", static_cast(1.0)) - .Run(); - return grad_input; -} - -at::Tensor NPUNativeFunctions::smooth_l1_loss_backward( - const at::Tensor& grad_out, - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - double beta) { - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - - NPUNativeFunctions::smooth_l1_loss_backward_out( - grad_out, self, target, reduction, beta, grad_input); - return grad_input; -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/loss/SmoothL1LossKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/SmoothL1LossKernelNpu.cpp deleted file mode 100644 index 3cc4b051ee..0000000000 --- a/torch_npu/csrc/aten/ops/loss/SmoothL1LossKernelNpu.cpp +++ /dev/null @@ -1,81 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& smooth_l1_loss_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - double beta) { - if (self.numel()==0) { - // In this scenario, needs to return nan. And the nan of the NPU can only be fp32. - result = result.to(at::kFloat).fill_(0); - result = result / 0; - return result; - } - - string reductionStr(CalcuOpUtil::get_reduction_str(reduction)); - OpCommand cmd; - cmd.Name("SmoothL1LossV2") - .Input(self) - .Input(target) - .Output(result) - .Attr("reduction", reductionStr) - .Attr("sigma", static_cast(beta)) - .Run(); - return result; -} - -at::Tensor& NPUNativeFunctions::smooth_l1_loss_out( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - double beta, - at::Tensor& result) { - auto outputSize = smooth_l1_loss_npu_output_size(self, target, reduction); - - OpPreparation::CheckOut( - {self, target}, - result, - CalcuOpUtil::get_tensor_npu_format(self), - self.scalar_type(), - outputSize); - - OpPreparation::CheckMemory({self, target}, {result}); - smooth_l1_loss_out_npu_nocheck(result, self, target, reduction, beta); - return result; -} - -at::Tensor NPUNativeFunctions::smooth_l1_loss( - const at::Tensor& self, - const at::Tensor& target, - int64_t reduction, - double beta) { - auto outputSize = smooth_l1_loss_npu_output_size(self, target, reduction); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - smooth_l1_loss_out_npu_nocheck(result, self, target, reduction, beta); - return result; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/loss/SoftMarginLossBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/SoftMarginLossBackwardKernelNpu.cpp deleted file mode 100644 index f0ae15e9ba..0000000000 --- a/torch_npu/csrc/aten/ops/loss/SoftMarginLossBackwardKernelNpu.cpp +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::soft_margin_loss_backward_out( - const at::Tensor& grad_output, - const at::Tensor& input, - const at::Tensor& target, - int64_t reduction, - at::Tensor& grad_input) { - string reductionStr(CalcuOpUtil::get_reduction_str(reduction)); - - OpPreparation::CheckMemory({grad_output, input, target}, {grad_input}); - OpCommand cmd; - cmd.Name("SoftMarginLossGrad") - .Input(input) - .Input(target) - .Input(grad_output) - .Output(grad_input) - .Attr("reduction", reductionStr) - .Run(); - return grad_input; -} - -at::Tensor NPUNativeFunctions::soft_margin_loss_backward( - const at::Tensor& grad_output, - const at::Tensor& input, - const at::Tensor& target, - int64_t reduction) { - at::Tensor grad_input = OpPreparation::ApplyTensor(input); - - NPUNativeFunctions::soft_margin_loss_backward_out( - grad_output, input, target, reduction, grad_input); - return grad_input; -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/loss/SoftMarginLossKernelNpu.cpp b/torch_npu/csrc/aten/ops/loss/SoftMarginLossKernelNpu.cpp deleted file mode 100644 index 989fde79ae..0000000000 --- a/torch_npu/csrc/aten/ops/loss/SoftMarginLossKernelNpu.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::soft_margin_loss_out( - const at::Tensor& self, const at::Tensor& target, int64_t reduction, at::Tensor& result) { - at::Tensor target_broadcast = target; - if(target.sizes() != self.sizes()) { - target_broadcast = NPUNativeFunctions::npu_broadcast(target, self.sizes()); - } - - OpPreparation::CheckMemory({self, target}, {result}); - string reductionStr(CalcuOpUtil::get_reduction_str(reduction)); - OpCommand cmd; - cmd.Name("SoftMarginLoss") - .Input(self) - .Input(target_broadcast) - .Output(result) - .Attr("reduction", reductionStr) - .Run(); - return result; -} - -at::Tensor NPUNativeFunctions::soft_margin_loss(const at::Tensor& self, const at::Tensor& target, int64_t reduction) { - auto outputSize = soft_margin_loss_npu_output_size( - self, - target, - reduction); - at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - - NPUNativeFunctions::soft_margin_loss_out(self, target, reduction, result); - if (reduction == at::Reduction::None) { - return result; - } else { - return result.reshape({}); - } -} - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardElemtKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardElemtKernelNpu.cpp deleted file mode 100644 index 889587ef29..0000000000 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardElemtKernelNpu.cpp +++ /dev/null @@ -1,100 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& batch_norm_backward_elemt_npu_nocheck( - const at::Tensor& grad_out, - const at::Tensor& input, - const at::Tensor& mean, - const at::Tensor& invstd, - const at::Tensor& weight, - const at::Tensor& mean_dy, - const at::Tensor& mean_dy_xmu, - at::Tensor& grad_input) { - OpCommand cmd; - cmd.Name("SyncBatchNormBackwardElemt") - .Input(grad_out) - .Input(input) - .Input(mean) - .Input(invstd) - .Input(weight) - .Input(mean_dy) - .Input(mean_dy_xmu) - .Output(grad_input) - .Run(); - return grad_input; -} - -void batch_norm_backward_elemt_npu_expand_tensor( - at::Tensor& expand_tensor, - size_t dim_c, - int64_t input_ndim, - at::IntArrayRef input_shape) { - if (input_ndim >2) { - expand_tensor = NPUNativeFunctions::npu_broadcast(expand_tensor, {1, dim_c}).t(); - for (int64_t i = 0; i < input_ndim - 3; i++) { - expand_tensor = expand_tensor.unsqueeze(1); - } - } - expand_tensor = NPUNativeFunctions::npu_broadcast(expand_tensor, input_shape); -} - -at::Tensor NPUNativeFunctions::batch_norm_backward_elemt( - const at::Tensor& grad_out, - const at::Tensor& input, - const at::Tensor& mean, - const at::Tensor& invstd, - const c10::optional& weight_opt, - const at::Tensor& mean_dy, - const at::Tensor& mean_dy_xmu) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - int64_t input_ndim = input.dim(); - TORCH_CHECK(input_ndim > 1, "input.dim() <= 1") - size_t dim_c = input.size(1); - at::IntArrayRef input_shape = input.sizes(); - at::Tensor mean_expanded(mean); - - batch_norm_backward_elemt_npu_expand_tensor(mean_expanded, dim_c, input_ndim, input_shape); - at::Tensor invstd_expanded(invstd); - - batch_norm_backward_elemt_npu_expand_tensor(invstd_expanded, dim_c, input_ndim, input_shape); - at::Tensor weight_expanded(weight); - - batch_norm_backward_elemt_npu_expand_tensor(weight_expanded, dim_c, input_ndim, input_shape); - at::Tensor mean_dy_expanded(mean_dy); - - batch_norm_backward_elemt_npu_expand_tensor(mean_dy_expanded, dim_c, input_ndim, input_shape); - at::Tensor mean_dy_xmu_expanded(mean_dy_xmu); - - batch_norm_backward_elemt_npu_expand_tensor(mean_dy_xmu_expanded, dim_c, input_ndim, input_shape); - at::Tensor grad_input = OpPreparation::ApplyTensor(input); - return batch_norm_backward_elemt_npu_nocheck( - grad_out, - input, - mean_expanded, - invstd_expanded, - weight_expanded, - mean_dy_expanded, - mean_dy_xmu_expanded, - grad_input); -} -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardKernelNpu.cpp index 91f2a7734c..619aae1f16 100644 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardKernelNpu.cpp @@ -1,5 +1,5 @@ // Copyright (c) 2020 Huawei Technologies Co., Ltd -// Copyright (c) 2019, Facebook CORPORATION. +// Copyright (c) 2019, Facebook CORPORATION. // All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); @@ -16,8 +16,10 @@ #include #include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" + #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" + namespace at_npu { namespace native { @@ -36,17 +38,13 @@ tuple batch_norm_backward_training_update_nocheck( bool train, double eps) { OpCommand cmd; - - string name = (self.dim() == 5) ? "BN3DTrainingUpdateGrad" : "BNTrainingUpdateGrad"; - auto format = (self.dim() == 5) ? ACL_FORMAT_NCDHW : ACL_FORMAT_NCHW; - - cmd.Name(name) - .Input(grad_out, "grads", format) - .Input(self, "x", format) - .Input(save_mean, "batch_mean", format) - .Input(save_invstd, "batch_variance", format) - .Output(grad_weight, "diff_scale", format) - .Output(grad_bias, "diff_offset", format) + cmd.Name("BNTrainingUpdateGrad") + .Input(grad_out) + .Input(self) + .Input(save_mean) + .Input(save_invstd) + .Output(grad_weight) + .Output(grad_bias) .Attr("epsilon", static_cast(eps)) .Run(); @@ -67,19 +65,15 @@ at::Tensor& batch_norm_backward_training_reduce_nocheck( bool train, double eps) { OpCommand cmd; - - string name = (self.dim() == 5) ? "BN3DTrainingReduceGrad" : "BNTrainingReduceGrad"; - auto format = (self.dim() == 5) ? ACL_FORMAT_NCDHW : ACL_FORMAT_NCHW; - - cmd.Name(name) - .Input(grad_out, "grads", format) - .Input(self, "x", format) - .Input(grad_weight, "diff_scale", format) - .Input(grad_bias, "diff_offset", format) - .Input(weight, "scale", format) - .Input(save_mean, "batch_mean", format) - .Input(save_invstd, "batch_variance", format) - .Output(grad_input, "y", format) + cmd.Name("BNTrainingReduceGrad") + .Input(grad_out) + .Input(self) + .Input(grad_weight) + .Input(grad_bias) + .Input(weight) + .Input(save_mean) + .Input(save_invstd) + .Output(grad_input) .Attr("epsilon", static_cast(eps)) .Run(); @@ -101,14 +95,14 @@ at::Tensor& batch_norm_backward_infer_nocheck( double eps) { OpCommand cmd; cmd.Name("BNInferGrad") - .Input(grad_out, "grads", ACL_FORMAT_NCHW) - .Input(weight, "scale", ACL_FORMAT_NCHW) - .Input(running_var, "batch_variance", ACL_FORMAT_NCHW) - .Output(grad_input, "x_backprop", ACL_FORMAT_NCHW) + .Input(grad_out) + .Input(weight) + .Input(running_var) + .Output(grad_input) .Attr("epsilon", static_cast(eps)) .Run(); - - return grad_input; + + return grad_input; } tuple batch_norm_backward_impl( @@ -142,7 +136,7 @@ tuple batch_norm_backward_impl( train, eps); - // calculate grad_input by NPU + // calculate grad_input by NPU if (grad_input_mask[0]) { if (!train) { batch_norm_backward_infer_nocheck( @@ -174,12 +168,12 @@ tuple batch_norm_backward_impl( eps); } } - + return tuple(grad_input, grad_weight, grad_bias); } } -tuple NPUNativeFunctions::native_batch_norm_backward( +tuple XLANativeFunctions::native_batch_norm_backward( const at::Tensor& grad_out, const at::Tensor& self, const c10::optional& weight_opt, @@ -196,58 +190,47 @@ tuple NPUNativeFunctions::native_batch_norm_ const at::Tensor& running_var = c10::value_or_else(running_var_opt, [] {return at::Tensor();}); const at::Tensor& save_mean = c10::value_or_else(save_mean_opt, [] {return at::Tensor();}); const at::Tensor& save_invstd = c10::value_or_else(save_invstd_opt, [] {return at::Tensor();}); - - at::Tensor self_reshape; - at::Tensor grad_out_reshape; + + at::Tensor self_4d; + at::Tensor grad_out_4d; c10::SmallVector self_shape = array_to_small_vector(self.sizes()); if (grad_out.dim() <= 4) { c10::SmallVector nchw_shape(self_shape); nchw_shape.resize(4, 1); - self_reshape = self.reshape(nchw_shape); - grad_out_reshape = grad_out.reshape(nchw_shape); - } else if (train && grad_out.dim() == 5) { - // Use 3D BN ops for training, merging axes is not required. - self_reshape = self; - grad_out_reshape = grad_out; - } else { - // Infering uses 2dInfer Op, case no matched 3DInfer Op + self_4d = self.reshape(nchw_shape); + grad_out_4d = grad_out.reshape(nchw_shape); + } else if (grad_out.dim() == 5) { // ncdhw -> ndchw - self_reshape = self.permute({0, 2, 1, 3, 4}); - grad_out_reshape = grad_out.permute({0, 2, 1, 3, 4}); + self_4d = self.permute({0, 2, 1, 3, 4}); + grad_out_4d = grad_out.permute({0, 2, 1, 3, 4}); // nchw=(n*d, c, h, w) c10::SmallVector nchw_shape = {self_shape[0] * self_shape[2], self_shape[1], self_shape[3], self_shape[4]}; // ndchw -> nchw - self_reshape = self_reshape.reshape(nchw_shape); - grad_out_reshape = grad_out_reshape.reshape(nchw_shape); - + self_4d = self_4d.reshape(nchw_shape); + grad_out_4d = grad_out_4d.reshape(nchw_shape); } // init optional input - int64_t dim_c = self_reshape.size(1); - at::TensorOptions options = self.options().dtype(at::ScalarType::Float); - - at::Tensor weight_cp = weight; - at::Tensor running_mean_cp = running_mean; - at::Tensor running_var_cp = running_var; + int64_t dim_c = self_4d.size(1); + at::TensorOptions options = self.options().dtype(c10::ScalarType::Float); - // 2D/3D BN Ops support ACL_FORMAT_NC1HWC0 format 1D Input tensor. - at::Tensor weight_tensor = weight.defined() ? NPUNativeFunctions::npu_format_cast_(weight_cp, ACL_FORMAT_NC1HWC0) : at::ones({dim_c}, options); - at::Tensor running_mean_tensor = running_mean.defined() ? NPUNativeFunctions::npu_format_cast_(running_mean_cp, ACL_FORMAT_NC1HWC0) : at::zeros({dim_c}, options); - at::Tensor running_var_tensor = running_var.defined() ? NPUNativeFunctions::npu_format_cast_(running_var_cp, ACL_FORMAT_NC1HWC0) : at::ones({dim_c}, options); + at::Tensor weight_tensor = weight.defined() ? weight : at::ones({dim_c}, options); + at::Tensor running_mean_tensor = running_mean.defined() ? running_mean : at::zeros({dim_c}, options); + at::Tensor running_var_tensor = running_var.defined() ? running_var : at::ones({dim_c}, options); // construct the output tensor of the NPU - at::Tensor grad_input = OpPreparation::ApplyTensor(self_reshape.sizes(), self_reshape.options(), self_reshape); - at::Tensor grad_weight = OpPreparation::ApplyTensor(weight_tensor, weight_tensor.options().dtype(at::ScalarType::Float)); - at::Tensor grad_bias = OpPreparation::ApplyTensor(weight_tensor, weight_tensor.options().dtype(at::ScalarType::Float)); + at::Tensor grad_input = OpPreparation::ApplyTensor(self_4d.sizes(), self_4d.options(), self_4d); + at::Tensor grad_weight = OpPreparation::ApplyTensor(weight_tensor.sizes(), weight_tensor.options(), weight_tensor); + at::Tensor grad_bias = OpPreparation::ApplyTensor(weight_tensor.sizes(), weight_tensor.options(), weight_tensor); // calculate the output result of the NPU batch_norm_backward_impl( grad_input, grad_weight, grad_bias, - grad_out_reshape, - self_reshape, + grad_out_4d, + self_4d, weight_tensor, running_mean_tensor, running_var_tensor, @@ -256,14 +239,14 @@ tuple NPUNativeFunctions::native_batch_norm_ train, eps, grad_input_mask); - + // grad_input_mask at::Tensor undefine_grad_input; at::Tensor undefine_grad_weight; at::Tensor undefine_grad_bias; if (grad_input_mask[0]) { - if (!train && self.dim() == 5) { + if (self.dim() == 5) { // NCHW -> NDCHW ->NCDHW std::swap(self_shape[1], self_shape[2]); grad_input = grad_input.view(self_shape); @@ -287,5 +270,6 @@ tuple NPUNativeFunctions::native_batch_norm_ return std::make_tuple(grad_input, grad_weight, grad_bias); } + } // namespace native -} // namespace at_npu \ No newline at end of file +} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardReduceKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardReduceKernelNpu.cpp deleted file mode 100644 index 974dfa0955..0000000000 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormBackwardReduceKernelNpu.cpp +++ /dev/null @@ -1,152 +0,0 @@ - -// Copyright (c) 2022 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple batch_norm_backward_reduce_npu_impl( - at::Tensor& sum_dy, - at::Tensor& sum_dy_xmu, - at::Tensor& grad_weight, - at::Tensor& grad_bias, - const at::Tensor& grad_out, - const at::Tensor& self, - const at::Tensor& mean, - const at::Tensor& invstd, - const at::Tensor& weight, - bool input_g, - bool weight_g, - bool bias_g, - bool isFullyFp16 = false) { - at::Tensor sum_dy_; - at::Tensor sum_dy_xmu_; - at::Tensor grad_bias_; - - at::Tensor grad_out_ = grad_out.scalar_type() == at::kFloat ? grad_out : - NPUNativeFunctions::npu_dtype_cast(grad_out, at::kFloat); - at::Tensor self_ = self.scalar_type() == at::kFloat ? self : - NPUNativeFunctions::npu_dtype_cast(self, at::kFloat); - at::Tensor mean_ = mean.scalar_type() == at::kFloat ? mean : - NPUNativeFunctions::npu_dtype_cast(mean, at::kFloat); - at::Tensor invstd_ = invstd.scalar_type() == at::kFloat ? invstd : - NPUNativeFunctions::npu_dtype_cast(invstd, at::kFloat); - at::Tensor weight_ = weight.scalar_type() == at::kFloat ? weight : - NPUNativeFunctions::npu_dtype_cast(weight, at::kFloat); - - c10::SmallVector axes; - int dimN = self_.ndimension(); - for(int i = 0; i < dimN; i++){ - if (i == 1) { - continue; - } - axes.emplace_back(i); - } - // sum_dy_xmu - at::Tensor mul_dy_dx = grad_out_ * self_; - sum_dy_xmu_ = at::sum(mul_dy_dx, axes, false); - grad_bias_ = at::sum(grad_out_, axes, false); - sum_dy_ = grad_bias_; - - // grad_weight - at::Tensor sum_dy_xmu_out = OpPreparation::ApplyTensor(sum_dy_); - at::Tensor grad_weight_res = OpPreparation::ApplyTensor(invstd_); - OpCommand cmd; - cmd.Name("SyncBatchNormBackwardReduce") - .Input(sum_dy_) - .Input(sum_dy_xmu_) - .Input(mean_) - .Input(invstd_) - .Output(sum_dy_xmu_out) - .Output(grad_weight_res) - .Run(); - if (input_g){ - sum_dy_xmu.copy_(sum_dy_xmu_out); - sum_dy.copy_(sum_dy_); - } - if (weight_g) { - grad_weight.copy_(grad_weight_res); - } - if (bias_g) { - grad_bias.copy_(grad_bias_); - } - - return std::tie(sum_dy, sum_dy_xmu, grad_weight, grad_bias); -} - -std::tuple NPUNativeFunctions::batch_norm_backward_reduce( - const at::Tensor& grad_out, - const at::Tensor& self, - const at::Tensor& mean, - const at::Tensor& invstd, - const c10::optional& weight_opt, - bool input_g, - bool weight_g, - bool bias_g) { - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - TORCH_CHECK( - self.scalar_type() == grad_out.scalar_type(), - "Expected input's dtype equal grad_out's dtype ", - grad_out.scalar_type(), - "But found ", - self.scalar_type()); - bool isFullyFp16 = false; - if (self.scalar_type() == mean.scalar_type() && self.scalar_type() == at::kHalf) { - isFullyFp16 = true; - } - int64_t n_input = self.size(1); - at::Tensor sum_dy_; - at::Tensor sum_dy_xmu_; - at::Tensor grad_weight_; - at::Tensor grad_bias_; - - at::Tensor weight_ = weight.defined() ? weight : at::native::ones({n_input}, self.options().dtype( - isFullyFp16 ? at::kHalf : at::kFloat)); - - if (input_g) { - sum_dy_ = OpPreparation::ApplyTensor(mean, mean.options().dtype(isFullyFp16 ? at::kHalf : at::kFloat)); - sum_dy_xmu_ = OpPreparation::ApplyTensor(mean, mean.options().dtype(isFullyFp16 ? at::kHalf : at::kFloat)); - } - if (weight_g) { - grad_weight_ = OpPreparation::ApplyTensor({n_input}, weight_.options().dtype( - isFullyFp16 ? at::kHalf : at::kFloat), weight_); - } - if (bias_g) { - grad_bias_ = OpPreparation::ApplyTensor({n_input}, weight_.options().dtype( - isFullyFp16 ? at::kHalf : at::kFloat), weight_); - } - batch_norm_backward_reduce_npu_impl( - sum_dy_, - sum_dy_xmu_, - grad_weight_, - grad_bias_, - grad_out, - self, - mean, - invstd, - weight, - input_g, - weight_g, - bias_g, - isFullyFp16); - return std::tie(sum_dy_, sum_dy_xmu_, grad_weight_, grad_bias_); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormElemtKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormElemtKernelNpu.cpp deleted file mode 100644 index a83affa7a3..0000000000 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormElemtKernelNpu.cpp +++ /dev/null @@ -1,93 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& batch_norm_elemt_nocheck( - at::Tensor& result, - const at::Tensor& self, - const c10::optional& weight_opt, - const c10::optional& bias_opt, - const at::Tensor& mean, - const at::Tensor& invstd, - double eps) { - auto dimC = self.size(1); - auto options = self.options().dtype(at::kFloat); - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - - at::Tensor weight_ = weight.defined() ? weight : at::ones({dimC}, options); - at::Tensor bias_ = bias.defined() ? bias : at::ones({dimC}, options); - at::Tensor mean_ = mean.defined() ? mean : at::ones({dimC}, options); - at::Tensor invstd_ = invstd.defined() ? invstd : at::ones({dimC}, options); - TORCH_CHECK(weight.dim() == 1 && bias.dim() == 1 && mean.dim() == 1 && invstd.dim() == 1, - "weight, bias, mean, invstd: must be only one dimension."); - TORCH_CHECK(weight.size(0) == dimC && bias.size(0) == dimC && mean.size(0) == dimC && invstd.size(0) == dimC, - "weight, bias, mean, invstd: shape must be equal to self's dimC."); - at::Tensor one = at::ones({1}, options); - auto variance = at::mul(invstd_, invstd_); - variance = at::div(one, variance) - eps; - int64_t selfDim = self.dim(); - at::Tensor self5d(self); - c10::SmallVector selfShape = array_to_small_vector(self.sizes()); - if (selfDim > 5) { - self5d = self.reshape({self.size(0), self.size(1), self.size(2), self.size(3), -1}); - } - std::tuple bnReult = at::native_batch_norm( - self5d, weight_, bias_, mean_, variance, false, 0.0, eps); - result.copy_(std::get<0>(bnReult)); - if (selfDim > 5) { - result = result.view(selfShape); - } - return result; -} - -at::Tensor& NPUNativeFunctions::batch_norm_elemt_out( - const at::Tensor& self, - const c10::optional& weight_opt, - const c10::optional& bias_opt, - const at::Tensor& mean, - const at::Tensor& invstd, - double eps, - at::Tensor& result) { - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - OpPreparation::CheckOut({self}, result, self); - OpPipeWithDefinedOut pipe; - return pipe.CheckMemory({self, weight, bias, mean, invstd}, {result}) - .Func([&self, &weight, &bias, &mean, &invstd, &eps](at::Tensor& result) - {batch_norm_elemt_nocheck(result, self, weight, bias, mean, invstd, eps);}) - .Call(result); -} - -at::Tensor NPUNativeFunctions::batch_norm_elemt( - const at::Tensor& self, - const c10::optional& weight, - const c10::optional& bias, - const at::Tensor& mean, - const at::Tensor& invstd, - double eps) { - at::Tensor result = OpPreparation::ApplyTensor(self); - batch_norm_elemt_nocheck(result, self, weight, bias, mean, invstd, eps); - return result; -} - -} // namespace native -} // namespace at \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormGatherStatsWithCountsKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormGatherStatsWithCountsKernelNpu.cpp deleted file mode 100644 index 846f7190fa..0000000000 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormGatherStatsWithCountsKernelNpu.cpp +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) 2022 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple batch_norm_gather_stats_with_counts_npu_impl( - at::Tensor& mean_all, - at::Tensor& invstd_all, - const at::Tensor& self, - const at::Tensor& mean, - const at::Tensor& invstd, - const at::Tensor& running_mean, - const at::Tensor& running_var, - double momentum, - double eps, - const at::Tensor& counts) { - auto options = self.options(); - auto dimC = self.size(1); - at::Tensor meanCp = NPUNativeFunctions::npu_dtype_cast(mean, at::kFloat); - at::Tensor invstdCp = NPUNativeFunctions::npu_dtype_cast(invstd, at::kFloat); - auto running_mean_dtype = running_mean.scalar_type(); - at::Tensor running_mean_ = NPUNativeFunctions::npu_dtype_cast(NPUNativeFunctions::npu_format_cast((running_mean.defined() ? - running_mean.unsqueeze(0) :at::native::zeros({1, dimC}, options)), ACL_FORMAT_ND), at::kFloat); - at::Tensor running_var_ = NPUNativeFunctions::npu_dtype_cast(NPUNativeFunctions::npu_format_cast((running_var.defined() ? - running_var.unsqueeze(0) :at::native::ones({1, dimC}, options)), ACL_FORMAT_ND), at::kFloat); - at::IntArrayRef axes({0}); - at::Tensor countsTensor; - countsTensor = NPUNativeFunctions::npu_dtype_cast(counts, meanCp.scalar_type()); - at::Tensor countsTensorT = countsTensor.unsqueeze(-1); - at::Tensor countsTensorBroadcast = NPUNativeFunctions::npu_broadcast(countsTensorT, invstd.sizes()); - at::Tensor countsAllSum = OpPreparation::ApplyTensorWithSizes({1, dimC}, meanCp.options()); - OpCommand cmd1; - cmd1.Name("ReduceSum") - .Input(countsTensorBroadcast) - .Input(axes, at::kInt) - .Attr("keep_dims", true) - .Output(countsAllSum) - .Run(); - - at::Tensor countsAllSumBroadcast = countsAllSum.expand(countsTensorBroadcast.sizes()); - OpCommand cmd2; - cmd2.Name("ReduceMeanWithCount") - .Input(meanCp) - .Input(countsTensorBroadcast) - .Input(countsAllSumBroadcast) - .Output(mean_all) - .Attr("axes", axes) - .Attr("keep_dims", true) - .Run(); - - at::Tensor meanBroadcast = mean_all.expand(mean.sizes()); - OpCommand cmd3; - cmd3.Name("SyncBatchNormGatherStatsWithCounts") - .Input(meanCp) - .Input(invstdCp) - .Input(countsTensorBroadcast) - .Input(meanBroadcast) - .Input(countsAllSum) - .Input(running_var_) - .Output(invstd_all) - .Output(running_var_) - .Attr("momentum", static_cast(momentum)) - .Attr("epsilon", static_cast(eps)) - .Run(); - - if (running_mean.defined()){ - OpCommand cmd4; - cmd4.Name("SyncBNTrainingUpdate") - .Input(mean_all) - .Input(running_mean_) - .Output(running_mean_) - .Attr("momentum", static_cast(momentum)) - .Run(); - // running_mean almost apply is the same as running_var - if (running_mean_.scalar_type() != running_mean_dtype) { - running_mean_ = NPUNativeFunctions::npu_dtype_cast(running_mean_, running_mean_dtype); - running_var_ = NPUNativeFunctions::npu_dtype_cast(running_var_, running_mean_dtype); - } - running_mean.copy_(running_mean_.squeeze(0)); - running_var.copy_(running_var_.squeeze(0)); - } - - return std::tie(mean_all, invstd_all); -} - -std::tuple NPUNativeFunctions::batch_norm_gather_stats_with_counts( - const at::Tensor& self, - const at::Tensor& mean, - const at::Tensor& invstd, - const c10::optional& running_mean_opt, - const c10::optional& running_var_opt, - double momentum, - double eps, - const at::Tensor& counts) { - const at::Tensor& running_mean = c10::value_or_else(running_mean_opt, [] {return at::Tensor();}); - const at::Tensor& running_var = c10::value_or_else(running_var_opt, [] {return at::Tensor();}); - bool isFullyFp16 = false; - if (self.scalar_type() == mean.scalar_type() && self.scalar_type() == at::kHalf) { - isFullyFp16 = true; - } - - at::Tensor mean_all = OpPreparation::ApplyTensor({1, self.size(1)}, self.options().dtype(at::kFloat), self); - at::Tensor invstd_all = OpPreparation::ApplyTensor({1, self.size(1)}, self.options().dtype(at::kFloat), self); - - batch_norm_gather_stats_with_counts_npu_impl(mean_all, invstd_all, self, - mean, invstd, running_mean, running_var, - momentum, eps, counts); - - if (isFullyFp16) { - mean_all = NPUNativeFunctions::npu_dtype_cast(mean_all, at::kHalf); - invstd_all = NPUNativeFunctions::npu_dtype_cast(invstd_all, at::kHalf); - } - return std::make_tuple(mean_all.squeeze(0), invstd_all.squeeze(0)); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormKernelNpu.cpp index b53dc6264d..e999bafcf9 100644 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/normalization/BatchNormKernelNpu.cpp @@ -1,5 +1,5 @@ // Copyright (c) 2020 Huawei Technologies Co., Ltd -// Copyright (c) 2019, Facebook CORPORATION. +// Copyright (c) 2019, Facebook CORPORATION. // All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); @@ -15,9 +15,12 @@ // limitations under the License. #include +#include #include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" + #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" + namespace at_npu { namespace native { @@ -35,12 +38,12 @@ at::Tensor& batch_norm_infer_nocheck( double eps) { OpCommand cmd; cmd.Name("BNInfer") - .Input(self, "x", ACL_FORMAT_NCHW) - .Input(weight, "scale", ACL_FORMAT_NCHW) - .Input(bias, "offset", ACL_FORMAT_NCHW) - .Input(running_mean, "mean", ACL_FORMAT_NCHW) - .Input(running_var, "variance", ACL_FORMAT_NCHW) - .Output(result, "y", ACL_FORMAT_NCHW) + .Input(self) + .Input(weight) + .Input(bias) + .Input(running_mean) + .Input(running_var) + .Output(result) .Attr("epsilon", static_cast(eps)) .Run(); @@ -59,13 +62,10 @@ tuple batch_norm_training_reduce_nocheck( double momentum, double eps) { OpCommand cmd; - string name = (self.dim() == 5) ? "BN3DTrainingReduce" : "BNTrainingReduce"; - auto format = (self.dim() == 5) ? ACL_FORMAT_NCDHW : ACL_FORMAT_NCHW; - - cmd.Name(name) - .Input(self, "x", format) - .Output(sum, "sum", ACL_FORMAT_NCHW) - .Output(square_sum, "square_sum", ACL_FORMAT_NCHW) + cmd.Name("BNTrainingReduce") + .Input(self) + .Output(sum) + .Output(square_sum) .Attr("epsilon", static_cast(eps)) .Run(); @@ -87,25 +87,22 @@ tuple batch_norm_training_update_nocheck( double momentum, double eps) { OpCommand cmd; - string name = (self.dim() == 5) ? "BN3DTrainingUpdate" : "BNTrainingUpdate"; - auto format = (self.dim() == 5) ? ACL_FORMAT_NCDHW : ACL_FORMAT_NCHW; - - cmd.Name(name) - .Input(self, "x", format) - .Input(sum, "sum", ACL_FORMAT_NCHW) - .Input(square_sum, "square_sum", ACL_FORMAT_NCHW) - .Input(weight, "scale", ACL_FORMAT_NCHW) - .Input(bias, "offset", ACL_FORMAT_NCHW) - .Input(running_mean, "mean", ACL_FORMAT_NCHW) - .Input(running_var, "variance", ACL_FORMAT_NCHW) - .Output(result, "y", format) - .Output(const_cast(running_mean), "mean", ACL_FORMAT_NCHW) - .Output(const_cast(running_var), "variance", ACL_FORMAT_NCHW) - .Output(save_mean, "batch_mean", ACL_FORMAT_NCHW) - .Output(save_invstd, "batch_variance", ACL_FORMAT_NCHW) + cmd.Name("BNTrainingUpdate") + .Input(self) + .Input(sum) + .Input(square_sum) + .Input(weight) + .Input(bias) + .Input(running_mean) + .Input(running_var) + .Output(result) + .Output(const_cast(running_mean)) + .Output(const_cast(running_var)) + .Output(save_mean) + .Output(save_invstd) .Attr("epsilon", static_cast(eps)) .Attr("factor", static_cast(momentum)) - .Run(); + .Run(); return tuple(result, save_mean, save_invstd); } @@ -152,24 +149,6 @@ tuple batch_norm_impl( momentum, eps); - // BNTrainingUpdate can only support FP32 for mean and var - auto running_mean_fp32 = running_mean; - auto running_var_fp32 = running_var; - auto weight_fp32 = weight; - - if (train && (running_mean.scalar_type() != at::kFloat)) { - running_mean_fp32 = NPUNativeFunctions::npu_dtype_cast(running_mean, at::kFloat); - } - - if (train && (running_var.scalar_type() != at::kFloat)) { - running_var_fp32 = NPUNativeFunctions::npu_dtype_cast(running_var, at::kFloat); - } - - // (Ascend) change dtype for matching op requirement. - if (train && (weight.scalar_type() != at::kFloat)) { - weight_fp32 = NPUNativeFunctions::npu_dtype_cast(weight, at::kFloat); - } - batch_norm_training_update_nocheck( result, save_mean, @@ -177,10 +156,10 @@ tuple batch_norm_impl( self, sum, square_sum, - weight_fp32, + weight, bias, - running_mean_fp32, - running_var_fp32, + running_mean, + running_var, train, momentum, eps); @@ -189,7 +168,7 @@ tuple batch_norm_impl( } } // namespace -tuple NPUNativeFunctions::native_batch_norm( +tuple XLANativeFunctions::native_batch_norm( const at::Tensor& self, const c10::optional& weight_opt, const c10::optional& bias_opt, @@ -198,59 +177,38 @@ tuple NPUNativeFunctions::native_batch_norm( bool train, double momentum, double eps) { - - const at::Tensor& weight = c10::value_or_else(weight_opt, [] {return at::Tensor();}); - const at::Tensor& bias = c10::value_or_else(bias_opt, [] {return at::Tensor();}); - const at::Tensor& running_mean = c10::value_or_else(running_mean_opt, [] {return at::Tensor();}); - const at::Tensor& running_var = c10::value_or_else(running_var_opt, [] {return at::Tensor();}); - - at::Tensor self_reshape; + at::Tensor self_4d; c10::SmallVector self_shape = array_to_small_vector(self.sizes()); - int64_t self_npu_format = CalcuOpUtil::get_tensor_npu_format(self); - // BatchNorm is axis sensitive, the size of mean/var depends on dim_c. - if (self_npu_format == ACL_FORMAT_NDHWC || - self_npu_format == ACL_FORMAT_NHWC) { - AT_ERROR( - "at::Tensor with channel last format (", - self_npu_format, - ") is not supported in BatchNorm."); - } - if (self.dim() <= 4) { c10::SmallVector nchw_shape(self_shape); nchw_shape.resize(4, 1); - self_reshape = self.reshape(nchw_shape); - } else if (train && self.dim() == 5) { - // Use 3D BN ops for training, merging axes is not required. - self_reshape = self; - } else { - // Infering uses 2dInfer Op, case no matched 3DInfer Op + self_4d = self.reshape(nchw_shape); + } else if (self.dim() == 5) { // ncdhw -> ndchw - self_reshape = self.permute({0, 2, 1, 3, 4}); + self_4d = self.permute({0, 2, 1, 3, 4}); // nchw=(n*d, c, h, w) c10::SmallVector nchw_shape = {self_shape[0] * self_shape[2], self_shape[1], self_shape[3], self_shape[4]}; // ndchw -> nchw - self_reshape = self_reshape.reshape(nchw_shape); + self_4d = self_4d.reshape(nchw_shape); } // process when affine=Flase and track_running_stats=False - int64_t dim_c = self_reshape.size(1); - at::TensorOptions options = self.options().dtype(at::ScalarType::Float); + int64_t dim_c = self_4d.size(1); + at::TensorOptions options = self.options().dtype(c10::ScalarType::Float); - at::Tensor weight_cp = weight; - at::Tensor bias_cp = bias; - at::Tensor running_mean_cp = running_mean; - at::Tensor running_var_cp = running_var; + at::Tensor running_mean_tensor = + (running_mean_opt.has_value() && running_mean_opt.value().defined()) ? running_mean_opt.value() : at::zeros({dim_c}, options); + at::Tensor running_var_tensor = + (running_var_opt.has_value() && running_var_opt.value().defined()) ? running_var_opt.value() : at::ones({dim_c}, options); - // 2D/3D BN Ops support ACL_FORMAT_NC1HWC0 format tensor(1D). - at::Tensor running_mean_tensor = running_mean.defined() ? NPUNativeFunctions::npu_format_cast_(running_mean_cp, ACL_FORMAT_NC1HWC0) : at::zeros({dim_c}, options); - at::Tensor running_var_tensor = running_var.defined() ? NPUNativeFunctions::npu_format_cast_(running_var_cp, ACL_FORMAT_NC1HWC0) : at::ones({dim_c}, options); - at::Tensor weight_tensor = weight.defined() ? NPUNativeFunctions::npu_format_cast_(weight_cp, ACL_FORMAT_NC1HWC0) : at::ones({dim_c}, options); - at::Tensor bias_tensor = bias.defined() ? NPUNativeFunctions::npu_format_cast_(bias_cp, ACL_FORMAT_NC1HWC0) : at::zeros({dim_c}, options); + at::Tensor weight_tensor = + (weight_opt.has_value() && weight_opt.value().defined()) ? weight_opt.value() : at::ones({dim_c}, options); + at::Tensor bias_tensor = + (bias_opt.has_value() && bias_opt.value().defined()) ? bias_opt.value() : at::zeros({dim_c}, options); // construct the output tensor of the NPU - at::Tensor result = OpPreparation::ApplyTensor(self_reshape.sizes(), self_reshape.options(), self_reshape); + at::Tensor result = OpPreparation::ApplyTensor(self_4d.sizes(), self_4d.options(), self_4d); at::Tensor save_mean; at::Tensor save_invstd; @@ -258,8 +216,8 @@ tuple NPUNativeFunctions::native_batch_norm( save_mean = OpPreparation::ApplyTensor(running_mean_tensor.sizes(), running_mean_tensor.options().dtype(at::kFloat), running_mean_tensor); save_invstd = OpPreparation::ApplyTensor(running_var_tensor.sizes(), running_var_tensor.options().dtype(at::kFloat), running_var_tensor); } else { - save_mean = {}; - save_invstd = {}; + //save_mean = {}; + //save_invstd = {}; } // calculate the output result of the NPU @@ -267,7 +225,7 @@ tuple NPUNativeFunctions::native_batch_norm( result, save_mean, save_invstd, - self_reshape, + self_4d, weight_tensor, bias_tensor, running_mean_tensor, @@ -276,8 +234,7 @@ tuple NPUNativeFunctions::native_batch_norm( momentum, eps); - // Inverse reshape procedure using for recovering original shape of self. - if (!train && self.dim() == 5) { + if (self.dim() == 5) { // NCHW -> NDCHW -> NCDHW std::swap(self_shape[1], self_shape[2]); result = result.view(self_shape); diff --git a/torch_npu/csrc/aten/ops/normalization/BatchNormStatsKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/BatchNormStatsKernelNpu.cpp deleted file mode 100644 index 6898ea6a7d..0000000000 --- a/torch_npu/csrc/aten/ops/normalization/BatchNormStatsKernelNpu.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) 2022 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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -std::tuple batch_norm_stats_out_npu_nocheck( - at::Tensor& mean, - at::Tensor& invstd, - const at::Tensor& self, - double eps) { - c10::SmallVector dim; - int dimN = self.ndimension(); - for(int i = 0; i < dimN; i++){ - if (i == 1) { - continue; - } - dim.emplace_back(i); - } - at::Tensor selfCp = self; - if (self.scalar_type() != at::kFloat){ - selfCp = NPUNativeFunctions::npu_dtype_cast(selfCp, at::kFloat); - } - OpCommand cmd1; - cmd1.Name("ReduceMean") - .Input(selfCp) - .Input(dim, at::kInt) - .Output(mean) - .Attr("keep_dims", (bool) false) - .Run(); - - at::Tensor meanCp = mean; - if (mean.dim() != 0) { - auto dimVector = array_to_small_vector(dim); - for (int64_t i = 0; i < dimVector.size(); i++) { - meanCp = meanCp.unsqueeze(dimVector[i]); - } - } - meanCp = meanCp.expand(self.sizes()); - OpCommand cmd2; - cmd2.Name("ReduceStdWithMean") - .Input(selfCp) - .Input(meanCp) - .Output(invstd) - .Attr("dim", dim) - .Attr("unbiased", false) - .Attr("keepdim", false) - .Attr("invert", true) - .Attr("epsilon", static_cast(eps)) - .Run(); - - return std::tie(mean, invstd); -} - -std::tuple NPUNativeFunctions::batch_norm_stats( - const at::Tensor& self, - double eps) { - TORCH_CHECK( - self.ndimension() >= 2, - "Expected 2D+ Tensor, but got tensor with ", - self.ndimension(), - " Dimension"); - at::Tensor mean = OpPreparation::ApplyTensor({self.size(1)}, self.options().dtype(at::kFloat), self); - at::Tensor invstd = OpPreparation::ApplyTensor({self.size(1)}, self.options().dtype(at::kFloat), self); - batch_norm_stats_out_npu_nocheck(mean, invstd, self, eps); - - return std::tie(mean, invstd); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/normalization/NormalizationKernelNpu.cpp b/torch_npu/csrc/aten/ops/normalization/NormalizationKernelNpu.cpp index 0a0e0049e4..214ecd95ee 100644 --- a/torch_npu/csrc/aten/ops/normalization/NormalizationKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/normalization/NormalizationKernelNpu.cpp @@ -20,13 +20,13 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - -at::Tensor NPUNativeFunctions::batch_norm( +/* +at::Tensor XLANativeFunctions::batch_norm( const at::Tensor& input, const c10::optional& weight_opt, const c10::optional& bias_opt, @@ -67,7 +67,7 @@ at::Tensor NPUNativeFunctions::batch_norm( cudnn_enabled)); } -tuple NPUNativeFunctions::_batch_norm_impl_index( +tuple XLANativeFunctions::_batch_norm_impl_index( const at::Tensor& input, const c10::optional& weight, const c10::optional& bias, @@ -92,7 +92,7 @@ tuple NPUNativeFunction std::make_tuple(0)); } -tuple NPUNativeFunctions::_batch_norm_impl_index_backward( +tuple XLANativeFunctions::_batch_norm_impl_index_backward( int64_t impl_index, const at::Tensor& input, const at::Tensor& grad_output, @@ -116,7 +116,7 @@ tuple NPUNativeFunctions::_batch_norm_impl_i train, epsilon, output_mask); -} +}*/ } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool1dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool1dKernelNpu.cpp deleted file mode 100644 index ae50870d0f..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool1dKernelNpu.cpp +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -static void check1d( - const char* function_name, - const char* argument_name, - at::IntArrayRef x) { - TORCH_CHECK( - x.size() == 1, - function_name, "() argument '", argument_name, - "' should contain one int (got ", x.size(), ")"); -} - -at::Tensor NPUNativeFunctions::adaptive_avg_pool1d(const at::Tensor& self, at::IntArrayRef output_size) { - at::checkDim("adaptive_avg_pool1d", at::TensorArg(self, "self", 1), 3); - check1d("adaptive_avg_pool1d", "output_size", output_size); -// construct the output tensor of the NPU - auto output = NPUNativeFunctions::adaptive_avg_pool2d( - self.unsqueeze(2), - {1, output_size[0]}); - - return output.squeeze(2); -} - -} // namespace native -} // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dBackwardKernelNpu.cpp index c81be15ca4..b017df24a2 100644 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dBackwardKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -56,7 +56,7 @@ at::Tensor& adaptive_avg_pool2d_backward_out_npu( return result; } -at::Tensor NPUNativeFunctions::_adaptive_avg_pool2d_backward( +at::Tensor XLANativeFunctions::_adaptive_avg_pool2d_backward( const at::Tensor& grad_output, const at::Tensor& self) { at::Tensor result = OpPreparation::ApplyTensor(self); diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dKernelNpu.cpp index 80c0f85958..b517794670 100644 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool2dKernelNpu.cpp @@ -15,13 +15,13 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::adaptive_avg_pool2d_out( +at::Tensor& XLANativeFunctions::adaptive_avg_pool2d_out( const at::Tensor& self, at::IntArrayRef output_size, at::Tensor& result) { @@ -38,13 +38,13 @@ at::Tensor& NPUNativeFunctions::adaptive_avg_pool2d_out( return result; } - -at::Tensor NPUNativeFunctions::adaptive_avg_pool2d(const at::Tensor& self, at::IntArrayRef output_size) { +/* +at::Tensor XLANativeFunctions::adaptive_avg_pool2d(const at::Tensor& self, at::IntArrayRef output_size) { // The logic is a little different from CPU_impl return at::_adaptive_avg_pool2d(self, output_size); -} +}*/ -at::Tensor NPUNativeFunctions::_adaptive_avg_pool2d(const at::Tensor& self, at::IntArrayRef output_size) { +at::Tensor XLANativeFunctions::_adaptive_avg_pool2d(const at::Tensor& self, at::IntArrayRef output_size) { for (int64_t i = 0; i < self.dim(); i++) { TORCH_CHECK( self.size(i) > 0, @@ -66,7 +66,7 @@ at::Tensor NPUNativeFunctions::_adaptive_avg_pool2d(const at::Tensor& self, at:: at::Tensor result = OpPreparation::ApplyTensor(self, outputSize); - NPUNativeFunctions::adaptive_avg_pool2d_out(self, output_size, result); + XLANativeFunctions::adaptive_avg_pool2d_out(self, output_size, result); return result; } diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool3dBackwardKernelNpu.cpp deleted file mode 100644 index 161511f9ff..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,61 +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. - -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -int64_t adaptive_avg_pool3d_backward_safe_size(const at::Tensor& self){ - c10::SmallVector dims = {-3, -2, -1}; - int64_t size = 1; - if (self.sizes().empty()) { - return size; - } - for (int64_t ndim : dims) { - ndim = CalcuOpUtil::make_wrap_dim(ndim, self.sizes().size()); - size *= self.sizes()[ndim]; - } - return size; -} - -at::Tensor& NPUNativeFunctions::adaptive_avg_pool3d_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - at::Tensor& result){ - if (grad_output.size(grad_output.dim() - 3) == 1 && grad_output.size(grad_output.dim() - 2) == 1 && - grad_output.size(grad_output.dim() - 1) == 1){ - result.fill_(1.0 / adaptive_avg_pool3d_backward_safe_size(self)); - result.mul_(grad_output); - } else { - TORCH_CHECK(false, - "adaptive_avg_pool3d_backward only support D=1 && H=1 && W=1 current!"); - } - return result; -} - -at::Tensor NPUNativeFunctions::adaptive_avg_pool3d_backward(const at::Tensor& grad_output, const at::Tensor& self){ - at::Tensor result = OpPreparation::ApplyTensor(self); - NPUNativeFunctions::adaptive_avg_pool3d_backward_out(grad_output, self, result); - return result; -} - - -} // native -} // at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool3dKernelNpu.cpp deleted file mode 100644 index 3abf58d50c..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveAvgPool3dKernelNpu.cpp +++ /dev/null @@ -1,62 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -at::Tensor& NPUNativeFunctions::adaptive_avg_pool3d_out( - const at::Tensor& self, - at::IntArrayRef output_size, - at::Tensor& result) { - // reuse the mean out when d,h,w=1 - if (output_size[0] == 1 && output_size[1] == 1 && output_size[2] == 1) { - at::mean_out(result, self, {self.dim() - 3, self.dim() - 2, self.dim() - 1}, true); - } else { - TORCH_CHECK(false, - "adaptive_avg_pool3d only support D=1 && H=1 && W=1 current!"); - } - return result; -} - -at::Tensor NPUNativeFunctions::adaptive_avg_pool3d(const at::Tensor& self, at::IntArrayRef output_size) { - for (int64_t i = 0; i < self.dim(); i++) { - TORCH_CHECK( - self.size(i) > 0, - "adaptive_avg_pooling3d(): expected input to have non-empty spatial dimensions, " - "but input has sizes ", - self.sizes(), - " with dimension ", - i, - " being " - "empty"); - } - TORCH_CHECK( - (self.dim() == 4 || self.dim() == 5), - "non-empty 4D or 5D (batch mode) tensor expected for input"); - auto outputSize = adaptive_avg_pool3d_npu_output_size(self, output_size); - at::Tensor result = OpPreparation::ApplyTensor(outputSize, self.options(), self); - - NPUNativeFunctions::adaptive_avg_pool3d_out(self, output_size, result); - return result; -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveMaxPool2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveMaxPool2dBackwardKernelNpu.cpp deleted file mode 100644 index 5ba51d951e..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveMaxPool2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -at::Tensor& NPUNativeFunctions::adaptive_max_pool2d_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& indices, - at::Tensor& grad_input) { - auto inputsize = self.sizes(); - c10::SmallVector input_size; - if (inputsize.size() == 3) { - c10::SmallVector size = { inputsize[1], inputsize[2] }; - input_size = at::IntArrayRef(size); - } else if (inputsize.size() == 4) { - c10::SmallVector size = { inputsize[2], inputsize[3] }; - input_size = at::IntArrayRef(size); - } - c10::SmallVector output_size = { - grad_output.size(grad_output.dim() - 2), - grad_output.size(grad_output.dim() - 1)}; - - if (input_size[0] % output_size[0] == 0 && input_size[1] % output_size[1] == 0) { - int64_t kernel_size[2]; - int64_t stride[2]; - int64_t padding[2]; - int64_t strideH = input_size[0] / output_size[0]; - int64_t strideW = input_size[1] / output_size[1]; - int64_t kernel_sizeH = input_size[0] - (output_size[0] - 1) * strideH; - int64_t kernel_sizeW = input_size[1] - (output_size[1] - 1) * strideW; - stride[0] = strideH; - stride[1] = strideW; - kernel_size[0] = kernel_sizeH; - kernel_size[1] = kernel_sizeW; - padding[0] = padding[1] = 0; - c10::SmallVector kernelSize = {1, kernel_size[0], kernel_size[1], 1}; - c10::SmallVector stridesSize = {1, stride[0], stride[1], 1}; - c10::SmallVector paddings = {1, padding[0], padding[1], 1}; - c10::SmallVector dilations = {1, 1, 1, 1}; - bool ceil_mode = false; - OpCommand cmd; - cmd.Name("MaxPoolGradWithArgmaxV1") - .Input(self) - .Input(grad_output) - .Input(indices, "", c10::nullopt, "uint16") - .Output(grad_input) - .Attr("ksize", kernelSize) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilations", dilations) - .Attr("ceil_mode", ceil_mode) - .Run(); - } else { - // H and W can not be divided, temporarily reported error processing - AT_ERROR("H and W must be divisible"); - } - return grad_input; -} - -at::Tensor NPUNativeFunctions::adaptive_max_pool2d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& indices) { - TORCH_CHECK( - (self.dim() == 3 || self.dim() == 4), - "non-empty 3D or 4D (batch mode) tensor expected for input"); - at::Tensor grad_input = OpPreparation::ApplyTensorWithFormat(self, ACL_FORMAT_NC1HWC0); - NPUNativeFunctions::adaptive_max_pool2d_backward_out(grad_output, self, indices, grad_input); - return grad_input; -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/AdaptiveMaxPool2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AdaptiveMaxPool2dKernelNpu.cpp deleted file mode 100644 index 64bd6cd9e3..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AdaptiveMaxPool2dKernelNpu.cpp +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -tuple NPUNativeFunctions::adaptive_max_pool2d_out( - const at::Tensor& self, - at::IntArrayRef output_size, - at::Tensor& output, - at::Tensor& indices) { - OpPreparation::CheckMemory({self}, {output, indices}); - auto inputsize = self.sizes(); - c10::SmallVector input_size; - if (inputsize.size() == 3) { - c10::SmallVector size = { inputsize[1], inputsize[2] }; - input_size = at::IntArrayRef(size); - } else if (inputsize.size() == 4) { - c10::SmallVector size = { inputsize[2], inputsize[3] }; - input_size = at::IntArrayRef(size); - } - if (input_size[0] % output_size[0] == 0 && input_size[1] % output_size[1] == 0) { - int64_t kernel_size[2]; - int64_t stride[2]; - int64_t padding[2]; - int64_t strideH = input_size[0] / output_size[0]; - int64_t strideW = input_size[1] / output_size[1]; - int64_t kernel_sizeH = input_size[0] - (output_size[0] - 1) * strideH; - int64_t kernel_sizeW = input_size[1] - (output_size[1] - 1) * strideW; - stride[0] = strideH; - stride[1] = strideW; - kernel_size[0] = kernel_sizeH; - kernel_size[1] = kernel_sizeW; - padding[0] = padding[1] = 0; - c10::SmallVector kernelSize = {1, kernel_size[0], kernel_size[1], 1}; - c10::SmallVector stridesSize = {1, stride[0], stride[1], 1}; - c10::SmallVector paddings = {1, padding[0], padding[1], 1}; - c10::SmallVector dilations = {1, 1, 1, 1}; - bool ceil_mode = false; - - OpCommand cmd; - cmd.Name("MaxPoolWithArgmaxV1") - .Input(self) - .Output(output) - .Output(indices, "", c10::nullopt, "uint16") - .Attr("ksize", kernelSize) - .Attr("strides", stridesSize) - .Attr("pads", paddings) - .Attr("dilation", dilations) - .Attr("ceil_mode", ceil_mode) - .Run(); - - } else { - // H and W can not be divided, temporarily reported error processing - AT_ERROR("H and W must be divisible"); - } - return tuple(output, indices); -} - -tuple NPUNativeFunctions::adaptive_max_pool2d( - const at::Tensor& self, - at::IntArrayRef output_size) { - for (int64_t i = 0; i < self.dim(); i++) { - TORCH_CHECK( - self.size(i) > 0, - "adaptive_max_pooling2d(): expected input to have non-empty spatial dimensions, " - "but input has sizes ", - self.sizes(), - " with dimension ", - i, - " being " - "empty"); - } - TORCH_CHECK( - (self.dim() == 3 || self.dim() == 4), - "non-empty 3D or 4D (batch mode) tensor expected for input"); - TORCH_CHECK( - (output_size.size() == 2), - "adaptive_max_pool2d: internal error: output_size.size() must be 2"); - int64_t n = self.size(0); - int64_t c = self.size(1); - int64_t h = self.size(2); - int64_t w = self.size(3); - int64_t strideH = h / output_size[0]; - int64_t strideW = w / output_size[1]; - int64_t kernel_sizeH = h - (output_size[0] - 1) * strideH; - int64_t kernel_sizeW = w - (output_size[1] - 1) * strideW; - int64_t Ho = output_size[0]; - int64_t Wo = output_size[1]; - c10::SmallVector outputSize = {n, c, Ho, Wo}; - const int64_t BLOCKSIZE = 16; - int64_t maskH = kernel_sizeH * kernel_sizeW; - int64_t maskW = (CeilDiv(Ho * Wo, BLOCKSIZE) + 1); - c10::SmallVector indicesSize = {n, c, maskH, maskW}; - at::Tensor output = OpPreparation::ApplyTensorWithFormat(self, outputSize, ACL_FORMAT_NC1HWC0); - at::Tensor indices = OpPreparation::ApplyTensorWithFormat(indicesSize, self.options().dtype(at::kLong), ACL_FORMAT_NC1HWC0); - - NPUNativeFunctions::adaptive_max_pool2d_out(self, output_size, output, indices); - return tuple(output, indices); -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/AvgPool2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AvgPool2dBackwardKernelNpu.cpp index f3f6ee2100..b35e225a43 100644 --- a/torch_npu/csrc/aten/ops/pooling/AvgPool2dBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/AvgPool2dBackwardKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -48,7 +48,7 @@ at::Tensor& avg_pool2d_backward_out_npu_nocheck( OpPreparation::CheckMemory({grad_output, self}, {grad_input}); OpCommand cmd; cmd.Name("AvgPoolV2Grad") - .Input(self.sizes()) + .Input(self.sizes(), at::kInt) .Input(grad_output) .Output(grad_input) .Attr("ksize", kernelSize) @@ -63,7 +63,7 @@ at::Tensor& avg_pool2d_backward_out_npu_nocheck( return grad_input; } -at::Tensor& NPUNativeFunctions::avg_pool2d_backward_out( +at::Tensor& XLANativeFunctions::avg_pool2d_backward_out( const at::Tensor& grad_output, const at::Tensor& self, at::IntArrayRef kernel_size, @@ -105,7 +105,7 @@ at::Tensor& NPUNativeFunctions::avg_pool2d_backward_out( return grad_input; } -at::Tensor NPUNativeFunctions::avg_pool2d_backward( +at::Tensor XLANativeFunctions::avg_pool2d_backward( const at::Tensor& grad_output, const at::Tensor& self, at::IntArrayRef kernel_size, @@ -116,7 +116,7 @@ at::Tensor NPUNativeFunctions::avg_pool2d_backward( c10::optional divisor_override) { at::Tensor grad_input = OpPreparation::ApplyTensor(self); - NPUNativeFunctions::avg_pool2d_backward_out( + XLANativeFunctions::avg_pool2d_backward_out( grad_output, self, kernel_size, diff --git a/torch_npu/csrc/aten/ops/pooling/AvgPool2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AvgPool2dKernelNpu.cpp index 6027418b30..9bb97b1b5f 100644 --- a/torch_npu/csrc/aten/ops/pooling/AvgPool2dKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/AvgPool2dKernelNpu.cpp @@ -16,7 +16,7 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { @@ -62,7 +62,7 @@ at::Tensor& avg_pool2d_out_npu_nocheck( return result; } -at::Tensor& NPUNativeFunctions::avg_pool2d_out( +at::Tensor& XLANativeFunctions::avg_pool2d_out( const at::Tensor& self, at::IntArrayRef kernel_size, at::IntArrayRef stride, @@ -101,7 +101,7 @@ at::Tensor& NPUNativeFunctions::avg_pool2d_out( return result; } -at::Tensor NPUNativeFunctions::avg_pool2d( +at::Tensor XLANativeFunctions::avg_pool2d( const at::Tensor& self, at::IntArrayRef kernel_size, at::IntArrayRef stride, diff --git a/torch_npu/csrc/aten/ops/pooling/AvgPool3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AvgPool3dBackwardKernelNpu.cpp deleted file mode 100644 index 62ddd65ee8..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AvgPool3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,188 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -void avg_pool3d_backward_out_npu_nocheck( - at::Tensor& grad_output, - const at::Tensor& grad_input, - const at::Tensor& self, - at::IntArrayRef kernel_sizess, - at::IntArrayRef stridess, - at::IntArrayRef paddingss, - bool ceil_mode, - bool count_include_pad, - c10::optional divisor_override) { - at::Tensor input = self; - at::Tensor grads = grad_input.contiguous(); - - grad_output.resize_as_(input); - grad_output.zero_(); - if (self.ndimension() == 4) { - input = input.unsqueeze(0); - grads = grads.unsqueeze(0); - grad_output = grad_output.unsqueeze(0); - } - - c10::SmallVector dimList(input.sizes()); - c10::SmallVector pads = {paddingss[0], paddingss[0], paddingss[1], paddingss[1], paddingss[2], paddingss[2]}; - - OpCommand cmd; - cmd.Name("AvgPool3DGrad") - .Input(dimList) - .Input(grads) - .Output(grad_output) - .Attr("ksize", kernel_sizess) - .Attr("strides", stridess) - .Attr("pads", pads) - .Attr("ceil_mode", ceil_mode) - .Attr("count_include_pad", count_include_pad); - - if (divisor_override.has_value()) { - cmd.Attr("divisor_override", divisor_override.value()); - } - - cmd.Attr("data_format", (string)"NCDHW") - .Run(); - - if (self.ndimension() == 4) { - grad_output = grad_output.squeeze(0); - } -} - -at::Tensor& NPUNativeFunctions::avg_pool3d_backward_out( - const at::Tensor& grad_input, - const at::Tensor& self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - bool ceil_mode, - bool count_include_pad, - c10::optional divisor_override, - at::Tensor& grad_output) { - TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, - "avg_pool3d_backward: kernel_size must be a single int, or a tuple of three ints"); - TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, - "avg_pool3d_backward: stride must be omitted, a single int, or a tuple of three ints"); - TORCH_CHECK(padding.size() == 1 || padding.size() == 3, - "avg_pool3d_backward: padding must be a single int, or a tuple of three ints"); - TORCH_CHECK((self.ndimension() == 4 || self.ndimension() == 5), - "non-empty 4D or 5D (batch mode) tensor expected for input"); - TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, - "avg_pool3d_backward divisor must be not zero"); - - const int kT = at::native::safe_downcast(kernel_size[0]); - const int kH = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[1]); - const int kW = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[2]); - c10::SmallVector kernel_sizes = {1, 1, kT, kH, kW}; - at::IntArrayRef kernel_sizess = at::IntArrayRef(kernel_sizes); - - const int dT = stride.empty() ? kT : at::native::safe_downcast(stride[0]); - const int dH = stride.empty() ? kH : - stride.size() == 1 ? dT : at::native::safe_downcast(stride[1]); - const int dW = stride.empty() ? kW : - stride.size() == 1 ? dT : at::native::safe_downcast(stride[2]); - c10::SmallVector strides = {1, 1, dT, dH, dW}; - at::IntArrayRef stridess = at::IntArrayRef(strides); - - const int padT = at::native::safe_downcast(padding[0]); - const int padH = padding.size() == 1 ? padT : at::native::safe_downcast(padding[1]); - const int padW = padding.size() == 1 ? padT : at::native::safe_downcast(padding[2]); - c10::SmallVector paddings = {padH, padW, padT}; - at::IntArrayRef paddingss = at::IntArrayRef(paddings); - - const int64_t nslices = self.size(-4); - const int64_t itime = self.size(-3); - const int64_t iheight = self.size(-2); - const int64_t iwidth = self.size(-1); - const int64_t otime = grad_input.size(-3); - const int64_t oheight = grad_input.size(-2); - const int64_t owidth = grad_input.size(-1); - - /* XXX shape check behavior from TH */ - const int64_t otime_for_shape_check = at::native::pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode); - const int64_t oheight_for_shape_check = at::native::pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode); - const int64_t owidth_for_shape_check = at::native::pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode); - - at::native::avg_pool3d_backward_shape_check( - self, - grad_input, - nslices, - kT, kH, kW, - dT, dH, dW, - padT, padH, padW, - itime, iheight, iwidth, - otime_for_shape_check, oheight_for_shape_check, owidth_for_shape_check); - - avg_pool3d_backward_out_npu_nocheck( - grad_output, - grad_input, - self, - kernel_sizess, - stridess, - paddingss, - ceil_mode, - count_include_pad, - divisor_override); - - return grad_output; -} - -at::Tensor NPUNativeFunctions::avg_pool3d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - bool ceil_mode, - bool count_include_pad, - c10::optional divisor_override) { - at::Tensor input = self; - at::Tensor grad_input = grad_output; - if (self.ndimension() == 4) { - input = self.unsqueeze(0); - grad_input = grad_input.unsqueeze(0); - } - - at::Tensor output = OpPreparation::ApplyTensorWithFormat(input, ACL_FORMAT_NCDHW); - NPUNativeFunctions::avg_pool3d_backward_out( - grad_input, - input, - kernel_size, - stride, - padding, - ceil_mode, - count_include_pad, - divisor_override, - output); - - if (self.ndimension() == 4) { - output = output.squeeze(0); - } - - return output; -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/AvgPool3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/AvgPool3dKernelNpu.cpp deleted file mode 100644 index e6a156f96f..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/AvgPool3dKernelNpu.cpp +++ /dev/null @@ -1,159 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -at::Tensor& NPUNativeFunctions::avg_pool3d_out( - const at::Tensor& self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - bool ceil_mode, - bool count_include_pad, - c10::optional divisor_override, - at::Tensor& out) { - c10::SmallVector pads = {0, 0, 0, padding[0], padding[1], padding[2]}; - at::Tensor input = self; - if (self.ndimension() == 4) { - input = input.unsqueeze(0); - out = out.unsqueeze(0); - } - int D = self.size(-3); - int H = self.size(-2); - int W = self.size(-1); - int64_t D_size = ceil_mode - ? (CeilDiv(D + 2 * padding[0] - kernel_size[0], stride[0]) + 1) - : ((D + 2 * padding[0] - kernel_size[0]) / stride[0] + 1); - int64_t H_size = ceil_mode - ? (CeilDiv(H + 2 * padding[1] - kernel_size[1], stride[1]) + 1) - : ((H + 2 * padding[1] - kernel_size[1]) / stride[1] + 1); - int64_t W_size = ceil_mode - ? (CeilDiv(W + 2 * padding[2] - kernel_size[2], stride[2]) + 1) - : ((W + 2 * padding[2] - kernel_size[2]) / stride[2] + 1); - c10::SmallVector outputSize = {input.size(0), input.size(1), D_size, H_size, W_size}; - - OpPreparation::CheckOut( - {self}, - out, - ACL_FORMAT_NCDHW, - out.scalar_type(), - outputSize); - OpCommand cmd; - cmd.Name("AvgPool3D") - .Input(input) - .Output(out) - .Attr("ksize", kernel_size) - .Attr("strides", stride) - .Attr("pads", pads) - .Attr("ceil_mode", ceil_mode) - .Attr("count_include_pad", count_include_pad); - if (divisor_override.has_value()) { - cmd.Attr("divisor_override", divisor_override.value()); - } - cmd.Attr("data_format", (string)"NCDHW") - .Run(); - - if (self.ndimension() == 4) { - out = out.squeeze(0); - } - return out; -} - -at::Tensor NPUNativeFunctions::avg_pool3d( - const at::Tensor& self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - bool ceil_mode, - bool count_include_pad, - c10::optional divisor_override) { - TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, - "avg_pool3d: kernel_size must be a single int, or a tuple of three ints"); - const int kT = at::native::safe_downcast(kernel_size[0]); - const int kH = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[1]); - const int kW = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[2]); - c10::SmallVector kernel_sizes = {kT, kH, kW}; - at::IntArrayRef kernel_sizess = at::IntArrayRef(kernel_sizes); - TORCH_CHECK(stride.empty() || stride.size() == 1 || stride.size() == 3, - "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints"); - const int dT = stride.empty() ? kT : at::native::safe_downcast(stride[0]); - const int dH = stride.empty() ? kH : - stride.size() == 1 ? dT : at::native::safe_downcast(stride[1]); - const int dW = stride.empty() ? kW : - stride.size() == 1 ? dT : at::native::safe_downcast(stride[2]); - c10::SmallVector strides = {dT, dH, dW}; - at::IntArrayRef stridess = at::IntArrayRef(strides); - TORCH_CHECK(padding.size() == 1 || padding.size() == 3, - "avg_pool3d: padding must be a single int, or a tuple of three ints"); - const int padT = at::native::safe_downcast(padding[0]); - const int padH = padding.size() == 1 ? padT : at::native::safe_downcast(padding[1]); - const int padW = padding.size() == 1 ? padT : at::native::safe_downcast(padding[2]); - c10::SmallVector paddings = {padT, padH, padW}; - at::IntArrayRef paddingss = at::IntArrayRef(paddings); - TORCH_CHECK((self.ndimension() == 4 || self.ndimension() == 5), - "non-empty 4D or 5D (batch mode) tensor expected for input"); - TORCH_CHECK(!divisor_override.has_value() || divisor_override.value() != 0, - "divisor must be not zero"); - const int64_t nslices = self.size(-4); - const int64_t itime = self.size(-3); - const int64_t iheight = self.size(-2); - const int64_t iwidth = self.size(-1); - const int64_t otime = at::native::pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode); - const int64_t oheight = at::native::pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode); - const int64_t owidth = at::native::pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode); - - at::native::pool3d_shape_check( - self, - nslices, - kT, kH, kW, - dT, dH, dW, - padT, padH, padW, - 1, 1, 1, - itime, iheight, iwidth, - otime, oheight, owidth, - true); - - at::Tensor input = self; - if (self.ndimension() == 4) { - input = self.unsqueeze(0); - } - c10::SmallVector outputSize = {input.size(0), input.size(1), otime, oheight, owidth}; - at::Tensor result = OpPreparation::ApplyTensorWithFormat(input, outputSize, ACL_FORMAT_NCDHW); - NPUNativeFunctions::avg_pool3d_out( - input, - kernel_sizess, - stridess, - paddingss, - ceil_mode, - count_include_pad, - divisor_override, - result); - if (self.ndimension() == 4) { - result = result.squeeze(0); - } - return result; -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesBackwardKernelNpu.cpp index 1e3b7dbc1e..fdbf2e0383 100644 --- a/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesBackwardKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesBackwardKernelNpu.cpp @@ -17,13 +17,13 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -at::Tensor& NPUNativeFunctions::max_pool2d_with_indices_backward_out( +at::Tensor& XLANativeFunctions::max_pool2d_with_indices_backward_out( const at::Tensor& grad_output, const at::Tensor& self, at::IntArrayRef kernel_size, @@ -63,7 +63,7 @@ at::Tensor& NPUNativeFunctions::max_pool2d_with_indices_backward_out( return grad_input; } -at::Tensor NPUNativeFunctions::max_pool2d_with_indices_backward( +at::Tensor XLANativeFunctions::max_pool2d_with_indices_backward( const at::Tensor& grad_output_, const at::Tensor& self, at::IntArrayRef kernel_size, @@ -121,7 +121,7 @@ at::Tensor NPUNativeFunctions::max_pool2d_with_indices_backward( at::Tensor grad_input = OpPreparation::ApplyTensor(self); // calculate the output result of the NPU - NPUNativeFunctions::max_pool2d_with_indices_backward_out( + XLANativeFunctions::max_pool2d_with_indices_backward_out( grad_output, self, kernel_sizess, diff --git a/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesKernelNpu.cpp index 6be2e061bd..e0de406eb8 100644 --- a/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/MaxPool2dWithIndicesKernelNpu.cpp @@ -17,13 +17,13 @@ #include "torch_npu/csrc/framework/utils/OpAdapter.h" #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { -tuple NPUNativeFunctions::max_pool2d_with_indices_out( +tuple XLANativeFunctions::max_pool2d_with_indices_out( const at::Tensor& self, at::IntArrayRef kernel_size, at::IntArrayRef stride, @@ -61,7 +61,7 @@ tuple NPUNativeFunctions::max_pool2d_with_indices_out( return tuple(output, indices); } -tuple NPUNativeFunctions::max_pool2d_with_indices( +tuple XLANativeFunctions::max_pool2d_with_indices( const at::Tensor& self, at::IntArrayRef kernel_size, at::IntArrayRef stride, @@ -130,7 +130,7 @@ tuple NPUNativeFunctions::max_pool2d_with_indices( at::Tensor indices = OpPreparation::ApplyTensorWithFormat(self, indicesSize, ACL_FORMAT_NC1HWC0); // calculate the output result of the NPU - NPUNativeFunctions::max_pool2d_with_indices_out( + XLANativeFunctions::max_pool2d_with_indices_out( self, kernel_sizess, stridess, padss, dilationss, ceil_mode, output, indices); return tuple(output, indices); } diff --git a/torch_npu/csrc/aten/ops/pooling/MaxPool3dWithIndicesBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxPool3dWithIndicesBackwardKernelNpu.cpp deleted file mode 100644 index 77221446dd..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/MaxPool3dWithIndicesBackwardKernelNpu.cpp +++ /dev/null @@ -1,185 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu -{ - namespace native - { - - at::Tensor &NPUNativeFunctions::max_pool3d_with_indices_backward_out( - const at::Tensor &grad_output, - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - bool ceil_mode, - const at::Tensor &indices, - at::Tensor &grad_input) - { - int64_t strideT = 1; - int64_t strideH = 1; - int64_t strideW = 1; - if (stride.empty()) - { - strideT = kernel_size[0]; - strideH = kernel_size[1]; - strideW = kernel_size[2]; - } - else - { - strideT = stride[0]; - strideH = stride[1]; - strideW = stride[2]; - } - - string padstr = "CALCULATED"; - int64_t ds = self.size(-3); - int64_t hs = self.size(-2); - int64_t ws = self.size(-1); - c10::SmallVector padrs(padding); - if (ceil_mode) - { - padrs[0] += CalcuOpUtil::completePad(ds, padding[0], kernel_size[0], strideT); - padrs[1] += CalcuOpUtil::completePad(hs, padding[1], kernel_size[1], strideH); - padrs[2] += CalcuOpUtil::completePad(ws, padding[2], kernel_size[2], strideW); - } - c10::SmallVector kernel_sizes = {1, 1, kernel_size[0], kernel_size[1], kernel_size[2]}; - c10::SmallVector stride_sizes = {1, 1, strideT, strideH, strideW}; - c10::SmallVector padding_sizes = {padding[0], padrs[0], padding[1], padrs[1], padding[2], padrs[2]}; - - string data_format = "NCDHW"; - - OpCommand cmd; - cmd.Name("MaxPool3DGrad") - .Input(self) - .Input(indices) - .Input(grad_output) - .Output(grad_input) - .Attr("ksize", kernel_sizes) - .Attr("strides", stride_sizes) - .Attr("padding", padstr) - .Attr("pads", padding_sizes) - .Attr("data_format", data_format) - .Run(); - - return grad_input; - } - - at::Tensor NPUNativeFunctions::max_pool3d_with_indices_backward( - const at::Tensor &grad_output, - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::IntArrayRef dilation, - bool ceil_mode, - const at::Tensor &indices) - { - TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, - "max_pool3d: kernel_size must either be a single int, or a tuple of three ints") - const int kT = at::native::safe_downcast(kernel_size[0]); - const int kH = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[1]); - const int kW = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[2]); - c10::SmallVector kernel_sizes = {kT, kH, kW}; - at::IntArrayRef kernel_sizess = at::IntArrayRef(kernel_sizes); - - TORCH_CHECK(stride.size() == 0 || stride.size() == 1 || stride.size() == 3, - "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints") - const int dT = stride.empty() ? kT : at::native::safe_downcast(stride[0]); - const int dH = stride.empty() ? kH : stride.size() == 1 ? dT - : at::native::safe_downcast(stride[1]); - const int dW = stride.empty() ? kW : stride.size() == 1 ? dT - : at::native::safe_downcast(stride[2]); - c10::SmallVector strides = {dT, dH, dW}; - at::IntArrayRef stridess = at::IntArrayRef(strides); - - TORCH_CHECK(padding.size() == 1 || padding.size() == 3, - "max_pool3d: padding must be either be a single int, or a tuple of three ints"); - const int pT = at::native::safe_downcast(padding[0]); - const int pH = padding.size() == 1 ? pT : at::native::safe_downcast(padding[1]); - const int pW = padding.size() == 1 ? pT : at::native::safe_downcast(padding[2]); - c10::SmallVector paddings = {pT, pH, pW}; - at::IntArrayRef paddingss = at::IntArrayRef(paddings); - - TORCH_CHECK(dilation.size() == 1 || dilation.size() == 3, - "max_pool3d: dilation must be either a single int, or a tuple of three ints"); - const int dilationT = at::native::safe_downcast(dilation[0]); - const int dilationH = dilation.size() == 1 ? dilationT : at::native::safe_downcast(dilation[1]); - const int dilationW = dilation.size() == 1 ? dilationT : at::native::safe_downcast(dilation[2]); - c10::SmallVector dilations = {dilationT, dilationH, dilationW}; - at::IntArrayRef dilationss = at::IntArrayRef(dilations); - - TORCH_CHECK((self.ndimension() == 5 || self.ndimension() == 4), - "maxpool3d expected input to be non-empty 5D(batch mode) or 4D tensor", - "but input has dim: ", - self.ndimension()); - const int64_t nslices = self.size(-4); - const int64_t itime = self.size(-3); - const int64_t iheight = self.size(-2); - const int64_t iwidth = self.size(-1); - const int64_t otime = grad_output.size(-3); - const int64_t oheight = grad_output.size(-2); - const int64_t owidth = grad_output.size(-1); - - at::native::max_pool3d_backward_shape_check( - self, - grad_output, - indices, - nslices, - kT, kH, kW, - dT, dH, dW, - pT, pH, pW, - dilationT, dilationH, dilationW, - itime, iheight, iwidth, - otime, oheight, owidth); - at::Tensor selfCp = self; - at::Tensor grad_outputCp = grad_output.clone(); - at::Tensor indicesCp = indices; - if (self.ndimension() == 4) - { - selfCp = selfCp.unsqueeze(0); - grad_outputCp = grad_outputCp.unsqueeze(0); - indicesCp = indicesCp.unsqueeze(0); - } - auto outputSize = input_same_output_size(selfCp); - at::Tensor grad_input = OpPreparation::ApplyTensorWithFormat( - outputSize, - selfCp.options().dtype(c10::ScalarType::Float), - ACL_FORMAT_NDC1HWC0); - - NPUNativeFunctions::max_pool3d_with_indices_backward_out( - grad_outputCp, - selfCp, - kernel_sizess, - stridess, - paddingss, - dilationss, - ceil_mode, - indicesCp, - grad_input); - grad_input = self.ndimension() == 4 ? grad_input.squeeze(0) : grad_input; - return grad_input; - } - - } // native -} // at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/pooling/MaxPool3dWithIndicesKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxPool3dWithIndicesKernelNpu.cpp deleted file mode 100644 index 0d904aa587..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/MaxPool3dWithIndicesKernelNpu.cpp +++ /dev/null @@ -1,163 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu -{ - namespace native - { - - std::tuple NPUNativeFunctions::max_pool3d_with_indices_out( - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef pads, - at::IntArrayRef dilation, - bool ceil_mode, - at::Tensor &result, - at::Tensor &indice) - { - int64_t strideT = 1; - int64_t strideH = 1; - int64_t strideW = 1; - if (stride.empty()) - { - strideT = kernel_size[0]; - strideH = kernel_size[1]; - strideW = kernel_size[2]; - } - else - { - strideT = stride[0]; - strideH = stride[1]; - strideW = stride[2]; - } - - string padding = "CALCULATED"; - int64_t ds = self.size(-3); - int64_t hs = self.size(-2); - int64_t ws = self.size(-1); - c10::SmallVector padrs(pads); - if (ceil_mode) - { - padrs[0] += CalcuOpUtil::completePad(ds, pads[0], kernel_size[0], strideT); - padrs[1] += CalcuOpUtil::completePad(hs, pads[1], kernel_size[1], strideH); - padrs[2] += CalcuOpUtil::completePad(ws, pads[2], kernel_size[2], strideW); - } - c10::SmallVector kernel_sizes = {1, 1, kernel_size[0], kernel_size[1], kernel_size[2]}; - c10::SmallVector stride_sizes = {1, 1, strideT, strideH, strideW}; - c10::SmallVector pads_sizes = {pads[0], padrs[0], pads[1], padrs[1], pads[2], padrs[2]}; - c10::SmallVector dilation_sizes = {1, 1, dilation[0], dilation[1], dilation[2]}; - string data_format = "NCDHW"; - - OpCommand cmd; - cmd.Name("MaxPool3D") - .Input(self) - .Output(result) - .Attr("ksize", kernel_sizes) - .Attr("strides", stride_sizes) - .Attr("padding", padding) - .Attr("pads", pads_sizes) - .Attr("dilation", dilation_sizes) - .Attr("ceil_mode", (int64_t)ceil_mode) - .Attr("data_format", data_format) - .Run(); - return std::tie(result, result); - } - - std::tuple NPUNativeFunctions::max_pool3d_with_indices( - const at::Tensor &self, - at::IntArrayRef kernel_size, - at::IntArrayRef stride, - at::IntArrayRef pads, - at::IntArrayRef dilation, - bool ceil_mode) - { - TORCH_CHECK(kernel_size.size() == 1 || kernel_size.size() == 3, - "max_pool3d: kernel_size must either be a single int, or a tuple of three ints") - const int kT = at::native::safe_downcast(kernel_size[0]); - const int kH = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[1]); - const int kW = kernel_size.size() == 1 ? kT : at::native::safe_downcast(kernel_size[2]); - c10::SmallVector kernel_sizes = {kT, kH, kW}; - at::IntArrayRef kernel_sizess = at::IntArrayRef(kernel_sizes); - - TORCH_CHECK(stride.size() == 0 || stride.size() == 1 || stride.size() == 3, - "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints") - const int dT = stride.empty() ? kT : at::native::safe_downcast(stride[0]); - const int dH = stride.empty() ? kH : stride.size() == 1 ? dT - : at::native::safe_downcast(stride[1]); - const int dW = stride.empty() ? kW : stride.size() == 1 ? dT - : at::native::safe_downcast(stride[2]); - c10::SmallVector strides = {dT, dH, dW}; - at::IntArrayRef stridess = at::IntArrayRef(strides); - - TORCH_CHECK(pads.size() == 1 || pads.size() == 3, - "max_pool3d: padding must be either be a single int, or a tuple of three ints"); - const int pT = at::native::safe_downcast(pads[0]); - const int pH = pads.size() == 1 ? pT : at::native::safe_downcast(pads[1]); - const int pW = pads.size() == 1 ? pT : at::native::safe_downcast(pads[2]); - c10::SmallVector paddings = {pT, pH, pW}; - at::IntArrayRef padss = at::IntArrayRef(paddings); - - TORCH_CHECK(dilation.size() == 1 || dilation.size() == 3, - "max_pool3d: dilation must be either a single int, or a tuple of three ints"); - const int dilationT = at::native::safe_downcast(dilation[0]); - const int dilationH = dilation.size() == 1 ? dilationT : at::native::safe_downcast(dilation[1]); - const int dilationW = dilation.size() == 1 ? dilationT : at::native::safe_downcast(dilation[2]); - c10::SmallVector dilations = {dilationT, dilationH, dilationW}; - at::IntArrayRef dilationss = at::IntArrayRef(dilations); - - TORCH_CHECK((self.ndimension() == 5 || self.ndimension() == 4), - "maxpool3d expected input to be non-empty 5D(batch mode) or 4D tensor", - "but input has dim: ", - self.ndimension()); - - const int64_t nslices = self.size(-4); - const int64_t itime = self.size(-3); - const int64_t iheight = self.size(-2); - const int64_t iwidth = self.size(-1); - - const int64_t otime = at::native::pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode); - const int64_t oheight = at::native::pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode); - const int64_t owidth = at::native::pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode); - - at::native::pool3d_shape_check( - self, - nslices, - kT, kH, kW, - dT, dH, dW, - pT, pH, pW, - dilationT, dilationH, dilationW, - itime, iheight, iwidth, - otime, oheight, owidth); - at::Tensor selfCp = self.ndimension() == 4 ? self.unsqueeze(0) : self; - c10::SmallVector outputSize = {selfCp.size(0), selfCp.size(1), otime, oheight, owidth}; - at::Tensor result = OpPreparation::ApplyTensorWithFormat( - outputSize, selfCp.options(), ACL_FORMAT_NDC1HWC0); - - NPUNativeFunctions::max_pool3d_with_indices_out( - selfCp, kernel_sizess, stridess, padss, dilationss, ceil_mode, result, result); - result = self.ndimension() == 4 ? result.squeeze(0) : result; - return std::tie(result, result); - } - - } // native -} // at_npu \ No newline at end of file diff --git a/torch_npu/csrc/aten/ops/pooling/MaxUnpool2dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxUnpool2dBackwardKernelNpu.cpp deleted file mode 100644 index 91bab6bbb5..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/MaxUnpool2dBackwardKernelNpu.cpp +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::max_unpool2d_backward_out( - const at::Tensor& gradOutput, - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef outputSize, - at::Tensor& gradInput) { - OpPreparation::CheckOut( - {self, gradOutput}, - gradInput, - self); - TORCH_CHECK( - outputSize.size() == 2, - "There should be exactly two elements (height, width) in outputSize"); - TORCH_CHECK( - (self.ndimension() == 3 || self.ndimension() == 4), - "Input to max_unpooling2d should be a 3d or 4d Tensor"); - TORCH_CHECK( - self.sizes() == indices.sizes(), - "Shape of indices should match shape of input"); - TORCH_CHECK(self.numel() > 0, "Input must be non-empty"); - - auto oheight = outputSize[0]; - auto owidth = outputSize[1]; - int64_t n = 1; - int64_t c = self.size(0); - int64_t h = self.size(1); - int64_t w = self.size(2); - int64_t selfDim = self.ndimension(); - - if (selfDim == 4) { - n = self.size(0); - c = self.size(1); - h = self.size(2); - w = self.size(3); - } - - auto gradOutputContiguous = gradOutput.contiguous(); - auto indicesContiguous = indices.contiguous(); - gradOutputContiguous = gradOutputContiguous.reshape({n, c, oheight * owidth}); - indicesContiguous = indicesContiguous.reshape({n, c, h * w}); - gradInput.resize_as_(self); - gradInput.zero_(); - gradInput = gradInput.reshape({n, c, h * w}); - const int dim = 2; - - gradInput = gather_out(gradOutputContiguous, dim, indicesContiguous, false, gradInput); - if (selfDim == 3) { - gradInput = gradInput.reshape({c, h, w}); - } else { - gradInput = gradInput.reshape({n, c, h, w}); - } - return gradInput; -} - -at::Tensor NPUNativeFunctions::max_unpool2d_backward( - const at::Tensor& gradOutput, - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef outputSize) { - auto gradInput = at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT); - max_unpool2d_backward_out(gradOutput, self, indices, outputSize, gradInput); - return gradInput; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/MaxUnpool2dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxUnpool2dKernelNpu.cpp deleted file mode 100644 index 4ab035a4e2..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/MaxUnpool2dKernelNpu.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2020, Huawei Technologies.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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - -at::Tensor& NPUNativeFunctions::max_unpool2d_out( - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef outputSize, - at::Tensor& output) { - OpPreparation::CheckOut( - {self, indices}, - output, - self); - TORCH_CHECK( - outputSize.size() == 2, - "There should be exactly two elements (height, width) in outputSize"); - TORCH_CHECK( - (self.ndimension() == 3 || self.ndimension() == 4), - "Input to max_unpooling2d should be a 3d or 4d Tensor"); - TORCH_CHECK( - self.sizes() == indices.sizes(), - "Shape of indices should match shape of input"); - TORCH_CHECK(self.numel() > 0, "Input must be non-empty"); - - auto oheight = outputSize[0]; - auto owidth = outputSize[1]; - auto selfContiguous = self.contiguous(); - auto indicesContiguous = indices.contiguous(); - int64_t h = -1; - int64_t w = -1; - int64_t selfDim = self.ndimension(); - int64_t numBatch = -1; - int64_t numChannels = -1; - if (selfDim == 3) { - numChannels = self.size(0); - h = self.size(1); - w = self.size(2); - output.resize_({numChannels, oheight * owidth}); - selfContiguous = selfContiguous.reshape({numChannels, h * w}); - indicesContiguous = indicesContiguous.reshape({numChannels, h * w}); - } else { - numBatch = self.size(0); - numChannels = self.size(1); - h = self.size(2); - w = self.size(3); - output.resize_({numBatch, numChannels, oheight * owidth}); - selfContiguous = selfContiguous.reshape({numBatch, numChannels, h * w}); - indicesContiguous = indicesContiguous.reshape({numBatch, numChannels, h * w}); - } - - output.zero_(); - int64_t dim = 2; - output = output.scatter(dim, indicesContiguous, selfContiguous); - if (selfDim == 3) { - output = output.reshape({numChannels, oheight, owidth}); - } else { - output = output.reshape({numBatch, numChannels, oheight, owidth}); - } - return output; -}; - -at::Tensor NPUNativeFunctions::max_unpool2d( - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef output_size) { - auto output = OpPreparation::ApplyTensor(self, {0}); - max_unpool2d_out(self, indices, output_size, output); - return output; -} -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/MaxUnpool3dBackwardKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxUnpool3dBackwardKernelNpu.cpp deleted file mode 100644 index 40a631ce11..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/MaxUnpool3dBackwardKernelNpu.cpp +++ /dev/null @@ -1,102 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - - -at::Tensor& max_unpool3d_backward_out_npu_nocheck( - at::Tensor& grad_input, - const at::Tensor& grad_output, - const at::Tensor& indices) { - int64_t N = 1; - int64_t C = indices.size(0); - if (grad_output.dim() == 5) { - N = indices.size(0); - C = indices.size(1); - } - at::Tensor reshape_grad_output = grad_output.reshape({N, C, -1}); - at::Tensor reshape_indices = indices.reshape({N, C, -1}); - grad_input = grad_input.reshape({N, C, -1}); - - int64_t dim = 2; - OpCommand cmd; - cmd.Name("GatherElements") - .Input(reshape_grad_output) - .Input(reshape_indices) - .Output(grad_input) - .Attr("dim", dim) - .Run(); - grad_input = grad_input.reshape(indices.sizes()); - return grad_input; -} - -at::Tensor& NPUNativeFunctions::max_unpool3d_backward_out( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef output_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& grad_input) { - OpPreparation::CheckOut( - {grad_output, self, indices}, - grad_input, - self); - if (!NpuUtils::check_match(&grad_input)) { - at::Tensor contiguous_result = NpuUtils::format_contiguous(grad_input); - - max_unpool3d_backward_out_npu_nocheck(contiguous_result, grad_output, indices); - NpuUtils::format_fresh_view(grad_input, contiguous_result); - } else { - max_unpool3d_backward_out_npu_nocheck(grad_input, grad_output, indices); - } - return grad_input; -} - -at::Tensor NPUNativeFunctions::max_unpool3d_backward( - const at::Tensor& grad_output, - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef output_size, - at::IntArrayRef stride, - at::IntArrayRef padding) { - TORCH_CHECK( - output_size.size() == 3, - "There should be exactly 3 elements (depth, height, width) in output_size"); - TORCH_CHECK( - (self.ndimension() == 4 || self.ndimension() == 5), - "Input to max_unpooling2d should be a 4d or 5d Tensor"); - TORCH_CHECK( - self.sizes() == indices.sizes(), - "Shape of indices should match shape of input"); - TORCH_CHECK(self.numel() > 0, "Input must be non-empty"); - - at::Tensor grad_input = OpPreparation::ApplyTensor(self); - - max_unpool3d_backward_out_npu_nocheck(grad_input, grad_output, indices); - - return grad_input; -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/MaxUnpool3dKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/MaxUnpool3dKernelNpu.cpp deleted file mode 100644 index d85122e793..0000000000 --- a/torch_npu/csrc/aten/ops/pooling/MaxUnpool3dKernelNpu.cpp +++ /dev/null @@ -1,125 +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. - -#include "torch_npu/csrc/framework/utils/OpAdapter.h" - -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" - -namespace at_npu { -namespace native { - - -namespace { - -c10::SmallVector max_pool3d_npu_output_size( - const at::Tensor& self, - at::IntArrayRef output_size) { - c10::SmallVector shape = {}; - if (self.dim() == 4) { - shape = {self.size(0), output_size[0], output_size[1], output_size[2]}; - } else { - shape = {self.size(0), self.size(1), output_size[0], output_size[1], output_size[2]}; - } - return shape; -} // max_pool3d_npu_output_size - -} // namespace - -at::Tensor& max_unpool3d_out_npu_nocheck( - at::Tensor& result, - const at::Tensor& self, - const at::Tensor& indices, - const at::Tensor& data, - at::IntArrayRef output_size) { - int64_t N = 1; - int64_t C = self.size(0); - if (self.dim() == 5) { - N = self.size(0); - C = self.size(1); - } - at::Tensor reshape_self = self.reshape({N, C, -1}); - at::Tensor reshape_indices = indices.reshape({N, C, -1}); - at::Tensor reshape_data = data.reshape({N, C, -1}); - result = result.reshape({N, C, -1}); - - int64_t axis = 2; - OpCommand cmd; - cmd.Name("ScatterElements") - .Input(reshape_data) - .Input(reshape_indices) - .Input(reshape_self) - .Output(result) - .Attr("axis", axis) - .Run(); - result = result.reshape({data.sizes()}); - return result; -} - -at::Tensor& NPUNativeFunctions::max_unpool3d_out( - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef output_size, - at::IntArrayRef stride, - at::IntArrayRef padding, - at::Tensor& result) { - auto out_shape = max_pool3d_npu_output_size(self, output_size); - - at::Tensor data = at::zeros(out_shape, self.options()); - OpPreparation::CheckOut( - {self, indices, data}, - result, - data); - if (!NpuUtils::check_match(&result)) { - at::Tensor contiguous_result = NpuUtils::format_contiguous(result); - - max_unpool3d_out_npu_nocheck(contiguous_result, self, indices, data, output_size); - NpuUtils::format_fresh_view(result, contiguous_result); - } else { - max_unpool3d_out_npu_nocheck(result, self, indices, data, output_size); - } - return result; -} - -at::Tensor NPUNativeFunctions::max_unpool3d( - const at::Tensor& self, - const at::Tensor& indices, - at::IntArrayRef output_size, - at::IntArrayRef stride, - at::IntArrayRef padding) { - TORCH_CHECK( - output_size.size() == 3, - "There should be exactly 3 elements (depth, height, width) in output_size"); - TORCH_CHECK( - (self.ndimension() == 4 || self.ndimension() == 5), - "Input to max_unpooling2d should be a 4d or 5d Tensor"); - TORCH_CHECK( - self.sizes() == indices.sizes(), - "Shape of indices should match shape of input"); - TORCH_CHECK(self.numel() > 0, "Input must be non-empty"); - - auto out_shape = max_pool3d_npu_output_size(self, output_size); - - at::Tensor data = at::zeros(out_shape, self.options()); - at::Tensor result = OpPreparation::ApplyTensor(data); - - max_unpool3d_out_npu_nocheck(result, self, indices, data, output_size); - - return result; -} - - -} // namespace native -} // namespace at_npu diff --git a/torch_npu/csrc/aten/ops/pooling/PoolingKernelNpu.cpp b/torch_npu/csrc/aten/ops/pooling/PoolingKernelNpu.cpp index 857c3b9a6f..c5c70560ab 100644 --- a/torch_npu/csrc/aten/ops/pooling/PoolingKernelNpu.cpp +++ b/torch_npu/csrc/aten/ops/pooling/PoolingKernelNpu.cpp @@ -17,14 +17,14 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { - - at::Tensor NPUNativeFunctions::max_pool2d( + /* + at::Tensor XLANativeFunctions::max_pool2d( const at::Tensor &self, at::IntArrayRef kernel_size, at::IntArrayRef stride, @@ -36,6 +36,6 @@ namespace at_npu self, kernel_size, stride, padding, dilation, ceil_mode); return std::get<0>(output_and_indices); } - + */ } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/core/npu/NPUAllocator.h b/torch_npu/csrc/core/npu/NPUAllocator.h index 0d8036494e..9124b5480c 100644 --- a/torch_npu/csrc/core/npu/NPUAllocator.h +++ b/torch_npu/csrc/core/npu/NPUAllocator.h @@ -22,7 +22,7 @@ #include #include #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" C10_DECLARE_bool(caffe2_report_npu_memory_usage); C10_DECLARE_bool(caffe2_npu_allocator_do_zero_fill); diff --git a/torch_npu/csrc/core/npu/NPUCachingAllocator.cpp b/torch_npu/csrc/core/npu/NPUCachingAllocator.cpp index 9a45937e18..29eff71c78 100644 --- a/torch_npu/csrc/core/npu/NPUCachingAllocator.cpp +++ b/torch_npu/csrc/core/npu/NPUCachingAllocator.cpp @@ -31,7 +31,6 @@ #include #include #include -#include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" #include "third_party/acl/inc/acl/acl_base.h" #include "third_party/acl/inc/acl/acl_rt.h" @@ -238,8 +237,6 @@ struct THNCachingAllocator { // lock around calls to aclFree (to prevent deadlocks with NCCL) mutable std::mutex npu_free_mutex; - mutable std::mutex recorded_event_mutex; - // cached blocks larger than 1 MB BlockPool large_blocks; @@ -252,8 +249,6 @@ struct THNCachingAllocator { // outstanding acl events std::deque> npu_events; - std::set recorded_events; - THNCachingAllocator() : large_blocks(BlockComparator), small_blocks(BlockComparator) {} @@ -291,8 +286,8 @@ struct THNCachingAllocator { allocated_blocks.erase(it); block->allocated = false; - c10::reportMemoryUsageToProfiler( - block, -block->size, c10::Device(at_npu::key::NativeDeviceType, block->device)); + // c10::reportMemoryUsageToProfiler( + // block, -block->size, c10::Device(at_npu::key::NativeDeviceType, block->device)); DeviceStats_& stats_ = get_stats_for_device_(block->device); StatTypes stat_types; @@ -633,7 +628,6 @@ struct THNCachingAllocator { err = aclrtMalloc( devPtr, size, aclrtMemMallocPolicy::ACL_MEM_MALLOC_HUGE_FIRST); if (err != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); return err; } } @@ -698,14 +692,6 @@ struct THNCachingAllocator { for (auto& e : npu_events) { aclrtEvent event = e.first; - { - std::lock_guard lock(recorded_event_mutex); - auto it = recorded_events.find(event); - if (c10_npu::option::OptionsManager::CheckQueueEnable() && - it == recorded_events.end()) { - break; - } - } Block* block = e.second; if (device.has_value() && block->device != *device) { remaining_events.push_back(e); @@ -713,13 +699,6 @@ struct THNCachingAllocator { } C10_NPU_CHECK(aclrtSynchronizeEvent(event)); - { - std::lock_guard lock(recorded_event_mutex); - auto it = recorded_events.find(event); - if (it != recorded_events.end()) { - recorded_events.erase(it); - } - } C10_NPU_CHECK(aclrtDestroyEvent(event)); block->event_count--; if (block->event_count == 0) { @@ -738,11 +717,6 @@ struct THNCachingAllocator { return it->second; } - void insertRecordedEvent(aclrtEvent event) { - std::lock_guard lock(recorded_event_mutex); - recorded_events.insert(event); - } - void insert_events(Block* block) { int prev_device = 0; C10_NPU_CHECK(aclrtGetDevice(&prev_device)); @@ -758,9 +732,9 @@ struct THNCachingAllocator { C10_NPU_CHECK(aclrtSetDevice(it->device_index())); } - aclrtEvent event = nullptr; - C10_NPU_CHECK(c10_npu::acl::AclrtCreateEventWithFlag(&event, ACL_EVENT_TIME_LINE)); - c10_npu::queue::NpuAllocatorLaunchRecordEventTask(event, *it); + aclrtEvent event; + aclrtCreateEvent(&event); + aclrtRecordEvent(event, it->stream()); block->event_count++; npu_events.emplace_back(event, block); @@ -786,15 +760,6 @@ struct THNCachingAllocator { aclrtEvent event = e.first; Block* block = e.second; - { - std::lock_guard lock(recorded_event_mutex); - auto it = recorded_events.begin(); - it = recorded_events.find(event); - if (c10_npu::option::OptionsManager::CheckQueueEnable() && - it == recorded_events.end()) { - break; - } - } aclrtEventStatus status = ACL_EVENT_STATUS_RESERVED; aclError err = aclrtQueryEvent(event, &status); @@ -805,14 +770,7 @@ struct THNCachingAllocator { break; } - { - std::lock_guard lock(recorded_event_mutex); - auto it = recorded_events.find(event); - if (it != recorded_events.end()) { - recorded_events.erase(it); - } - } - C10_NPU_CHECK(aclrtDestroyEvent(event)); + aclrtDestroyEvent(event); block->event_count--; if (block->event_count == 0) { @@ -836,7 +794,8 @@ struct THNCachingAllocator { DeviceStats_& stats_ = get_stats_for_device_(temp_block->device); StatTypes stat_types; stat_types[static_cast(StatType::AGGREGATE)] = true; - stat_types[static_cast(get_stat_type_for_pool(*(temp_block->pool)))] = true; + stat_types[static_cast( + get_stat_type_for_pool(*(temp_block->pool)))] = true; update_stat_array(stats_.allocation, -1, {stat_types}); update_stat_array(stats_.allocated_bytes, -temp_block->size, {stat_types}); update_stat_array(stats_.active, -1, {stat_types}); @@ -1031,8 +990,8 @@ void THNCachingAllocator::malloc(void** devPtr, size_t size, aclrtStream stream, *devPtr = block->ptr; stats.increaseAllocated(block->size); - c10::reportMemoryUsageToProfiler( - block, block->size, c10::Device(at_npu::key::NativeDeviceType, device)); + // c10::reportMemoryUsageToProfiler( + // block, block->size, c10::Device(at_npu::key::NativeDeviceType, device)); update_stat_array(stats_.allocation, 1, stat_types); update_stat_array(stats_.allocated_bytes, block->size, stat_types); @@ -1046,6 +1005,16 @@ static void NPUCachingDeleter(void* ptr) { caching_allocator.free(ptr); } +bool forceUncachedAllocator() { + static bool force_uncached = + getenv("PYTORCH_NO_NPU_MEMORY_CACHING") != nullptr; + return force_uncached; +} + +static void uncached_delete(void* ptr) { + C10_NPU_CHECK(aclrtFree(ptr)); +} + // NB: I decided not to fold this into THNCachingAllocator, because the latter // has a lot more methods and it wasn't altogether clear that they should // actually be publically exposed @@ -1054,6 +1023,16 @@ struct NPUCachingAllocator : public c10::Allocator { int device = 0; C10_NPU_CHECK(aclrtGetDevice(&device)); void* r = nullptr; + + if (forceUncachedAllocator()) { + // Deliberately don't use cudaMallocMaybeCapturing here, to force an error + // if someone tries to use forceUncachedAllocator while capturing. + if (size != 0) { + C10_NPU_CHECK(aclrtMalloc(&r, size, aclrtMemMallocPolicy::ACL_MEM_MALLOC_HUGE_FIRST)); + } + return {r, r, &uncached_delete, c10::Device(at_npu::key::NativeDeviceType, device)}; + } + if (size != 0) { caching_allocator.malloc( &r, size, c10_npu::getCurrentNPUStreamNoWait(device), device); @@ -1061,7 +1040,12 @@ struct NPUCachingAllocator : public c10::Allocator { return {r, r, &NPUCachingDeleter, c10::Device(at_npu::key::NativeDeviceType, device)}; } c10::DeleterFnPtr raw_deleter() const override { - return &NPUCachingDeleter; + + if (forceUncachedAllocator()) { + return &uncached_delete; + } else { + return &NPUCachingDeleter; + } } }; @@ -1137,10 +1121,6 @@ std::vector snapshot() { return caching_allocator.snapshot(); } -void NpuAllocatorInsertRecordedEvent(aclrtEvent event) { - return caching_allocator.insertRecordedEvent(event); -} - uint64_t currentMemoryAllocated(int device) { assertValidDevice(device); return caching_allocator.get_stats_for_device(device).amount_allocated; diff --git a/torch_npu/csrc/core/npu/NPUCachingAllocator.h b/torch_npu/csrc/core/npu/NPUCachingAllocator.h index 30bcd376c0..2ac308a073 100644 --- a/torch_npu/csrc/core/npu/NPUCachingAllocator.h +++ b/torch_npu/csrc/core/npu/NPUCachingAllocator.h @@ -20,7 +20,6 @@ #include #include #include "torch_npu/csrc/core/npu/NPUMacros.h" -#include "torch_npu/csrc/core/npu/register/OptionsManager.h" #include "torch_npu/csrc/core/npu/NPUStream.h" @@ -142,7 +141,5 @@ std::mutex* getFreeMutex(); void FreeDeviceCachedMemory(int device); -void NpuAllocatorInsertRecordedEvent(aclrtEvent event); - } // namespace NPUCachingAllocator } // namespace c10_npu diff --git a/torch_npu/csrc/core/npu/NPUEvent.h b/torch_npu/csrc/core/npu/NPUEvent.h index c7813e7025..db7c6815d0 100644 --- a/torch_npu/csrc/core/npu/NPUEvent.h +++ b/torch_npu/csrc/core/npu/NPUEvent.h @@ -9,7 +9,7 @@ #include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" #include #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace c10_npu { /* @@ -32,7 +32,7 @@ struct NPUEvent { C10_NPU_CHECK(c10_npu::queue::LaunchLazyDestroyEventTask(event_)); C10_NPU_CHECK(c10_npu::NPUEventManager::GetInstance().QueryAndDestroyEvent()); } - } catch (...) {} // No throw. + } catch (...) {} } NPUEvent(const NPUEvent&) = delete; diff --git a/torch_npu/csrc/core/npu/NPUGuard.h b/torch_npu/csrc/core/npu/NPUGuard.h index cbbb774972..e426f130c2 100644 --- a/torch_npu/csrc/core/npu/NPUGuard.h +++ b/torch_npu/csrc/core/npu/NPUGuard.h @@ -66,7 +66,7 @@ struct NPUGuard { return guard_.current_device(); } -private: + private: /// The guard for the current device. c10::impl::InlineDeviceGuard guard_; }; @@ -134,7 +134,7 @@ struct OptionalNPUGuard { guard_.reset(); } -private: + private: c10::impl::InlineOptionalDeviceGuard guard_; }; @@ -197,7 +197,7 @@ struct NPUStreamGuard { return guard_.original_device(); } -private: + private: c10::impl::InlineStreamGuard guard_; }; @@ -266,7 +266,7 @@ struct OptionalNPUStreamGuard { guard_.reset(); } -private: + private: c10::impl::InlineOptionalStreamGuard guard_; }; diff --git a/torch_npu/csrc/core/npu/NPUQueue.cpp b/torch_npu/csrc/core/npu/NPUQueue.cpp index 4916a4ad86..1790e073d0 100644 --- a/torch_npu/csrc/core/npu/NPUQueue.cpp +++ b/torch_npu/csrc/core/npu/NPUQueue.cpp @@ -28,8 +28,6 @@ namespace c10_npu { -constexpr int32_t MAX_JUDGE_NUM = 1000000; - namespace { class CallBackManager { @@ -48,14 +46,6 @@ public: this->releaseFunc = func; } - void SetCopyReleaseParam(const ACL_COPY_RELEASE_PARM_FUNC& func) { - this->copyReleaseParamFunc = func; - } - - void SetReleaseParam(const ACL_RELEASE_PARAM_FUNC& func) { - this->releaseParamFunc = func; - } - void SetNew(const ACL_NEW_FUNC& func) { this->newFunc = func; } @@ -64,34 +54,22 @@ public: this->deleteFunc = func; } - int Call(void* head, int offset, uint32_t queueLen) { + int Call(void* head, int offset, aclrtStream stream) { TORCH_CHECK(this->execFunc, "Failed to find execution function."); auto dstPtr = (uint8_t*)head + sizePerParams * offset; - return this->execFunc(dstPtr, queueLen); + return this->execFunc(dstPtr, stream); } - void Copy(void* dstHead, int offset, void* src, uint32_t queueLen) { + void Copy(void* dstHead, int offset, void* src) { TORCH_CHECK(this->copyFunc, "Failed to find copy function."); auto dstPtr = (uint8_t*)dstHead + sizePerParams * offset; - return this->copyFunc(dstPtr, src, queueLen); + return this->copyFunc(dstPtr, src); } - void Release(void* head, int offset, ReleaseQueue& releaseQueue) { + void Release(void* head, int offset) { TORCH_CHECK(this->releaseFunc, "Failed to find release function."); auto ptr = (uint8_t*)head + sizePerParams * offset; - return this->releaseFunc(ptr, releaseQueue); - } - - void CopyRealseParam(void* dstHead, int offset, void* src) { - TORCH_CHECK(this->copyReleaseParamFunc, "Failed to find copy release params function."); - auto dstPtr = (uint8_t*)dstHead + sizePerParams * offset; - return this->copyReleaseParamFunc(dstPtr, src); - } - - void ReleaseParam(void* head, int offset) { - TORCH_CHECK(this->releaseParamFunc, "Failed to find release params function."); - auto ptr = (uint8_t*)head + sizePerParams * offset; - return this->releaseParamFunc(ptr); + return this->releaseFunc(ptr); } void* Init(int capacity) { @@ -114,35 +92,23 @@ private: ACL_RELEASE_FUNC releaseFunc = nullptr; ACL_NEW_FUNC newFunc = nullptr; ACL_DELETE_FUNC deleteFunc = nullptr; - ACL_COPY_RELEASE_PARM_FUNC copyReleaseParamFunc = nullptr; - ACL_RELEASE_PARAM_FUNC releaseParamFunc = nullptr; }; // class CallBackManager CallBackManager& manager() { static CallBackManager instance; return instance; } - -CallBackManager& releaseManager() { - static CallBackManager releaseinstance; - return releaseinstance; -} } // namespace namespace register_queue_cb { NPUCallBackRegisterBuilder::NPUCallBackRegisterBuilder(const ACL_EXEC_FUNC& execFunc, const ACL_COPY_FUNC& copyFunc, const ACL_RELEASE_FUNC& releaseFunc, - const ACL_NEW_FUNC& newFunc, const ACL_DELETE_FUNC& deleteFunc, - const ACL_COPY_RELEASE_PARM_FUNC& copyReleaseParamF, const ACL_RELEASE_PARAM_FUNC& releaseParamF) { + const ACL_NEW_FUNC& newFunc, const ACL_DELETE_FUNC& deleteFunc) { manager().SetExec(execFunc); manager().SetCopy(copyFunc); manager().SetRelease(releaseFunc); manager().SetNew(newFunc); manager().SetDelete(deleteFunc); - releaseManager().SetCopyReleaseParam(copyReleaseParamF); - releaseManager().SetReleaseParam(releaseParamF); - releaseManager().SetNew(newFunc); - releaseManager().SetDelete(deleteFunc); } } // namespace register_queue_cb @@ -151,7 +117,7 @@ NPUCallBackRegisterBuilder::NPUCallBackRegisterBuilder(const ACL_EXEC_FUNC& exec // a large amount of device memory is occupied at the same time; // if the capacity is too small, and the main thread is fast enough, // it does not make full use of concurrent design capabilities. -static constexpr size_t kQueueCapacity = 4096; +static constexpr size_t kQueueCapacity = 1000; RepoStatus Repository::GetStatus() const { if (initialized == false) { @@ -208,11 +174,7 @@ NPUStatus Repository::MakeSureQueueEmpty() { s = eventfd_read(efd_empty, &u); } if (s != 0) { - if (errno == EINTR) { - QUEUE_DEBUG("EINTR occurs on the eventfd_read"); - continue; - } - NPU_LOGE("eventfd_read failed. s=%zd, errno=%s.", s, strerror(errno)); + NPU_LOGE("eventfd_read failed !!"); return INTERNEL_ERROR; } QUEUE_DEBUG("waiting ok, queue is empty now"); @@ -250,18 +212,18 @@ bool Repository::NeedNotify(RepoRole role) const { } bool Repository::WriteQueue(void* cur_paras) { - std::lock_guard lock(mu_enqueue); QUEUE_DEBUG("write_idx=%d, read_idx=%d", write_idx.idx, read_idx.idx); if (IsFullQueue()) { QUEUE_DEBUG("queue is full"); return false; } - uint32_t queueLen = (write_idx.idx - read_idx.idx + kQueueCapacity) % kQueueCapacity; - manager().Copy(datas, write_idx.idx, cur_paras, queueLen); + std::lock_guard lock(mu_enqueue); + manager().Copy(datas, write_idx.idx, cur_paras); __sync_synchronize(); - write_idx.idx = (write_idx.idx + 1) % kQueueCapacity; + write_idx.idx++; + write_idx.idx %= kQueueCapacity; return true; } @@ -272,8 +234,7 @@ bool Repository::ReadQueue() { return false; } - uint32_t queueLen = (write_idx.idx - read_idx.idx + kQueueCapacity) % kQueueCapacity; - auto ret = manager().Call(datas, read_idx.idx, queueLen); + auto ret = manager().Call(datas, read_idx.idx, calcu_stream_); if (ret != 0) { while (!IsEmptyQueue()) { // ignore other tasks @@ -281,8 +242,9 @@ bool Repository::ReadQueue() { << ": device=" << device_idx << ", write_idx=" << write_idx.idx << ", read_idx=" << read_idx.idx << ", status=" << GetStatus() << ", ret = " << ret << std::endl; - manager().Release(datas, read_idx.idx, releaseQueue); - read_idx.idx = (read_idx.idx + 1) % kQueueCapacity; + manager().Release(datas, read_idx.idx); + read_idx.idx++; + read_idx.idx %= kQueueCapacity; } ReleaseResource(); std::stringstream msg; @@ -290,10 +252,11 @@ bool Repository::ReadQueue() { TORCH_CHECK(0, msg.str()); } - manager().Release(datas, read_idx.idx, releaseQueue); + manager().Release(datas, read_idx.idx); __sync_synchronize(); - read_idx.idx = (read_idx.idx + 1) % kQueueCapacity; + read_idx.idx++; + read_idx.idx %= kQueueCapacity; QUEUE_DEBUG("read success, now read of repo is %d", read_idx.idx); return true; @@ -327,11 +290,7 @@ void Repository::Enqueue(void* cur_paras) { s = eventfd_read(efd_write, &u); } if (s != 0) { - if (errno == EINTR) { - QUEUE_DEBUG("EINTR occurs on the eventfd_read"); - continue; - } - NPU_LOGE("waiting queue not full failed. s=%zd, errno=%s.", s, strerror(errno)); + NPU_LOGE("waiting queue not full failed !!"); return; } DisableInterrupt(RepoRole::WRITER); @@ -340,18 +299,13 @@ void Repository::Enqueue(void* cur_paras) { continue; } __sync_synchronize(); - while (NeedNotify(RepoRole::READER)) { + if (NeedNotify(RepoRole::READER)) { QUEUE_DEBUG("need notify consumer"); s = eventfd_write(efd_read, u); if (s != 0) { - if (errno == EINTR) { - QUEUE_DEBUG("EINTR occurs on the eventfd_write"); - continue; - } - NPU_LOGE("notify consumer failed!! s=%zd, errno=%s", s, strerror(errno)); + NPU_LOGE("notify consumer failed !!"); return; } - break; } } EnableInterrupt(RepoRole::WRITER); @@ -376,65 +330,38 @@ void Repository::Dequeue() { ChangeStatus(NEED_EXIT, CAN_EXIT); break; } - // reduce system wait time - bool emptyFlag = true; - for (int i = 0; i < MAX_JUDGE_NUM; ++i) { - if (IsEmptyQueue()) { - continue; - } else { - emptyFlag = false; - break; - } - } - - if (emptyFlag) { - EnableInterrupt(RepoRole::READER); - __sync_synchronize(); - if (IsEmptyQueue()) { - s = eventfd_read(efd_read, &u); - if (s != 0) { - if (errno == EINTR) { - QUEUE_DEBUG("EINTR occurs on the eventfd_read"); - continue; - } - NPU_LOGE("waiting queue not empty failed. s=%zd, errno=%s.", s, strerror(errno)); - return; - } - DisableInterrupt(RepoRole::READER); - QUEUE_DEBUG("waiting ok, queue isn't empty now"); + EnableInterrupt(RepoRole::READER); + __sync_synchronize(); + if (IsEmptyQueue()) { + s = eventfd_read(efd_read, &u); + if (s != 0) { + NPU_LOGE("waiting queue not empty failed !!"); + return; } + DisableInterrupt(RepoRole::READER); + QUEUE_DEBUG("waiting ok, queue isn't empty now"); } continue; } __sync_synchronize(); notify_empty = need_empty && IsEmptyQueue(); // need_empty && (ret == false || IsEmptyQueue()); - while (notify_empty) { + if (notify_empty) { QUEUE_DEBUG("need notify make_sure"); s = eventfd_write(efd_empty, u); if (s != 0) { - if (errno == EINTR) { - QUEUE_DEBUG("EINTR occurs on the eventfd_write"); - continue; - } - NPU_LOGE("notify make_sure failed. s=%zd, errno=%s.", s, strerror(errno)); + NPU_LOGE("notify make_sure failed !!"); return; } - break; } __sync_synchronize(); - while (NeedNotify(RepoRole::WRITER)) { + if (NeedNotify(RepoRole::WRITER)) { QUEUE_DEBUG("need notify producer"); s = eventfd_write(efd_write, u); if (s != 0) { - if (errno == EINTR) { - QUEUE_DEBUG("EINTR occurs on the eventfd_write"); - continue; - } - NPU_LOGE("notify producer failed. s=%zd, errno=%s.", s, strerror(errno)); + NPU_LOGE("notify producer failed !!"); return; } - break; } } EnableInterrupt(RepoRole::READER); @@ -485,6 +412,10 @@ Repository::~Repository() { } } +bool Repository::IsEmptyQueue() const { + return read_idx.idx == write_idx.idx; +} + bool Repository::IsFullQueue() const { return ((write_idx.idx + 1) % kQueueCapacity) == read_idx.idx; } @@ -500,7 +431,6 @@ void StartConsume(Repository* repo, c10::DeviceIndex device_id) { aclError ret = aclrtSetDevice(device_id); if (ret != 0) { - C10_NPU_SHOW_ERR_MSG(); std::cout << "***Thread*" << std::this_thread::get_id() << ": set device (" << device_id << "): ret = " << ret << std::endl; } @@ -511,7 +441,7 @@ void StartConsume(Repository* repo, c10::DeviceIndex device_id) { return; } -void Repository::InitRepo(c10::DeviceIndex device_id) { +void Repository::InitRepo(c10::DeviceIndex device_id, aclrtStream calcu_stream) { struct timeval tv; gettimeofday(&tv, NULL); QUEUE_COUT( @@ -523,7 +453,11 @@ void Repository::InitRepo(c10::DeviceIndex device_id) { if (datas == nullptr) { datas = manager().Init(kQueueCapacity); } - + if (calcu_stream == nullptr) { + NPU_LOGE("stream should not be null when init task queue."); + return; + } + calcu_stream_ = calcu_stream; efd_read = eventfd(0, 0); efd_write = eventfd(0, 0); efd_empty = eventfd(0, 0); @@ -533,132 +467,7 @@ void Repository::InitRepo(c10::DeviceIndex device_id) { device_idx = device_id; std::thread cur_consumer(StartConsume, this, device_id); consumer = std::move(cur_consumer); - - releaseQueue.InitReleaseQueue(); } -static constexpr size_t kReleaseQueueCapacity = 8192; -bool ReleaseQueue::WriteToReleaseQueue(void* cur_paras) -{ - if (IsFullQueue()) { - QUEUE_DEBUG("Release queue is full"); - return false; - } - releaseManager().CopyRealseParam(datas, write_idx.idx, cur_paras); - - __sync_synchronize(); - write_idx.idx = (write_idx.idx + 1) % kReleaseQueueCapacity; - return true; -} - -void ReleaseQueue::PushToReleaseQueue(void* cur_paras) { - if (initialized == false) { - NPU_LOGE("Release queue is not initialized, shouldn't call PushToReleaseQueue(). !!"); - return; - } - - bool ret = false; - while (ret == false) { - ret = WriteToReleaseQueue(cur_paras); - if (ret == true) { - break; - } - } -} - -bool ReleaseQueue::ReadFromReleaseQueue() { - if (IsEmptyQueue()) { - QUEUE_DEBUG("Release queue is empty"); - return false; - } - - releaseManager().ReleaseParam(datas, read_idx.idx); - - __sync_synchronize(); - read_idx.idx = (read_idx.idx + 1) % kReleaseQueueCapacity; - - return true; -} - -void ReleaseQueue::PopFromReleaseQueue() { - if (initialized == false) { - NPU_LOGE("Release queue is not initialized, shouldn't call PopFromReleaseQueue(). !!"); - return; - } - - bool ret = false; - while ((ret == false) && (GetStatus() != RepoStatus::CAN_EXIT)) { - ret = ReadFromReleaseQueue(); - if (ret == false) { - if (GetStatus() == RepoStatus::NEED_EXIT) { - ChangeStatus(NEED_EXIT, CAN_EXIT); - break; - } - usleep(2); - } - } -} - -void StartRelease(ReleaseQueue* releaseQue) { - if (prctl(PR_SET_NAME, ("Release_thread")) != 0) { - std::cout << "set thread name failed!" << std::endl; - } - - while (releaseQue->GetStatus() != RepoStatus::CAN_EXIT) { - releaseQue->PopFromReleaseQueue(); - } - return; -} - -void ReleaseQueue::InitReleaseQueue() { - if (datas == nullptr) { - datas = releaseManager().Init(kReleaseQueueCapacity); - } - - initialized = true; - SetStatus(INIT); - std::thread cur_releaser(StartRelease, this); - releaser = std::move(cur_releaser); -} - -ReleaseQueue::~ReleaseQueue() { - if (initialized) { - if (releaser.joinable()) { - SetStatus(NEED_EXIT); - releaser.join(); - } - } - releaseManager().DeInit(datas); -} - -bool ReleaseQueue::IsFullQueue() const { - return ((write_idx.idx + 1) % kReleaseQueueCapacity) == read_idx.idx; -} - -RepoStatus ReleaseQueue::GetStatus() const { - if (initialized == false) { - NPU_LOGE("Release queue is not initialized, shouldn't call GetStatus(). !!"); - } - - return repo_status.load(); -} - -void ReleaseQueue::SetStatus(RepoStatus desired) { - if (initialized == false) { - NPU_LOGE("Release queue is not initialized, shouldn't call SetStatus(). !!"); - return; - } - - repo_status = desired; -} - -void ReleaseQueue::ChangeStatus(RepoStatus expected, RepoStatus desired) { - if (initialized == false) { - NPU_LOGE("Release queue is not initialized, shouldn't call ChangeStatus(). !!"); - return; - } - - repo_status.compare_exchange_strong(expected, desired); -} -} // namespace c10_npu +} // namespace c10_npu \ No newline at end of file diff --git a/torch_npu/csrc/core/npu/NPUQueue.h b/torch_npu/csrc/core/npu/NPUQueue.h index 12eea6f0da..6a06595898 100644 --- a/torch_npu/csrc/core/npu/NPUQueue.h +++ b/torch_npu/csrc/core/npu/NPUQueue.h @@ -28,39 +28,8 @@ enum RepoStatus { CAN_EXIT = 3, }; -// c10::SmallVector max size -const int N = 32; - -class ReleaseQueue { -public: - ReleaseQueue() = default; - ~ReleaseQueue(); - void PushToReleaseQueue(void* cur_paras); - void PopFromReleaseQueue(); - void InitReleaseQueue(); - RepoStatus GetStatus() const; - -private: - inline bool IsEmptyQueue() {return read_idx.idx == write_idx.idx;}; - bool IsFullQueue() const; - bool WriteToReleaseQueue(void* cur_paras); - bool ReadFromReleaseQueue(); - void SetStatus(RepoStatus desired); - void ChangeStatus(RepoStatus expected, RepoStatus desired); - -private: - void* datas = nullptr; - std::thread releaser; - -private: - sring_idx read_idx; - sring_idx write_idx; - std::atomic repo_status; - bool initialized = false; -}; - class NPUQueueBase { -public: + public: virtual ~NPUQueueBase() {} virtual RepoStatus GetStatus() const = 0; virtual void SetStatus(RepoStatus desired) = 0; @@ -68,7 +37,7 @@ public: virtual void Enqueue(void* cur_paras) = 0; virtual void Dequeue() = 0; virtual NPUStatus MakeSureQueueEmpty() = 0; - virtual void InitRepo(c10::DeviceIndex device_id) = 0; + virtual void InitRepo(c10::DeviceIndex device_id, aclrtStream calcu_stream) = 0; virtual bool CheckInit() const = 0; }; @@ -79,7 +48,7 @@ public: }; class Repository : public NPUQueueBase { -public: + public: Repository() = default; ~Repository() override; RepoStatus GetStatus() const override; @@ -88,12 +57,12 @@ public: void Enqueue(void* cur_paras) override; void Dequeue() override; NPUStatus MakeSureQueueEmpty() override; - void InitRepo(c10::DeviceIndex device_id) override; + void InitRepo(c10::DeviceIndex device_id, aclrtStream calcu_stream) override; bool CheckInit() const override; -private: + private: void ReleaseResource(); - inline bool IsEmptyQueue() {return read_idx.idx == write_idx.idx;}; + bool IsEmptyQueue() const; bool IsFullQueue() const; void EnableInterrupt(RepoRole role); void DisableInterrupt(RepoRole role); @@ -101,7 +70,7 @@ private: bool WriteQueue(void* cur_paras); bool ReadQueue(); -private: + private: void* datas = nullptr; std::thread consumer; int efd_read; @@ -109,7 +78,7 @@ private: int efd_empty; c10::DeviceIndex device_idx; -private: + private: sring_idx read_idx; sring_idx write_idx; std::atomic repo_status; @@ -120,28 +89,25 @@ private: // The logic is ensured by original pytorch, but this is added here just in // case. std::mutex mu_enqueue; - ReleaseQueue releaseQueue; + aclrtStream calcu_stream_; }; -using ACL_EXEC_FUNC = std::function; -using ACL_COPY_FUNC = std::function; -using ACL_RELEASE_FUNC = std::function; +using ACL_EXEC_FUNC = std::function; +using ACL_COPY_FUNC = std::function; +using ACL_RELEASE_FUNC = std::function; using ACL_NEW_FUNC = std::function; using ACL_DELETE_FUNC = std::function; -using ACL_COPY_RELEASE_PARM_FUNC = std::function; -using ACL_RELEASE_PARAM_FUNC = std::function; namespace register_queue_cb { class NPUCallBackRegisterBuilder { public: - NPUCallBackRegisterBuilder(const ACL_EXEC_FUNC& execF, const ACL_COPY_FUNC& copyF, - const ACL_RELEASE_FUNC& releaseF, const ACL_NEW_FUNC& newF, const ACL_DELETE_FUNC& deleteF, - const ACL_COPY_RELEASE_PARM_FUNC& copyReleaseParamF, const ACL_RELEASE_PARAM_FUNC& releaseParamF); + NPUCallBackRegisterBuilder(const ACL_EXEC_FUNC& execF, const ACL_COPY_FUNC& copyF, const ACL_RELEASE_FUNC& releaseF, const ACL_NEW_FUNC& newF, const ACL_DELETE_FUNC& deleteF); ~NPUCallBackRegisterBuilder(){} }; } // namespace register_queue_cb -#define REGISTER_QUEUE_FUNC(execF, copyF, releaseF, newF, deleteF, copyReleaseParamF, releaseParamF) \ - static ::c10_npu::register_queue_cb::NPUCallBackRegisterBuilder \ - register_queue_func_builder(execF, copyF, releaseF, newF, deleteF, copyReleaseParamF, releaseParamF); -} // namespace c10_npu \ No newline at end of file +#define REGISTER_QUEUE_FUNC(execF, copyF, releaseF, newF, deleteF) \ + static ::c10_npu::register_queue_cb::NPUCallBackRegisterBuilder \ + register_queue_func_builder(execF, copyF, releaseF, newF, deleteF); + +} // namespace c10_npu diff --git a/torch_npu/csrc/core/npu/NPUStream.cpp b/torch_npu/csrc/core/npu/NPUStream.cpp index 1468a495b6..131428cff5 100644 --- a/torch_npu/csrc/core/npu/NPUStream.cpp +++ b/torch_npu/csrc/core/npu/NPUStream.cpp @@ -149,7 +149,7 @@ static void initGlobalStreamState() { auto& default_streamsi = default_streams[device_id]; C10_NPU_CHECK(aclrtCreateStream(&default_streamsi.stream)); if (c10_npu::option::OptionsManager::CheckQueueEnable()) { - default_streamsi.repo->InitRepo(device_id); + default_streamsi.repo->InitRepo(device_id, default_streamsi.stream); } // Initializes secondary streams secondary_streams[device_id].device_index = device_id; @@ -364,12 +364,10 @@ void enCurrentNPUStream( device_index = current_device(); } check_npu(device_index); - c10_npu::queue::QueueParas* queueParam = static_cast(cur_paras); - queueParam->paramStream = current_streams[device_index]->stream; - default_streams[device_index].repo->Enqueue(cur_paras); - if (default_streams[device_index].repo->GetStatus() == RepoStatus::INIT) { - default_streams[device_index].repo->MakeSureQueueEmpty(); - default_streams[device_index].repo->ChangeStatus(RepoStatus::INIT, RepoStatus::RUN); + current_streams[device_index]->repo->Enqueue(cur_paras); + if (current_streams[device_index]->repo->GetStatus() == RepoStatus::INIT) { + current_streams[device_index]->repo->MakeSureQueueEmpty(); + current_streams[device_index]->repo->ChangeStatus(RepoStatus::INIT, RepoStatus::RUN); } } diff --git a/torch_npu/csrc/core/npu/NPUStream.h b/torch_npu/csrc/core/npu/NPUStream.h index 80ce9910ca..8c416bab0e 100644 --- a/torch_npu/csrc/core/npu/NPUStream.h +++ b/torch_npu/csrc/core/npu/NPUStream.h @@ -12,7 +12,7 @@ #include "torch_npu/csrc/core/npu/npu_log.h" #include "third_party/acl/inc/acl/acl_op.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace c10_npu { diff --git a/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.cpp b/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.cpp index d0f8f0fcb3..e3e7158876 100644 --- a/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.cpp +++ b/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.cpp @@ -18,10 +18,6 @@ #include "torch_npu/csrc/core/npu/npu_log.h" #include #include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h" -#include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" -#include "torch_npu/csrc/core/npu/interface/AclInterface.h" -#include "torch_npu/csrc/core/npu/register/OptionsManager.h" - #include #include @@ -75,11 +71,6 @@ struct HostAllocator { // outstanding ACL events std::deque> npu_events; - // record events - std::mutex record_mutex; - std::set complete_events; - - HostAllocator() : available(BlockComparator) {} aclError malloc(void** ptr, size_t size) { @@ -137,7 +128,7 @@ struct HostAllocator { // we process the streams. block.allocated = false; - // insert npu events for each stream on which this block was used. This + // insert NPU events for each stream on which this block was used. This err = insertEvents(block); if (err != ACL_ERROR_NONE) { return err; @@ -158,7 +149,6 @@ struct HostAllocator { // Sync when host memory is allocated by malloc aclError error = aclrtSynchronizeStream(stream); if (error != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); AT_ERROR("ACL stream synchronize failed."); return error; } @@ -172,33 +162,6 @@ struct HostAllocator { return ACL_ERROR_NONE; } - bool isPinndPtr(void* ptr) - { - std::lock_guard lock(mutex); - return blocks.find(ptr) != blocks.end(); - } - - void insertCompleteEvent(aclrtEvent event) - { - if (c10_npu::option::OptionsManager::CheckQueueEnable()) { - std::lock_guard lock(record_mutex); - complete_events.insert(event); - } - } - - bool findAndEraseCompleteEvent(aclrtEvent event) - { - if (c10_npu::option::OptionsManager::CheckQueueEnable()) { - std::lock_guard lock(record_mutex); - auto it = complete_events.find(event); - if (it == complete_events.end()) { - return false; - } - complete_events.erase(it); - } - return true; - } - aclError processEvents() { // Process outstanding npuEvents. Events that are completed are removed // from the queue, and the 'event_count' for the corresponding allocation @@ -208,27 +171,15 @@ struct HostAllocator { while (!npu_events.empty()) { auto& e = npu_events.front(); aclrtEvent event = e.first; - // when TASK_QUEUE_ENABLE is set, pytorch thread can destroy event - // after acl thread has launched record event task - if (!findAndEraseCompleteEvent(event)) { - break; - } - aclrtEventStatus status = ACL_EVENT_STATUS_RESERVED; + aclrtEventStatus status = ACL_EVENT_STATUS_COMPLETE; aclError err = aclrtQueryEvent(event, &status); - if (err != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - insertCompleteEvent(event); + if (status == ACL_EVENT_STATUS_NOT_READY) { + break; + } else if (err != ACL_ERROR_NONE) { return err; } - if (status != ACL_EVENT_STATUS_COMPLETE) { - insertCompleteEvent(event); - break; - } - err = aclrtDestroyEvent(event); if (err != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - insertCompleteEvent(event); return err; } @@ -251,7 +202,6 @@ struct HostAllocator { Block& block = blocks.at(it->second); if (!block.allocated) { if (aclrtDestroyEvent(event) != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); NPU_LOGW("destory acl event fail"); } block.event_count--; @@ -294,24 +244,21 @@ struct HostAllocator { if (ret != ACL_ERROR_NONE) { err = aclrtSetDevice(it->device_index()); if (err != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); break; } } else if (pre_device != it->device_index()) { err = aclrtSetDevice(it->device_index()); if (err != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); break; } } aclrtEvent event = nullptr; - err = c10_npu::acl::AclrtCreateEventWithFlag(&event, ACL_EVENT_TIME_LINE); - if (err != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - break; - } - err = c10_npu::queue::HostAllocatorLaunchRecordEventTask(event, *it); + err = aclrtCreateEvent(&event); + if (err != ACL_ERROR_NONE) + break; + + err = aclrtRecordEvent(event, it->stream()); if (err != ACL_ERROR_NONE) break; @@ -339,14 +286,6 @@ aclError THNPUCachingHostAllocator_recordEvent( return allocator.recordEvent(ptr, stream); } -void THNPUCachingHostAllocator_insertCompleteEvent(aclrtEvent event) { - return allocator.insertCompleteEvent(event); -} - -bool THNPUCachingHostAllocator_isPinndPtr(void* ptr) { - return allocator.isPinndPtr(ptr); -} - void THNPUCachingHostAllocator_emptyCache() { allocator.emptyCache(); } diff --git a/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h b/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h index 79b3ca1a4f..5b63ff14bb 100644 --- a/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h +++ b/torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h @@ -19,14 +19,10 @@ #include #include #include - c10::Allocator* getTHNPUCachingHostAllocator(void); aclError THNPUCachingHostAllocator_recordEvent(void* ptr, c10_npu::NPUStream stream); -void THNPUCachingHostAllocator_insertCompleteEvent(aclrtEvent event); - -bool THNPUCachingHostAllocator_isPinndPtr(void* ptr); // Releases cached pinned memory allocations via npuHostFree void THNPUCachingHostAllocator_emptyCache(void); diff --git a/torch_npu/csrc/core/npu/impl/NPUGuardImpl.h b/torch_npu/csrc/core/npu/impl/NPUGuardImpl.h index 54e65b7d92..036f96cb25 100644 --- a/torch_npu/csrc/core/npu/impl/NPUGuardImpl.h +++ b/torch_npu/csrc/core/npu/impl/NPUGuardImpl.h @@ -8,7 +8,7 @@ #include "torch_npu/csrc/core/npu/NPUFunctions.h" #include "torch_npu/csrc/core/npu/NPUStream.h" #include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include #include #include diff --git a/torch_npu/csrc/core/npu/interface/AclInterface.cpp b/torch_npu/csrc/core/npu/interface/AclInterface.cpp index a88b191cd0..4112cb7380 100644 --- a/torch_npu/csrc/core/npu/interface/AclInterface.cpp +++ b/torch_npu/csrc/core/npu/interface/AclInterface.cpp @@ -25,7 +25,6 @@ LOAD_FUNCTION(aclprofStop) LOAD_FUNCTION(aclprofFinalize) LOAD_FUNCTION(aclprofCreateConfig) LOAD_FUNCTION(aclprofDestroyConfig) -LOAD_FUNCTION(aclrtGetSocName) aclprofStepInfoPtr init_stepinfo(){ typedef aclprofStepInfoPtr(*npdInitFunc)(); @@ -174,14 +173,5 @@ aclError AclProfilingDestroyConfig(const aclprofConfig *profilerConfig) { return func(profilerConfig); } -const char *AclrtGetSocName() { - typedef const char *(*aclrtGetSocNameFunc)(); - static aclrtGetSocNameFunc func = nullptr; - if (func == nullptr) { - func = (aclrtGetSocNameFunc)GET_FUNC(aclrtGetSocName); - } - TORCH_CHECK(func, "Failed to find function ", "aclrtGetSocName"); - return func(); -} } // namespace acl } // namespace c10 diff --git a/torch_npu/csrc/core/npu/interface/AclInterface.h b/torch_npu/csrc/core/npu/interface/AclInterface.h index 8daf51791b..8565bfd3fc 100644 --- a/torch_npu/csrc/core/npu/interface/AclInterface.h +++ b/torch_npu/csrc/core/npu/interface/AclInterface.h @@ -70,6 +70,6 @@ aclprofConfig * AclProfilingCreateConfig( aclprofAicoreEvents *aicoreEvents, uint64_t dataTypeConfig); aclError AclProfilingDestroyConfig(const aclprofConfig *profilerConfig); -const char *AclrtGetSocName(); + } // namespace acl } // namespace c10_npu diff --git a/torch_npu/csrc/core/npu/register/OptionsManager.cpp b/torch_npu/csrc/core/npu/register/OptionsManager.cpp index 63c06d4e2e..c0bba742e2 100644 --- a/torch_npu/csrc/core/npu/register/OptionsManager.cpp +++ b/torch_npu/csrc/core/npu/register/OptionsManager.cpp @@ -69,5 +69,50 @@ bool OptionsManager::CheckUseNpuLogEnable() { return (useNpuLog == 1); } + +bool OptionsManager::CheckScalarToHostMemEnable() +{ + static int32_t scalarToHostMemFlag = -1; + if (scalarToHostMemFlag == -1) { + // this env will be deleted when cann sets scalar input to data input + // whether in fuzzy compile or no fuzzy compile + scalarToHostMemFlag = GetBoolTypeOption("SCALAR_TO_HOST_MEM"); + } + return (scalarToHostMemFlag == 1); +} + +bool OptionsManager::CheckDynamicOptimizer(const char* op) { + static int isGetOps = 0; + static std::map op_map = {{"ADD", false}, {"MUL", false}}; + if (isGetOps == 0) { + char* dynamicOptimizerEnv = std::getenv("DYNAMIC_OP"); + if (dynamicOptimizerEnv != nullptr) { + std::string dynamicOptimizerEnvStr = dynamicOptimizerEnv; + const std::string separator = "#"; + std::string::size_type pos1 = 0; + std::string::size_type pos2 = dynamicOptimizerEnvStr.find(separator); + std::string substr; + while (pos2 != std::string::npos) { + substr = dynamicOptimizerEnvStr.substr(pos1, pos2 - pos1); + if (op_map.find(substr) != op_map.end()) { + op_map[substr] = true; + } + pos1 = pos2 + separator.size(); + pos2 = dynamicOptimizerEnvStr.find(separator, pos1); + } + if (pos1 != dynamicOptimizerEnvStr.size()) { + substr = dynamicOptimizerEnvStr.substr(pos1); + if (op_map.find(substr) != op_map.end()) { + op_map[substr] = true; + } + } + } + isGetOps = 1; + } + TORCH_CHECK( + op_map.find(op) != op_map.end(), "This op is not currently optimized."); + return op_map[op]; +} + } // namespace option } // namespace c10_npu \ No newline at end of file diff --git a/torch_npu/csrc/core/npu/register/OptionsManager.h b/torch_npu/csrc/core/npu/register/OptionsManager.h index 9503cbe3c1..e2772f5bd0 100644 --- a/torch_npu/csrc/core/npu/register/OptionsManager.h +++ b/torch_npu/csrc/core/npu/register/OptionsManager.h @@ -30,6 +30,8 @@ public: static bool CheckTriCombinedOptimizerEnable(); static bool CheckAclDumpDateEnable(); static bool CheckSwitchMMOutputEnable(); + static bool CheckScalarToHostMemEnable(); + static bool CheckDynamicOptimizer(const char* op); static bool CheckUseNpuLogEnable(); static std::string CheckDisableDynamicPath(); private: diff --git a/torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.cpp b/torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.cpp index 6f66f49064..3fadf4ed92 100644 --- a/torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.cpp +++ b/torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.cpp @@ -133,7 +133,10 @@ NpuSysCtrl::NpuSysCtrl() : init_flag_(false), device_id_(0) {} } } - C10_NPU_CHECK(ge::GEInitialize(config)); + auto ge_ret = ge::GEInitialize(config); + if (ge_ret != ge::SUCCESS) { + AT_ERROR("GE init failed!"); + } // set default compile cache mode and dir for users to improve op compile time MakeCompileCacheDirAndSetOption(); @@ -160,13 +163,13 @@ NpuSysCtrl::NpuSysCtrl() : init_flag_(false), device_id_(0) {} } this->RegisterReleaseFn([=]() ->void { - c10_npu::NPUEventManager::GetInstance().ClearEvent(); - auto stream = c10_npu::getCurrentNPUStream(); - (void)aclrtDestroyStream(stream); - C10_NPU_CHECK(ge::GEFinalize()); - C10_NPU_CHECK(aclrtResetDevice(device_id_)); - C10_NPU_CHECK(aclFinalize()); - }, ReleasePriority::PriorityLast); + c10_npu::NPUEventManager::GetInstance().ClearEvent(); + auto stream = c10_npu::getCurrentNPUStream(); + (void)aclrtDestroyStream(stream); + C10_NPU_CHECK(ge::GEFinalize()); + C10_NPU_CHECK(aclrtResetDevice(device_id_)); + C10_NPU_CHECK(aclFinalize()); + }, ReleasePriority::PriorityLast); init_flag_ = false; diff --git a/torch_npu/csrc/distributed/CMakeLists.txt b/torch_npu/csrc/distributed/CMakeLists.txt index 374323b304..a68305dd46 100644 --- a/torch_npu/csrc/distributed/CMakeLists.txt +++ b/torch_npu/csrc/distributed/CMakeLists.txt @@ -1,6 +1,6 @@ -FILE(GLOB _DIST_SRCS *.cpp) +#FILE(GLOB _DIST_SRCS *.cpp) -LIST(APPEND DIST_SRCS ${_DIST_SRCS}) +#LIST(APPEND DIST_SRCS ${_DIST_SRCS}) # Pass to parent -set(DIST_SRCS ${DIST_SRCS} PARENT_SCOPE) \ No newline at end of file +#set(DIST_SRCS ${DIST_SRCS} PARENT_SCOPE) \ No newline at end of file diff --git a/torch_npu/csrc/distributed/HCCLUtils.hpp b/torch_npu/csrc/distributed/HCCLUtils.hpp index 8c7a534b77..5af915ca06 100644 --- a/torch_npu/csrc/distributed/HCCLUtils.hpp +++ b/torch_npu/csrc/distributed/HCCLUtils.hpp @@ -52,8 +52,8 @@ public: C10D_HCCL_CHECK( HcclCommInitRootInfo(numRanks, &rootInfo, rank, &(comm->hcclComm_))); c10_npu::NpuSysCtrl::GetInstance().RegisterReleaseFn([=]() ->void { - HcclCommDestroy(comm->hcclComm_); - }, c10_npu::ReleasePriority::PriorityMiddle); + HcclCommDestroy(comm->hcclComm_); + }, c10_npu::ReleasePriority::PriorityMiddle); return comm; } diff --git a/torch_npu/csrc/distributed/HcclCompile.h b/torch_npu/csrc/distributed/HcclCompile.h deleted file mode 100644 index 11d6a9f752..0000000000 --- a/torch_npu/csrc/distributed/HcclCompile.h +++ /dev/null @@ -1,46 +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. - -#include -#include "torch_npu/csrc/core/npu/register/FunctionLoader.h" - -namespace c10d_npu { -#undef LOAD_FUNCTION -#define LOAD_FUNCTION(funcName) \ - REGISTER_FUNCTION(libhccl, funcName) -#undef GET_FUNC -#define GET_FUNC(funcName) \ - GET_FUNCTION(libhccl, funcName) - - REGISTER_LIBRARY(libhccl) - LOAD_FUNCTION(HcclAlltoAllV) - -extern HcclResult hcclAlltoAllV(const void *sendBuf, const void *sendCounts, const void *sdispls, - HcclDataType sendType, const void *recvBuf, const void *recvCounts, const void *rdispls, - HcclDataType recvType, HcclComm comm, aclrtStream stream) { - typedef HcclResult(*HcclAlltoAllVFunc)( - const void *, const void *, const void *, HcclDataType, - const void *, const void *, const void *, HcclDataType, - HcclComm, aclrtStream); - static HcclAlltoAllVFunc func = nullptr; - if (func == nullptr) { - func = (HcclAlltoAllVFunc)GET_FUNC(HcclAlltoAllV); - } - TORCH_CHECK(func, "Failed to find function ", "HcclAlltoAllV"); - auto ret = func(sendBuf, sendCounts, sdispls, sendType, - recvBuf, recvCounts, rdispls, recvType, comm, stream); - return ret; -} -} diff --git a/torch_npu/csrc/distributed/Init.cpp b/torch_npu/csrc/distributed/Init.cpp index 0520c28a9a..9761fefa38 100644 --- a/torch_npu/csrc/distributed/Init.cpp +++ b/torch_npu/csrc/distributed/Init.cpp @@ -33,9 +33,9 @@ #include "torch_npu/csrc/distributed/ProcessGroupHCCL.hpp" #include "torch_npu/csrc/distributed/Init.h" #include "torch_npu/csrc/distributed/reducer.hpp" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" - +/* namespace torch_npu { namespace distributed { @@ -49,7 +49,7 @@ class BroadcastWork { public: inline std::vector cast_tensors(at::TensorList tensors) { static auto cast_back_to_ori_format = [](const at::Tensor &t) { - return at_npu::native::NPUNativeFunctions::npu_format_cast(t, torch_npu::NPUBridge::GetNpuStorageImpl(t)->npu_desc_.origin_format_); + return at_npu::native::XLANativeFunctions::npu_format_cast(t, torch_npu::NPUBridge::GetNpuStorageImpl(t)->npu_desc_.origin_format_); }; return c10::fmap(tensors, cast_back_to_ori_format); } @@ -388,3 +388,4 @@ PyMethodDef* python_functions() { } // namespace distributed } // namespace torch_npu +*/ \ No newline at end of file diff --git a/torch_npu/csrc/distributed/ProcessGroupHCCL.cpp b/torch_npu/csrc/distributed/ProcessGroupHCCL.cpp index 55e031c1c6..3733734a2e 100644 --- a/torch_npu/csrc/distributed/ProcessGroupHCCL.cpp +++ b/torch_npu/csrc/distributed/ProcessGroupHCCL.cpp @@ -29,7 +29,6 @@ #include "third_party/acl/inc/acl/acl_base.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" -#include "torch_npu/csrc/distributed/HcclCompile.h" namespace c10d_npu { namespace { @@ -607,7 +606,7 @@ c10::intrusive_ptr ProcessGroupHCCL::allgather( }); } -c10::intrusive_ptr ProcessGroupHCCL::allgather_base( +c10::intrusive_ptr ProcessGroupHCCL::_allgather_base( at::Tensor& /* unused */, at::Tensor& /* unused */, const c10d::AllgatherOptions& /* unused */) { @@ -758,68 +757,4 @@ c10::intrusive_ptr ProcessGroupHCCL::recvAnysource( int /* unused */) { throw std::runtime_error("ProcessGroupHCCL does not support recv"); } - -c10::intrusive_ptr ProcessGroupHCCL::alltoall_base( - at::Tensor& outputTensor, - at::Tensor& inputTensor, - std::vector& outputSplitSizes, - std::vector& inputSplitSizes, - const c10d::AllToAllOptions& opts){ - std::vector inputTensors = {inputTensor}; - std::vector outputTensors = {outputTensor}; - int ranks = getSize(); - uint64_t index = inputTensor.numel() / ranks; - if (outputSplitSizes.empty()) { - for (int i = 0; i < ranks; i++) { - inputSplitSizes.push_back(index); - outputSplitSizes.push_back(index); - } - } - - int inputSize = inputSplitSizes.size(); - int outSize = outputSplitSizes.size(); - uint64_t inputCounts[inputSize]; - uint64_t inputSpl[inputSize]; - uint64_t outputCounts[outSize]; - uint64_t outputSpl[outSize]; - - inputSpl[0] = 0; - outputSpl[0] = 0; - for (int i = 0; i < outSize; i++) { - outputCounts[i] = outputSplitSizes[i]; - if(i > 0){ - outputSpl[i] = outputSpl[i-1] + outputCounts[i-1]; - } - } - for (int i = 0; i < inputSize; i++) { - inputCounts[i] = inputSplitSizes[i]; - if (i > 0) { - inputSpl[i] = inputSpl[i-1] + inputCounts[i-1]; - } - } - - check_npu_tensors(inputTensors); - check_npu_tensors(outputTensors); - return collective( - inputTensors, - outputTensors, - [&](at::Tensor& input, - at::Tensor& output, - HcclComm comm, - c10_npu::NPUStream& stream) { - RECORD_FUNCTION("HcclAlltoAllV", std::vector({input})); - return hcclAlltoAllV( - input.data_ptr(), - inputCounts, - inputSpl, - getHcclDataType(input.scalar_type()), - output.data_ptr(), - outputCounts, - outputSpl, - getHcclDataType(output.scalar_type()), - comm, - stream.stream()); - }); -} - } // namespace c10d_npu diff --git a/torch_npu/csrc/distributed/ProcessGroupHCCL.hpp b/torch_npu/csrc/distributed/ProcessGroupHCCL.hpp index ac3fb73377..4c4e9dc791 100644 --- a/torch_npu/csrc/distributed/ProcessGroupHCCL.hpp +++ b/torch_npu/csrc/distributed/ProcessGroupHCCL.hpp @@ -19,8 +19,9 @@ #include #include #include - -#include +#include +#include +// #include #include #include "third_party/hccl/inc/hccl/hccl.h" @@ -185,6 +186,9 @@ public: virtual ~ProcessGroupHCCL(); + const std::string getBackendName() const { + return "undefined" + } c10::intrusive_ptr broadcast( std::vector& tensors, const c10d::BroadcastOptions& opts = c10d::BroadcastOptions()) override; @@ -207,7 +211,7 @@ public: std::vector& inputTensors, const c10d::AllgatherOptions& opts = c10d::AllgatherOptions()) override; - c10::intrusive_ptr allgather_base( + c10::intrusive_ptr _allgather_base( at::Tensor& outputbuffer, at::Tensor& inputbuffer, const c10d::AllgatherOptions& opts = c10d::AllgatherOptions()) override; @@ -246,13 +250,6 @@ public: std::vector& tensors, int tag) override; - c10::intrusive_ptr alltoall_base( - at::Tensor& outputTensor, - at::Tensor& inputTensor, - std::vector& outputSplitSizes, - std::vector& inputSplitSizes, - const c10d::AllToAllOptions& opts = c10d::AllToAllOptions()) override; - static const int64_t kProcessGroupHCCLOpTimeoutMillis; protected: diff --git a/torch_npu/csrc/distributed/reducer.cpp b/torch_npu/csrc/distributed/reducer.cpp index f437f8f593..100c36d653 100644 --- a/torch_npu/csrc/distributed/reducer.cpp +++ b/torch_npu/csrc/distributed/reducer.cpp @@ -31,7 +31,7 @@ #include #include "torch_npu/csrc/distributed/reducer.hpp" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/utils/OpPreparation.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" @@ -410,9 +410,9 @@ void Reducer::copy_grad_to_bucket( if (comm_hook_ == nullptr) { // imitates wrapped_scalar_tensor in ATen/native/BinaryOps.cpp // Divides while copying into the bucket view. - at_npu::native::NPUNativeFunctions::copy_memory_(bucket_view, grad.mul(float(1.) / divFactor_), true); + at_npu::native::XLANativeFunctions::copy_memory_(bucket_view, grad.mul(float(1.) / divFactor_), true); } else { - at_npu::native::NPUNativeFunctions::copy_memory_(bucket_view, grad, true); + at_npu::native::XLANativeFunctions::copy_memory_(bucket_view, grad, true); } } @@ -445,7 +445,7 @@ void Reducer::mark_variable_ready_dense(VariableIndex index) { // make sure grad has the same format as variable if (torch_npu::NPUBridge::GetNpuStorageImpl(grad)->npu_desc_.npu_format_ != torch_npu::NPUBridge::GetNpuStorageImpl(variable)->npu_desc_.npu_format_) { - grad = at_npu::native::NPUNativeFunctions::npu_format_cast(grad, + grad = at_npu::native::XLANativeFunctions::npu_format_cast(grad, torch_npu::NPUBridge::GetNpuStorageImpl(variable)->npu_desc_.npu_format_); } this->copy_grad_to_bucket(grad, bucket_view); @@ -1079,9 +1079,9 @@ void Reducer::copy_bucket_to_grad( grad = at_npu::native::OpPreparation::ApplyTensorWithFormat( variable.sizes(), bucket_view.options(), torch_npu::NPUBridge::GetNpuStorageImpl(variable)->npu_desc_.npu_format_); - at_npu::native::NPUNativeFunctions::copy_memory_(grad, bucket_view, true); + at_npu::native::XLANativeFunctions::copy_memory_(grad, bucket_view, true); } else { - at_npu::native::NPUNativeFunctions::copy_memory_(grad, bucket_view, true); + at_npu::native::XLANativeFunctions::copy_memory_(grad, bucket_view, true); } // The grad is modified and needs to be written back. return true; diff --git a/torch_npu/csrc/framework/NPUDefine.cpp b/torch_npu/csrc/framework/NPUDefine.cpp index 5235cc6004..1753851fe2 100644 --- a/torch_npu/csrc/framework/NPUDefine.cpp +++ b/torch_npu/csrc/framework/NPUDefine.cpp @@ -25,7 +25,7 @@ namespace at_npu void ExecuteParas::Release() { // if useDynamicCompile, this attr will be freed in dynamic compile. - if (attr != nullptr) + if (!isCompiling) { aclopDestroyAttr(attr); } @@ -41,33 +41,46 @@ namespace at_npu void ExecuteParas::Copy(ExecuteParas &other) { - this->opType = other.opType; - this->paras = other.paras; - this->attr = other.attr; - this->constParams = other.constParams; - this->hostMemory = other.hostMemory; - this->isFuzzy = other.isFuzzy; + auto srcPtr = &other; + this->opType = srcPtr->opType; + this->attrInfo = srcPtr->attrInfo; + this->paras = srcPtr->paras; + this->attr = srcPtr->attr; + this->constParams = srcPtr->constParams; + this->hostMemory = srcPtr->hostMemory; } - void ExecuteParas::CopyEx(ExecuteParas& other) + NPUStatus DestroyAclParams(ACL_PARAMS ¶ms) { - this->paras = other.paras; - this->attr = other.attr; - this->constParams = other.constParams; - } - - NPUStatus DestroyAclParams(ACL_PARAMS& params) - { - if (params.input_num != 0) { - if (params.input_desc != nullptr) { - for (int i = 0; i < params.input_num; ++i) { + if (params.input_num != 0) + { + if (params.input_desc != nullptr) + { + for (int i = 0; i < params.input_num; ++i) + { aclDestroyTensorDesc(params.input_desc[i]); } + delete[] params.input_desc; + params.input_desc = nullptr; } - if (params.input_data_buf != nullptr) { - for (int i = 0; i < params.input_num; ++i) { + if (params.inputDims != nullptr) + { + delete[] params.inputDims; + params.inputDims = nullptr; + } + if (params.inputFormats != nullptr) + { + delete[] params.inputFormats; + params.inputFormats = nullptr; + } + if (params.input_data_buf != nullptr) + { + for (int i = 0; i < params.input_num; ++i) + { C10_NPU_CHECK(aclDestroyDataBuffer(params.input_data_buf[i])); } + delete[] params.input_data_buf; + params.input_data_buf = nullptr; } params.input_num = 0; } @@ -79,20 +92,31 @@ namespace at_npu { aclDestroyTensorDesc(params.output_desc[i]); } + delete[] params.output_desc; + params.output_desc = nullptr; } + if (params.outputDims != nullptr) + { + delete[] params.outputDims; + params.outputDims = nullptr; + } + if (params.outputFormats != nullptr) + { + delete[] params.outputFormats; + params.outputFormats = nullptr; + } + if (params.output_data_buf != nullptr) { - for (int i = 0; i < params.output_num; ++i) { + for (int i = 0; i < params.output_num; ++i) + { C10_NPU_CHECK(aclDestroyDataBuffer(params.output_data_buf[i])); } + delete[] params.output_data_buf; + params.output_data_buf = nullptr; } params.output_num = 0; } - free(params.input_desc); - params.input_desc = nullptr; - params.input_data_buf = nullptr; - params.output_desc = nullptr; - params.output_data_buf = nullptr; return SUCCESS; } @@ -102,13 +126,21 @@ namespace at_npu { for (int i = 0; i < params.constNum; ++i) { - if (params.constList[i] != nullptr) { + if (params.constList[i] != nullptr) + { delete[] params.constList[i]; } } + delete[] params.constList; + params.constList = nullptr; + } + + if (params.constIdx != nullptr) + { + delete[] params.constIdx; + params.constIdx = nullptr; } - params.constList = nullptr; - params.constIdx = nullptr; } + } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/framework/NPUDefine.h b/torch_npu/csrc/framework/NPUDefine.h index fbfcb6909a..d4285b330a 100644 --- a/torch_npu/csrc/framework/NPUDefine.h +++ b/torch_npu/csrc/framework/NPUDefine.h @@ -33,6 +33,11 @@ namespace at_npu input_data_buf = nullptr; output_desc = nullptr; output_data_buf = nullptr; + inputDims = nullptr; + outputDims = nullptr; + inputFormats = nullptr; + outputFormats = nullptr; + hasAttr = false; } int input_num; @@ -41,6 +46,11 @@ namespace at_npu int output_num; const aclTensorDesc **output_desc; aclDataBuffer **output_data_buf; + int64_t *inputDims; + int64_t *outputDims; + aclFormat *inputFormats; + aclFormat *outputFormats; + bool hasAttr; }; struct ACL_DYNAMIC_PARAMS @@ -88,7 +98,8 @@ namespace at_npu struct ExecuteParas { std::string opType; - bool isFuzzy = false; + std::string attrInfo; + bool isCompiling = false; ACL_PARAMS paras; CONST_PARAMS constParams; const aclopAttr *attr; @@ -106,7 +117,6 @@ namespace at_npu ExecuteParas() = default; void Release(); void Copy(ExecuteParas &other); - void CopyEx(ExecuteParas& other); }; NPUStatus DestroyAclParams(ACL_PARAMS ¶ms); diff --git a/torch_npu/csrc/framework/OpCmdHelper.cpp b/torch_npu/csrc/framework/OpCmdHelper.cpp index 01a187ffb8..6b5210b7e5 100644 --- a/torch_npu/csrc/framework/OpCmdHelper.cpp +++ b/torch_npu/csrc/framework/OpCmdHelper.cpp @@ -43,7 +43,7 @@ namespace at_npu .SetName(descName) .Get(); - int64_t numel = at::prod_intlist(storageDims); + int64_t numel = c10::multiply_integers(storageDims); AclTensorBufferMaker buffer(tensor, numel); auto aclBuff = buffer.Get(); return std::tie(aclDesc, aclBuff); @@ -84,7 +84,7 @@ namespace at_npu return std::tie(aclDesc, aclBuff); } - std::tuple OpCmdHelper::CovertScalarToAclInput( + std::tuple OpCmdHelper::CovertScalarToAclInput( const at::Tensor &aclInput, at::ScalarType type) { aclDataType aclDataType = CalcuOpUtil::convert_to_acl_data_type(type); @@ -93,7 +93,9 @@ namespace at_npu auto aclDesc = desc.Create(aclDataType, ACL_FORMAT_ND).Get(); AclTensorBufferMaker aclBuffer(aclInput); auto aclBuff = aclBuffer.Get(); - return std::tie(aclDesc, aclBuff); + int64_t storageDim = 0; + aclFormat stroageFormate = ACL_FORMAT_ND; + return std::tie(aclDesc, aclBuff, storageDim, stroageFormate); } std::tuple OpCmdHelper::CovertHostTensorToAclInput( @@ -106,7 +108,7 @@ namespace at_npu auto aclDesc = desc.Create(aclDataType, dims, format) .SetPlacement(static_cast(compileType)) .Get(); - int64_t numel = at::prod_intlist(dims); + int64_t numel = c10::multiply_integers(dims); AclTensorBufferMaker buffer(tensor, numel); auto aclBuff = buffer.Get(); return std::tie(aclDesc, aclBuff); @@ -125,7 +127,7 @@ namespace at_npu .SetFormat(npuDesc.npu_format_) .SetShape(storageDims) .Get(); - auto numel = at::prod_intlist(storageDims); + auto numel = c10::multiply_integers(storageDims); AclTensorBufferMaker aclBuffer(tensor, numel); auto aclBuff = aclBuffer.Get(); return std::tie(aclDesc, aclBuff); diff --git a/torch_npu/csrc/framework/OpCmdHelper.h b/torch_npu/csrc/framework/OpCmdHelper.h index 043cac3635..97616ecafb 100644 --- a/torch_npu/csrc/framework/OpCmdHelper.h +++ b/torch_npu/csrc/framework/OpCmdHelper.h @@ -43,7 +43,7 @@ namespace at_npu static std::tuple CovertNPUTensorWithZeroDimToAclInput(const at::Tensor &tensor, const string &descName); - static std::tuple + static std::tuple CovertScalarToAclInput(const at::Tensor &tensor, at::ScalarType type); static std::tuple diff --git a/torch_npu/csrc/framework/OpCommand.cpp b/torch_npu/csrc/framework/OpCommand.cpp index f818a73c6b..87940d410a 100644 --- a/torch_npu/csrc/framework/OpCommand.cpp +++ b/torch_npu/csrc/framework/OpCommand.cpp @@ -12,7 +12,6 @@ // 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. - #include #include "torch_npu/csrc/framework/OpCommand.h" #include "torch_npu/csrc/core/npu/register/OptionsManager.h" @@ -61,7 +60,7 @@ OpCommand& OpCommand::Input( auto contiguous_input = Contiguous(input); if (commonType.has_value() && commonType.value() != contiguous_input.scalar_type()) { - contiguous_input = NPUNativeFunctions::npu_dtype_cast(contiguous_input, commonType.value()); + contiguous_input = XLANativeFunctions::npu_dtype_cast(contiguous_input, commonType.value()); } graphCmd.AddInput(contiguous_input, descName, realData, sensitive_format); ) @@ -122,39 +121,29 @@ OpCommand& OpCommand::Output( IF_GRAPH_MODE_THEN_RUN_WITH_RET_THIS( if (sensitive_format.has_value() && FormatHelper::GetBaseFormat(output) != sensitive_format.value()) { - output = NPUNativeFunctions::npu_format_cast(output, sensitive_format.value()); + output = XLANativeFunctions::npu_format_cast(output, sensitive_format.value()); } graphCmd.AddOutput(output, descName, realType, sensitive_format); if (!resultTypeDefined && commonType.has_value() && output.scalar_type() != commonType.value()) { - output = NPUNativeFunctions::npu_dtype_cast(output, commonType.value()); - } + output = XLANativeFunctions::npu_dtype_cast(output, commonType.value()); + } ) - outputTensor.emplace_back(output); return AddOutput(output, realType); } void OpCommand::Run() { IF_GRAPH_MODE_THEN_RUN(return;) - if (c10_npu::option::OptionsManager::CheckQueueEnable() && !sync) { - ExecuteParas execParams; - aclCmd->ExportParams(execParams); - c10_npu::queue::QueueParas params(c10_npu::queue::COMPILE_AND_EXECUTE, sizeof(ExecuteParas), &execParams); + if (c10_npu::option::OptionsManager::CheckQueueEnable()) { + ExecuteParas params; + aclCmd->ExportParams(params); c10_npu::enCurrentNPUStream(¶ms); aclCmd->releaseSource(false); } else { - aclCmd->Run(sync, sync_index, outputTensor); + aclCmd->Run(); aclCmd->releaseSource(); - } - aclCmds->Pop(); -} - -OpCommand& OpCommand::Sync(c10::SmallVector &index) { - sync_index = index; - if (!index.empty()) { - sync = true; } - return *this; + aclCmds->Pop(); } OpCommand& OpCommand::AddTensorInput(at::Tensor &tensor, @@ -163,7 +152,7 @@ OpCommand& OpCommand::AddTensorInput(at::Tensor &tensor, const string &realData) { std::tuple < aclTensorDesc * , aclDataBuffer *> res; if (commonType.has_value() && commonType.value() != tensor.scalar_type()) { - tensor = NPUNativeFunctions::npu_dtype_cast(tensor, commonType.value()); + tensor = XLANativeFunctions::npu_dtype_cast(tensor, commonType.value()); } // 针对dim=0的场景,绝对不会有输入为uint16的情况,因为这个是TBE引入的,TBE没有dim=0的情况 if (tensor.dim() == 0) { @@ -196,7 +185,7 @@ OpCommand& OpCommand::AddNoneTensor() { OpCommand& OpCommand::AddOutput(at::Tensor &output, const string &realType) { if (resultTypeDefined == false && commonType.has_value() && commonType.value() != output.scalar_type()) { - output = NPUNativeFunctions::npu_dtype_cast(output, commonType.value()); + output = XLANativeFunctions::npu_dtype_cast(output, commonType.value()); } auto res = OpCmdHelper::CovertToAclOutput(output, realType); aclCmd->AddOutput(std::get<0>(res), std::get<1>(res)); diff --git a/torch_npu/csrc/framework/OpCommand.h b/torch_npu/csrc/framework/OpCommand.h index a7e6eaa76b..4afb3a4b84 100644 --- a/torch_npu/csrc/framework/OpCommand.h +++ b/torch_npu/csrc/framework/OpCommand.h @@ -18,7 +18,7 @@ #include "torch_npu/csrc/framework/OpParamMaker.h" #include "torch_npu/csrc/framework/FormatHelper.h" #include "torch_npu/csrc/core/npu/NPURunMode.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/framework/graph/construct/GraphConstructor.h" #include "torch_npu/csrc/aten/mirror/NPUTensorIterator.h" @@ -117,8 +117,6 @@ public: // Run a single op void Run(); - OpCommand& Sync(c10::SmallVector &sync_index); - private: OpCommand& AddTensorInput(at::Tensor &tensor, at::ScalarType forceScaleType = at::ScalarType::Undefined, @@ -152,10 +150,6 @@ private: c10::optional commonType = c10::nullopt; c10::optional commonShape = c10::nullopt; bool resultTypeDefined = false; - bool sync = false; - c10::SmallVector sync_index; - c10::SmallVector outputTensor; - }; // class OpCommand } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/framework/OpParamMaker.cpp b/torch_npu/csrc/framework/OpParamMaker.cpp index 969b889693..d552d78527 100644 --- a/torch_npu/csrc/framework/OpParamMaker.cpp +++ b/torch_npu/csrc/framework/OpParamMaker.cpp @@ -22,70 +22,53 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/OpParamMaker.h" -#include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" -#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" -#include "torch_npu/csrc/core/npu/NPUEventManager.h" -#include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" namespace at_npu { namespace native { - using namespace c10_npu::queue; - constexpr size_t MAX_VAL_SIZE = (sizeof(ExecuteParas) > sizeof(CopyParas)) ? - ((sizeof(ExecuteParas) > sizeof(EventParas)) ? sizeof(ExecuteParas) : sizeof(EventParas)) : - ((sizeof(CopyParas) > sizeof(EventParas)) ? sizeof(CopyParas) : sizeof(EventParas)); - void OpAttrMaker::Set(aclopAttr *attr, const string &name, bool value) + void OpAttrMaker::Set(aclopAttr *attr, string name, bool value) { aclopSetAttrBool(attr, name.c_str(), value); } - void OpAttrMaker::Set(aclopAttr *attr, const string &name, int64_t value) + void OpAttrMaker::Set(aclopAttr *attr, string name, int64_t value) { aclopSetAttrInt(attr, name.c_str(), value); } - void OpAttrMaker::Set(aclopAttr *attr, const string &name, float value) + void OpAttrMaker::Set(aclopAttr *attr, string name, float value) { aclopSetAttrFloat(attr, name.c_str(), value); } - void OpAttrMaker::Set(aclopAttr *attr, const string &name, string value) + void OpAttrMaker::Set(aclopAttr *attr, string name, string value) { aclopSetAttrString(attr, name.c_str(), value.c_str()); } - void OpAttrMaker::Set(aclopAttr *attr, const string &name, c10::IntArrayRef value) + void OpAttrMaker::Set(aclopAttr *attr, string name, c10::IntArrayRef value) { - aclopSetAttrListInt(attr, name.c_str(), value.size(), value.data()); + auto vec = value.vec(); + aclopSetAttrListInt(attr, name.c_str(), vec.size(), vec.data()); } - void OpAttrMaker::Set(aclopAttr *attr, const string &name, at::ArrayRef value) + void OpAttrMaker::Set(aclopAttr *attr, string name, at::ArrayRef value) { - aclopSetAttrListFloat(attr, name.c_str(), value.size(), value.data()); + auto vec = value.vec(); + aclopSetAttrListFloat(attr, name.c_str(), vec.size(), vec.data()); } - void OpAttrMaker::Set(aclopAttr* attr, const string& name, at::ArrayRef value) - { - aclopSetAttrListBool(attr, name.c_str(), value.size(), value.data()); - } - - void OpAttrMaker::Set(aclopAttr *attr, const string &name, c10::Scalar value) + void OpAttrMaker::Set(aclopAttr *attr, string name, c10::Scalar value) { float val = CalcuOpUtil::get_scalar_float_value(value); aclopSetAttrFloat(attr, name.c_str(), val); } - void OpAttrMaker::Set(aclopAttr* attr, const string& name, at::ScalarType value) - { - aclDataType val = CalcuOpUtil::convert_to_acl_data_type(value); - aclopSetAttrDataType(attr, name.c_str(), val); - } - void OpAttrMaker::Set( aclopAttr *attr, - const string &name, + string name, at::ArrayRef value) { // Pointer to values of each listInt. @@ -113,28 +96,79 @@ namespace at_npu attrValue.data()); } - void OpCommandImpl::Run( - bool sync, - c10::SmallVector &sync_index, - c10::SmallVector &outputTensor) { - NPU_LOGD("Op %s Run.", opName.c_str()); - RECORD_FUNCTION(opName, std::vector({})); - if (PyGILState_Check()) { - // we need to release GIL for NPU to compile op. - Py_BEGIN_ALLOW_THREADS - ACL_REQUIRE_OK_OP(InnerRun(opName, execParam, sync, sync_index, outputTensor), opName.c_str()); - Py_END_ALLOW_THREADS - } else { - ACL_REQUIRE_OK_OP(InnerRun(opName, execParam, sync, sync_index, outputTensor), opName.c_str()); - } + void AttrInfoMaker::Add(bool value, string &attrInfo) + { + attrInfo += std::to_string(value) + "-"; } - aclError OpCommandImpl::InnerRun( - string name, - AclExecParam ¶ms, - bool sync, - c10::SmallVector &sync_index, - c10::SmallVector &outputTensor) { + void AttrInfoMaker::Add(int64_t value, string &attrInfo) + { + attrInfo += std::to_string(value) + "-"; + } + + void AttrInfoMaker::Add(float value, string &attrInfo) + { + attrInfo += std::to_string(value) + "-"; + } + + void AttrInfoMaker::Add(string value, string &attrInfo) + { + attrInfo += value + "-"; + } + + void AttrInfoMaker::Add(c10::IntArrayRef value, string &attrInfo) + { + auto vec = value.vec(); + for (unsigned i = 0; i < vec.size(); i++) + attrInfo += std::to_string(vec.at(i)) + ","; + attrInfo += "-"; + } + + void AttrInfoMaker::Add( + at::ArrayRef value, + string &attrInfo) + { + auto vec = value.vec(); + for (unsigned i = 0; i < vec.size(); i++) + attrInfo += std::to_string(vec.at(i)) + ","; + attrInfo += "-"; + } + + void AttrInfoMaker::Add(c10::Scalar value, string &attrInfo) + { + float val = CalcuOpUtil::get_scalar_float_value(value); + attrInfo += std::to_string(val) + "-"; + } + + void AttrInfoMaker::Add( + at::ArrayRef value, + string &attrInfo) + { + // Pointer to values of each listInt. + c10::SmallVector attrValue; + // Pointer to number of each listInt. + c10::SmallVector eachListIntNum; + // Value of each listInt. + c10::SmallVector, N> eachListIntVal; + for (int i = 0; i < value.size(); i++) + { + int64_t valueSize = value[i].size(); + attrInfo += std::to_string(valueSize) + ","; + } + attrInfo += "-"; + } + + void OpCommandImpl::Run() + { + InitAttr(); + NPU_LOGD("Op %s Run.", opName.c_str()); + RECORD_FUNCTION(opName, std::vector({})); + + ACL_REQUIRE_OK_OP(InnerRun(opName, execParam), opName.c_str()); + } + + aclError OpCommandImpl::InnerRun(string name, AclExecParam ¶ms) + { auto stream = c10_npu::getCurrentNPUStream(); auto inputSize = params.inBuffer.size(); auto outputSize = params.outBuffer.size(); @@ -148,8 +182,7 @@ namespace at_npu int index = 0; do { - if (at_npu::native::aoe::aoe_manager().IsAoeEnabled() && - at_npu::native::aoe::aoe_manager().IsInWhiltelist(name)) { + if (at_npu::native::aoe::aoe_manager().IsAoeEnabled()) { ret = at_npu::native::AclGenGraphAndDumpForOp( name.c_str(), inputSize, @@ -167,45 +200,19 @@ namespace at_npu TORCH_CHECK(false, "In aoe mode, AclGenGraphAndDumpForOp failed!"); } } - if (!sync) { - ret = aclopCompileAndExecute( - name.c_str(), - inputSize, - params.inDesc.data(), - params.inBuffer.data(), - outputSize, - params.outDesc.data(), - params.outBuffer.data(), - params.attr, - ACL_ENGINE_SYS, - ACL_COMPILE_SYS, - NULL, - stream); - } else { - int64_t dimSize; - ret = AclopCompileAndExecuteV2( - name.c_str(), - inputSize, - const_cast(params.inDesc.data()), - const_cast(params.inBuffer.data()), - outputSize, - const_cast(params.outDesc.data()), - params.outBuffer.data(), - params.attr, - ACL_ENGINE_SYS, - ACL_COMPILE_SYS, - NULL, - stream); - - for (size_t i = 0; i < sync_index.size(); i++) { - c10::SmallVector real_shape; - for (int64_t j = 0; j < outputTensor[sync_index[i]].dim(); j++) { - C10_NPU_CHECK(aclGetTensorDescDimV2(params.outDesc[sync_index[i]], j, &dimSize)); - real_shape.emplace_back(dimSize); - } - outputTensor[sync_index[i]].resize_(real_shape); - } - } + ret = aclopCompileAndExecute( + name.c_str(), + inputSize, + params.inDesc.data(), + params.inBuffer.data(), + outputSize, + params.outDesc.data(), + params.outBuffer.data(), + params.attr, + ACL_ENGINE_SYS, + ACL_COMPILE_SYS, + NULL, + stream); ++index; } while (NpuUtils::IsOomError(ret, index) && (index < NPU_MAX_OP_EXEC_TRY_NUM)); if (reset_flag) @@ -215,21 +222,40 @@ namespace at_npu return ret; } - int ExecFunc(c10_npu::queue::QueueParas* in, aclrtStream stream) + int ExecFunc(void *in, aclrtStream stream) { - auto cur_paras = static_cast(in->paramVal); + auto cur_paras = (ExecuteParas *)in; NPU_LOGD("Op %s Run.", cur_paras->opType.c_str()); aclError ret; bool reset_flag = false; - if (!cur_paras->isFuzzy) + if (FuzzyCompileBlacklist::GetInstance().IsInBlacklist(cur_paras->opType) && env::CheckFuzzyEnable()) { AclopSetCompileFlag(aclOpCompileFlag::ACL_OP_COMPILE_DEFAULT); reset_flag = true; } - if (at_npu::native::aoe::aoe_manager().IsAoeEnabled() && - at_npu::native::aoe::aoe_manager().IsInWhiltelist(cur_paras->opType)) { - ret = at_npu::native::AclGenGraphAndDumpForOp( + int index = 0; + do + { + if (at_npu::native::aoe::aoe_manager().IsAoeEnabled()) { + ret = at_npu::native::AclGenGraphAndDumpForOp( + (cur_paras->opType).c_str(), + cur_paras->paras.input_num, + cur_paras->paras.input_desc, + cur_paras->paras.input_data_buf, + cur_paras->paras.output_num, + cur_paras->paras.output_desc, + cur_paras->paras.output_data_buf, + cur_paras->attr, + ACL_ENGINE_SYS, + at_npu::native::aoe::aoe_manager().GetDumpGraphPath().c_str(), + nullptr); + if (ret != ACL_ERROR_NONE) { + C10_NPU_SHOW_ERR_MSG(); + TORCH_CHECK(false, "In aoe mode, AclGenGraphAndDumpForOp failed!"); + } + } + ret = aclopCompileAndExecute( (cur_paras->opType).c_str(), cur_paras->paras.input_num, cur_paras->paras.input_desc, @@ -239,26 +265,12 @@ namespace at_npu cur_paras->paras.output_data_buf, cur_paras->attr, ACL_ENGINE_SYS, - at_npu::native::aoe::aoe_manager().GetDumpGraphPath().c_str(), - nullptr); - if (ret != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - TORCH_CHECK(false, "In aoe mode, AclGenGraphAndDumpForOp failed!"); - } - } - ret = aclopCompileAndExecute( - (cur_paras->opType).c_str(), - cur_paras->paras.input_num, - cur_paras->paras.input_desc, - cur_paras->paras.input_data_buf, - cur_paras->paras.output_num, - cur_paras->paras.output_desc, - cur_paras->paras.output_data_buf, - cur_paras->attr, - ACL_ENGINE_SYS, - ACL_COMPILE_SYS, - nullptr, - stream); + ACL_COMPILE_SYS, + nullptr, + stream); + ++index; + } while (NpuUtils::IsOomError(ret, index) && (index < NPU_MAX_OP_EXEC_TRY_NUM)); + if (reset_flag) { AclopSetCompileFlag(aclOpCompileFlag::ACL_OP_COMPILE_FUZZ); @@ -276,138 +288,31 @@ namespace at_npu return ret; } - int MemcopyAsyncFunc(c10_npu::queue::QueueParas* in, aclrtStream stream) + void CopyFunc(void *dst, void *src) { - auto cur_paras = static_cast(in->paramVal); - aclError ret = aclrtMemcpyAsync(cur_paras->dst, cur_paras->dstLen, cur_paras->src, - cur_paras->srcLen, cur_paras->kind, stream); - if (ret != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - } - return ret; + auto dstPtr = (ExecuteParas *)dst; + auto srcPtr = (ExecuteParas *)src; + dstPtr->Copy(*srcPtr); } - int RecordEventFunc(c10_npu::queue::QueueParas* in, aclrtStream stream) + void ReleaseFunc(void *ptr) { - auto cur_paras = static_cast(in->paramVal); - aclError ret = aclrtRecordEvent(cur_paras->event, stream); - if (ret != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - } - - // Temporary modification to avoid problem that - // event must be recorded before query - if (cur_paras->eventAllocatorType == c10_npu::queue::HOST_ALLOCATOR_EVENT) { - THNPUCachingHostAllocator_insertCompleteEvent(cur_paras->event); - } else if (cur_paras->eventAllocatorType == c10_npu::queue::NPU_ALLOCATOR_EVENT) { - c10_npu::NPUCachingAllocator::NpuAllocatorInsertRecordedEvent(cur_paras->event); - } - - return ret; + auto cur_paras = (ExecuteParas *)ptr; + cur_paras->Release(); } - int WaitEventFunc(c10_npu::queue::QueueParas* in, aclrtStream stream) { - auto cur_paras = static_cast(in->paramVal); - aclError ret = aclrtStreamWaitEvent(stream, cur_paras->event); - if (ret != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - } - return ret; - } - - int LazyDestroyEventFunc(c10_npu::queue::QueueParas* in, aclrtStream stream) { - auto cur_paras = static_cast(in->paramVal); - aclError ret = c10_npu::NPUEventManager::GetInstance().LazyDestroy(cur_paras->event); - if (ret != ACL_ERROR_NONE) { - C10_NPU_SHOW_ERR_MSG(); - } - return ret; - } - - void CopyFunc(void* dst, void* src, uint32_t queueLen) + void *NewFunc(int caption, int &size) { - auto dstPtr = static_cast(dst); - auto srcPtr = static_cast(src); - dstPtr->paramVal = static_cast(dst) + sizeof(c10_npu::queue::QueueParas); - if (dstPtr->paramType == c10_npu::queue::COMPILE_AND_EXECUTE) { - // string or smallvector of struct is used, deconstructor need be called before memset - (static_cast(dstPtr->paramVal))->~ExecuteParas(); - } - dstPtr->paramStream = srcPtr->paramStream; - dstPtr->paramType = srcPtr->paramType; - dstPtr->paramLen = srcPtr->paramLen; - memset(dstPtr->paramVal, 0, MAX_VAL_SIZE); - if (srcPtr->paramType == c10_npu::queue::COMPILE_AND_EXECUTE) { - (static_cast(dstPtr->paramVal))->Copy(*(static_cast(srcPtr->paramVal))); - } else if ((srcPtr->paramType == c10_npu::queue::ASYNC_MEMCPY)) { - (static_cast(dstPtr->paramVal))-> - Copy(*(static_cast(srcPtr->paramVal))); - } else { - (static_cast(dstPtr->paramVal))-> - Copy(*(static_cast(srcPtr->paramVal))); - } + size = sizeof(ExecuteParas); + return (void *)new ExecuteParas[caption]; } - void ReleaseFunc(void* ptr, c10_npu::ReleaseQueue& releaseQueue) + void DeleteFunc(void *ptr) { - releaseQueue.PushToReleaseQueue(ptr); + delete[](ExecuteParas *) ptr; } - void* NewFunc(int caption, int& size) - { - size = sizeof(c10_npu::queue::QueueParas) + MAX_VAL_SIZE; - void *ptr = malloc(size * caption); - TORCH_CHECK(ptr != nullptr, "OpCommand new buffer must be not NULL"); - memset(ptr, 0, size * caption); - return ptr; - } - - void DeleteFunc(void* ptr) - { - free(ptr); - } - - using Func = int(*)(c10_npu::queue::QueueParas*, aclrtStream); - using AsyncFuncMap = std::map; - AsyncFuncMap funcMap = { - {c10_npu::queue::COMPILE_AND_EXECUTE, ExecFunc}, - {c10_npu::queue::ASYNC_MEMCPY, MemcopyAsyncFunc}, - {c10_npu::queue::RECORD_EVENT, RecordEventFunc}, - {c10_npu::queue::WAIT_EVENT, WaitEventFunc}, - {c10_npu::queue::LAZY_DESTROY_EVENT, LazyDestroyEventFunc}, - }; - - int AsncExecFunc(void* data, uint32_t queueLen) { - auto queueParam = static_cast(data); - auto type = queueParam->paramType; - aclrtStream stream = queueParam->paramStream; - auto ret = funcMap[type](queueParam, stream); - return ret; - } - - void CopyReleaseParamFunc(void* dst, void* src) - { - auto dstPtr = static_cast(dst); - auto srcPtr = static_cast(src); - dstPtr->paramType = srcPtr->paramType; - dstPtr->paramVal = static_cast(dst) + sizeof(c10_npu::queue::QueueParas); - if (srcPtr->paramType == c10_npu::queue::COMPILE_AND_EXECUTE) { - (static_cast(dstPtr->paramVal))->CopyEx(*(static_cast(srcPtr->paramVal))); - (static_cast(srcPtr->paramVal))->hostMemory.clear(); - } - } - - void ReleaseParamFunc(void* ptr) { - auto queueParam = static_cast(ptr); - auto type = queueParam->paramType; - if (type == c10_npu::queue::COMPILE_AND_EXECUTE) { - auto cur_paras = static_cast(queueParam->paramVal); - cur_paras->Release(); - } - } - - REGISTER_QUEUE_FUNC(AsncExecFunc, CopyFunc, ReleaseFunc, NewFunc, DeleteFunc, - CopyReleaseParamFunc, ReleaseParamFunc) + REGISTER_QUEUE_FUNC(ExecFunc, CopyFunc, ReleaseFunc, NewFunc, DeleteFunc) OpCommandImpls *OpCommandImpls::GetInstance() { @@ -417,11 +322,11 @@ namespace at_npu void OpCommandImpls::Push(OpCommandImpl *&ptr) { - ++offset; + offset += 1; if (objs.size() <= offset) { OpCommandImpl impl; - objs.emplace_back(std::move(impl)); + objs.push_back(impl); } TORCH_CHECK( objs.size() > offset, diff --git a/torch_npu/csrc/framework/OpParamMaker.h b/torch_npu/csrc/framework/OpParamMaker.h index 9fb3983828..e10ba6bbb2 100644 --- a/torch_npu/csrc/framework/OpParamMaker.h +++ b/torch_npu/csrc/framework/OpParamMaker.h @@ -36,21 +36,33 @@ namespace at_npu class OpAttrMaker { public: - static void Set(aclopAttr *attr, const string &name, bool value); - static void Set(aclopAttr *attr, const string &name, int64_t value); - static void Set(aclopAttr *attr, const string &name, float value); - static void Set(aclopAttr *attr, const string &name, string value); - static void Set(aclopAttr *attr, const string &name, c10::IntArrayRef value); - static void Set(aclopAttr *attr, const string &name, at::ArrayRef value); - static void Set(aclopAttr* attr, const string& name, at::ArrayRef value); - static void Set(aclopAttr *attr, const string &name, c10::Scalar value); - static void Set(aclopAttr* attr, const string& name, at::ScalarType value); + static void Set(aclopAttr *attr, string name, bool value); + static void Set(aclopAttr *attr, string name, int64_t value); + static void Set(aclopAttr *attr, string name, float value); + static void Set(aclopAttr *attr, string name, string value); + static void Set(aclopAttr *attr, string name, c10::IntArrayRef value); + static void Set(aclopAttr *attr, string name, at::ArrayRef value); + static void Set(aclopAttr *attr, string name, c10::Scalar value); static void Set( aclopAttr *attr, - const string &name, + string name, at::ArrayRef value); }; // class OpAttrMaker + class AttrInfoMaker + { + public: + static void Add(bool value, string &attrInfo); + static void Add(int64_t value, string &attrInfo); + static void Add(float value, string &attrInfo); + static void Add(string value, string &attrInfo); + static void Add(c10::IntArrayRef value, string &attrInfo); + static void Add(at::ArrayRef value, string &attrInfo); + static void Add(c10::Scalar value, string &attrInfo); + static void Add(at::ArrayRef value, string &attrInfo); + }; + + // class AclTensorDescMaker { public: @@ -59,13 +71,13 @@ namespace at_npu AclTensorDescMaker &Create(aclDataType dataType, torch_npu::NPUStorageDesc storageDesc) { - auto& dims = storageDesc.base_sizes_; + auto dims = storageDesc.base_sizes_; auto format = storageDesc.origin_format_; desc = aclCreateTensorDesc(dataType, dims.size(), dims.data(), format); return *this; } - inline AclTensorDescMaker &Create( + AclTensorDescMaker &Create( aclDataType dataType, c10::IntArrayRef dims, aclFormat format) @@ -74,26 +86,26 @@ namespace at_npu return *this; } - inline AclTensorDescMaker &Create(aclDataType dataType, aclFormat format) + AclTensorDescMaker &Create(aclDataType dataType, aclFormat format) { desc = aclCreateTensorDesc(dataType, 0, nullptr, format); return *this; } - inline AclTensorDescMaker &SetFormat(aclFormat format) + AclTensorDescMaker SetFormat(aclFormat format) { aclSetTensorFormat(desc, format); return *this; } - inline AclTensorDescMaker &SetPlacement(aclMemType memType) + AclTensorDescMaker SetPlacement(aclMemType memType) { aclSetTensorPlaceMent(desc, memType); return *this; } template - inline AclTensorDescMaker &SetShape(const c10::SmallVector &dims) + AclTensorDescMaker &SetShape(const c10::SmallVector &dims) { aclSetTensorShape(desc, dims.size(), dims.data()); return *this; @@ -115,15 +127,16 @@ namespace at_npu return *this; } - inline AclTensorDescMaker &SetName(const std::string &name) + AclTensorDescMaker &SetName(const string &name) { - if (!name.empty()) { + if (name != "") + { aclSetTensorDescName(desc, name.c_str()); } return *this; } - inline AclTensorDescMaker &SetConstAttr(c10::optional cpu_tensor) + AclTensorDescMaker &SetConstAttr(c10::optional cpu_tensor) { if (cpu_tensor.has_value() && cpu_tensor.value().defined()) { @@ -136,7 +149,7 @@ namespace at_npu return *this; } - inline aclTensorDesc *Get() const + aclTensorDesc *Get() const { return desc; } @@ -183,7 +196,7 @@ namespace at_npu ~AclTensorBufferMaker() = default; - inline aclDataBuffer *Get() const + aclDataBuffer *Get() const { return ptr; } @@ -247,33 +260,30 @@ namespace at_npu // export op execute params void ExportParams(ExecuteParas ¶ms) { + InitAttr(); params.opType = opName; + params.attrInfo = attrInfo; params.attr = execParam.attr; // make params int inputNum = execParam.inDesc.size(); int outputNum = execParam.outDesc.size(); + int constNum = execParam.constLists.size(); + const int64_t **constListArr = new const int64_t *[constNum]; + const aclTensorDesc **aclTensorInputDescArr = + new const aclTensorDesc *[inputNum]; + const aclTensorDesc **aclTensorOutputDescArr = + new const aclTensorDesc *[outputNum]; + const aclDataBuffer **aclDataInputBuffArr = + new const aclDataBuffer *[inputNum]; + aclDataBuffer **aclDataOutputBuffArr = new aclDataBuffer *[outputNum]; - size_t inputTensorDescArrLen = inputNum * sizeof(uintptr_t); - size_t inputDataBuffArrLen = inputNum * sizeof(uintptr_t); + int64_t *constIdxArr = new int64_t[constNum]; + int64_t *inputDimsArr = new int64_t[inputNum]; + int64_t *outputDimsArr = new int64_t[outputNum]; + aclFormat *inputFormatsArr = new aclFormat[inputNum]; + aclFormat *outputFormatsArr = new aclFormat[outputNum]; - size_t outputTensorDescArrLen = outputNum * sizeof(uintptr_t); - size_t outputDataBuffArrLen = outputNum * sizeof(uintptr_t); - - size_t totalMemLen = inputTensorDescArrLen + inputDataBuffArrLen + - outputTensorDescArrLen + outputDataBuffArrLen; - - char* basePtr = static_cast(malloc(totalMemLen)); - AT_ASSERT(basePtr != nullptr); - const aclTensorDesc** aclTensorInputDescArr = reinterpret_cast(basePtr); - basePtr += inputTensorDescArrLen; - const aclDataBuffer** aclDataInputBuffArr = reinterpret_cast(basePtr); - basePtr += inputDataBuffArrLen; - - const aclTensorDesc** aclTensorOutputDescArr = reinterpret_cast(basePtr); - basePtr += outputTensorDescArrLen; - aclDataBuffer** aclDataOutputBuffArr = reinterpret_cast(basePtr); - std::copy( execParam.inDesc.begin(), execParam.inDesc.end(), @@ -291,20 +301,52 @@ namespace at_npu execParam.outBuffer.end(), aclDataOutputBuffArr); + std::copy( + execParam.inDims.begin(), + execParam.inDims.end(), + inputDimsArr); + std::copy( + execParam.outDims.begin(), + execParam.outDims.end(), + outputDimsArr); + std::copy( + execParam.inFormats.begin(), + execParam.inFormats.end(), + inputFormatsArr); + std::copy( + execParam.outFormats.begin(), + execParam.outFormats.end(), + outputFormatsArr); + + std::copy( + execParam.constLists.begin(), + execParam.constLists.end(), + constListArr); + std::copy( + execParam.constIdxs.begin(), + execParam.constIdxs.end(), + constIdxArr); + params.paras.input_num = inputNum; params.paras.output_num = outputNum; params.paras.input_desc = aclTensorInputDescArr; params.paras.input_data_buf = aclDataInputBuffArr; params.paras.output_desc = aclTensorOutputDescArr; params.paras.output_data_buf = aclDataOutputBuffArr; + + params.paras.inputDims = inputDimsArr; + params.paras.outputDims = outputDimsArr; + params.paras.inputFormats = inputFormatsArr; + params.paras.outputFormats = outputFormatsArr; + params.paras.hasAttr = execParam.hasAttr; + + params.constParams.constNum = constNum; + params.constParams.constList = constListArr; + params.constParams.constIdx = constIdxArr; params.hostMemory = execParam.hostMem; + } - if (!FuzzyCompileBlacklist::GetInstance().IsInBlacklist(opName) && env::CheckFuzzyEnable()) { - params.isFuzzy = true; - } - } - - void Run(bool sync, c10::SmallVector &sync_index, c10::SmallVector &outputTensor); + void Run(); void releaseSource(bool no_blocking = true) { @@ -326,6 +368,11 @@ namespace at_npu execParam.outBuffer.begin(), execParam.outBuffer.end(), aclDestroyDataBuffer); + std::for_each( + execParam.constLists.begin(), + execParam.constLists.end(), + [](const int64_t *constList) + { delete[] constList; }); if (execParam.attr != nullptr) { aclopDestroyAttr(execParam.attr); @@ -335,15 +382,24 @@ namespace at_npu execParam.inDesc.clear(); execParam.inBuffer.clear(); + execParam.inDims.clear(); + execParam.inFormats.clear(); execParam.outDesc.clear(); execParam.outBuffer.clear(); + execParam.outDims.clear(); + execParam.outFormats.clear(); + execParam.constIdxs.clear(); + execParam.constLists.clear(); execParam.hostMem.clear(); // recover + execParam.hasAttr = false; execParam.attr = nullptr; opName = ""; + attrInfo = "attrs:"; + inputCounter = 0; } private: @@ -353,8 +409,16 @@ namespace at_npu c10::SmallVector inBuffer; // owned c10::SmallVector outDesc; // owned c10::SmallVector outBuffer; // owned - c10::SmallVector hostMem; + c10::SmallVector inDims; + c10::SmallVector outDims; + c10::SmallVector inFormats; + c10::SmallVector outFormats; + c10::SmallVector constLists; + c10::SmallVector constIdxs; + c10::SmallVector hostMem; + aclopAttr *attr = nullptr; + bool hasAttr = false; }; void InitAttr() @@ -365,16 +429,12 @@ namespace at_npu } } - aclError InnerRun( - string name, - AclExecParam ¶ms, - bool sync, - c10::SmallVector &sync_index, - c10::SmallVector &outputTensor - ); + aclError InnerRun(string name, AclExecParam ¶ms); private: + int64_t inputCounter = 0; string opName; + string attrInfo = "attrs:"; AclExecParam execParam; }; // class OpCommandImpl diff --git a/torch_npu/csrc/framework/StorageDescHelper.cpp b/torch_npu/csrc/framework/StorageDescHelper.cpp index 2332210e0d..073d6e2f62 100644 --- a/torch_npu/csrc/framework/StorageDescHelper.cpp +++ b/torch_npu/csrc/framework/StorageDescHelper.cpp @@ -165,7 +165,7 @@ namespace at_npu int64_t StorageDescHelper::GetMemorySize(const torch_npu::NPUStorageDesc &desc) { const auto &physical_size = FormatHelper::GetStorageSizes(desc); - return at::prod_intlist(physical_size); + return c10::multiply_integers(physical_size); } int64_t StorageDescHelper::GetMemorySize(const at::Tensor &dst) @@ -177,7 +177,7 @@ namespace at_npu int64_t StorageDescHelper::GetMemorySize(const c10::IntArrayRef& size, aclFormat format) { const auto &physical_size = FormatHelper::GetStorageSizes(format, size); - return at::prod_intlist(physical_size); + return c10::multiply_integers(physical_size); } int64_t StorageDescHelper::GetValidMemorySize(const at::Tensor &tensor) diff --git a/torch_npu/csrc/framework/contiguous/ContiguousUtils.cpp b/torch_npu/csrc/framework/contiguous/ContiguousUtils.cpp index 6803b1a711..4bf7b475f1 100644 --- a/torch_npu/csrc/framework/contiguous/ContiguousUtils.cpp +++ b/torch_npu/csrc/framework/contiguous/ContiguousUtils.cpp @@ -19,7 +19,7 @@ namespace at_npu { namespace native { void ContiguousTensorDesc::refresh_contiguous_using_size_and_stride() { - if (at::prod_intlist(sizes_) == 0) { + if (c10::multiply_integers(sizes_) == 0) { is_contiguous_ = true; } int64_t infer_axis_size = 1; @@ -61,7 +61,7 @@ void ContiguousTensorDesc::find_match_optimization_cases() { } // Considering combined-cases, we cannot split slice cases any further. - if (at::prod_intlist(sizes_) < at::prod_intlist(base_sizes_)) { + if (c10::multiply_integers(sizes_) < c10::multiply_integers(base_sizes_)) { opt_cases_.emplace_back("slice"); opt_cases_.emplace_back("select"); opt_cases_.emplace_back("indexing"); diff --git a/torch_npu/csrc/framework/contiguous/ReshapeOpt.cpp b/torch_npu/csrc/framework/contiguous/ReshapeOpt.cpp index bb8ba4a025..d8bf19570b 100644 --- a/torch_npu/csrc/framework/contiguous/ReshapeOpt.cpp +++ b/torch_npu/csrc/framework/contiguous/ReshapeOpt.cpp @@ -53,8 +53,8 @@ bool can_use_memcpy_for_other_format(const ContiguousTensorDesc &tensor_desc) { return false; } // Make sure no pandding happens - if (at::prod_intlist(tensor_desc.sizes_) != - at::prod_intlist(tensor_desc.storage_sizes_)) { + if (c10::multiply_integers(tensor_desc.sizes_) != + c10::multiply_integers(tensor_desc.storage_sizes_)) { return false; } return true; diff --git a/torch_npu/csrc/framework/contiguous/broadcast_opt.cpp b/torch_npu/csrc/framework/contiguous/broadcast_opt.cpp index 148dbfe639..6ce3a2fe02 100644 --- a/torch_npu/csrc/framework/contiguous/broadcast_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/broadcast_opt.cpp @@ -16,7 +16,6 @@ #include "torch_npu/csrc/core/npu/NPUStream.h" #include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" #include "torch_npu/csrc/framework/contiguous/ContiguousOpt.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" namespace at_npu { namespace native { @@ -31,16 +30,6 @@ public: if (can_use_broadcast(src_desc)) { RECORD_FUNCTION("npuBroadcast", std::vector({src})); - IF_GRAPH_MODE_THEN_RUN( - at::IntArrayRef target_shape = self.sizes(); - OpCommand cmd; - cmd.Name("BroadcastTo") - .InputWithoutContiguous(src) - .Input(target_shape, at::kLong) - .Output(self) - .Run(); - return true; - ) bool can_contiguous = broadcast_to_contiguous(self, src, src_desc); return can_contiguous; } @@ -106,14 +95,21 @@ private: temp_src.unsafeGetTensorImpl()->set_sizes_and_strides(src_size, src.strides()); - if (temp_src.is_contiguous()) { - auto temp_dst = NPUNativeFunctions::npu_broadcast(temp_src, self.sizes()); - c10_npu::queue::LaunchAsyncCopyTask(self.data_ptr(), self.nbytes(), temp_dst.data_ptr(), - self.nbytes(), ACL_MEMCPY_DEVICE_TO_DEVICE); - return true; - } - return false; - } + c10_npu::NPUStream copy_stream = c10_npu::getCurrentNPUStream(); + if (temp_src.is_contiguous()) + { + auto temp_dst = XLANativeFunctions::npu_broadcast(temp_src, self.sizes()); + aclrtMemcpyAsync( + self.data_ptr(), + self.nbytes(), + temp_dst.data_ptr(), + self.nbytes(), + ACL_MEMCPY_DEVICE_TO_DEVICE, + copy_stream); + return true; + } + return false; + } }; // class BroadcastContiguousOpt diff --git a/torch_npu/csrc/framework/contiguous/combined_opt.cpp b/torch_npu/csrc/framework/contiguous/combined_opt.cpp index 7121a0289a..03028ea119 100644 --- a/torch_npu/csrc/framework/contiguous/combined_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/combined_opt.cpp @@ -18,7 +18,6 @@ #include -#include "torch_npu/csrc/core/npu/NPURunMode.h" #include "torch_npu/csrc/framework/contiguous/ContiguousOpt.h" #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" @@ -86,8 +85,8 @@ private: } auto npu_desc = torch_npu::NPUBridge::GetNpuStorageImpl(tensor)->get_npu_desc(); - if ((at::prod_intlist(tensor.sizes()) != - at::prod_intlist(npu_desc.base_sizes_)) || + if ((c10::multiply_integers(tensor.sizes()) != + c10::multiply_integers(npu_desc.base_sizes_)) || (tensor.storage_offset() != npu_desc.base_offset_)) { return false; } @@ -154,8 +153,8 @@ private: // Weak constrains for slice cases bool maybe_slice(const ContiguousTensorDesc &tensor_desc) { // tensors with reduced numel will be taken into consideration. - if (at::prod_intlist(tensor_desc.sizes_) < - at::prod_intlist(tensor_desc.base_sizes_)) { + if (c10::multiply_integers(tensor_desc.sizes_) < + c10::multiply_integers(tensor_desc.base_sizes_)) { for (auto i = 0; i < tensor_desc.sizes_.size() - 2; i++) { if (tensor_desc.strides_[i] % tensor_desc.strides_[i + 1] != 0) { return false; @@ -280,8 +279,8 @@ Inference order: permute, select, slice. slice_size[i] = (view_strides[i - 1] / view_strides[i]); } slice_size[0] = 1; - slice_size[0] = (at::prod_intlist(tensor_desc.base_sizes_) / - at::prod_intlist(slice_size)); + slice_size[0] = (c10::multiply_integers(tensor_desc.base_sizes_) / + c10::multiply_integers(slice_size)); infer_offset = tensor_desc.offset_; // Refresh tensor's base info and storage info to construct sliced tensor tensor_desc.base_sizes_ = slice_size; @@ -424,10 +423,8 @@ Inference order: permute, select, slice. if (reconstruct_tensor(src, shape_stride_stacks, offset_stacks)) { ContiguousTensorDesc src_desc_ = TransContiguous::GetTensorDescInfo(src); OptimizationCases opt_cases_first{"reshape", "slice", "select"}; - if ((!c10_npu::NpuRunMode::IsGraphMode()) && reshape_without_copy_match(src)) { + if (reshape_without_copy_match(src)) { // case 1 : The first tensor is reshape-type, refresh its info is enough - // In single op, refresh is inplace operation, but in graph mode, reshape is not. - // In graph mode, there is not matching operator for this case. return combined_to_contiguous(self, src, shape_stride_stacks, offset_stacks); } else if (can_be_optimize_from_default_cases(src_desc_)) { diff --git a/torch_npu/csrc/framework/contiguous/indexing_opt.cpp b/torch_npu/csrc/framework/contiguous/indexing_opt.cpp index 872d28c437..3a72a6eb88 100644 --- a/torch_npu/csrc/framework/contiguous/indexing_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/indexing_opt.cpp @@ -39,8 +39,8 @@ private: c10::SmallVector &start, c10::SmallVector &end, c10::SmallVector &step) { - if (at::prod_intlist(src_desc.sizes_) >= - at::prod_intlist(src_desc.base_sizes_)) { + if (c10::multiply_integers(src_desc.sizes_) >= + c10::multiply_integers(src_desc.base_sizes_)) { return false; } @@ -90,7 +90,7 @@ private: // (5) 对step!=1的轴, // size(i)不可以为1:主要排除潜在的unsqueeze(0)+select(1,x)等走入indexing分支 // case 1 & 2 - if (at::prod_intlist(step) == 1 || step[step.size() - 1] != 1) { + if (c10::multiply_integers(step) == 1 || step[step.size() - 1] != 1) { return false; } // case 3 @@ -129,7 +129,7 @@ private: temp_src.strides()); // call StridedSlice op - NPUNativeFunctions::npu_indexing_out(temp_src, start, end, step, 0, 0, 0, 0, + XLANativeFunctions::npu_indexing_out(temp_src, start, end, step, 0, 0, 0, 0, 0, self); return; diff --git a/torch_npu/csrc/framework/contiguous/permute_opt.cpp b/torch_npu/csrc/framework/contiguous/permute_opt.cpp index 4cce654540..f1ba825bca 100644 --- a/torch_npu/csrc/framework/contiguous/permute_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/permute_opt.cpp @@ -17,7 +17,6 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" namespace at_npu { namespace native { @@ -39,7 +38,7 @@ public: static_cast(sizes)); src_desc.storage_sizes_ = sizes; - NPUNativeFunctions::npu_transpose_out(src, perm, false, self); + XLANativeFunctions::npu_transpose_out(src, perm, self); src_desc = src_desc_stored; return true; } @@ -68,7 +67,7 @@ private: // After permute or reshape+permute, the total amount of data remains // unchanged. - if (at::prod_intlist(view_sizes) != at::prod_intlist(base_sizes)) { + if (c10::multiply_integers(view_sizes) != c10::multiply_integers(base_sizes)) { return false; } @@ -199,9 +198,7 @@ private: } template void squeeze_shape_and_stride(T &shape, T &stride) { - IF_GRAPH_MODE_THEN_RUN(return;) - auto shape_size = shape.size(); - for (auto i = 0; i < shape_size; i++) { + for (auto i = 0; i < shape.size(); i++) { if (shape[i] == 1) { shape.erase(shape.begin() + i); stride.erase(stride.begin() + i); diff --git a/torch_npu/csrc/framework/contiguous/reshapeV2_opt.cpp b/torch_npu/csrc/framework/contiguous/reshapeV2_opt.cpp index 0cb4dfad19..8811e833ff 100644 --- a/torch_npu/csrc/framework/contiguous/reshapeV2_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/reshapeV2_opt.cpp @@ -20,16 +20,16 @@ namespace native { class ReshapeV2ContiguousOpt : public ContiguousOpt { public: - bool Optimizer(at::Tensor &result, const at::Tensor &src, + bool Optimizer(at::Tensor &self, const at::Tensor &src, const ContiguousTensorDesc &src_desc) override { - ContiguousTensorDesc result_desc = TransContiguous::GetTensorDescInfo(result); - if (check_reshape_match(result_desc, src_desc)) { - if ((!c10_npu::NpuRunMode::IsGraphMode()) && can_use_memory_repoint(src_desc) && - reshape_match_by_memory_repoint(src, result)) { + ContiguousTensorDesc self_desc = TransContiguous::GetTensorDescInfo(self); + if (check_reshape_match(self_desc, src_desc)) { + if (can_use_memory_repoint(src_desc) && + reshape_match_by_memory_repoint(src, self)) { return true; } RECORD_FUNCTION("View_d2dCopyAsync", std::vector({src})); - NPUNativeFunctions::npu_reshape_out(src, src.sizes(), false, result); + copy_d2d_by_memcpy(self, src, c10::multiply_integers(self_desc.storage_sizes_)); return true; } return false; diff --git a/torch_npu/csrc/framework/contiguous/reshape_opt.cpp b/torch_npu/csrc/framework/contiguous/reshape_opt.cpp index 1d9739523c..cdf7fa7a92 100644 --- a/torch_npu/csrc/framework/contiguous/reshape_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/reshape_opt.cpp @@ -20,12 +20,12 @@ namespace native { class ReshapeContiguousOpt : public ContiguousOpt { public: - bool Optimizer(at::Tensor &result, const at::Tensor &src, + bool Optimizer(at::Tensor &self, const at::Tensor &src, const ContiguousTensorDesc &src_desc) override { - ContiguousTensorDesc result_desc = TransContiguous::GetTensorDescInfo(result); - if (check_reshape_match(result_desc, src_desc)) { + ContiguousTensorDesc self_desc = TransContiguous::GetTensorDescInfo(self); + if (check_reshape_match(self_desc, src_desc)) { RECORD_FUNCTION("View_d2dCopyAsync", std::vector({src})); - NPUNativeFunctions::npu_reshape_out(src, src.sizes(), false, result); + copy_d2d_by_memcpy(self, src, c10::multiply_integers(self_desc.storage_sizes_)); return true; } return false; diff --git a/torch_npu/csrc/framework/contiguous/select_opt.cpp b/torch_npu/csrc/framework/contiguous/select_opt.cpp index c2bde0e5be..7a8b0fc6fc 100644 --- a/torch_npu/csrc/framework/contiguous/select_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/select_opt.cpp @@ -133,7 +133,7 @@ private: } // call StridedSlice op to contiguous - NPUNativeFunctions::npu_indexing_out(temp_src, start, end, strides, 0, 0, 0, + XLANativeFunctions::npu_indexing_out(temp_src, start, end, strides, 0, 0, 0, 0, shrink_mask, self); return; } diff --git a/torch_npu/csrc/framework/contiguous/slice_opt.cpp b/torch_npu/csrc/framework/contiguous/slice_opt.cpp index 3afc3077c5..bbdf21d51a 100644 --- a/torch_npu/csrc/framework/contiguous/slice_opt.cpp +++ b/torch_npu/csrc/framework/contiguous/slice_opt.cpp @@ -63,8 +63,8 @@ private: if (view_strides[view_strides.size() - 1] != 1 && FormatHelper::IsBaseFormatType(src_desc.npu_format_) && view_strides.size() < base_strides.size() && - at::prod_intlist(view_sizes) < - at::prod_intlist(base_sizes) / base_sizes[base_sizes.size() - 1]) { + c10::multiply_integers(view_sizes) < + c10::multiply_integers(base_sizes) / base_sizes[base_sizes.size() - 1]) { view_sizes.emplace_back(1); view_strides.emplace_back(1); } @@ -126,7 +126,7 @@ private: temp_src.set_(src.storage(), temp_src.storage_offset(), temp_src.sizes(), temp_src.strides()); - NPUNativeFunctions::npu_slice_out(temp_src, offsets, size, self); + XLANativeFunctions::npu_slice_out(temp_src, offsets, size, self); return; } diff --git a/torch_npu/csrc/framework/graph/construct/GraphConstructor.cpp b/torch_npu/csrc/framework/graph/construct/GraphConstructor.cpp index b467c3efb9..932a5d59cc 100644 --- a/torch_npu/csrc/framework/graph/construct/GraphConstructor.cpp +++ b/torch_npu/csrc/framework/graph/construct/GraphConstructor.cpp @@ -15,6 +15,7 @@ #include #include "GraphConstructor.h" +#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" #include "torch_npu/csrc/framework/graph/util/GraphUtils.h" #include "torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.h" @@ -41,7 +42,8 @@ void GraphCommandImpl::AddInput( if (!input.storage().data()) { auto storage_impl = input.storage().unsafeGetStorageImpl(); size_t n_bytes = GraphUtils::GetTensorCapacity(storage_impl); - GraphUtils::SetDataPtrAndNbytes(storage_impl, n_bytes); + auto data_ptr = c10_npu::NPUCachingAllocator::get()->allocate(n_bytes); + storage_impl->set_data_ptr(std::move(data_ptr)); } GraphUtils::SetDataOp(input.storage().unsafeGetStorageImpl()); } @@ -133,71 +135,38 @@ void GraphCommandImpl::ReduceScalarValue( const at::Scalar& input, const at::ScalarType type, uint32_t& host_ptr_offset) { - switch (type) - { - case at::ScalarType::Float: - { - float value = input.toFloat(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Int: - { - int value = input.toInt(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Long: - { - int64_t value = input.toLong(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Double: - { - double value = input.toDouble(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Half: - { - at::Half value = input.toHalf(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Byte: - { - uint8_t value = input.toByte(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Char: - { - int8_t value = input.toChar(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Short: - { - int16_t value = input.toShort(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::Bool: - { - bool value = input.toBool(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - case at::ScalarType::BFloat16: - { - at::BFloat16 value = input.toBFloat16(); - ReduceScalarValueOp(&value, host_ptr_offset); - } - break; - default: + if (at::ScalarType::Float == type) { + float value = input.toFloat(); + ScalarMemContext::GetContext().AppendToHostMem( + reinterpret_cast(&value), + sizeof(float), + host_ptr_offset); + } else if (at::ScalarType::Int == type) { + int value = input.toInt(); + ScalarMemContext::GetContext().AppendToHostMem( + reinterpret_cast(&value), + sizeof(int), + host_ptr_offset); + } else if (at::ScalarType::Long == type) { + int64_t value = input.toLong(); + ScalarMemContext::GetContext().AppendToHostMem( + reinterpret_cast(&value), + sizeof(int64_t), + host_ptr_offset); + } else if (at::ScalarType::Double == type) { + double value = input.toDouble(); + ScalarMemContext::GetContext().AppendToHostMem( + reinterpret_cast(&value), + sizeof(double), + host_ptr_offset); + } else if (at::ScalarType::Half == type) { + auto value = input.toHalf(); + ScalarMemContext::GetContext().AppendToHostMem( + reinterpret_cast(&value), + sizeof(at::ScalarType::Half), + host_ptr_offset); + } else { AT_ERROR("scalar not support '", at::toString(type), "' type currently."); - break; } } diff --git a/torch_npu/csrc/framework/graph/construct/GraphConstructor.h b/torch_npu/csrc/framework/graph/construct/GraphConstructor.h index 8d6ac12d7e..a1c38f77e6 100644 --- a/torch_npu/csrc/framework/graph/construct/GraphConstructor.h +++ b/torch_npu/csrc/framework/graph/construct/GraphConstructor.h @@ -18,8 +18,6 @@ #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/graph/util/NPUGraph.h" -#include "torch_npu/csrc/framework/graph/util/ATenGeBridge.h" -#include "torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.h" #include namespace at_npu { @@ -100,16 +98,6 @@ public: NodeExtInfoType::ATTR_TYPE_FLOAT, std::make_pair(attr_name, val)); node->UpdateNodeHash(val); } - - static void SetAttr( - const string& attr_name, - const c10::ScalarType& value, - NodePtr node) { - ge::DataType val = ATenGeBridge::GetGeDType(value); - node->AddExtInfo( - NodeExtInfoType::ATTR_TYPE_DATATYPE, std::make_pair(attr_name, val)); - node->UpdateNodeHash(val); - } }; class GraphCommandImpl { @@ -154,14 +142,6 @@ public: OperatorAttrMaker::SetAttr(attr_name, value, ir_node_); } - template - void ReduceScalarValueOp(T* value, uint32_t& host_ptr_offset) { - ScalarMemContext::GetContext().AppendToHostMem( - reinterpret_cast(value), - sizeof(T), - host_ptr_offset); - } - private: void AddZeroDimInput(const at::Tensor& input, const string& desc_name); diff --git a/torch_npu/csrc/framework/graph/execute/GraphExecutor.cpp b/torch_npu/csrc/framework/graph/execute/GraphExecutor.cpp index e3821c5a41..f66977bbee 100644 --- a/torch_npu/csrc/framework/graph/execute/GraphExecutor.cpp +++ b/torch_npu/csrc/framework/graph/execute/GraphExecutor.cpp @@ -21,6 +21,7 @@ #include "torch_npu/csrc/framework/graph/util/ATenGeBridge.h" #include "torch_npu/csrc/framework/graph/util/GraphUtils.h" #include "torch_npu/csrc/framework/interface/AclInterface.h" +#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" #include "torch_npu/csrc/core/npu/NPUFunctions.h" #include #include "torch_npu/csrc/core/npu/register/OptionRegister.h" @@ -170,7 +171,6 @@ void GraphExecutor::Init() { config["ge.session_device_id"] = ge::AscendString(device_id.data()); config["ge.exec.reuseZeroCopyMemory"] = ge::AscendString("1"); - config["GE_USE_STATIC_MEMORY"] = ge::AscendString("2"); session_ = std::make_unique(config); C10_NPU_CHECK(aclrtSetDevice(init_device_id_)); if (session_ == nullptr) { @@ -305,7 +305,8 @@ CombinedInfo GraphExecutor::GetOutputCombinedInfo() { if ((output_storage->data() == nullptr) && (!graph_desc.graph_value.GetScalarMemOffset().has_value())) { size_t nbytes = GraphUtils::GetTensorCapacity(output_storage); - GraphUtils::SetDataPtrAndNbytes(output_storage, nbytes); + auto data_ptr = c10_npu::NPUCachingAllocator::get()->allocate(nbytes); + output_storage->set_data_ptr(std::move(data_ptr)); } continue; } @@ -349,17 +350,17 @@ ge::Tensor GraphExecutor::PrepareOutputTenosr( graph_desc.graph_value.HashNode(), "graph desc in storage must have node"); size_t nbytes = GraphUtils::GetTensorCapacity(storage); + c10::DataPtr data_ptr; // In the case of in-place operator // we can not call set_data_ptr // for this will cause the old data ptr to be released // and if one value have data node which has no device memory // we should malloc for it - // After decoupling, we cannot simply set nbytes for NPUStorageImpl - // by calling set_data_ptr. Instead, we need to call set_nbytes if (!(graph_desc.graph_value.GetDataNode().has_value() && storage->data() != nullptr)) { - GraphUtils::SetDataPtrAndNbytes(storage, nbytes); + data_ptr = c10_npu::NPUCachingAllocator::get()->allocate(nbytes); + storage->set_data_ptr(std::move(data_ptr)); } return MakeGeTensor(desc, storage->data(), nbytes); } diff --git a/torch_npu/csrc/framework/graph/execute/GraphExecutor.h b/torch_npu/csrc/framework/graph/execute/GraphExecutor.h index f6553204f2..b702582439 100644 --- a/torch_npu/csrc/framework/graph/execute/GraphExecutor.h +++ b/torch_npu/csrc/framework/graph/execute/GraphExecutor.h @@ -66,7 +66,7 @@ public: void Finalize(); -private: + private: GraphExecutor() = default; void Init(); diff --git a/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.cpp b/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.cpp index bc891643c4..896404b31a 100644 --- a/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.cpp +++ b/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.cpp @@ -8,7 +8,7 @@ namespace native { void ScalarMemContext::Init() { cpu_tensor_ = at::empty( {HOST_MEM_INIT_SIZE}, - at::TensorOptions().pinned_memory(false).device(at::kCPU).dtype(at::kByte)).pin_memory(); + at::TensorOptions().pinned_memory(true).device(at::kCPU).dtype(at::kByte)); host_mem_valid_len_ = 0; inited_ = true; } @@ -51,7 +51,7 @@ void ScalarMemContext::CheckForExpand(uint32_t input_valid_len) { uint32_t expand_tensor_size = tmp_tensor.nbytes() + HOST_MEM_INIT_SIZE; cpu_tensor_ = at::empty( {expand_tensor_size}, - at::TensorOptions().pinned_memory(false).device(at::kCPU).dtype(at::kByte)).pin_memory(); + at::TensorOptions().pinned_memory(true).device(at::kCPU).dtype(at::kByte)); C10_NPU_CHECK( aclrtMemcpy( diff --git a/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.h b/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.h index b7d511bda1..c8a3280ba3 100644 --- a/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.h +++ b/torch_npu/csrc/framework/graph/scalar/ScalarMemoryOps.h @@ -18,7 +18,7 @@ #include "torch_npu/csrc/core/npu/THNPUCachingHostAllocator.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { namespace native { diff --git a/torch_npu/csrc/framework/graph/util/ATenGeBridge.cpp b/torch_npu/csrc/framework/graph/util/ATenGeBridge.cpp index 84616464b5..02a0cdf4fa 100644 --- a/torch_npu/csrc/framework/graph/util/ATenGeBridge.cpp +++ b/torch_npu/csrc/framework/graph/util/ATenGeBridge.cpp @@ -203,9 +203,6 @@ void ATenGeBridge::AddNodeExtInfoIntoGeOp( case NodeExtInfoType::ATTR_TYPE_STRING: SetGeOpAttr>(info.second, ge_op); break; - case NodeExtInfoType::ATTR_TYPE_DATATYPE: - SetGeOpAttr>(info.second, ge_op); - break; case NodeExtInfoType::ATTR_TYPE_LIST_LONG: SetGeOpAttr>>(info.second, ge_op); break; diff --git a/torch_npu/csrc/framework/graph/util/GraphUtils.cpp b/torch_npu/csrc/framework/graph/util/GraphUtils.cpp index 9ca71c1421..d39773c7a8 100644 --- a/torch_npu/csrc/framework/graph/util/GraphUtils.cpp +++ b/torch_npu/csrc/framework/graph/util/GraphUtils.cpp @@ -13,10 +13,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" #include "torch_npu/csrc/framework/graph/util/GraphUtils.h" #include "torch_npu/csrc/framework/graph/util/NPUGraphContextManager.h" -#include "torch_npu/csrc/core/NPUStorageImpl.h" namespace at_npu { namespace native { @@ -32,7 +30,7 @@ hash_t GraphUtils::GetTensorIrValueHash(const at::Tensor& tensor) { size_t GraphUtils::GetTensorCapacity(c10::StorageImpl* storage) { auto npu_desc = torch_npu::NPUBridge::GetNpuStorageImpl(storage)->get_npu_desc(); - size_t nbytes = at::prod_intlist(npu_desc.storage_sizes_) * npu_desc.data_type_.itemsize(); + size_t nbytes = c10::multiply_integers(npu_desc.storage_sizes_) * npu_desc.data_type_.itemsize(); return nbytes; } @@ -61,12 +59,6 @@ void GraphUtils::SetDataOp(const at::Tensor& tensor) { SetDataOp(tensor.storage().unsafeGetStorageImpl()); } -void GraphUtils::SetDataPtrAndNbytes(c10::StorageImpl* storage, size_t nbytes) { - auto data_ptr = c10_npu::NPUCachingAllocator::get()->allocate(nbytes); - storage->set_data_ptr(std::move(data_ptr)); - storage->set_nbytes(nbytes); -} - void GraphUtils::ResetOp(c10::StorageImpl* storage) { TORCH_CHECK(storage != nullptr, "Storage is null"); torch_npu::NPUBridge::GetNpuStorageImpl(storage)->get_mutable_npu_graph_desc().graph_value.ResetValue(); diff --git a/torch_npu/csrc/framework/graph/util/GraphUtils.h b/torch_npu/csrc/framework/graph/util/GraphUtils.h index 1273f5fd07..9d901e86cb 100644 --- a/torch_npu/csrc/framework/graph/util/GraphUtils.h +++ b/torch_npu/csrc/framework/graph/util/GraphUtils.h @@ -42,8 +42,6 @@ public: static void SetDataOp(const at::Tensor& tensor); - static void SetDataPtrAndNbytes(c10::StorageImpl* storage, size_t nbytes); - static void ResetOp(c10::StorageImpl* storage); static void ResetOp(at::Tensor& tensor); diff --git a/torch_npu/csrc/framework/graph/util/NPUGraph.h b/torch_npu/csrc/framework/graph/util/NPUGraph.h index 16e712b1cf..7fe01d875c 100644 --- a/torch_npu/csrc/framework/graph/util/NPUGraph.h +++ b/torch_npu/csrc/framework/graph/util/NPUGraph.h @@ -123,7 +123,6 @@ enum class NodeExtInfoType : uint8_t { ATTR_TYPE_LONG, ATTR_TYPE_FLOAT, ATTR_TYPE_STRING, - ATTR_TYPE_DATATYPE, ATTR_TYPE_LIST_BOOL, ATTR_TYPE_LIST_LONG, ATTR_TYPE_LIST_FLOAT, diff --git a/torch_npu/csrc/framework/interface/AclOpCompileInterface.cpp b/torch_npu/csrc/framework/interface/AclOpCompileInterface.cpp index c8c67af34a..dd464b3a68 100644 --- a/torch_npu/csrc/framework/interface/AclOpCompileInterface.cpp +++ b/torch_npu/csrc/framework/interface/AclOpCompileInterface.cpp @@ -35,7 +35,6 @@ namespace at_npu LOAD_FUNCTION(aclGenGraphAndDumpForOp) LOAD_FUNCTION(aclCreateGraphDumpOpt) LOAD_FUNCTION(aclDestroyGraphDumpOpt) - LOAD_FUNCTION(aclopCompileAndExecuteV2) aclError AclopSetCompileFlag(aclOpCompileFlag flag) { typedef aclError (*aclopSetCompileFlagFunc)(aclOpCompileFlag); @@ -88,25 +87,5 @@ aclError AclDestroyGraphDumpOpt(aclGraphDumpOption* aclGraphDumpOpt) { return func(aclGraphDumpOpt); } -aclError AclopCompileAndExecuteV2(const char *opType, - int numInputs, aclTensorDesc *inputDesc[], aclDataBuffer *inputs[], - int numOutputs, aclTensorDesc *outputDesc[], aclDataBuffer *outputs[], - aclopAttr *attr, aclopEngineType engineType, aclopCompileType compileFlag, - const char *opPath, aclrtStream stream) { - typedef aclError(*AclopCompileAndExecuteV2Func)(const char *, - int, aclTensorDesc * [], aclDataBuffer * [], - int, aclTensorDesc * [], aclDataBuffer * [], - aclopAttr *, aclopEngineType, aclopCompileType, - const char *, aclrtStream); - static AclopCompileAndExecuteV2Func func = nullptr; - if (func == nullptr) { - func = (AclopCompileAndExecuteV2Func)GET_FUNC(aclopCompileAndExecuteV2); - } - TORCH_CHECK(func, "Failed to find function ", "aclopCompileAndExecuteV2"); - auto ret = func(opType, numInputs, inputDesc, inputs, numOutputs, - outputDesc, outputs, attr, engineType, compileFlag, opPath, stream); - return ret; -} - } // namespace native } // namespace at_npu \ No newline at end of file diff --git a/torch_npu/csrc/framework/interface/AclOpCompileInterface.h b/torch_npu/csrc/framework/interface/AclOpCompileInterface.h index 85f783dd32..f59f7fe841 100644 --- a/torch_npu/csrc/framework/interface/AclOpCompileInterface.h +++ b/torch_npu/csrc/framework/interface/AclOpCompileInterface.h @@ -72,33 +72,6 @@ aclGraphDumpOption* AclCreateGraphDumpOpt(); */ aclError AclDestroyGraphDumpOpt(aclGraphDumpOption* aclGraphDumpOpt); -/** - * @ingroup AscendCL - * @brief compile and execute op - * - * @param opType [IN] op type - * @param numInputs [IN] number of inputs - * @param inputDesc [IN] pointer to array of input tensor descriptions - * @param inputs [IN] pointer to array of input buffers - * @param numOutputs [IN] number of outputs - * @param outputDesc [IN] pointer to array of output tensor descriptions - * @param outputs [IN] pointer to array of outputs buffers - * @param attr [IN] pointer to instance of aclopAttr. - * may pass nullptr if the op has no attribute - * @param engineType [IN] engine type - * @param compileFlag [IN] compile flag - * @param opPath [IN] path of op - * @param stream [IN] stream handle - * @retval ACL_ERROR_NONE The function is successfully executed. - * @retval OtherValues Failure - */ -aclError AclopCompileAndExecuteV2(const char *opType, - int numInputs, aclTensorDesc *inputDesc[], aclDataBuffer *inputs[], - int numOutputs, aclTensorDesc *outputDesc[], aclDataBuffer *outputs[], - aclopAttr *attr, aclopEngineType engineType, aclopCompileType compileFlag, - const char *opPath, aclrtStream stream); - - } // namespace native } // namespace at_npu diff --git a/torch_npu/csrc/framework/interface/EnvVariables.cpp b/torch_npu/csrc/framework/interface/EnvVariables.cpp index 822aa25af1..3efb5592cb 100644 --- a/torch_npu/csrc/framework/interface/EnvVariables.cpp +++ b/torch_npu/csrc/framework/interface/EnvVariables.cpp @@ -98,22 +98,22 @@ REGISTER_OPTION_HOOK(NPU_FUZZY_COMPILE_BLACKLIST, [](const std::string &val) { FuzzyCompileBlacklist::GetInstance().RegisterBlacklist(val); }) REGISTER_OPTION_HOOK(deliverswitch, [](const std::string &val) { - if (val == "enable") { - torch_npu::profiler::NpuProfilingDispatch::Instance().start(); - } else { - torch_npu::profiler::NpuProfilingDispatch::Instance().stop(); - } + // if (val == "enable") { + // torch_npu::profiler::NpuProfilingDispatch::Instance().start(); + // } else { + // torch_npu::profiler::NpuProfilingDispatch::Instance().stop(); + // } }) REGISTER_OPTION_HOOK(profilerResultPath, [](const std::string &val) { - torch_npu::profiler::NpuProfiling::Instance().Init(val); + // torch_npu::profiler::NpuProfiling::Instance().Init(val); }) REGISTER_OPTION_HOOK(profiling, [](const std::string &val) { if (val.compare("stop") == 0) { - torch_npu::profiler::NpuProfiling::NpuProfiling::Instance().Stop(); + // torch_npu::profiler::NpuProfiling::NpuProfiling::Instance().Stop(); } else if (val.compare("finalize") == 0) { - torch_npu::profiler::NpuProfiling::NpuProfiling::Instance().Finalize(); + // torch_npu::profiler::NpuProfiling::NpuProfiling::Instance().Finalize(); } else { TORCH_CHECK(false, "profiling input: (", val, " ) error!") } diff --git a/torch_npu/csrc/framework/utils/CalcuOpUtil.cpp b/torch_npu/csrc/framework/utils/CalcuOpUtil.cpp index 093d8b95cd..3bfaeaf145 100644 --- a/torch_npu/csrc/framework/utils/CalcuOpUtil.cpp +++ b/torch_npu/csrc/framework/utils/CalcuOpUtil.cpp @@ -182,19 +182,14 @@ namespace at_npu } NPUStatus CalcuOpUtil::AclrtMemcpyAsync( - const std::pair& dst, + void *dst, size_t dst_size, - const std::pair& src, + const void *src, size_t src_size, aclrtMemcpyKind kind) { - GraphModeGuard mode_guard(c10_npu::ModeKind::SINGLE_OP_MODE); - void* dst_ptr = reinterpret_cast(dst.first.data_ptr()) + - dst.second * dst.first.itemsize(); - void* src_ptr = reinterpret_cast(src.first.data_ptr()) + - src.second * src.first.itemsize(); - C10_NPU_CHECK(c10_npu::queue::LaunchAsyncCopyTask( - dst_ptr, dst_size, const_cast(src_ptr), src_size, kind)); + C10_NPU_CHECK(aclrtMemcpyAsync( + dst, dst_size, src, src_size, kind, c10_npu::getCurrentNPUStream())); return "SUCCESS"; } @@ -412,26 +407,20 @@ namespace at_npu int inputNum = input.size(); int outputNum = output.size(); - size_t inputTensorDescArrLen = inputNum * sizeof(uintptr_t); - size_t inputDataBuffArrLen = inputNum * sizeof(uintptr_t); + const aclTensorDesc **aclTensorInputDescArr = + inputNum == 0 ? nullptr : new const aclTensorDesc *[inputNum]; + const aclTensorDesc **aclTensorOutputDescArr = + outputNum == 0 ? nullptr : new const aclTensorDesc *[outputNum]; - size_t outputTensorDescArrLen = outputNum * sizeof(uintptr_t); - size_t outputDataBuffArrLen = outputNum * sizeof(uintptr_t); + const aclDataBuffer **aclDataInputBuffArr = + inputNum == 0 ? nullptr : new const aclDataBuffer *[inputNum]; + aclDataBuffer **aclDataOutputBuffArr = + outputNum == 0 ? nullptr : new aclDataBuffer *[outputNum]; - size_t totalMemLen = - inputTensorDescArrLen + inputDataBuffArrLen + - outputTensorDescArrLen + outputDataBuffArrLen; - char* basePtr = static_cast(malloc(totalMemLen)); - AT_ASSERT(basePtr != nullptr); - - const aclTensorDesc** aclTensorInputDescArr = reinterpret_cast(basePtr); - basePtr += inputTensorDescArrLen; - const aclDataBuffer** aclDataInputBuffArr = reinterpret_cast(basePtr); - basePtr += inputDataBuffArrLen; - - const aclTensorDesc** aclTensorOutputDescArr = reinterpret_cast(basePtr); - basePtr += outputTensorDescArrLen; - aclDataBuffer** aclDataOutputBuffArr = reinterpret_cast(basePtr); + int64_t *inputDimsArr = new int64_t[inputNum]; + int64_t *outputDimsArr = new int64_t[outputNum]; + aclFormat *inputFormatsArr = new aclFormat[inputNum]; + aclFormat *outputFormatsArr = new aclFormat[outputNum]; for (int i = 0; i < inputNum; i++) { @@ -449,6 +438,8 @@ namespace at_npu aclTensorInputDescArr[i] = aclCreateTensorDesc( ACL_DT_UNDEFINED, 0, nullptr, ACL_FORMAT_UNDEFINED); aclDataInputBuffArr[i] = aclCreateDataBuffer(nullptr, 0); + inputDimsArr[i] = 0; + inputFormatsArr[i] = ACL_FORMAT_UNDEFINED; } else if ( input[i].tensorDescType == NPUTensorDesc::TensorDescType::TENSOR) @@ -547,6 +538,11 @@ namespace at_npu params.output_desc = aclTensorOutputDescArr; params.output_data_buf = aclDataOutputBuffArr; + params.inputDims = inputDimsArr; + params.outputDims = outputDimsArr; + params.inputFormats = inputFormatsArr; + params.outputFormats = outputFormatsArr; + return "SUCCESS"; } @@ -634,10 +630,11 @@ namespace at_npu return dimList; } - aclopAttr* CalcuOpUtil::CreateNpuAttrDesc( + std::tuple CalcuOpUtil::CreateNpuAttrDesc( const c10::SmallVector &attrs) { aclopAttr *attr = aclopCreateAttr(); + string attrInfo = "attrs="; for (NPUAttrDesc npuAttrDesc : attrs) { @@ -646,20 +643,24 @@ namespace at_npu case NPUAttrDesc::AttrDescType::BOOL_TYPE: aclopSetAttrBool( attr, npuAttrDesc.attrName.c_str(), npuAttrDesc.boolAttrValue); + attrInfo += std::to_string(npuAttrDesc.boolAttrValue) + "-"; break; case NPUAttrDesc::AttrDescType::INT_TYPE: aclopSetAttrInt( attr, npuAttrDesc.attrName.c_str(), npuAttrDesc.intAttrValue); + attrInfo += std::to_string(npuAttrDesc.intAttrValue) + "-"; break; case NPUAttrDesc::AttrDescType::FLOAT_TYPE: aclopSetAttrFloat( attr, npuAttrDesc.attrName.c_str(), npuAttrDesc.floatAttrValue); + attrInfo += std::to_string(npuAttrDesc.floatAttrValue) + "-"; break; case NPUAttrDesc::AttrDescType::STRING_TYPE: aclopSetAttrString( attr, npuAttrDesc.attrName.c_str(), npuAttrDesc.stringAttrValue.c_str()); + attrInfo += npuAttrDesc.stringAttrValue + "-"; break; case NPUAttrDesc::AttrDescType::LIST_INT_TYPE: aclopSetAttrListInt( @@ -667,6 +668,9 @@ namespace at_npu npuAttrDesc.attrName.c_str(), npuAttrDesc.listIntAttrValue.size(), npuAttrDesc.listIntAttrValue.data()); + for (unsigned i = 0; i < npuAttrDesc.listIntAttrValue.size(); i++) + attrInfo += std::to_string(npuAttrDesc.listIntAttrValue.at(i)) + ","; + attrInfo += "-"; break; case NPUAttrDesc::AttrDescType::LIST_FLOAT_TYPE: aclopSetAttrListFloat( @@ -674,6 +678,9 @@ namespace at_npu npuAttrDesc.attrName.c_str(), npuAttrDesc.listFloatAttrValue.size(), npuAttrDesc.listFloatAttrValue.data()); + for (unsigned i = 0; i < npuAttrDesc.listFloatAttrValue.size(); i++) + attrInfo += std::to_string(npuAttrDesc.listFloatAttrValue.at(i)) + ","; + attrInfo += "-"; break; case NPUAttrDesc::AttrDescType::LIST_LIST_INT_TYPE: aclopSetAttrListListInt( @@ -682,13 +689,16 @@ namespace at_npu npuAttrDesc.listListIntAttrValue.size(), npuAttrDesc.listListIntAttrListIntNum.data(), npuAttrDesc.listListIntAttrValue.data()); + for (unsigned i = 0; i < npuAttrDesc.listListIntAttrValue.size(); i++) + attrInfo += std::to_string(*npuAttrDesc.listListIntAttrValue.at(i)) + ","; + attrInfo += "-"; break; default: AT_ERROR("unsupport attr type", npuAttrDesc.attrType); } } - return attr; + return std::tuple(attr, attrInfo); } void CalcuOpUtil::execute_npu_operate( @@ -701,22 +711,20 @@ namespace at_npu { ExecuteParas cur_paras; cur_paras.opType = opName; + cur_paras.paras.hasAttr = attrs.size() == 0 ? false : true; CalcuOpUtil::CreateAclTensorDescInfo( inputs, outputs, cur_paras.paras, opName, attrs); auto attrRes = CalcuOpUtil::CreateNpuAttrDesc(attrs); - cur_paras.attr = attrRes; - if (!FuzzyCompileBlacklist::GetInstance().IsInBlacklist(cur_paras.opType) && env::CheckFuzzyEnable()) { - cur_paras.isFuzzy = true; - } - c10_npu::queue::QueueParas params(c10_npu::queue::COMPILE_AND_EXECUTE, sizeof(ExecuteParas), &cur_paras); - c10_npu::enCurrentNPUStream(¶ms); + cur_paras.attr = std::get<0>(attrRes); + cur_paras.attrInfo = std::get<1>(attrRes); + c10_npu::enCurrentNPUStream(&cur_paras); return; } ACL_PARAMS params; CalcuOpUtil::CreateAclTensorDescInfo(inputs, outputs, params, opName, attrs); - aclopAttr *attr = CalcuOpUtil::CreateNpuAttrDesc(attrs); + aclopAttr *attr = std::get<0>(CalcuOpUtil::CreateNpuAttrDesc(attrs)); auto stream = c10_npu::getCurrentNPUStream(); RECORD_FUNCTION(opName, std::vector({})); diff --git a/torch_npu/csrc/framework/utils/CalcuOpUtil.h b/torch_npu/csrc/framework/utils/CalcuOpUtil.h index 33418f3325..2e00ce33e9 100644 --- a/torch_npu/csrc/framework/utils/CalcuOpUtil.h +++ b/torch_npu/csrc/framework/utils/CalcuOpUtil.h @@ -221,9 +221,9 @@ namespace at_npu at::ScalarType scalar_data_type); static at::Tensor copy_tensor_host_to_device(const at::Tensor &cpu_tensor); static NPUStatus AclrtMemcpyAsync( - const std::pair& dst, + void *dst, size_t dst_size, - const std::pair& src, + const void *src, size_t src_size, aclrtMemcpyKind kind); static void check_memory_over_laps( @@ -252,7 +252,7 @@ namespace at_npu at::ScalarType scalar_type); static c10::SmallVector create_npu_output_tensor_desc( const c10::SmallVector &outputTensor); - static aclopAttr* CreateNpuAttrDesc(const c10::SmallVector &attrs); + static std::tuple CreateNpuAttrDesc(const c10::SmallVector &attrs); static NPUStatus CreateAclTensorDescInfo( c10::SmallVector &input, c10::SmallVector &output, diff --git a/torch_npu/csrc/framework/utils/KernelNpuOutputSize.cpp b/torch_npu/csrc/framework/utils/KernelNpuOutputSize.cpp index 07dae556f0..1df3343f87 100644 --- a/torch_npu/csrc/framework/utils/KernelNpuOutputSize.cpp +++ b/torch_npu/csrc/framework/utils/KernelNpuOutputSize.cpp @@ -15,7 +15,7 @@ // limitations under the License. #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace at_npu { @@ -422,7 +422,7 @@ namespace at_npu int64_t srcIdx = new_indices.size() + j; if (index.size(j) != self.size(srcIdx)) { - TORCH_CHECK_INDEX("The shape of boolTensorIndex does not match the self"); + TORCH_CHECK_INDEX(false, "The shape of boolTensorIndex does not match the self"); } } // Replace with nonzeros @@ -681,8 +681,8 @@ namespace at_npu c10::SmallVector nonzero_npu_output_size(const at::Tensor &self) { int64_t dim = self.dim(); - at::Tensor boolSelf = NPUNativeFunctions::npu_dtype_cast(self, at::ScalarType::Bool); - at::Tensor intSelf = NPUNativeFunctions::npu_dtype_cast(boolSelf, at::ScalarType::Int); + at::Tensor boolSelf = XLANativeFunctions::npu_dtype_cast(self, at::ScalarType::Bool); + at::Tensor intSelf = XLANativeFunctions::npu_dtype_cast(boolSelf, at::ScalarType::Int); at::Tensor coutNonzeroSelf = intSelf; if (self.numel() > 10000000) diff --git a/torch_npu/csrc/framework/utils/NpuUtils.cpp b/torch_npu/csrc/framework/utils/NpuUtils.cpp index b49c6ac8ef..9dea45323f 100644 --- a/torch_npu/csrc/framework/utils/NpuUtils.cpp +++ b/torch_npu/csrc/framework/utils/NpuUtils.cpp @@ -20,7 +20,7 @@ #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" #include "torch_npu/csrc/core/npu/interface/AsyncTaskQueueInterface.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" #include "torch_npu/csrc/framework/FormatHelper.h" @@ -31,7 +31,6 @@ #include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h" #include "torch_npu/csrc/framework/utils/NpuUtils.h" #include "torch_npu/csrc/framework/utils/OpPreparation.h" -#include "torch_npu/csrc/framework/utils/OpAdapter.h" namespace at_npu { namespace native { @@ -83,11 +82,16 @@ bool NpuUtils::check_5d_5d_match(const at::Tensor &tensor) { // (1) NC1HWC0 format in storage, NCHW format in des. // (2) 4d format situation, only uncontiguous in Channel size // (3) size and start point must be 16*, make sure the memory be contiguous + const c10::Storage storage = tensor.storage(); + const torch_npu::NPUStorageDesc npuDesc = + torch_npu::NPUBridge::GetNpuStorageImpl(storage.unsafeGetStorageImpl()) + ->get_npu_desc(); + if (tensor.is_contiguous()) { return false; } - if (torch_npu::NPUBridge::GetNpuStorageImpl(tensor)->npu_desc_.npu_format_ != ACL_FORMAT_NC1HWC0) { + if (npuDesc.npu_format_ != ACL_FORMAT_NC1HWC0) { return false; } @@ -113,8 +117,8 @@ bool NpuUtils::check_5d_5d_match(const at::Tensor &tensor) { int64_t contiguous_len = 16; int64_t c0_len = 16; - for (int i = 2; i < torch_npu::NPUBridge::GetNpuStorageImpl(tensor)->npu_desc_.base_sizes_.size(); i++) { - contiguous_len *= torch_npu::NPUBridge::GetNpuStorageImpl(tensor)->npu_desc_.base_sizes_[i]; + for (int i = 2; i < npuDesc.base_sizes_.size(); i++) { + contiguous_len *= npuDesc.base_sizes_[i]; } bool is_offset_match = (tensor.storage_offset() % contiguous_len == 0); bool is_length_match = (tensor.size(1) % c0_len == 0); @@ -142,9 +146,9 @@ at::Tensor metadata_convert_match(const at::Tensor &src, bool numelEq) { // NCHW will generate a temporary tensor, which always monopolizes its own // storage. if (numelEq && (!FormatHelper::IsBaseFormatType(src))) { - at::Tensor tempTensor = NPUNativeFunctions::npu_format_cast( + at::Tensor tempTensor = XLANativeFunctions::npu_format_cast( src, FormatHelper::GetBaseFormat(src)); - NPUNativeFunctions::npu_reshape_out(tempTensor, tempTensor.sizes(), true, + XLANativeFunctions::npu_reshape_out(tempTensor, tempTensor.sizes(), true, tempTensor); NpuUtils::RefreshFormat(tempTensor); return tempTensor; @@ -158,13 +162,13 @@ at::Tensor metadata_convert_match(const at::Tensor &src, bool numelEq) { at::Tensor metadata_convert_match_without_copy_optimize(const at::Tensor &src) { auto &src_desc = torch_npu::NPUBridge::GetNpuStorageImpl(src)->npu_desc_; - bool numelEq = (src.numel() == at::prod_intlist(src_desc.base_sizes_)); + bool numelEq = (src.numel() == c10::multiply_integers(src_desc.base_sizes_)); return metadata_convert_match(src, numelEq); } at::Tensor metadata_convert_match_with_copy_optimize(const at::Tensor &src) { auto &src_desc = torch_npu::NPUBridge::GetNpuStorageImpl(src)->npu_desc_; - bool numelEq = (src.numel() == at::prod_intlist(src_desc.base_sizes_)); + bool numelEq = (src.numel() == c10::multiply_integers(src_desc.base_sizes_)); // For unmatched Tensors with base format, we can: OptimizationCases optimizations_reshape{"reshapeV2"}; diff --git a/torch_npu/csrc/framework/utils/NpuUtils.h b/torch_npu/csrc/framework/utils/NpuUtils.h index b2c5e95624..4db516b04b 100644 --- a/torch_npu/csrc/framework/utils/NpuUtils.h +++ b/torch_npu/csrc/framework/utils/NpuUtils.h @@ -23,10 +23,10 @@ #include #include "torch_npu/csrc/core/npu/npu_log.h" -#include "third_party/acl/inc/ge/ge_error_codes.h" #include "third_party/acl/inc/acl/acl.h" #include "third_party/acl/inc/acl/acl_base.h" #include "third_party/acl/inc/acl/acl_op.h" +#include "third_party/acl/inc/ge/ge_error_codes.h" #include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" #include "torch_npu/csrc/framework/interface/AclOpCompileInterface.h" diff --git a/torch_npu/csrc/framework/utils/OpPreparation.cpp b/torch_npu/csrc/framework/utils/OpPreparation.cpp index effa5c888f..7044863827 100644 --- a/torch_npu/csrc/framework/utils/OpPreparation.cpp +++ b/torch_npu/csrc/framework/utils/OpPreparation.cpp @@ -17,7 +17,7 @@ #include "torch_npu/csrc/framework/FormatHelper.h" #include "torch_npu/csrc/framework/InferFormat.h" #include "torch_npu/csrc/framework/utils/CalcuOpUtil.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/NPUBridge.h" #include "torch_npu/csrc/core/NPUStorageImpl.h" @@ -177,21 +177,21 @@ namespace at_npu if (CalcuOpUtil::get_tensor_npu_format(output) != format) { TORCH_CHECK(!is_read_write, "can not cast format when output is input"); - NPUNativeFunctions::npu_format_cast_(output, format); + XLANativeFunctions::npu_format_cast_(output, format); } } at::Tensor OpPreparation::CastBackToOriFormat(const at::Tensor &tensor) { auto &tensor_desc = torch_npu::NPUBridge::GetNpuStorageImpl(tensor)->npu_desc_; - auto ret = NPUNativeFunctions::npu_format_cast(tensor, tensor_desc.origin_format_); + auto ret = XLANativeFunctions::npu_format_cast(tensor, tensor_desc.origin_format_); return ret; } at::Tensor &OpPreparation::CastBackToOriFormat(at::Tensor &tensor) { auto &tensor_desc = torch_npu::NPUBridge::GetNpuStorageImpl(tensor)->npu_desc_; - NPUNativeFunctions::npu_format_cast_(tensor, tensor_desc.origin_format_); + XLANativeFunctions::npu_format_cast_(tensor, tensor_desc.origin_format_); return tensor; } @@ -228,7 +228,7 @@ namespace at_npu at::Tensor OpPreparation::ApplyTensorWithFormat(c10::IntArrayRef sizes, const c10::TensorOptions &options, int64_t format) { auto fixFormat = InferFormat::GuessStorageFormat(sizes, (aclFormat)format); - return NPUNativeFunctions::empty_with_format( + return XLANativeFunctions::empty_with_format( sizes, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), fixFormat); } @@ -236,7 +236,7 @@ namespace at_npu at::Tensor OpPreparation::ApplyTensorWithSizes(c10::IntArrayRef sizes, const c10::TensorOptions &options) { auto format = InferFormat::GuessBaseFormat(sizes); - return NPUNativeFunctions::empty_with_format( + return XLANativeFunctions::empty_with_format( sizes, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt(), format); } diff --git a/torch_npu/csrc/npu/Generator.cpp b/torch_npu/csrc/npu/Generator.cpp index f5f98836f3..f82ba30150 100644 --- a/torch_npu/csrc/npu/Generator.cpp +++ b/torch_npu/csrc/npu/Generator.cpp @@ -4,7 +4,7 @@ #include #include -#include +// #include #include #include #include @@ -16,7 +16,7 @@ #include "torch_npu/csrc/aten/NPUGeneratorImpl.h" #include "torch_npu/csrc/npu/Generator.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" using namespace at; using namespace torch; @@ -92,7 +92,7 @@ static PyObject * THPGenerator_setState(PyObject *_self, PyObject *_new_state) } auto self = (THPGenerator*)_self; auto& gen = self->cdata; - auto& new_state_tensor = ((THPVariable*)_new_state)->cdata; + auto& new_state_tensor = THPVariable_Unpack(_new_state); // See Note [Acquire lock when using random generators] std::lock_guard lock(gen.mutex()); diff --git a/torch_npu/csrc/npu/Module.cpp b/torch_npu/csrc/npu/Module.cpp index d2d4a9148b..3bcb06343c 100644 --- a/torch_npu/csrc/npu/Module.cpp +++ b/torch_npu/csrc/npu/Module.cpp @@ -17,7 +17,7 @@ #include #include -#include +// #include #include "torch_npu/csrc/core/npu/NPUException.h" #include "torch_npu/csrc/core/npu/NPUFunctions.h" #include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" @@ -37,54 +37,12 @@ #include "third_party/acl/inc/acl/acl.h" #include "torch_npu/csrc/core/npu/register/OptionRegister.h" -#include "torch_npu/csrc/profiler/cann_profiling.h" -#include "torch_npu/csrc/profiler/e2e_profiler.h" +// #include "torch_npu/csrc/profiler/cann_profiling.h" +// #include "torch_npu/csrc/profiler/e2e_profiler.h" #include "torch_npu/csrc/framework/graph/execute/GraphExecutor.h" #include "torch_npu/csrc/core/npu/NPURunMode.h" #include "torch_npu/csrc/aten/NPUGeneratorImpl.h" #include "torch_npu/csrc/utils/LazyInit.h" -#include "torch_npu/csrc/npu/Module.h" - -struct NPUDeviceProp { - std::string name; - size_t totalGlobalMem = 0; -}; -NPUDeviceProp prop; -void RegisterNPUDeviceProperties(PyObject* module) { - auto m = py::handle(module).cast(); - py::class_(m, "_NPUDeviceProperties") - .def_readonly("name", &NPUDeviceProp::name) - .def_readonly("total_memory", &NPUDeviceProp::totalGlobalMem) - .def("__repr__", [](const NPUDeviceProp &prop) { - std::ostringstream stream; - stream << "_NPUDeviceProperties(name='" << prop.name << "', total_memory=" - << prop.totalGlobalMem / (CHANGE_UNIT_SIZE * CHANGE_UNIT_SIZE) << "MB)"; - return stream.str(); - }); -} - -NPUDeviceProp* GetDeviceProperties(int64_t deviceid) { - const char* device_name; - size_t device_free; - size_t device_total; - device_name = c10_npu::acl::AclrtGetSocName(); - if (device_name == nullptr) { - prop.name = " "; - NPU_LOGE("NPU get device name fail."); - } else { - prop.name = std::string(device_name); - } - C10_NPU_CHECK(aclrtGetMemInfo(ACL_HBM_MEM, &device_free, &device_total)); - prop.totalGlobalMem = device_total; - return ∝ -} - -void BindGetDeviceProperties(PyObject* module) { - auto m = py::handle(module).cast(); - m.def("_npu_getDeviceProperties", [](int deviceid) -> NPUDeviceProp* { - return GetDeviceProperties(deviceid); - }, py::return_value_policy::reference); -} static PyObject* THNPModule_initExtension(PyObject* self, PyObject* noargs) { HANDLE_TH_ERRORS @@ -504,7 +462,7 @@ PyObject* THNPModule_prof_start(PyObject* self, PyObject* args) { uint64_t npu_event = THPUtils_unpackLong(value_1); uint64_t aicore_metrics = THPUtils_unpackLong(value_2); pybind11::gil_scoped_release no_gil; - torch_npu::profiler::NpuProfiling::Instance().Start(npu_event, aicore_metrics); + // torch_npu::profiler::NpuProfiling::Instance().Start(npu_event, aicore_metrics); Py_RETURN_NONE; END_HANDLE_TH_ERRORS } @@ -525,7 +483,7 @@ PyObject* THNPModule_enable_e2eProfiler(PyObject* self, PyObject* args) { uint64_t npu_event = THPUtils_unpackLong(value_2); uint64_t aicore_metrics = THPUtils_unpackLong(value_3); pybind11::gil_scoped_release no_gil; - torch_npu::profiler::InitE2eProfiler(dump_path, npu_event, aicore_metrics); + // torch_npu::profiler::init_e2e_profiler(dump_path, npu_event, aicore_metrics); Py_RETURN_NONE; END_HANDLE_TH_ERRORS } @@ -533,7 +491,7 @@ PyObject* THNPModule_enable_e2eProfiler(PyObject* self, PyObject* args) { PyObject* THNPModule_disable_e2eProfiler(PyObject* _unused, PyObject* noargs) { HANDLE_TH_ERRORS pybind11::gil_scoped_release no_gil; - torch_npu::profiler::FinalizeE2eProfiler(); + // torch_npu::profiler::finalize_e2e_profiler(); Py_RETURN_NONE; END_HANDLE_TH_ERRORS } diff --git a/torch_npu/csrc/npu/Module.h b/torch_npu/csrc/npu/Module.h index e2e3a42bab..0ec0dd13af 100644 --- a/torch_npu/csrc/npu/Module.h +++ b/torch_npu/csrc/npu/Module.h @@ -19,8 +19,6 @@ void THNPModule_setDevice(int idx); -void RegisterNPUDeviceProperties(PyObject *module); -void BindGetDeviceProperties(PyObject *module); PyObject * THNPModule_getDevice_wrap(PyObject *self); PyObject * THNPModule_setDevice_wrap(PyObject *self, PyObject *arg); PyObject * THNPModule_getDeviceName_wrap(PyObject *self, PyObject *arg); @@ -28,5 +26,4 @@ PyObject * THNPModule_getDriverVersion(PyObject *self); PyObject * THNPModule_isDriverSufficient(PyObject *self); PyObject * THNPModule_getCurrentBlasHandle_wrap(PyObject *self); -#define CHANGE_UNIT_SIZE 1024.0 #endif diff --git a/torch_npu/csrc/profiler/CMakeLists.txt b/torch_npu/csrc/profiler/CMakeLists.txt index 9a39c2d4d8..42e36fd6a6 100644 --- a/torch_npu/csrc/profiler/CMakeLists.txt +++ b/torch_npu/csrc/profiler/CMakeLists.txt @@ -1,6 +1,6 @@ -FILE(GLOB _PROF_SRCS *.cpp) +#FILE(GLOB _PROF_SRCS *.cpp) -LIST(APPEND PROF_SRCS ${_PROF_SRCS}) +#LIST(APPEND PROF_SRCS ${_PROF_SRCS}) # Pass to parent -set(PROF_SRCS ${PROF_SRCS} PARENT_SCOPE) \ No newline at end of file +#set(PROF_SRCS ${PROF_SRCS} PARENT_SCOPE) \ No newline at end of file diff --git a/torch_npu/csrc/profiler/e2e_profiler.cpp b/torch_npu/csrc/profiler/e2e_profiler.cpp index 543a94d106..7196f41c1b 100644 --- a/torch_npu/csrc/profiler/e2e_profiler.cpp +++ b/torch_npu/csrc/profiler/e2e_profiler.cpp @@ -27,7 +27,7 @@ namespace profiler { aclprofConfig* local_profCfg = nullptr; -void CheckProfilerRet(aclError ret, const char* message) { +void checkProfilerRet(aclError ret, const char* message) { if (ret != ACL_ERROR_NONE) { NPU_LOGE(message); C10_NPU_SHOW_ERR_MSG(); @@ -36,11 +36,11 @@ void CheckProfilerRet(aclError ret, const char* message) { } } -void CheckProfilerRet(aclError ret, const std::string message) { - CheckProfilerRet(ret, message.c_str()); +void checkProfilerRet(aclError ret, const std::string message) { + checkProfilerRet(ret, message.c_str()); } -void InitMsPorf(const std::string dump_path, uint64_t npu_event, +void initMsPorf(const std::string dump_path, uint64_t npu_event, uint64_t aicore_metrics) { // to init MsProf, there are 4 steps: // 1. create profile config, configure option, @@ -88,44 +88,44 @@ void InitMsPorf(const std::string dump_path, uint64_t npu_event, } } -void PushStartTime(at::RecordFunction& fn) { +void pushStartTime(at::RecordFunction& fn) { auto local_stamp_ = at_npu::native::AclprofCreateStamp(); if (local_stamp_ == nullptr) { NPU_LOGE("In npu e2e profiling, aclprofCreateStamp failed, created stamp is nullptr."); return; } auto ret = at_npu::native::AclprofSetStampTraceMessage( - local_stamp_, fn.name().str(), strlen(fn.name().str())); - CheckProfilerRet(ret, "In npu e2e profiling, AclprofSetStampTraceMessage set failed."); + local_stamp_, fn.name(), strlen(fn.name()))); + checkProfilerRet(ret, "In npu e2e profiling, AclprofSetStampTraceMessage set failed."); uint32_t range_id_ = 0; ret = at_npu::native::AclprofRangeStart(local_stamp_, &range_id_); - CheckProfilerRet(ret, "In npu e2e profiling, AclprofRangeStart failed."); + checkProfilerRet(ret, "In npu e2e profiling, AclprofRangeStart failed."); fn.setHandle((uint64_t)range_id_); fn.setForwardThreadId((uint64_t)local_stamp_); } -void PopEndTime(const at::RecordFunction& fn) { +void popEndTime(const at::RecordFunction& fn) { auto ret = at_npu::native::AclprofRangeStop((uint32_t)fn.handle()); - CheckProfilerRet(ret, "In npu e2e profiling, AclprofRangeStop failed."); + checkProfilerRet(ret, "In npu e2e profiling, AclprofRangeStop failed."); at_npu::native::AclprofDestroyStamp((void*)fn.forwardThreadId()); } -void InitE2eProfiler(const std::string dump_path, uint64_t npu_event, +void init_e2e_profiler(const std::string dump_path, uint64_t npu_event, uint64_t aicore_metrics) { - InitMsPorf(dump_path, npu_event, aicore_metrics); + initMsPorf(dump_path, npu_event, aicore_metrics); auto handle = at::addThreadLocalCallback(at::RecordFunctionCallback( [](const at::RecordFunction& fn) -> std::unique_ptr { - torch_npu::profiler::PushStartTime(const_cast(fn)); + // torch_npu::profiler::pushStartTime(const_cast(fn)); return nullptr; }, [](const at::RecordFunction& fn, at::ObserverContext*) { - torch_npu::profiler::PopEndTime(fn); + // torch_npu::profiler::popEndTime(fn); })); } -void FinalizeE2eProfiler() { +void finalize_e2e_profiler() { c10_npu::npuSynchronizeDevice(); auto ret = at_npu::native::AclProfilingStop(local_profCfg); if (ret) { diff --git a/torch_npu/csrc/profiler/e2e_profiler.h b/torch_npu/csrc/profiler/e2e_profiler.h index 60a5449029..44959e0926 100644 --- a/torch_npu/csrc/profiler/e2e_profiler.h +++ b/torch_npu/csrc/profiler/e2e_profiler.h @@ -29,15 +29,15 @@ namespace torch_npu { namespace profiler { -void InitMsPorf(const std::string dump_path, uint64_t npu_event, +void initMsPorf(const std::string dump_path, uint64_t npu_event, uint64_t aicore_metrics); -void PushStartTime(at::RecordFunction& fn); -void PopEndTime(const at::RecordFunction& fn); +void pushStartTime(at::RecordFunction& fn); +void popEndTime(const at::RecordFunction& fn); -void InitE2eProfiler(const std::string dump_path, uint64_t npu_event, uint64_t aicore_metrics); +void init_e2e_profiler(const std::string dump_path, uint64_t npu_event, uint64_t aicore_metrics); -void FinalizeE2eProfiler(); +void finalize_e2e_profiler(); } // namespace profiler } // namespace torch_npu diff --git a/torch_npu/csrc/profiler/profiler_legacy.h b/torch_npu/csrc/profiler/profiler_legacy.h index bd85266fd0..6d187de79e 100644 --- a/torch_npu/csrc/profiler/profiler_legacy.h +++ b/torch_npu/csrc/profiler/profiler_legacy.h @@ -29,7 +29,7 @@ #include #include #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #ifndef _WIN32 #include #endif diff --git a/torch_npu/csrc/utils/LazyInit.h b/torch_npu/csrc/utils/LazyInit.h index ba613dae6e..e47f81a8e0 100644 --- a/torch_npu/csrc/utils/LazyInit.h +++ b/torch_npu/csrc/utils/LazyInit.h @@ -1,6 +1,6 @@ #pragma once #include -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" #include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h" namespace torch_npu { diff --git a/torch_npu/csrc/utils/TensorMethods.cpp b/torch_npu/csrc/utils/TensorMethods.cpp index 73a9444f43..0ca249d86c 100644 --- a/torch_npu/csrc/utils/TensorMethods.cpp +++ b/torch_npu/csrc/utils/TensorMethods.cpp @@ -243,7 +243,7 @@ static PyObject * THPVariable_record_stream(PyObject* self, PyObject* args) if (!PyArg_ParseTuple(args, "OO", &_tensor, &_stream)) { throw torch::TypeError("record_stream useage: tensor.record_stream(stream)"); } - auto& self_ = reinterpret_cast(_tensor)->cdata; + auto& self_ = THPVariable_Unpack(_tensor); c10_npu::NPUCachingAllocator::recordStream(self_.storage().data_ptr(), c10_npu::NPUStream::unpack(((THNPStream*)_stream)->cdata)); Py_RETURN_NONE; END_HANDLE_TH_ERRORS diff --git a/torch_npu/csrc/utils/TensorMethods.h b/torch_npu/csrc/utils/TensorMethods.h index 06d78d69ed..f2ced74436 100644 --- a/torch_npu/csrc/utils/TensorMethods.h +++ b/torch_npu/csrc/utils/TensorMethods.h @@ -15,7 +15,7 @@ #include "torch_npu/csrc/core/npu/NPUCachingAllocator.h" #include "torch_npu/csrc/npu/Stream.h" #include "torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.h" -#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "torch_npu/csrc/aten/XLANativeFunctions.h" namespace torch_npu { namespace utils { diff --git a/torch_npu/distributed/__init__.py b/torch_npu/distributed/__init__.py index e04b96e751..794fa3d0e6 100644 --- a/torch_npu/distributed/__init__.py +++ b/torch_npu/distributed/__init__.py @@ -1,49 +1,49 @@ -import torch_npu +# import torch_npu -__all__ = [ - "Backend", "_backend", "group", "GroupMember", "is_hccl_available", "is_initialized", - "get_backend", "init_process_group", "destroy_process_group", "get_rank", "get_world_size", - "isend", "irecv", "send", "recv", "P2POp", "batch_isend_irecv", "broadcast", "all_reduce", - "all_reduce_coalesced", "reduce", "all_gather", "all_gather_coalesced", "gather", "scatter", - "reduce_scatter", "all_to_all_single", "all_to_all", "barrier", "new_group", "ProcessGroupHCCL", - "Reducer", "_DEFAULT_FIRST_BUCKET_BYTES", "_register_comm_hook", "_register_builtin_comm_hook", - "_broadcast_coalesced", "_compute_bucket_assignment_by_size", "_set_construction_logging_data", - "_get_ddp_logging_data", "_get_global_rank" -] +# __all__ = [ +# "Backend", "_backend", "group", "GroupMember", "is_hccl_available", "is_initialized", +# "get_backend", "init_process_group", "destroy_process_group", "get_rank", "get_world_size", +# "isend", "irecv", "send", "recv", "P2POp", "batch_isend_irecv", "broadcast", "all_reduce", +# "all_reduce_coalesced", "reduce", "all_gather", "all_gather_coalesced", "gather", "scatter", +# "reduce_scatter", "all_to_all_single", "all_to_all", "barrier", "new_group", "ProcessGroupHCCL", +# "Reducer", "_DEFAULT_FIRST_BUCKET_BYTES", "_register_comm_hook", "_register_builtin_comm_hook", +# "_broadcast_coalesced", "_compute_bucket_assignment_by_size", "_set_construction_logging_data", +# "_get_ddp_logging_data", "_get_global_rank" +# ] -def is_available(): - """ - Returns ``True`` if the distributed package is available. Otherwise, - ``torch.distributed`` does not expose any other APIs. Currently, - ``torch.distributed`` is available on Linux, MacOS and Windows. Set - ``USE_DISTRIBUTED=1`` to enable it when building PyTorch from source. - Currently, the default value is ``USE_DISTRIBUTED=1`` for Linux and Windows, - ``USE_DISTRIBUTED=0`` for MacOS. - """ - return hasattr(torch_npu._C, "_c10d_init") +# def is_available(): +# """ +# Returns ``True`` if the distributed package is available. Otherwise, +# ``torch.distributed`` does not expose any other APIs. Currently, +# ``torch.distributed`` is available on Linux, MacOS and Windows. Set +# ``USE_DISTRIBUTED=1`` to enable it when building PyTorch from source. +# Currently, the default value is ``USE_DISTRIBUTED=1`` for Linux and Windows, +# ``USE_DISTRIBUTED=0`` for MacOS. +# """ +# return hasattr(torch_npu._C, "_c10d_init") -if is_available() and not torch_npu._C._c10d_init(): - raise RuntimeError("Failed to initialize torch_npu.distributed") +# if is_available() and not torch_npu._C._c10d_init(): +# raise RuntimeError("Failed to initialize torch_npu.distributed") -from torch_npu._C._distributed_c10d import ( - Reducer, - _DEFAULT_FIRST_BUCKET_BYTES, - _register_comm_hook, - _register_builtin_comm_hook, - _broadcast_coalesced, - _compute_bucket_assignment_by_size, - _set_construction_logging_data, - _get_ddp_logging_data -) -from .distributed_c10d import Group as group -from .distributed_c10d import ( - _backend, Backend, GroupMember, is_hccl_available, is_initialized, get_backend, - init_process_group, destroy_process_group, get_rank, get_world_size, isend, - irecv, send, recv, P2POp, batch_isend_irecv, broadcast, all_reduce, all_reduce_coalesced, - reduce, all_gather, all_gather_coalesced, gather, scatter, reduce_scatter, - all_to_all_single, all_to_all, barrier, new_group, ProcessGroupHCCL, _get_global_rank -) +# from torch_npu._C._distributed_c10d import ( +# Reducer, +# _DEFAULT_FIRST_BUCKET_BYTES, +# _register_comm_hook, +# _register_builtin_comm_hook, +# _broadcast_coalesced, +# _compute_bucket_assignment_by_size, +# _set_construction_logging_data, +# _get_ddp_logging_data +# ) +# from .distributed_c10d import Group as group +# from .distributed_c10d import ( +# _backend, Backend, GroupMember, is_hccl_available, is_initialized, get_backend, +# init_process_group, destroy_process_group, get_rank, get_world_size, isend, +# irecv, send, recv, P2POp, batch_isend_irecv, broadcast, all_reduce, all_reduce_coalesced, +# reduce, all_gather, all_gather_coalesced, gather, scatter, reduce_scatter, +# all_to_all_single, all_to_all, barrier, new_group, ProcessGroupHCCL, _get_global_rank +# ) diff --git a/torch_npu/distributed/distributed_c10d.py b/torch_npu/distributed/distributed_c10d.py index 3db53c9c40..e1cec5df88 100644 --- a/torch_npu/distributed/distributed_c10d.py +++ b/torch_npu/distributed/distributed_c10d.py @@ -1585,33 +1585,17 @@ def all_to_all_single(output_tensor, _check_single_tensor(input_tensor, "input") output_split_sizes = [] if output_split_sizes is None else output_split_sizes input_split_sizes = [] if input_split_sizes is None else input_split_sizes - input_format = torch.get_npu_format(input_tensor) - output_format = torch.get_npu_format(output_tensor) - judge_format = input_format != 0 and input_format != 2 - - if input_format != output_format: - raise RuntimeError("Input and output formats should be the same!") - in_tensor = input_tensor - out_tensor = output_tensor - if judge_format: - in_tensor = torch.npu_format_cast(input_tensor, 2) - out_tensor = torch.npu_format_cast(output_tensor, 2) if group is None: default_pg = _get_default_group() - work = default_pg.alltoall_base(out_tensor, in_tensor, output_split_sizes, input_split_sizes, opts) + work = default_pg.alltoall_base(output_tensor, input_tensor, output_split_sizes, input_split_sizes, opts) else: - work = group.alltoall_base(out_tensor, in_tensor, output_split_sizes, input_split_sizes, opts) - + work = group.alltoall_base(output_tensor, input_tensor, output_split_sizes, input_split_sizes, opts) + if async_op: - if judge_format: - raise RuntimeError("This format can't be operated asynchronously, please convert to ND or NCHW!") - else: - return work + return work else: work.wait() - if judge_format: - output_tensor.copy_(out_tensor) def all_to_all(output_tensor_list, input_tensor_list, diff --git a/torch_npu/hooks/__init__.py b/torch_npu/hooks/__init__.py deleted file mode 100644 index 2443fa6eec..0000000000 --- a/torch_npu/hooks/__init__.py +++ /dev/null @@ -1,44 +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. - - -__all__ = ["register_acc_cmp_hook", "set_dump_path", "seed_all"] - - -import os -import random -import torch -import numpy as np - -from . import wrap_tensor, wrap_torch -from .module import register_acc_cmp_hook -from .hooks import set_dump_path - -wrap_tensor.wrap_tensor_ops_and_bind() -for attr_name in dir(wrap_tensor.HOOKTensor): - if attr_name.startswith("wrap_"): - setattr(torch.Tensor, attr_name[5:], getattr(wrap_tensor.HOOKTensor, attr_name)) - -wrap_torch.wrap_torch_ops_and_bind() -for attr_name in dir(wrap_torch.HOOKTorchOP): - if attr_name.startswith("wrap_"): - setattr(torch, attr_name[5:], getattr(wrap_torch.HOOKTorchOP, attr_name)) - - -def seed_all(seed=1234): - random.seed(seed) - os.environ['PYTHONHASHSEED'] = str(seed) - np.random.seed(seed) - torch.manual_seed(seed) diff --git a/torch_npu/hooks/hooks.py b/torch_npu/hooks/hooks.py deleted file mode 100644 index 17e2677b62..0000000000 --- a/torch_npu/hooks/hooks.py +++ /dev/null @@ -1,53 +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. - - -import os -import json -import stat -import torch - - -def set_dump_path(fpath=None): - if fpath is None: - return - os.environ["DUMP_PATH"] = fpath - - -def get_dump_path(): - assert "DUMP_PATH" in os.environ, "Please set dump path for hook tools." - return os.environ.get("DUMP_PATH") - - -def dump_tensor(x, prefix=""): - f = os.fdopen(os.open(get_dump_path(), os.O_RDWR|os.O_CREAT, stat.S_IWUSR|stat.S_IRUSR), "a") - if isinstance(x, (tuple, list)) and x: - for i, item in enumerate(x): - dump_tensor(item, prefix="{}.{}".format(prefix, i)) - elif isinstance(x, torch.Tensor): - list_tensor = x.contiguous().view(-1).cpu().detach().float().numpy().tolist() - json.dump([prefix, list_tensor, str(x.dtype), tuple(x.shape)], f) - f.write('\n') - - f.close() - - -def warp_acc_cmp_hook(name): - def acc_cmp_hook(module, in_feat, out_feat): - name_template = f"{name}"+ "_{}" - dump_tensor(in_feat, name_template.format("input")) - dump_tensor(out_feat, name_template.format("output")) - - return acc_cmp_hook diff --git a/torch_npu/hooks/module.py b/torch_npu/hooks/module.py deleted file mode 100644 index ea3dadff1e..0000000000 --- a/torch_npu/hooks/module.py +++ /dev/null @@ -1,46 +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. - - -import torch.nn as nn - -from .hooks import warp_acc_cmp_hook, set_dump_path - - -class HOOKModule(nn.Module): - - def __init__(self) -> None: - super(HOOKModule, self).__init__() - prefix = "" - if hasattr(self, "prefix_op_name_"): - prefix = self.prefix_op_name_ - - self.register_forward_hook(warp_acc_cmp_hook(prefix + "forward")) - self.register_backward_hook(warp_acc_cmp_hook(prefix + "backward")) - - -def register_acc_cmp_hook(model, dump_path=None): - assert hasattr(model, "named_modules"), "Please register hooks to nn.Module." - set_dump_path(dump_path) - for _, module in model.named_modules(): - if not hasattr(module, "named_modules") or len(list(module.named_modules())) > 1: - continue - - prefix = "Module_" + module.__class__.__name__ + "_" - if hasattr(module, "prefix_op_name_"): - prefix = module.prefix_op_name_ - - module.register_forward_hook(warp_acc_cmp_hook(prefix + "forward")) - module.register_backward_hook(warp_acc_cmp_hook(prefix + "backward")) diff --git a/torch_npu/hooks/tools/__init__.py b/torch_npu/hooks/tools/__init__.py deleted file mode 100644 index fe9ecb62d8..0000000000 --- a/torch_npu/hooks/tools/__init__.py +++ /dev/null @@ -1,21 +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. - - -__all__ = ["compare"] - - -from .acc_compare import compare - diff --git a/torch_npu/hooks/tools/acc_compare.py b/torch_npu/hooks/tools/acc_compare.py deleted file mode 100644 index ae39baa93d..0000000000 --- a/torch_npu/hooks/tools/acc_compare.py +++ /dev/null @@ -1,142 +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. - - -import json -import argparse -import numpy as np -import pandas as pd - - -def cosine_similarity(a, b): - a, b = np.mat(a), np.mat(b) - num = float(a * b.T) - denorm = np.linalg.norm(a) * np.linalg.norm(b) - cos = num / denorm - sim = 0.5 + 0.5 * cos - return sim - - -def get_rmse(a, b): - rmse = np.linalg.norm(a - b) / np.sqrt(len(a)) - return rmse - - -def check_op(a, b): - return a["op_name"] == b["op_name"] - - -def merge_tensor(tensor_list): - op_dict = {} - op_dict["op_name"] = [] - op_dict["input_struct"] = [] - op_dict["output_struct"] = [] - op_dict["input_value"] = [] - op_dict["output_value"] = [] - for tensor in tensor_list: - op_dict["op_name"].append(tensor[0]) - if tensor[0].find("input") != -1: - op_dict["input_struct"].append((tensor[2], tensor[3])) - op_dict["input_value"].append(tensor[1]) - else: - op_dict["output_struct"].append((tensor[2], tensor[3])) - op_dict["output_value"].append(tensor[1]) - return op_dict - - -def read_op(ops_queue, pkl_file_handle): - tensor_list = [] - read_flag = True - while True: - tensor_line = pkl_file_handle.readline() - if len(tensor_line) == 0: - read_flag = False - break - tensor_data = json.loads(tensor_line) - tensor_list.append(tensor_data) - if tensor_data[0].find("output") != -1: - ops_queue.append(merge_tensor(tensor_list)) - break - return read_flag - - -def match_op(npu_queue, bench_queue): - if check_op(npu_queue[-1], bench_queue[-1]): - return len(npu_queue)-1, len(bench_queue)-1 - for b_index, b_op in enumerate(bench_queue[0: -1]): - if check_op(npu_queue[-1], b_op): - return len(npu_queue)-1, b_index - for n_index, n_op in enumerate(npu_queue[0: -1]): - if check_op(n_op, bench_queue[-1]): - return n_index, len(bench_queue)-1 - return -1, -1 - - -def get_accuracy(result, n_dict, b_dict): - for index, name in enumerate(n_dict["op_name"]): - if name.find("input") != -1: - n_value = np.array(n_dict["input_value"][index]) - b_value = np.array(b_dict["input_value"][index]) - n_struct = n_dict["input_struct"][index] - b_struct = b_dict["input_struct"][index] - else: - n_value = np.array(n_dict["output_value"][0]) - b_value = np.array(b_dict["output_value"][0]) - n_struct = n_dict["output_struct"][0] - b_struct = b_dict["output_struct"][0] - cos_sim = cosine_similarity(n_value, b_value) - if np.isnan(cos_sim): - cos_sim = "nan" - rmse = get_rmse(n_value, b_value) - result.append([name, n_struct[0], b_struct[0], - n_struct[1], b_struct[1], cos_sim, rmse]) - - -def compare(npu_pkl_path, bench_pkl_path, output_path): - npu_pkl = open(npu_pkl_path, "r") - bench_pkl = open(bench_pkl_path, "r") - npu_ops_queue = [] - bench_ops_queue = [] - result = [] - while True: - npu_file_flag = read_op(npu_ops_queue, npu_pkl) - bench_file_flag = read_op(bench_ops_queue, bench_pkl) - if (not npu_file_flag and not bench_file_flag) \ - or (len(npu_ops_queue) == 0 or len(bench_ops_queue) == 0): - break - n_match_point, b_match_point = match_op(npu_ops_queue, bench_ops_queue) - if n_match_point == -1 and b_match_point == -1: - continue - n_match_data = npu_ops_queue[n_match_point] - b_match_data = bench_ops_queue[b_match_point] - get_accuracy(result, n_match_data, b_match_data) - del npu_ops_queue[0: n_match_point + 1] - del bench_ops_queue[0: b_match_point + 1] - result_df = pd.DataFrame( - result, columns=["Name", "NPU Tensor Dtype", "Bench Tensor Dtype", - "NPU Tensor Shape", "Bench Tensor Shape", "Cosine", "RMSE"]) - result_df.to_csv(output_path, index=False) - npu_pkl.close() - bench_pkl.close() - - -if __name__ == "__main__": - parser = argparse.ArgumentParser() - parser.add_argument('--npu_pkl', type=str, required=True) - parser.add_argument('--bench_pkl', type=str, required=True) - parser.add_argument('--out_path', type=str, required=True) - args = parser.parse_args() - compare(args.npu_pkl, args.bench_pkl, args.out_path) - diff --git a/torch_npu/hooks/wrap_tensor.py b/torch_npu/hooks/wrap_tensor.py deleted file mode 100644 index 0d1f45a058..0000000000 --- a/torch_npu/hooks/wrap_tensor.py +++ /dev/null @@ -1,68 +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. - - -import torch - -from .module import HOOKModule - -_tensor_include_ops = ['__add__', '__div__', '__idiv__', '__isub__', '__mul__', '__sub__', 'abs', 'abs_', 'acos', - 'acos_', 'add', 'add_', 'addbmm', 'addbmm_', 'addcdiv', 'addcdiv_', 'addcmul', 'addcmul_', - 'addmm', 'addmm_', 'addmv', 'addmv_', 'addr', 'addr_', 'baddbmm', 'baddbmm_', 'bernoulli', - 'bernoulli_', 'bitwise_and', 'bitwise_and_', 'bitwise_not', 'bitwise_not_', 'bitwise_or', - 'bitwise_or_', 'bitwise_xor', 'bitwise_xor_', 'bmm', 'ceil', 'ceil_', 'clamp', 'clamp_', - 'clamp_max', 'clamp_max_', 'clamp_min', 'clamp_min_', 'cos', 'cos_', 'cosh', 'cosh_', 'div', - 'div_', 'dot', 'softmax'] - - -def get_tensor_ops(): - global _tensor_include_ops - _tensor_ops = dir(torch._C._TensorBase) - assert set(_tensor_include_ops) <= set(_tensor_ops) - return _tensor_include_ops - -class HOOKTensor(object): - pass - - -class TensorOPTemplate(HOOKModule): - - def __init__(self, op_name): - self.op_name_ = op_name - self.prefix_op_name_ = "Tensor_" + str(op_name) + "_" - super().__init__() - - def forward(self, *args, **kwargs): - return getattr(torch._C._TensorBase, str(self.op_name_))(*args, **kwargs) - - -def wrap_tensor_op(op_name): - def tensor_op_template(*args, **kwargs): - return TensorOPTemplate(op_name)(*args, **kwargs) - return tensor_op_template - - -def add_tensor_ops_hook(torch_ops): - torch_ops_bind_dict = {} - for op_name in torch_ops: - torch_ops_bind_dict[op_name] = wrap_tensor_op(op_name) - return torch_ops_bind_dict - - -def wrap_tensor_ops_and_bind(): - tensor_ops = get_tensor_ops() - tensor_ops_dict = add_tensor_ops_hook(tensor_ops) - for key, value in tensor_ops_dict.items(): - setattr(HOOKTensor, "wrap_" + str(key), value) diff --git a/torch_npu/hooks/wrap_torch.py b/torch_npu/hooks/wrap_torch.py deleted file mode 100644 index f276b6a93f..0000000000 --- a/torch_npu/hooks/wrap_torch.py +++ /dev/null @@ -1,62 +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. - - -import torch - -from .module import HOOKModule - -_torch_include_ops = ['add', 'sub', 'relu', 'batch_norm', 'conv2d'] - -def get_torch_ops(): - global _torch_include_ops - _torch_ops = dir(torch._C._VariableFunctionsClass) - assert set(_torch_include_ops) <= set(_torch_ops) - return _torch_include_ops - - -class HOOKTorchOP(object): - pass - - -class TorchOPTemplate(HOOKModule): - - def __init__(self, op_name): - self.op_name_ = op_name - self.prefix_op_name_ = "Torch_" + str(op_name) + "_" - super().__init__() - - def forward(self, *args, **kwargs): - return getattr(torch._C._VariableFunctionsClass, str(self.op_name_))(*args, **kwargs) - - -def wrap_torch_op(op_name): - def torch_op_template(*args, **kwargs): - return TorchOPTemplate(op_name)(*args, **kwargs) - return torch_op_template - - -def add_torch_ops_hook(torch_dirs): - torch_op_dirs_dict = {} - for op_name in torch_dirs: - torch_op_dirs_dict[op_name] = wrap_torch_op(op_name) - return torch_op_dirs_dict - - -def wrap_torch_ops_and_bind(): - _torch_op_dirs = get_torch_ops() - torch_op_dirs_dict = add_torch_ops_hook(_torch_op_dirs) - for key, value in torch_op_dirs_dict.items(): - setattr(HOOKTorchOP, "wrap_" + str(key), value) diff --git a/torch_npu/npu/__init__.py b/torch_npu/npu/__init__.py index c7a93d5d47..6ef454b7d6 100644 --- a/torch_npu/npu/__init__.py +++ b/torch_npu/npu/__init__.py @@ -16,8 +16,8 @@ __all__ = [ "native_device", "npu_device", "is_initialized", "_lazy_call", "_lazy_init", "init", "set_dump", - "synchronize", "device_count", "set_device", "current_device", "get_device_name", - "get_device_properties", "_get_device_index", "is_available", "device", "device_of", + "synchronize", "device_count", "set_device", "current_device", + "_get_device_index", "is_available", "device", "device_of", "stream", "current_stream", "default_stream", "init_dump", "finalize_dump", "set_dump", "manual_seed", "manual_seed_all", "seed", "seed_all", "initial_seed", "_free_mutex", "caching_allocator_alloc", @@ -26,13 +26,12 @@ __all__ = [ "reset_peak_memory_stats", "reset_max_memory_allocated", "reset_max_memory_cached", "memory_allocated", "max_memory_allocated", "memory_reserved", "max_memory_reserved", "memory_cached", "max_memory_cached", "memory_snapshot", "memory_summary", - "Stream", "Event", "profiler", "set_option", "set_aoe", "profile", "prof_init", - "prof_start", "prof_stop", "prof_finalize", "iteration_start", "iteration_end", + "Stream", "Event", "set_option", "set_aoe", "profile", "prof_init", + "prof_start", "prof_stop", "prof_finalize", "iteration_start", "iteration_end", "profileConfig", "_in_bad_fork", "set_compile_mode", "FloatTensor", "IntTensor", "DoubleTensor", "LongTensor", "ShortTensor", "CharTensor", "ByteTensor", "HalfTensor", "set_mm_bmm_format_nd", "get_mm_bmm_format_nd", - "get_npu_overflow_flag", "clear_npu_overflow_flag", "get_rng_state", "set_rng_state", - "get_rng_state_all", "set_rng_state_all", + "get_npu_overflow_flag", "clear_npu_overflow_flag" ] import torch @@ -40,14 +39,12 @@ import torch from .device import __device__ as native_device from .device import __npu_device__ as npu_device from .utils import (is_initialized, _lazy_call, _lazy_init, init, set_dump, - synchronize, device_count, set_device, current_device, get_device_name, - get_device_properties, _get_device_index, is_available, device, device_of, + synchronize, device_count, set_device, current_device, + _get_device_index, is_available, device, device_of, stream, current_stream, default_stream, init_dump, finalize_dump, set_dump, _in_bad_fork, get_npu_overflow_flag, clear_npu_overflow_flag) -from .random import (manual_seed, manual_seed_all, seed, seed_all, initial_seed, - get_rng_state_all, set_rng_state_all, - get_rng_state, set_rng_state) +from .random import manual_seed, manual_seed_all, seed, seed_all, initial_seed from .memory import (_free_mutex, caching_allocator_alloc, caching_allocator_delete, empty_cache, memory_stats, memory_stats_as_nested_dict, reset_accumulated_memory_stats, reset_peak_memory_stats, @@ -56,10 +53,10 @@ from .memory import (_free_mutex, caching_allocator_alloc, caching_allocator_del memory_cached, max_memory_cached, memory_snapshot, memory_summary) from .streams import Stream, Event from .graph import is_graph_mode, disable_graph_mode, enable_graph_mode, launch_graph -from . import profiler +# from . import profiler from .npu_frontend_enhance import (set_option, set_aoe, profile, prof_init, prof_start, prof_stop, prof_finalize, iteration_start, iteration_end, profileConfig, set_compile_mode, set_mm_bmm_format_nd, get_mm_bmm_format_nd) from .tensor import FloatTensor, IntTensor, DoubleTensor, LongTensor, ShortTensor, CharTensor, ByteTensor, HalfTensor -torch.optim.Optimizer._hook_for_profile = profiler._hook_for_profile \ No newline at end of file +# torch.optim.Optimizer._hook_for_profile = profiler._hook_for_profile \ No newline at end of file diff --git a/torch_npu/npu/amp/grad_scaler.py b/torch_npu/npu/amp/grad_scaler.py index e2aa937dcb..9497c43d8e 100644 --- a/torch_npu/npu/amp/grad_scaler.py +++ b/torch_npu/npu/amp/grad_scaler.py @@ -20,7 +20,7 @@ from typing import Dict, List import torch import torch.distributed as dist -from torch._six import container_abcs +import collections.abc as container_abcs from torch.cuda.amp.grad_scaler import _MultiDeviceReplicator, OptState, _refresh_per_optimizer_state from torch.cuda.amp.grad_scaler import GradScaler as Cuda_GradScaler @@ -209,7 +209,6 @@ class GradScaler(Cuda_GradScaler): def _unscale_grads_(self, optimizer, inv_scale, found_inf, allow_fp16): per_device_found_inf = _NpuMultiDeviceReplicator(found_inf) - per_device_inv_scale = _NpuMultiDeviceReplicator(inv_scale) # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype. # There could be hundreds of grads, so we'd like to iterate through them just once. @@ -217,41 +216,35 @@ class GradScaler(Cuda_GradScaler): # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict # Google says mypy struggles with defaultdicts type annotations. - - per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list)) + def unscale(group, inv_scale, allow_fp16): + for param in group["params"]: + if param.grad is None: + continue + if (not allow_fp16) and param.grad.dtype == torch.float16: + raise ValueError("Attempting to unscale FP16 gradients.") + if param.grad.is_sparse: + # is_coalesced() == False means the sparse grad has values with duplicate indices. + # coalesce() deduplicates indices and adds all values that have the same index. + # For scaled fp16 values, there's a good chance coalescing will cause overflow, + # so we should check the coalesced _values(). + if param.grad.dtype is torch.float16: + param.grad = param.grad.coalesce() + to_unscale = param.grad._values() + else: + to_unscale = param.grad + to_unscale.mul_(inv_scale) + with torch.no_grad(): if self._dynamic: - for group in optimizer.param_groups: - for param in group["params"]: - if param.grad is None: - continue - if (not allow_fp16) and param.grad.dtype == torch.float16: - raise ValueError("Attempting to unscale FP16 gradients.") - if param.grad.is_sparse: - # is_coalesced() == False means the sparse grad has values with duplicate indices. - # coalesce() deduplicates indices and adds all values that have the same index. - # For scaled fp16 values, there's a good chance coalescing will cause overflow, - # so we should check the coalesced _values(). - if param.grad.dtype == torch.float16: - param.grad = param.grad.coalesce() - to_unscale = param.grad._values() - else: - to_unscale = param.grad - - # TODO: is there a way to split by device and dtype without appending in the inner loop? - per_device_and_dtype_grads[to_unscale.device][to_unscale.dtype].append(to_unscale) - - for device, per_dtype_grads in per_device_and_dtype_grads.items(): - for grads in per_dtype_grads.values(): - torch._amp_foreach_non_finite_check_and_unscale_(grads, - per_device_found_inf.get(device), - per_device_inv_scale.get(device)) - if per_device_found_inf.get(device)[0].item() > 0: - self._has_overflow = True - + self._has_overflow = get_npu_overflow_flag() self._sync_dist_overflow_count() + per_device_found_inf_tensor = per_device_found_inf.get(found_inf.device) if self._has_overflow: - per_device_found_inf.get(found_inf.device).add_(1) + per_device_found_inf_tensor.add_(1) + return per_device_found_inf._per_device_tensors + + for group in optimizer.param_groups: + unscale(group, inv_scale, allow_fp16) return per_device_found_inf._per_device_tensors diff --git a/torch_npu/npu/npu_frontend_enhance.py b/torch_npu/npu/npu_frontend_enhance.py index 90f84f26f1..9939fd5f6b 100644 --- a/torch_npu/npu/npu_frontend_enhance.py +++ b/torch_npu/npu/npu_frontend_enhance.py @@ -145,11 +145,11 @@ class profile(object): self.use_e2e_profiler = use_e2e_profiler self.config = config self.entered = False - if not os.path.exists(self.result_path): - try: - os.makedirs(self.result_path) - except Exception: - raise ValueError("the path of '%s' is invaild."%(self.result_path)) + # if not os.path.exists(self.result_path): + # try: + # os.makedirs(self.result_path) + # except Exception: + # raise ValueError("the path of '%s' is invaild."%(self.result_path)) def __enter__(self): if self.entered: diff --git a/torch_npu/npu/profiler.py b/torch_npu/npu/profiler.py index 77c0646f02..0451af7322 100644 --- a/torch_npu/npu/profiler.py +++ b/torch_npu/npu/profiler.py @@ -1,1764 +1,1521 @@ - # 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 os -import stat -import itertools -from typing import Any -from collections import defaultdict, namedtuple -from operator import attrgetter -from typing import Dict, List, Tuple, Optional -import math -from enum import Enum -import functools -import torch_npu - -try: - from contextlib import ContextDecorator -except ImportError: - import functools - - class ContextDecorator(object): # type: ignore[no-redef] - - def __enter__(self): - raise NotImplementedError - - def __exit__(self, exc_type, exc_val, exc_tb): - raise NotImplementedError - - def __call__(self, func): - @functools.wraps(func) - def wrapped(*args, **kwargs): - with self: - return func(*args, **kwargs) - - return wrapped -__all__ = ["profile", "record_function", ] - -if not torch_npu._C._profiler_init(): - raise RuntimeError("proflier initialization failed") - -file_flags = os.O_WRONLY | os.O_CREAT -file_modes = stat.S_IWUSR | stat.S_IRUSR - - -class DeviceType(Enum): - CPU = 0, - CUDA = 1, # CUDA. - MKLDNN = 2, # Reserved for explicit MKLDNN - OPENGL = 3, # OpenGL - OPENCL = 4, # OpenCL - IDEEP = 5, # IDEEP. - HIP = 6, # AMD HIP - FPGA = 7, # FPGA - MSNPU = 8, # MSNPU - XLA = 9, # XLA / TPU - Vulkan = 10, # Vulkan - Metal = 11, # Metal - XPU = 12, # XPU - NPU = 13, # NPU - - -class EventList(list): - """A list of Events (for pretty printing)""" - def __init__(self, *args, **kwargs): - use_cuda = False - use_npu = kwargs.pop('use_npu', True) and torch_npu.npu.is_available() - profile_memory = kwargs.pop('profile_memory', False) - with_flops = kwargs.pop('with_flops', False) - super(EventList, self).__init__(*args, **kwargs) - self._use_cuda = use_cuda - self._use_npu = use_npu - self._profile_memory = profile_memory - self._tree_built = False - self._with_flops = with_flops - assert not (self._use_cuda and self._use_npu), "use_cuda and use_npu can't be True simultaneously." - - def _build_tree(self): - self._populate_cpu_children() - self._remove_dup_nodes() - self._set_backward_stacktraces() - self._tree_built = True - - def __str__(self): - return self.table() - - def _remove_dup_nodes(self): - while True: - to_delete = [] - for idx, _ in enumerate(self): - if (self[idx].cpu_parent is not None and - self[idx].cpu_parent.name == self[idx].name and - len(self[idx].cpu_parent.cpu_children) == 1): - self[idx].cpu_parent.cpu_children = self[idx].cpu_children - self[idx].cpu_parent.kernels = self[idx].kernels # lift kernels up - for ch in self[idx].cpu_children: - ch.cpu_parent = self[idx].cpu_parent - to_delete.append(idx) - if len(to_delete) == 0: - break - new_evts = [ev for ind, ev in enumerate(self) if ind not in to_delete] - self.clear() - self.extend(new_evts) - - def _populate_cpu_children(self): - """Populates child events into each underlying FunctionEvent object. - One event is a child of another if [s1, e1) is inside [s2, e2). Where - s1 and e1 would be start and end of the child event's interval. And - s2 and e2 start and end of the parent event's interval - - Example: In event list [[0, 10], [1, 3], [3, 4]] would have make [0, 10] - be a parent of two other intervals. - - If for any reason two intervals intersect only partially, this function - will not record a parent child relationship between then. - """ - - # Some events can be async (i.e. start and end on different threads), - # since it's generally undefined how to attribute children ranges to - # async ranges, we do not use them when calculating nested ranges and stats - sync_events = [evt for evt in self if not evt.is_async and evt.device_type == DeviceType.CPU] - events = sorted( - sync_events, - key=attrgetter("thread"), - ) - # Group by both thread and node_id, so that events that happen to have - # the same thread_id but are from different nodes aren't incorrectly - # grouped together. - threads = itertools.groupby( - events, key=lambda event: (event.thread, event.node_id) - ) - - # For each thread we keep a stack of current nested parents. - # We maintain the invariant that each interval is a subset of all other - # intervals lower in the stack. - # - # First we sort the intervals by their start time. Then we iterate over them. - # Every time we see a new interval we remove several parents from - # the top until we restore the invariant. Then parent child relationship - # if recorded if the stack is not empty. - # Finally we add new interval to the list - # - # Algorithm has O(N * log(N)) complexity where N is number of - # intervals - for thread_id, thread_events in threads: - thread_events_ = sorted( - thread_events, - key=lambda event: [event.time_range.start, -event.time_range.end], - ) - current_events: List[FunctionEvent] = [] - cur_end = 0 - for event in thread_events_: - while len(current_events) > 0: - parent = current_events[-1] - if event.time_range.start >= parent.time_range.end or \ - event.time_range.end > parent.time_range.end: - # this can't be a parent - current_events.pop() - else: - parent.append_cpu_child(event) - assert ( - event.cpu_parent is None - ), "There is already a CPU parent event for {}".format( - event.key - ) - event.set_cpu_parent(parent) - break - - current_events.append(event) - - def _set_backward_stacktraces(self): - def bw_parent(evt): - if evt is None: - return None - elif evt.scope == 1: # BACKWARD_FUNCTION - return evt - else: - return bw_parent(evt.cpu_parent) - - fwd_stacks = {} - for evt in self: - if bw_parent(evt) is None and evt.stack is not None: - t = (evt.sequence_nr, evt.thread) - if t not in fwd_stacks: - fwd_stacks[t] = evt.stack - - for evt in self: - p = bw_parent(evt) - if p is not None: - assert p.fwd_thread is not None - t = (p.sequence_nr, p.fwd_thread) - if t in fwd_stacks: - evt.stack = fwd_stacks[t] - else: - evt.stack = [] - - @property - def self_cpu_time_total(self): - return sum([event.self_cpu_time_total for event in self]) - - def table(self, sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False): - """Prints an EventList as a nicely formatted table. - - Args: - sort_by (str, optional): Attribute used to sort entries. By default - they are printed in the same order as they were registered. - Valid keys include: ``cpu_time``, ``cuda_time``, ``cpu_time_total``, - ``cuda_time_total``, ``cpu_memory_usage``, ``cuda_memory_usage``, - ``self_cpu_memory_usage``, ``self_cuda_memory_usage``, ``count``. - top_level_events_only(bool, optional): Boolean flag to determine the - selection of events to display. If true, the profiler will only - display events at top level like top-level invocation of python - `lstm`, python `add` or other functions, nested events like low-level - cpu/cuda ops events are omitted for profiler result readability. - - Returns: - A string containing the table. - """ - return build_table( - self, - sort_by=sort_by, - row_limit=row_limit, - max_src_column_width=max_src_column_width, - header=header, - profile_memory=self._profile_memory, - with_flops=self._with_flops, - top_level_events_only=top_level_events_only, - use_cuda=self._use_cuda, - use_npu=self._use_npu) - - def export_chrome_trace(self, path): - """Exports an EventList as a Chrome tracing tools file. - - The checkpoint can be later loaded and inspected under ``chrome://tracing`` URL. - - Args: - path (str): Path where the trace will be written. - """ - with os.fdopen(os.open(path, file_flags, file_modes), 'w') as f: - chrome_events = [] - next_id = 0 - # Use file IO over using json.dump since JSON dumping is very slow and - # this technique is proven to give a 4x speedup. - f.write("[") - for evt in self: - if evt.trace_name is None: - continue - f.write( - '{"name": "%s", ' - '"ph": "X", ' - '"ts": %s, ' - '"dur": %s, ' - '"tid": %s, ' - '"pid": "CPU functions", ' - '"args": {}}, ' - % ( - evt.trace_name, - evt.time_range.start, - evt.time_range.elapsed_us(), - evt.thread - if not evt.is_remote - else f'" node_id:{evt.node_id}, thread_id:{evt.thread} "', - ) - ) - if self._use_cuda: - for k in evt.kernels: - # 's' and 'f' draw Flow arrows from - # the CPU launch to the GPU kernel - f.write('{"name": "%s", ' - '"ph": "s", ' - '"ts": %s, ' - '"tid": %s, ' - '"pid": "CPU functions", ' - '"id": %s, ' - '"cat": "cpu_to_cuda", ' - '"args": {}}, ' % (evt.trace_name, evt.time_range.start, - evt.thread, next_id)) - f.write('{"name": "%s", ' - '"ph": "f", ' - '"ts": %s, ' - '"tid": %s, ' - '"pid": "CUDA functions", ' - '"id": %s, ' - '"cat": "cpu_to_cuda", ' - '"args": {}}, ' % (k.name, k.interval.start, k.device, next_id)) - f.write('{"name": "%s", ' - '"ph": "X", ' - '"ts": %s, ' - '"dur": %s, ' - '"tid": %s, ' - '"pid": "CUDA functions", ' - '"args": {}}, ' % (k.name, k.interval.start, - k.interval.elapsed_us(), k.device)) - next_id += 1 - elif self._use_npu: - for k in evt.kernels: - # 's' and 'f' draw Flow arrows from - # the CPU launch to the GPU kernel - f.write('{"name": "%s", ' - '"ph": "s", ' - '"ts": %s, ' - '"tid": %s, ' - '"pid": "CPU functions", ' - '"id": %s, ' - '"cat": "cpu_to_npu", ' - '"args": {}}, ' % (evt.trace_name, evt.time_range.start, - evt.thread, next_id)) - f.write('{"name": "%s", ' - '"ph": "f", ' - '"ts": %s, ' - '"tid": %s, ' - '"pid": "NPU functions", ' - '"id": %s, ' - '"cat": "cpu_to_npu", ' - '"args": {}}, ' % (k.name, k.interval.start, k.device, next_id)) - f.write('{"name": "%s", ' - '"ph": "X", ' - '"ts": %s, ' - '"dur": %s, ' - '"tid": %s, ' - '"pid": "NPU functions", ' - '"args": {}}, ' % (k.name, k.interval.start, - k.interval.elapsed_us(), k.device)) - next_id += 1 - - # remove trailing whitespace and comma - f.seek(f.tell() - 2, os.SEEK_SET) - f.truncate() - f.write("]") - - def supported_export_stacks_metrics(self): - if self._use_npu: - return ["self_cpu_time_total", "self_npu_time_total"] - return ["self_cpu_time_total", "self_cuda_time_total"] - - def export_stacks(self, path: str, metric: str): - if metric not in self.supported_export_stacks_metrics(): - raise ValueError("metric should be one of: " + str(self.supported_export_stacks_metrics())) - translate_table = str.maketrans(" ;\t\n", "____") - with os.fdopen(os.open(path, file_flags, file_modes), 'w') as f: - for evt in self: - if evt.stack and len(evt.stack) > 0: - metric_value = getattr(evt, metric) - if int(metric_value) > 0: - stack_str = "" - for entry in reversed(evt.stack): - stack_str += entry.translate(translate_table) - stack_str += ";" - stack_str = stack_str[:-1] + " " + str(int(metric_value)) - f.write(stack_str + "\n") - - def key_averages(self, group_by_input_shapes=False, group_by_stack_n=0): - """Averages all function events over their keys. - - Args: - group_by_input_shapes: group entries by - (event name, input shapes) rather than just event name. - This is useful to see which input shapes contribute to the runtime - the most and may help with size-specific optimizations or - choosing the best candidates for quantization (aka fitting a roof line) - - group_by_stack_n: group by top n stack trace entries - - Returns: - An EventList containing FunctionEventAvg objects. - """ - assert self._tree_built - stats: Dict[Tuple[str, ...], FunctionEventAvg] = defaultdict(FunctionEventAvg) - - def get_key(event, group_by_input_shapes, group_by_stack_n) -> Tuple[str, ...]: - key = [str(event.key), str(event.node_id), str(event.device_type), str(event.is_legacy)] - if group_by_input_shapes: - key.append(str(event.input_shapes)) - if group_by_stack_n > 0: - key += event.stack[:group_by_stack_n] - return tuple(key) - for evt in self: - stats[get_key(evt, group_by_input_shapes, group_by_stack_n)].add(evt, self._use_cuda, self._use_npu) - - avg_list = EventList( - stats.values(), - use_cuda=self._use_cuda, - use_npu=self._use_npu, - profile_memory=self._profile_memory, - with_flops=self._with_flops) - for evt in avg_list: - evt.stack = evt.stack[:group_by_stack_n] - if not group_by_input_shapes: - evt.input_shapes = "" - return avg_list - - def total_average(self): - """Averages all events. - - Returns: - A FunctionEventAvg object. - """ - total_stat = FunctionEventAvg() - for evt in self: - total_stat += evt - total_stat.key = None - total_stat.key = 'Total' - return total_stat - -class profile(object): - """Context manager that manages autograd profiler state and holds a summary of results. - Under the hood it just records events of functions being executed in C++ and - exposes those events to Python. You can wrap any code into it and it will - only report runtime of PyTorch functions. - Note: profiler is thread local and is automatically propagated into the async tasks - - Args: - enabled (bool, optional): Setting this to False makes this context manager a no-op. - - use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API. - Adds approximately 4us of overhead to each tensor operation. - - use_npu (bool, optional): Enables timing of NPU events as well using the aclEvent API. - Adds approximately 4us of overhead to each tensor operation. - - record_shapes (bool, optional): If shapes recording is set, information - about input dimensions will be collected. This allows one to see which - dimensions have been used under the hood and further group by them - using prof.key_averages(group_by_input_shape=True). Please note that - shape recording might skew your profiling data. It is recommended to - use separate runs with and without shape recording to validate the timing. - Most likely the skew will be negligible for bottom most events (in a case - of nested function calls). But for higher level functions the total - self cpu time might be artificially increased because of the shape - collection. - - with_flops (bool, optional): If with_flops is set, the profiler will estimate - the FLOPS (floating pointer operations per second) value using the operator's input shape - and total time. This allows one to estimate the hardware performance. Currently, - this option only works for the matrix multiplication and 2D convolution operators. - - profile_memory (bool, optional): track tensor memory allocation/deallocation. - - with_stack (bool, optional): record source information (file and line number) for the ops. - - use_kineto (bool, optional): experimental, enable profiling with Kineto profiler. - - use_cpu (bool, optional): profile CPU events; setting to ``False`` requires - ``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling. - - .. warning: - Enabling memory profiling or source attribution incurs additional profiler - overhead - - .. warning: - This context managers should not be called recursively, i.e. no nested - instances are allowed - - .. warning: - Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_), - one cannot use the profiler with ``use_cuda = True`` to benchmark - DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading, - please use ``use_cuda = False`` or ``num_workers = 0``. - - Example: - >>> x = torch.randn((1, 1), requires_grad=True) - >>> with torch.autograd.profiler.profile() as prof: - >>> for _ in range(100): # any normal python code, really! - >>> y = x ** 2 - >> y.backward() - >>> # NOTE: some columns were removed for brevity - >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) - ----------------------------------- --------------- --------------- --------------- - Name Self CPU total CPU time avg Number of Calls - ----------------------------------- --------------- --------------- --------------- - mul 32.048ms 32.048ms 200 - pow 27.041ms 27.041ms 200 - PowBackward0 9.727ms 55.483ms 100 - torch::autograd::AccumulateGrad 9.148ms 9.148ms 100 - torch::autograd::GraphRoot 691.816us 691.816us 100 - ----------------------------------- --------------- --------------- --------------- - - """ - def __init__( - self, - enabled=True, - *, - use_cuda=False, - use_npu=False, - record_shapes=False, - with_flops=False, - profile_memory=False, - with_stack=False, - use_kineto=False, - use_cpu=True, - use_npu_simple=False): - self.enabled: bool = enabled - if not self.enabled: - return - self.use_cuda = use_cuda - self.use_npu = use_npu - self.use_npu_simple = use_npu_simple - self.function_events = None - self.entered = False - self.record_shapes = record_shapes - self.with_flops = with_flops - self.record_shapes |= self.with_flops - self.profile_memory = profile_memory - self.with_stack = with_stack - self.use_cpu = use_cpu - self.kineto_results = None - if not self.use_cpu: - assert use_kineto, \ - "Device-only events supported only with Kineto (use_kineto=True)" - - self.profiler_kind = None - self.kineto_activities = set() - if self.use_cuda: - # legacy CUDA mode - self.profiler_kind = torch_npu._C._profiler.ProfilerState.CUDA - elif self.use_npu: - self.profiler_kind = torch_npu._C._profiler.ProfilerState.NPU - else: - self.profiler_kind = torch_npu._C._profiler.ProfilerState.CPU - - - def config(self): - assert self.profiler_kind is not None - return torch_npu._C._profiler.ProfilerConfig( - self.profiler_kind, - self.record_shapes, - self.profile_memory, - self.with_stack, - self.with_flops, - self.use_npu_simple) - - def __enter__(self): - if not self.enabled: - raise RuntimeError("profiler is not enable") - if self.entered: - raise RuntimeError("profiler context manager is not reentrant") - self.entered = True - torch_npu._C._profiler._enable_profiler_legacy(self.config()) - return self - - def _prepare_kineto_trace(self): - assert self.kineto_activities - self.entered = True - torch_npu._C._profiler._prepare_profiler(self.config(), self.kineto_activities) - - def __exit__(self, exc_type, exc_val, exc_tb): - if not self.enabled: - raise RuntimeError("profiler is not enable") - records = torch_npu._C._profiler._disable_profiler_legacy() - parsed_results = parse_legacy_records(records) - self.function_events = EventList( - parsed_results, - use_cuda=self.use_cuda, - use_npu=self.use_npu, - profile_memory=self.profile_memory, - with_flops=self.with_flops) - self.function_events._build_tree() - return False - - def __repr__(self): - if self.function_events is None: - return '' - return repr(self.function_events) - - def __str__(self): - if self.function_events is None: - return '' - return str(self.function_events) - - def _check_finish(self): - if self.function_events is None: - raise RuntimeError("can't export a trace that didn't finish running") - - def table(self, sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False): - self._check_finish() - assert self.function_events is not None - return self.function_events.table( - sort_by=sort_by, row_limit=row_limit, max_src_column_width=max_src_column_width, header=header, - top_level_events_only=top_level_events_only - ) - table.__doc__ = EventList.table.__doc__ - - def export_chrome_trace(self, path): - self._check_finish() - if self.kineto_results is not None: - raise RuntimeError("not support for kineto.") - else: - assert self.function_events is not None - return self.function_events.export_chrome_trace(path) - export_chrome_trace.__doc__ = EventList.export_chrome_trace.__doc__ - - def export_stacks(self, path: str, metric: str = "self_cpu_time_total"): - self._check_finish() - assert self.function_events is not None, "Expected profiling results" - assert self.with_stack, "export_stacks() requires with_stack=True" - return self.function_events.export_stacks(path, metric) - - def key_averages(self, group_by_input_shape=False, group_by_stack_n=0): - self._check_finish() - assert self.function_events is not None, "Expected profiling results" - return self.function_events.key_averages(group_by_input_shape, group_by_stack_n) - key_averages.__doc__ = EventList.key_averages.__doc__ - - def total_average(self): - self._check_finish() - assert self.function_events is not None, "Expected profiling results" - return self.function_events.total_average() - total_average.__doc__ = EventList.total_average.__doc__ - - @property - def self_cpu_time_total(self): - """ Returns total time spent on CPU obtained as a sum of - all self times across all the events. - """ - self._check_finish() - assert self.function_events is not None - return self.function_events.self_cpu_time_total - - -class record_function(ContextDecorator): - """Context manager/function decorator that adds a label to a block of - Python code (or function) when running autograd profiler. It is - useful when tracing the code profile. - - Args: - name (str): Label assigned to the block of code. - node_id (int): ID of node, for distributed profiling. Unset in - non-distributed cases. - - Example: - >>> x = torch.randn((1, 1), requires_grad=True) - >>> with torch.autograd.profiler.profile() as prof: - ... y = x ** 2 - ... with torch.autograd.profiler.record_function("label-z"): # label the block - ... z = y ** 3 - ... y.backward() - ... - >>> # NOTE: some columns were removed for brevity - >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) - ----------------------------------- --------------- --------------- --------------- - Name Self CPU total % CPU time avg Number of Calls - ----------------------------------- --------------- --------------- --------------- - pow 60.77% 47.470us 3 - mul 21.73% 25.465us 2 - PowBackward0 12.03% 121.891us 1 - torch::autograd::AccumulateGrad 2.70% 6.324us 1 - label-z 2.13% 12.421us 1 - torch::autograd::GraphRoot 0.64% 1.503us 1 - ----------------------------------- --------------- --------------- --------------- - Self CPU time total: 234.344us - CUDA time total: 0.000us - - """ - def __init__(self, name: str): - self.name: str = name - # Whether or not we should run record function's end callbacks when exiting. - self.run_callbacks_on_exit: bool = True - # Stores underlying RecordFunction as a tensor. TODO: move to custom - # class (https://github.com/pytorch/pytorch/issues/35026). - self.handle = None - - def __enter__(self): - self.handle = torch_npu._C._profiler._record_function_enter(self.name) - return self - - def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any): - if self.run_callbacks_on_exit: - torch_npu._C._profiler._record_function_exit(self.handle) - - def _call_end_callbacks_on_future(self, fut): - """call_end_callbacks_on_future is meant to be used for profiling async - calls that return a future. Calling this function will extend recording - beyond this scope, until the future is satisfied. It is useful for profiling - the end to end time of asynchronous calls. This function should only be called - once to attach the callback onto the future, and will throw if called multiple - times. - - Args: - fut: (torch._C.Future): future for which to schedule - callback for. - - Returns: - A future that completes with the value of the passed in future when - the profiling callbacks have ran. - - """ - # Throw if we have already attached a callback onto the future. - if not self.run_callbacks_on_exit: - raise RuntimeError("_call_end_callbacks_on_future can only be called once.") - - # We are scheduling to run this RecordFunction's end callbacks when the - # passed in future completes, so don't run end callbacks on exit. - self.run_callbacks_on_exit = False - profiled_future = None - return profiled_future - - -def _hook_for_profile(self): - self._zero_grad_profile_name = "Optimizer.zero_grad#{}.zero_grad".format(self.__class__.__name__) - - def profile_hook_step(func): - - @functools.wraps(func) - def wrapper(*args, **kwargs): - obj, *_ = args - profile_name = "Optimizer.step#{}.step".format(obj.__class__.__name__) - with record_function(profile_name): - return func(*args, **kwargs) - return wrapper - - hooked = getattr(self.__class__.step, "hooked", None) - if not hooked: - self.__class__.step = profile_hook_step(self.__class__.step) - self.__class__.step.hooked = True - -def load_nvprof(path): - """Opens an nvprof trace file and parses autograd annotations. - - Args: - path (str): path to nvprof trace - """ - return EventList(parse_nvprof_trace(path)) - - -################################################################################ -# FunctionEvent - -def format_time(time_us): - """Defines how to format time in FunctionEvent""" - US_IN_SECOND = 1000.0 * 1000.0 - US_IN_MS = 1000.0 - if time_us >= US_IN_SECOND: - return '{:.3f}s'.format(time_us / US_IN_SECOND) - if time_us >= US_IN_MS: - return '{:.3f}ms'.format(time_us / US_IN_MS) - return '{:.3f}us'.format(time_us) - - -def format_time_share(time_us, total_time_us): - """Defines how to format time in FunctionEvent""" - if total_time_us == 0: - assert time_us == 0, "Expected time_us == 0 but got {}".format(time_us) - return "NaN" - return '{:.2f}%'.format(time_us * 100.0 / total_time_us) - -def format_memory(nbytes): - """Returns a formatted memory size string""" - KB = 1024 - MB = 1024 * KB - GB = 1024 * MB - if (abs(nbytes) >= GB): - return '{:.2f} Gb'.format(nbytes * 1.0 / GB) - elif (abs(nbytes) >= MB): - return '{:.2f} Mb'.format(nbytes * 1.0 / MB) - elif (abs(nbytes) >= KB): - return '{:.2f} Kb'.format(nbytes * 1.0 / KB) - else: - return str(nbytes) + ' b' - -def attr_formatter(name): - return property(lambda self: format_time(getattr(self, name))) - - -class FormattedTimesMixin(object): - """Helpers for FunctionEvent and FunctionEventAvg. - - The subclass should define `*_time_total` and `count` attributes. - """ - cpu_time_str = attr_formatter('cpu_time') - cuda_time_str = attr_formatter('cuda_time') - npu_time_str = attr_formatter('npu_time') - cpu_time_total_str = attr_formatter('cpu_time_total') - cuda_time_total_str = attr_formatter('cuda_time_total') - npu_time_total_str = attr_formatter('npu_time_total') - self_cpu_time_total_str = attr_formatter('self_cpu_time_total') - self_cuda_time_total_str = attr_formatter('self_cuda_time_total') - self_npu_time_total_str = attr_formatter('self_npu_time_total') - - @property - def cpu_time(self): - return 0.0 if self.count == 0 else 1.0 * self.cpu_time_total / self.count # type: ignore - - @property - def cuda_time(self): - return 0.0 if self.count == 0 else 1.0 * self.cuda_time_total / self.count # type: ignore - - @property - def npu_time(self): - return 0.0 if self.count == 0 else 1.0 * self.npu_time_total / self.count # type: ignore - -class Interval(object): - def __init__(self, start, end): - self.start = start - self.end = end - - def elapsed_us(self): - return self.end - self.start - - -Kernel = namedtuple('Kernel', ['name', 'device', 'interval']) - - -class FunctionEvent(FormattedTimesMixin): - """Profiling information about a single function.""" - def __init__( - self, id_event, name, thread, start_us, end_us, fwd_thread=None, input_shapes=None, - stack=None, scope=0, cpu_memory_usage=0, cuda_memory_usage=0, npu_memory_usage=0, - is_async=False, is_remote=False, sequence_nr=-1, node_id=-1, device_type=DeviceType.CPU, - device_index=0, is_legacy=False, flops=None, trace_name=None): - self.id: int = id_event - self.node_id: int = node_id - self.name: str = name - self.trace_name: str = trace_name - self.time_range: Interval = Interval(start_us, end_us) - self.thread: int = thread - self.fwd_thread: Optional[int] = fwd_thread - self.kernels: List[Kernel] = [] - self.count: int = 1 - self.cpu_children: List[FunctionEvent] = [] - self.cpu_parent: Optional[FunctionEvent] = None - self.input_shapes: Tuple[int, ...] = input_shapes - self.stack: List = stack - self.scope: int = scope - self.cpu_memory_usage: int = cpu_memory_usage - self.cuda_memory_usage: int = cuda_memory_usage - self.npu_memory_usage: int = npu_memory_usage - self.is_async: bool = is_async - self.is_remote: bool = is_remote - self.sequence_nr: int = sequence_nr - self.device_type: DeviceType = device_type - self.device_index: int = device_index - self.is_legacy: bool = is_legacy - self.flops: Optional[float] = flops - - def append_kernel(self, name, device, start, end): - assert self.device_type == DeviceType.CPU - self.kernels.append(Kernel(name, device, Interval(start, end))) - - def append_cpu_child(self, child): - """Append a CPU child of type FunctionEvent. - - One is supposed to append only direct children to the event to have - correct self cpu time being reported. - """ - assert(self.device_type == DeviceType.CPU) - assert(isinstance(child, FunctionEvent)) - assert(child.device_type == DeviceType.CPU) - self.cpu_children.append(child) - - def set_cpu_parent(self, parent): - """Set the immediate CPU parent of type FunctionEvent - - One profiling FunctionEvent should have only one CPU parent such that - the child's range interval is completely inside the parent's. We use - this connection to determine the event is from top-level op or not. - """ - assert(self.device_type == DeviceType.CPU) - assert(isinstance(parent, FunctionEvent)) - assert(parent.device_type == DeviceType.CPU) - self.cpu_parent = parent - - # Note: async events don't have children, are not used when computing 'self' - # metrics of other events, have only total cpu time - @property - def self_cpu_memory_usage(self): - if self.is_async or self.device_type != DeviceType.CPU: - return 0 - return self.cpu_memory_usage - sum( - [child.cpu_memory_usage for child in self.cpu_children] - ) - - @property - def self_cuda_memory_usage(self): - if self.is_async or self.device_type != DeviceType.CPU: - return 0 - return self.cuda_memory_usage - sum( - [child.cuda_memory_usage for child in self.cpu_children] - ) - - @property - def self_npu_memory_usage(self): - if self.is_async or self.device_type != DeviceType.CPU: - return 0 - return self.npu_memory_usage - sum( - [child.npu_memory_usage for child in self.cpu_children] - ) - - @property - def self_cpu_time_total(self): - if self.is_async or self.device_type != DeviceType.CPU: - return 0 - return self.cpu_time_total - sum( - [child.cpu_time_total for child in self.cpu_children] - ) - - @property - def cuda_time_total(self): - if self.is_async: - return 0 - if self.device_type == DeviceType.CPU: - if not self.is_legacy: - # account for the kernels in the children ops - return (sum(kinfo.interval.elapsed_us() for kinfo in self.kernels) + - sum(ch.cuda_time_total for ch in self.cpu_children)) - else: - # each legacy cpu events has a single (fake) kernel - return sum(kinfo.interval.elapsed_us() for kinfo in self.kernels) - else: - assert self.device_type == DeviceType.CUDA - return self.time_range.elapsed_us() - - @property - def self_cuda_time_total(self): - if self.is_async: - return 0 - if self.device_type == DeviceType.CPU: - return self.cuda_time_total - \ - sum([child.cuda_time_total for child in self.cpu_children]) - else: - assert(self.device_type == DeviceType.CUDA) - return self.cuda_time_total - - @property - def npu_time_total(self): - if self.is_async: - return 0 - if self.device_type == DeviceType.CPU: - assert self.is_legacy, "profiling with NPU only support for legacy." - # each legacy cpu events has a single (fake) kernel - return sum(kinfo.interval.elapsed_us() for kinfo in self.kernels) - else: - assert self.device_type == DeviceType.NPU - return self.time_range.elapsed_us() - - @property - def self_npu_time_total(self): - if self.is_async: - return 0 - if self.device_type == DeviceType.CPU: - return self.npu_time_total - \ - sum([child.npu_time_total for child in self.cpu_children]) - else: - assert(self.device_type == DeviceType.NPU) - return self.npu_time_total - - @property - def cpu_time_total(self): - if self.device_type == DeviceType.CPU: - return self.time_range.elapsed_us() - else: - return 0 - - @property - def key(self): - return self.name - - def __repr__(self): - return ( - ''.format( - self.id, - self.name, - self.device_type, - self.node_id, - self.cpu_time_str, - self.time_range.start, - self.time_range.end, - str([child.id for child in self.cpu_children]), - self.cuda_time_str, - self.npu_time_str, - self.name, - self.thread, - str(self.input_shapes), - self.cpu_memory_usage, - self.cuda_memory_usage, - self.npu_memory_usage, - self.is_async, - self.is_remote, - self.sequence_nr, - self.is_legacy, - ) - ) - - -class FunctionEventAvg(FormattedTimesMixin): - """Used to average stats over multiple FunctionEvent objects.""" - def __init__(self): - self.key: Optional[str] = None - self.count: int = 0 - self.node_id: int = 0 - self.is_async: bool = False - self.is_remote: bool = False - self.use_cuda = True - self.use_npu = False - self.cpu_time_total: int = 0 - self.cuda_time_total: int = 0 - self.npu_time_total: int = 0 - self.self_cpu_time_total: int = 0 - self.self_cuda_time_total: int = 0 - self.self_npu_time_total: int = 0 - self.input_shapes: Optional[List[List[int]]] = None - self.stack: Optional[List] = None - self.scope: Optional[int] = None - self.cpu_memory_usage: int = 0 - self.cuda_memory_usage: int = 0 - self.npu_memory_usage: int = 0 - self.self_cpu_memory_usage: int = 0 - self.self_cuda_memory_usage: int = 0 - self.self_npu_memory_usage: int = 0 - self.cpu_children: Optional[List[FunctionEvent]] = None - self.cpu_parent: Optional[FunctionEvent] = None - self.device_type: DeviceType = DeviceType.CPU - self.is_legacy: bool = False - self.flops: float = 0.0 - - def add(self, other, use_cuda=True, use_npu=False): - self.use_cuda = use_cuda - self.use_npu = use_npu - if self.key is None: - # First function being recorded as part of FunctionEventAvg, propagate - # fields. - self.key = other.key - self.node_id = other.node_id - self.is_async = other.is_async - self.is_remote = other.is_remote - self.cpu_parent = other.cpu_parent - self.cpu_children = other.cpu_children - - self.input_shapes = other.input_shapes - self.stack = other.stack - self.scope = other.scope - self.device_type = other.device_type - self.is_legacy = other.is_legacy - - assert isinstance(other, (FunctionEvent, FunctionEventAvg)) - assert other.key == self.key - self.cpu_time_total += other.cpu_time_total - self.self_cpu_time_total += other.self_cpu_time_total - self.cpu_memory_usage += other.cpu_memory_usage - self.self_cpu_memory_usage += other.self_cpu_memory_usage - self.count += other.count - if self.use_cuda: - self.cuda_time_total += other.cuda_time_total - self.self_cuda_time_total += other.self_cuda_time_total - self.cuda_memory_usage += other.cuda_memory_usage - self.self_cuda_memory_usage += other.self_cuda_memory_usage - elif self.use_npu: - self.npu_time_total += other.npu_time_total - self.self_npu_time_total += other.self_npu_time_total - self.npu_memory_usage += other.npu_memory_usage - self.self_npu_memory_usage += other.self_npu_memory_usage - if self.flops is None: - self.flops = other.flops - elif other.flops is not None: - self.flops += other.flops - return self - - def __iadd__(self, other): - return self.add(other) - - def __repr__(self): - if self.use_npu: - return ( - ''.format( - self.key, - self.self_cpu_time_total_str, - self.cpu_time_str, - self.self_npu_time_total_str, - self.npu_time_str, - str(self.input_shapes), - self.cpu_memory_usage, - self.npu_memory_usage, - ) - ) - else: - return ( - ''.format( - self.key, - self.self_cpu_time_total_str, - self.cpu_time_str, - self.self_cuda_time_total_str, - self.cuda_time_str, - str(self.input_shapes), - self.cpu_memory_usage, - self.cuda_memory_usage, - ) - ) - - -################################################################################ -# Utilities - -class StringTable(defaultdict): - def __missing__(self, key): - # manage cases like 't' (demangled to 'unsigned short') separately, - # for now simply check the length to avoid unexpected results for - # the short sequences - self[key] = key - return self[key] - -def filter_stack_entry(entry): - filtered_entries = [ - ("autograd/__init__", "_make_grads"), - ("autograd/__init__", "backward"), - ("torch/tensor", "backward"), - ("_internal/common_utils", "prof_callable"), - ("_internal/common_utils", "prof_func_call"), - ("_internal/common_utils", "prof_meth_call"), - ] - return all([not (f[0] in entry and f[1] in entry) for f in filtered_entries]) - -def filter_name(name): - # ignoring the following utility ops - filtered_out_names = [ - "profiler::_record_function_enter", - "profiler::_record_function_exit", - "aten::is_leaf", - "aten::output_nr", - "aten::_version", - ] - return name in filtered_out_names - -# Demangles and optionally rewrites the provided event name, -# with_wildcard - whether to replace certain numbered event names -# with a wildcard name to aggregate them together in the profiler table -# output -def rewrite_name(name, with_wildcard=False): - string_table = StringTable() - name = string_table[name] - if with_wildcard: - if name.startswith("ProfilerStep#"): - name = "ProfilerStep*" - return name - -# Parsing of kineto profiler events -def parse_kineto_results(result): - # result.events() has most of the events - PyTorch op-level and device-level events - # result.legacy_events() has events not yet ported to kineto - # (e.g. start/stop marks, tensor memory allocator events) - - # First, find __start_profile mark to get the absolute time of the start of the trace; - # save memory allocation records - start_record = None - mem_records = [] - for record in itertools.chain(*result.legacy_events()): - if record.kind() == 'mark' and record.name() == '__start_profile': - assert start_record is None - start_record = record - if record.kind() == 'memory_alloc': - mem_records.append([record, False]) - assert start_record is not None, "Invalid profiler output, __start_profile is missing" - - # Create and return FunctionEvent list - function_events = [] - cuda_corr_map: Dict[int, List[FunctionEvent]] = {} - for kineto_event in result.events(): - if filter_name(kineto_event.name()): - continue - rel_start_us = kineto_event.start_us() - start_record.start_us() - rel_end_us = rel_start_us + kineto_event.duration_us() - abs_end_us = kineto_event.start_us() + kineto_event.duration_us() - - cpu_memory_usage = 0 - cuda_memory_usage = 0 - if kineto_event.device_type() == DeviceType.CPU: - # find the corresponding memory allocation events - for mem_record in mem_records: - if (mem_record[0].start_us() >= kineto_event.start_us() and - mem_record[0].start_us() <= abs_end_us): - cpu_memory_usage += mem_record[0].cpu_memory_usage() - cuda_memory_usage += mem_record[0].cuda_memory_usage() - mem_record[1] = True - - is_async = kineto_event.start_thread_id() != kineto_event.end_thread_id() - fe = FunctionEvent( - id_event=kineto_event.correlation_id(), - name=rewrite_name(name=kineto_event.name(), with_wildcard=True), - trace_name=rewrite_name(name=kineto_event.name(), with_wildcard=False), - thread=kineto_event.start_thread_id(), - start_us=rel_start_us, - end_us=rel_end_us, - fwd_thread=kineto_event.fwd_thread_id(), - input_shapes=kineto_event.shapes(), - stack=[entry for entry in kineto_event.stack() if filter_stack_entry(entry)], - scope=kineto_event.scope(), - cpu_memory_usage=cpu_memory_usage, - cuda_memory_usage=cuda_memory_usage, - is_async=is_async, - sequence_nr=kineto_event.sequence_nr(), - device_type=kineto_event.device_type(), - device_index=kineto_event.device_index(), - flops=kineto_event.flops(), - ) - function_events.append(fe) - corr_id = kineto_event.linked_correlation_id() - if corr_id > 0: - if corr_id not in cuda_corr_map: - cuda_corr_map[corr_id] = [] - cuda_corr_map[corr_id].append(fe) - - # associate CUDA kernels and CUDA runtime (CPU) with CPU events - for fe in function_events: - if (fe.device_type == DeviceType.CPU and not fe.is_async and - fe.id in cuda_corr_map): - for f_evt in cuda_corr_map[fe.id]: - if f_evt.device_type == DeviceType.CUDA: - fe.append_kernel( - f_evt.name, - f_evt.device_index, - f_evt.time_range.start, - f_evt.time_range.end) - elif f_evt.device_type == DeviceType.CPU: - # make sure that 'thread' of a CPU Kineto (e.g. CUDA Runtime) event is associated - # with the 'thread' of the corresponding linked PyTorch event to properly track - # parents and children - f_evt.thread = fe.thread - - - # output top-level memory events - for mem_record in mem_records: - if not mem_record[1]: - fe = FunctionEvent( - id_event=mem_record[0].handle(), - name="[memory]", - trace_name=None, # not outputting in the trace - thread=mem_record[0].thread_id(), - start_us=mem_record[0].start_us(), - end_us=mem_record[0].start_us(), # no duration - fwd_thread=mem_record[0].fwd_thread_id(), - input_shapes=[], - stack=[], - scope=mem_record[0].scope(), - cpu_memory_usage=mem_record[0].cpu_memory_usage(), - cuda_memory_usage=mem_record[0].cuda_memory_usage(), - is_async=False, - sequence_nr=-1, - device_type=DeviceType.CPU, - device_index=0, - ) - function_events.append(fe) - - function_events.sort(key=lambda evt: [evt.time_range.start, -evt.time_range.end]) - return function_events - -# Parsing of legacy profiler events -def parse_legacy_records(thread_records): - def get_record_key(record): - """ - Returns a tuple to be used by parse_legacy_records for correlating start and - end records. - """ - return (record.handle(), record.node_id()) - - next_id = 0 - start_record = None - cuda_records = {} - npu_records = {} - functions = [] - record_stack = [] - profiler_type = DeviceType.CPU - - # cuda start events and the overall profiler start event don't happen - # at exactly the same time because we need to record an event on each device - # and each record takes ~4us. So we adjust here by the difference - # adding the difference in CPU time between the profiler start event - # and the CPU time of the cuda start event for the device - def adjusted_time(device_record, device_records_map): - assert device_record.device() != -1 - assert start_record is not None - if device_record.has_cuda(): - cuda_time_0 = device_records_map[(device_record.node_id(), device_record.device())] - return cuda_time_0.cuda_elapsed_us(device_record) + start_record.cpu_elapsed_us(cuda_time_0) - elif device_record.has_npu(): - npu_time_0 = device_records_map[(device_record.node_id(), device_record.device())] - return npu_time_0.npu_elapsed_us(device_record) + start_record.cpu_elapsed_us(npu_time_0) - else: - raise RuntimeError("device_record only support for npu") - - # '__start_profile' is not guaranteed to be first, so we must find it here - for record in itertools.chain(*thread_records): - name = record.name() - if start_record is None and name == '__start_profile': - start_record = record - elif '__cuda_start_event' in name: - # N.B.: Each CUDA device has its own __cuda_start_event. - assert record.device() != -1 - # key for cuda_records is (node_id, device) in case of multiple nodes - # having the same device - cuda_records[(record.node_id(), record.device())] = record - profiler_type = DeviceType.CUDA - elif '__npu_start_event' in name: - # N.B.: Each NPU device has its own __npu_start_event. - assert record.device() != -1 - # key for npu_records is (node_id, device) in case of multiple nodes - # having the same device - npu_records[(record.node_id(), record.device())] = record - profiler_type = DeviceType.NPU - - assert start_record is not None and not start_record.is_remote() - - for thread_record_list in thread_records: - # accumulated memory allocations per handle - cpu_memory_allocs = {} - cuda_memory_allocs = {} - npu_memory_allocs = {} - # ranges per handle - range_starts = {} - - filtered_handles = set() - prev_record = None - for record in thread_record_list: - record_key = get_record_key(record) - if (filter_name(record.name()) or - record_key in filtered_handles): - filtered_handles.add(record_key) - continue - - if record.kind() == 'push': - # workaround to reduce double logging from operator - # wrappers and redispatch - if prev_record is not None: - duplicate = ( - prev_record.name() == record.name() - and prev_record.kind() == record.kind() - and prev_record.node_id() == record.node_id() - ) - if duplicate: - filtered_handles.add(record_key) - continue - - range_starts[record_key] = record - cpu_memory_allocs[record_key] = 0 - cuda_memory_allocs[record_key] = 0 - npu_memory_allocs[record_key] = 0 - elif record.kind() == 'pop': - assert ( - record_key in range_starts - ), """Expected record with key {} to exist in range_starts. - This means that the pop event did not have a corresponding push.""".format( - record_key - ) - - start = range_starts[record_key] - - cpu_memory_usage = cpu_memory_allocs[record_key] - cuda_memory_usage = cuda_memory_allocs[record_key] - npu_memory_usage = npu_memory_allocs[record_key] - is_async = start.thread_id() != record.thread_id() - is_remote_event = record.is_remote() - start_flops = start.flops() - - fe = FunctionEvent( - id_event=record.handle(), - node_id=record.node_id(), - name=rewrite_name(name=start.name(), with_wildcard=True), - trace_name=rewrite_name(name=start.name(), with_wildcard=False), - thread=start.thread_id(), - start_us=start_record.cpu_elapsed_us(start), - end_us=start_record.cpu_elapsed_us(record), - fwd_thread=start.fwd_thread_id(), - input_shapes=start.shapes(), - stack=[entry for entry in start.stack() if filter_stack_entry(entry)], - scope=start.scope(), - cpu_memory_usage=cpu_memory_usage, - cuda_memory_usage=cuda_memory_usage, - npu_memory_usage=npu_memory_usage, - is_async=is_async, - is_remote=is_remote_event, - sequence_nr=start.sequence_nr(), - device_type=DeviceType.CPU, - is_legacy=True, - flops=start_flops, - ) - # note: async events have only cpu total time - if not is_async and start.has_cuda(): - cuda_start = adjusted_time(start, cuda_records) - cuda_end = adjusted_time(record, cuda_records) - if (cuda_end - cuda_start) > 0: - fe.append_kernel( - start.name(), - start.device(), - cuda_start, - cuda_end) - elif not is_async and start.has_npu(): - npu_start = adjusted_time(start, npu_records) - npu_end = adjusted_time(record, npu_records) - if (npu_end - npu_start) > 0: - fe.append_kernel( - start.name(), - start.device(), - npu_start, - npu_end) - functions.append(fe) - del range_starts[record_key] - del cpu_memory_allocs[record_key] - del cuda_memory_allocs[record_key] - del npu_memory_allocs[record_key] - elif record.kind() == 'memory_alloc': - num_open_handles_cpu = len(cpu_memory_allocs) - num_open_handles_cuda = len(cuda_memory_allocs) - assert num_open_handles_cpu == num_open_handles_cuda - for handle in cpu_memory_allocs.keys(): - cpu_memory_allocs[handle] += record.cpu_memory_usage() - for handle in cuda_memory_allocs.keys(): - cuda_memory_allocs[handle] += record.cuda_memory_usage() - for handle in npu_memory_allocs.keys(): - npu_memory_allocs[handle] += record.npu_memory_usage() - if num_open_handles_cpu == 0: - # output event as a top-level memory event - fe = FunctionEvent( - id_event=0, - name="[memory]", - trace_name=None, - thread=0, - start_us=0, - end_us=0, - stack=[], - cpu_memory_usage=record.cpu_memory_usage(), - cuda_memory_usage=record.cuda_memory_usage(), - npu_memory_usage=record.npu_memory_usage(), - is_legacy=True, - ) - functions.append(fe) - prev_record = record - - # Sort functions by start time then by end time ascending. - # This ensures that--in the case of nested events which - # have the same start time (which may happen due to the - # granularity of the given clock tick)--we always show - # the outermost nested call first. This adds stability - # in how FunctionEvents appear - functions.sort(key=lambda evt: [evt.time_range.start, -evt.time_range.end]) - if profiler_type == DeviceType.NPU: - for record in itertools.chain(*thread_records): - if record.has_npu(): - record.npu_destropy_event() - return functions - - -################################################################################ -# CUDA checkpoints - -class EnforceUnique(object): - """Raises an error if a key is seen more than once.""" - def __init__(self): - self.seen = set() - - def see(self, *key): - if key in self.seen: - raise RuntimeError('duplicate key: ' + str(key)) - self.seen.add(key) - - -################################################################################ -# Pretty printer - - -def build_table( - events, - sort_by=None, - header=None, - row_limit=100, - max_src_column_width=75, - with_flops=False, - profile_memory=False, - top_level_events_only=False, - use_cuda=False, - use_npu=False): - """Prints a summary of events (which can be a list of FunctionEvent or FunctionEventAvg).""" - if len(events) == 0: - return "" - - has_cuda_time = any([event.self_cuda_time_total > 0 for event in events]) and use_cuda - has_cuda_mem = any([event.self_cuda_memory_usage > 0 for event in events]) and use_cuda - has_npu_time = any([event.self_npu_time_total > 0 for event in events]) and use_npu - has_npu_mem = any([event.self_npu_memory_usage > 0 for event in events]) and use_npu - has_input_shapes = any( - [(event.input_shapes is not None and len(event.input_shapes) > 0) for event in events]) - - if sort_by is not None: - events = EventList(sorted( - events, key=lambda evt: getattr(evt, sort_by), reverse=True - ), use_cuda=has_cuda_time, use_npu=has_npu_time, profile_memory=profile_memory, with_flops=with_flops) - - MAX_NAME_COLUMN_WIDTH = 55 - name_column_width = max([len(evt.key) for evt in events]) + 4 - name_column_width = min(name_column_width, MAX_NAME_COLUMN_WIDTH) - - DEFAULT_COLUMN_WIDTH = 12 - shapes_column_width = max([len(str(evt.input_shapes)) for evt in events]) + 4 - shapes_column_width = min(shapes_column_width, 45) - - flops_column_width = DEFAULT_COLUMN_WIDTH - - src_column_width = None - stacks = [] - for evt in events: - if evt.stack is not None and len(evt.stack) > 0: - stacks.append(evt.stack) - has_stack = len(stacks) > 0 - if has_stack: - src_column_width = max([max([len(entry) for entry in stack]) for stack in stacks]) + 4 - src_column_width = min(src_column_width, max_src_column_width) - - headers = [ - 'Name', - 'Self CPU %', - 'Self CPU', - 'CPU total %', - 'CPU total', - 'CPU time avg', - ] - if has_cuda_time: - headers.extend([ - 'Self CUDA', - 'Self CUDA %', - 'CUDA total', - 'CUDA time avg', - ]) - if has_npu_time: - headers.extend([ - 'Self NPU', - 'Self NPU %', - 'NPU total', - 'NPU time avg', - ]) - if profile_memory: - headers.extend([ - 'CPU Mem', - 'Self CPU Mem', - ]) - if has_cuda_mem: - headers.extend([ - 'CUDA Mem', - 'Self CUDA Mem', - ]) - if has_npu_mem: - headers.extend([ - 'NPU Mem', - 'Self NPU Mem', - ]) - headers.append( - '# of Calls' - ) - # Only append Node ID if any event has a valid (>= 0) Node ID - append_node_id = any([evt.node_id != -1 for evt in events]) - if append_node_id: - headers.append('Node ID') - - # Have to use a list because nonlocal is Py3 only... - SPACING_SIZE = 2 - row_format_lst = [""] - header_sep_lst = [""] - line_length_lst = [-SPACING_SIZE] - MAX_STACK_ENTRY = 5 - - def add_column(padding, text_dir='>'): - row_format_lst[0] += '{: ' + text_dir + str(padding) + '}' + (' ' * SPACING_SIZE) - header_sep_lst[0] += '-' * padding + (' ' * SPACING_SIZE) - line_length_lst[0] += padding + SPACING_SIZE - - def auto_scale_flops(flops): - flop_headers = [ - 'FLOPS', - 'KFLOPS', - 'MFLOPS', - 'GFLOPS', - 'TFLOPS', - 'PFLOPS', - ] - assert flops > 0 - log_flops = max(0, min(math.log10(flops) / 3, float(len(flop_headers) - 1))) - assert log_flops >= 0 and log_flops < len(flop_headers) - return (pow(10, (math.floor(log_flops) * -3.0)), flop_headers[int(log_flops)]) - - add_column(name_column_width) - for _ in headers[1:]: - add_column(DEFAULT_COLUMN_WIDTH) - - if has_input_shapes: - headers.append('Input Shapes') - add_column(shapes_column_width) - - if has_stack: - headers.append('Source Location') - add_column(src_column_width, text_dir='<') - - if with_flops: - # Auto-scaling of flops header - US_IN_SECOND = 1000.0 * 1000.0 # cpu_time_total is in us - raw_flops = [] - for evt in events: - if evt.flops > 0: - if evt.cuda_time_total != 0: - evt.flops = float(evt.flops) / evt.cuda_time_total * US_IN_SECOND - else: - evt.flops = float(evt.flops) / evt.cpu_time_total * US_IN_SECOND - raw_flops.append(evt.flops) - if len(raw_flops) != 0: - (flops_scale, flops_header) = auto_scale_flops(min(raw_flops)) - headers.append(flops_header) - add_column(flops_column_width) - else: - with_flops = False # can't find any valid flops - - row_format = row_format_lst[0] - header_sep = header_sep_lst[0] - line_length = line_length_lst[0] - add_column = None # type: ignore - - # Have to use a list because nonlocal is Py3 only... - result = [] - - def append(s): - result.append(s) - result.append('\n') # Yes, newline after the end as well - - sum_self_cpu_time_total = sum([event.self_cpu_time_total for event in events]) - sum_self_cuda_time_total = 0 - sum_self_npu_time_total = 0 - for evt in events: - if evt.device_type == DeviceType.CPU: - # in legacy profiler, kernel info is stored in cpu events - if evt.is_legacy: - sum_self_cuda_time_total += evt.self_cuda_time_total - sum_self_npu_time_total += evt.self_npu_time_total - elif evt.device_type == DeviceType.CUDA: - # in kineto profiler, there're events with the correct device type (e.g. CUDA) - sum_self_cuda_time_total += evt.self_cuda_time_total - elif evt.device_type == DeviceType.NPU: - # in kineto profiler, there're events with the correct device type (e.g. CUDA) - sum_self_npu_time_total += evt.self_npu_time_total - - # Actual printing - if header is not None: - append('=' * line_length) - append(header) - if top_level_events_only: - append('=' * line_length) - append('This report only display top-level ops statistics') - append(header_sep) - append(row_format.format(*headers)) - - append(header_sep) - - def trim_path(path, src_column_width): - if len(path) > src_column_width: - offset = len(path) - src_column_width - path = path[offset:] - if len(path) > 3: - path = "..." + path[3:] - return path - - event_limit = 0 - for evt in events: - if event_limit == row_limit: - break - if top_level_events_only and evt.cpu_parent is not None: - continue - else: - event_limit += 1 - name = evt.key - if len(name) >= MAX_NAME_COLUMN_WIDTH - 3: - name = name[:(MAX_NAME_COLUMN_WIDTH - 3)] + "..." - row_values = [ - name, - # Self CPU total %, 0 for async events. - format_time_share(evt.self_cpu_time_total, - sum_self_cpu_time_total), - evt.self_cpu_time_total_str, # Self CPU total - # CPU total %, 0 for async events. - format_time_share(evt.cpu_time_total, sum_self_cpu_time_total) if not evt.is_async else 0, - evt.cpu_time_total_str, # CPU total - evt.cpu_time_str, # CPU time avg - ] - if has_cuda_time: - row_values.extend([ - evt.self_cuda_time_total_str, - # CUDA time total % - format_time_share(evt.self_cuda_time_total, sum_self_cuda_time_total), - evt.cuda_time_total_str, - evt.cuda_time_str, # Cuda time avg - ]) - if has_npu_time: - row_values.extend([ - evt.self_npu_time_total_str, - # NPU time total % - format_time_share(evt.self_npu_time_total, sum_self_npu_time_total), - evt.npu_time_total_str, - evt.npu_time_str, # Npu time avg - ]) - if profile_memory: - row_values.extend([ - # CPU Mem Total - format_memory(evt.cpu_memory_usage), - # Self CPU Mem Total - format_memory(evt.self_cpu_memory_usage), - ]) - if has_cuda_mem: - row_values.extend([ - # CUDA Mem Total - format_memory(evt.cuda_memory_usage), - # Self CUDA Mem Total - format_memory(evt.self_cuda_memory_usage), - ]) - if has_npu_mem: - row_values.extend([ - # NPU Mem Total - format_memory(evt.npu_memory_usage), - # Self NPU Mem Total - format_memory(evt.self_npu_memory_usage), - ]) - row_values.append( - evt.count, # Number of calls - ) - - if append_node_id: - row_values.append(evt.node_id) - if has_input_shapes: - row_values.append(str(evt.input_shapes)[:shapes_column_width]) - if with_flops: - if evt.flops <= 0.0: - row_values.append("--") - else: - row_values.append('{0:8.3f}'.format(evt.flops * flops_scale)) - if has_stack: - src_field = "" - if len(evt.stack) > 0: - src_field = trim_path(evt.stack[0], src_column_width) - row_values.append(src_field) - append(row_format.format(*row_values)) - - if has_stack: - empty_headers = [""] * (len(headers) - 1) - for entry in evt.stack[1:MAX_STACK_ENTRY]: - append(row_format.format(*(empty_headers + [trim_path(entry, src_column_width)]))) - empty_headers.append("") - append(row_format.format(*empty_headers)) - - append(header_sep) - append("Self CPU time total: {}".format(format_time(sum_self_cpu_time_total))) - if has_cuda_time: - append("Self CUDA time total: {}".format(format_time(sum_self_cuda_time_total))) - if has_npu_time: - append("Self NPU time total: {}".format(format_time(sum_self_npu_time_total))) - return ''.join(result) +# # 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 os +# import stat +# import itertools +# from typing import Any +# from collections import defaultdict, namedtuple +# from operator import attrgetter +# from typing import Dict, List, Tuple, Optional +# import math +# from enum import Enum +# import functools +# import torch_npu + +# try: +# from contextlib import ContextDecorator +# except ImportError: +# import functools + +# class ContextDecorator(object): # type: ignore[no-redef] + +# def __enter__(self): +# raise NotImplementedError + +# def __exit__(self, exc_type, exc_val, exc_tb): +# raise NotImplementedError + +# def __call__(self, func): +# @functools.wraps(func) +# def wrapped(*args, **kwargs): +# with self: +# return func(*args, **kwargs) + +# return wrapped +# __all__ = ["profile", "record_function", ] + +# if not torch_npu._C._profiler_init(): +# raise RuntimeError("proflier initialization failed") + +# file_flags = os.O_WRONLY | os.O_CREAT +# file_modes = stat.S_IWUSR | stat.S_IRUSR + +# class DeviceType(Enum): +# CPU = 0, +# CUDA = 1, # CUDA. +# MKLDNN = 2, # Reserved for explicit MKLDNN +# OPENGL = 3, # OpenGL +# OPENCL = 4, # OpenCL +# IDEEP = 5, # IDEEP. +# HIP = 6, # AMD HIP +# FPGA = 7, # FPGA +# MSNPU = 8, # MSNPU +# XLA = 9, # XLA / TPU +# Vulkan = 10, # Vulkan +# Metal = 11, # Metal +# XPU = 12, # XPU +# NPU = 13, # NPU +# class EventList(list): +# """A list of Events (for pretty printing)""" +# def __init__(self, *args, **kwargs): +# use_cuda = False +# use_npu = kwargs.pop('use_npu', True) and torch_npu.npu.is_available() +# profile_memory = kwargs.pop('profile_memory', False) +# with_flops = kwargs.pop('with_flops', False) +# super(EventList, self).__init__(*args, **kwargs) +# self._use_cuda = use_cuda +# self._use_npu = use_npu +# self._profile_memory = profile_memory +# self._tree_built = False +# self._with_flops = with_flops +# assert not (self._use_cuda and self._use_npu), "use_cuda and use_npu can't be True simultaneously." + +# def _build_tree(self): +# self._populate_cpu_children() +# self._remove_dup_nodes() +# self._set_backward_stacktraces() +# self._tree_built = True + +# def __str__(self): +# return self.table() + +# def _remove_dup_nodes(self): +# while True: +# to_delete = [] +# for idx, _ in enumerate(self): +# if (self[idx].cpu_parent is not None and +# self[idx].cpu_parent.name == self[idx].name and +# len(self[idx].cpu_parent.cpu_children) == 1): +# self[idx].cpu_parent.cpu_children = self[idx].cpu_children +# self[idx].cpu_parent.kernels = self[idx].kernels # lift kernels up +# for ch in self[idx].cpu_children: +# ch.cpu_parent = self[idx].cpu_parent +# to_delete.append(idx) +# if len(to_delete) == 0: +# break +# new_evts = [ev for ind, ev in enumerate(self) if ind not in to_delete] +# self.clear() +# self.extend(new_evts) + +# def _populate_cpu_children(self): +# """Populates child events into each underlying FunctionEvent object. +# One event is a child of another if [s1, e1) is inside [s2, e2). Where +# s1 and e1 would be start and end of the child event's interval. And +# s2 and e2 start and end of the parent event's interval + +# Example: In event list [[0, 10], [1, 3], [3, 4]] would have make [0, 10] +# be a parent of two other intervals. + +# If for any reason two intervals intersect only partially, this function +# will not record a parent child relationship between then. +# """ + +# # Some events can be async (i.e. start and end on different threads), +# # since it's generally undefined how to attribute children ranges to +# # async ranges, we do not use them when calculating nested ranges and stats +# sync_events = [evt for evt in self if not evt.is_async and evt.device_type == DeviceType.CPU] +# events = sorted( +# sync_events, +# key=attrgetter("thread"), +# ) +# # Group by both thread and node_id, so that events that happen to have +# # the same thread_id but are from different nodes aren't incorrectly +# # grouped together. +# threads = itertools.groupby( +# events, key=lambda event: (event.thread, event.node_id) +# ) + +# # For each thread we keep a stack of current nested parents. +# # We maintain the invariant that each interval is a subset of all other +# # intervals lower in the stack. +# # +# # First we sort the intervals by their start time. Then we iterate over them. +# # Every time we see a new interval we remove several parents from +# # the top until we restore the invariant. Then parent child relationship +# # if recorded if the stack is not empty. +# # Finally we add new interval to the list +# # +# # Algorithm has O(N * log(N)) complexity where N is number of +# # intervals +# for thread_id, thread_events in threads: +# thread_events_ = sorted( +# thread_events, +# key=lambda event: [event.time_range.start, -event.time_range.end], +# ) +# current_events: List[FunctionEvent] = [] +# cur_end = 0 +# for event in thread_events_: +# def _process_event(): +# while len(current_events) > 0: +# parent = current_events[-1] +# if event.time_range.start >= parent.time_range.end or \ +# event.time_range.end > parent.time_range.end: +# # this can't be a parent +# current_events.pop() +# else: +# parent.append_cpu_child(event) +# assert ( +# event.cpu_parent is None +# ), "There is already a CPU parent event for {}".format( +# event.key +# ) +# event.set_cpu_parent(parent) +# return + +# current_events.append(event) +# _process_event() + +# def _set_backward_stacktraces(self): +# def bw_parent(evt): +# if evt is None: +# return None +# elif evt.scope == 1: # BACKWARD_FUNCTION +# return evt +# else: +# return bw_parent(evt.cpu_parent) + +# fwd_stacks = {} +# for evt in self: +# if bw_parent(evt) is None and evt.stack is not None: +# t = (evt.sequence_nr, evt.thread) +# if t not in fwd_stacks: +# fwd_stacks[t] = evt.stack + +# for evt in self: +# p = bw_parent(evt) +# if p is not None: +# assert p.fwd_thread is not None +# t = (p.sequence_nr, p.fwd_thread) +# if t in fwd_stacks: +# evt.stack = fwd_stacks[t] +# else: +# evt.stack = [] + +# @property +# def self_cpu_time_total(self): +# return sum([event.self_cpu_time_total for event in self]) + +# def table(self, sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False): +# """Prints an EventList as a nicely formatted table. + +# Args: +# sort_by (str, optional): Attribute used to sort entries. By default +# they are printed in the same order as they were registered. +# Valid keys include: ``cpu_time``, ``cuda_time``, ``cpu_time_total``, +# ``cuda_time_total``, ``cpu_memory_usage``, ``cuda_memory_usage``, +# ``self_cpu_memory_usage``, ``self_cuda_memory_usage``, ``count``. +# top_level_events_only(bool, optional): Boolean flag to determine the +# selection of events to display. If true, the profiler will only +# display events at top level like top-level invocation of python +# `lstm`, python `add` or other functions, nested events like low-level +# cpu/cuda ops events are omitted for profiler result readability. + +# Returns: +# A string containing the table. +# """ +# return build_table( +# self, +# sort_by=sort_by, +# row_limit=row_limit, +# max_src_column_width=max_src_column_width, +# header=header, +# profile_memory=self._profile_memory, +# with_flops=self._with_flops, +# top_level_events_only=top_level_events_only, +# use_cuda=self._use_cuda, +# use_npu=self._use_npu) + +# def export_chrome_trace(self, path): +# """Exports an EventList as a Chrome tracing tools file. + +# The checkpoint can be later loaded and inspected under ``chrome://tracing`` URL. + +# Args: +# path (str): Path where the trace will be written. +# """ +# with os.fdopen(os.open(path, file_flags, file_modes), 'w') as f: +# chrome_events = [] +# next_id = 0 +# # Use file IO over using json.dump since JSON dumping is very slow and +# # this technique is proven to give a 4x speedup. +# f.write("[") +# for evt in self: +# if evt.trace_name is None: +# continue +# f.write( +# '{"name": "%s", ' +# '"ph": "X", ' +# '"ts": %s, ' +# '"dur": %s, ' +# '"tid": %s, ' +# '"pid": "CPU functions", ' +# '"args": {}}, ' +# % (evt.trace_name, evt.time_range.start, evt.time_range.elapsed_us(), +# evt.thread if not evt.is_remote else f'" node_id:{evt.node_id}, thread_id:{evt.thread} "',)) +# if self._use_npu: +# for k in evt.kernels: +# # 's' and 'f' draw Flow arrows from +# # the CPU launch to the GPU kernel +# f.write('{"name": "%s", ' +# '"ph": "s", ' +# '"ts": %s, ' +# '"tid": %s, ' +# '"pid": "CPU functions", ' +# '"id": %s, ' +# '"cat": "cpu_to_npu", ' +# '"args": {}}, ' % (evt.trace_name, evt.time_range.start, evt.thread, next_id)) +# f.write('{"name": "%s", ' +# '"ph": "f", ' +# '"ts": %s, ' +# '"tid": %s, ' +# '"pid": "NPU functions", ' +# '"id": %s, ' +# '"cat": "cpu_to_npu", ' +# '"args": {}}, ' % (k.name, k.interval.start, k.device, next_id)) +# f.write('{"name": "%s", ' +# '"ph": "X", ' +# '"ts": %s, ' +# '"dur": %s, ' +# '"tid": %s, ' +# '"pid": "NPU functions", ' +# '"args": {}}, ' % (k.name, k.interval.start, k.interval.elapsed_us(), k.device)) +# next_id += 1 + +# # remove trailing whitespace and comma +# f.seek(f.tell() - 2, os.SEEK_SET) +# f.truncate() +# f.write("]") + +# def supported_export_stacks_metrics(self): +# if self._use_npu: +# return ["self_cpu_time_total", "self_npu_time_total"] +# return ["self_cpu_time_total", "self_cuda_time_total"] + +# def export_stacks(self, path: str, metric: str): +# if metric not in self.supported_export_stacks_metrics(): +# raise ValueError("metric should be one of: " + str(self.supported_export_stacks_metrics())) +# translate_table = str.maketrans(" ;\t\n", "____") +# with os.fdopen(os.open(path, file_flags, file_modes), 'w') as f: +# for evt in self: +# if evt.stack and len(evt.stack) > 0 and len(getattr(evt, metric)) > 0: +# metric_value = getattr(evt, metric) +# stack_str = "" +# for entry in reversed(evt.stack): +# stack_str += entry.translate(translate_table) +# stack_str += ";" +# stack_str = stack_str[:-1] + " " + str(int(metric_value)) +# f.write(stack_str + "\n") + +# def key_averages(self, group_by_input_shapes=False, group_by_stack_n=0): +# """Averages all function events over their keys. + +# Args: +# group_by_input_shapes: group entries by +# (event name, input shapes) rather than just event name. +# This is useful to see which input shapes contribute to the runtime +# the most and may help with size-specific optimizations or +# choosing the best candidates for quantization (aka fitting a roof line) + +# group_by_stack_n: group by top n stack trace entries + +# Returns: +# An EventList containing FunctionEventAvg objects. +# """ +# assert self._tree_built +# stats: Dict[Tuple[str, ...], FunctionEventAvg] = defaultdict(FunctionEventAvg) + +# def get_key(event, group_by_input_shapes, group_by_stack_n) -> Tuple[str, ...]: +# key = [str(event.key), str(event.node_id), str(event.device_type), str(event.is_legacy)] +# if group_by_input_shapes: +# key.append(str(event.input_shapes)) +# if group_by_stack_n > 0: +# key += event.stack[:group_by_stack_n] +# return tuple(key) +# for evt in self: +# stats[get_key(evt, group_by_input_shapes, group_by_stack_n)].add(evt, self._use_cuda, self._use_npu) + +# avg_list = EventList( +# stats.values(), +# use_cuda=self._use_cuda, +# use_npu=self._use_npu, +# profile_memory=self._profile_memory, +# with_flops=self._with_flops) +# for evt in avg_list: +# evt.stack = evt.stack[:group_by_stack_n] +# if not group_by_input_shapes: +# evt.input_shapes = "" +# return avg_list + +# def total_average(self): +# """Averages all events. + +# Returns: +# A FunctionEventAvg object. +# """ +# total_stat = FunctionEventAvg() +# for evt in self: +# total_stat += evt +# total_stat.key = None +# total_stat.key = 'Total' +# return total_stat + +# class profile(object): +# """Context manager that manages autograd profiler state and holds a summary of results. +# Under the hood it just records events of functions being executed in C++ and +# exposes those events to Python. You can wrap any code into it and it will +# only report runtime of PyTorch functions. +# Note: profiler is thread local and is automatically propagated into the async tasks + +# Args: +# enabled (bool, optional): Setting this to False makes this context manager a no-op. + +# use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API. +# Adds approximately 4us of overhead to each tensor operation. + +# use_npu (bool, optional): Enables timing of NPU events as well using the aclEvent API. +# Adds approximately 4us of overhead to each tensor operation. + +# record_shapes (bool, optional): If shapes recording is set, information +# about input dimensions will be collected. This allows one to see which +# dimensions have been used under the hood and further group by them +# using prof.key_averages(group_by_input_shape=True). Please note that +# shape recording might skew your profiling data. It is recommended to +# use separate runs with and without shape recording to validate the timing. +# Most likely the skew will be negligible for bottom most events (in a case +# of nested function calls). But for higher level functions the total +# self cpu time might be artificially increased because of the shape +# collection. + +# with_flops (bool, optional): If with_flops is set, the profiler will estimate +# the FLOPS (floating pointer operations per second) value using the operator's input shape +# and total time. This allows one to estimate the hardware performance. Currently, +# this option only works for the matrix multiplication and 2D convolution operators. + +# profile_memory (bool, optional): track tensor memory allocation/deallocation. + +# with_stack (bool, optional): record source information (file and line number) for the ops. + +# use_kineto (bool, optional): experimental, enable profiling with Kineto profiler. + +# use_cpu (bool, optional): profile CPU events; setting to ``False`` requires +# ``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling. + +# .. warning: +# Enabling memory profiling or source attribution incurs additional profiler +# overhead + +# .. warning: +# This context managers should not be called recursively, i.e. no nested +# instances are allowed + +# .. warning: +# Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_), +# one cannot use the profiler with ``use_cuda = True`` to benchmark +# DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading, +# please use ``use_cuda = False`` or ``num_workers = 0``. + +# Example: +# >>> x = torch.randn((1, 1), requires_grad=True) +# >>> with torch.autograd.profiler.profile() as prof: +# >>> for _ in range(100): # any normal python code, really! +# >>> y = x ** 2 +# >> y.backward() +# >>> # NOTE: some columns were removed for brevity +# >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) +# ----------------------------------- --------------- --------------- --------------- +# Name Self CPU total CPU time avg Number of Calls +# ----------------------------------- --------------- --------------- --------------- +# mul 32.048ms 32.048ms 200 +# pow 27.041ms 27.041ms 200 +# PowBackward0 9.727ms 55.483ms 100 +# torch::autograd::AccumulateGrad 9.148ms 9.148ms 100 +# torch::autograd::GraphRoot 691.816us 691.816us 100 +# ----------------------------------- --------------- --------------- --------------- + +# """ +# def __init__( +# self, +# enabled=True, +# *, +# use_cuda=False, +# use_npu=False, +# record_shapes=False, +# with_flops=False, +# profile_memory=False, +# with_stack=False, +# use_kineto=False, +# use_cpu=True, +# use_npu_simple=False): +# self.enabled: bool = enabled +# if not self.enabled: +# return +# self.use_cuda = use_cuda +# self.use_npu = use_npu +# self.use_npu_simple = use_npu_simple +# self.function_events = None +# self.entered = False +# self.record_shapes = record_shapes +# self.with_flops = with_flops +# self.record_shapes |= self.with_flops +# self.profile_memory = profile_memory +# self.with_stack = with_stack +# self.use_cpu = use_cpu +# self.kineto_results = None +# if not self.use_cpu: +# assert use_kineto, \ +# "Device-only events supported only with Kineto (use_kineto=True)" + +# self.profiler_kind = None +# self.kineto_activities = set() +# if self.use_cuda: +# # legacy CUDA mode +# self.profiler_kind = torch_npu._C._profiler.ProfilerState.CUDA +# elif self.use_npu: +# self.profiler_kind = torch_npu._C._profiler.ProfilerState.NPU +# else: +# self.profiler_kind = torch_npu._C._profiler.ProfilerState.CPU + + +# def config(self): +# assert self.profiler_kind is not None +# return torch_npu._C._profiler.ProfilerConfig( +# self.profiler_kind, +# self.record_shapes, +# self.profile_memory, +# self.with_stack, +# self.with_flops, +# self.use_npu_simple) + +# def __enter__(self): +# if not self.enabled: +# raise RuntimeError("profiler is not enable") +# if self.entered: +# raise RuntimeError("profiler context manager is not reentrant") +# self.entered = True +# torch_npu._C._profiler._enable_profiler_legacy(self.config()) +# return self + +# def _prepare_kineto_trace(self): +# assert self.kineto_activities +# self.entered = True +# torch_npu._C._profiler._prepare_profiler(self.config(), self.kineto_activities) + +# def __exit__(self, exc_type, exc_val, exc_tb): +# if not self.enabled: +# raise RuntimeError("profiler is not enable") +# records = torch_npu._C._profiler._disable_profiler_legacy() +# parsed_results = parse_legacy_records(records) +# self.function_events = EventList( +# parsed_results, +# use_cuda=self.use_cuda, +# use_npu=self.use_npu, +# profile_memory=self.profile_memory, +# with_flops=self.with_flops) +# self.function_events._build_tree() +# return False + +# def __repr__(self): +# if self.function_events is None: +# return '' +# return repr(self.function_events) + +# def __str__(self): +# if self.function_events is None: +# return '' +# return str(self.function_events) + +# def _check_finish(self): +# if self.function_events is None: +# raise RuntimeError("can't export a trace that didn't finish running") + +# def table(self, sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False): +# self._check_finish() +# assert self.function_events is not None +# return self.function_events.table( +# sort_by=sort_by, row_limit=row_limit, max_src_column_width=max_src_column_width, header=header, +# top_level_events_only=top_level_events_only +# ) +# table.__doc__ = EventList.table.__doc__ + +# def export_chrome_trace(self, path): +# self._check_finish() +# if self.kineto_results is not None: +# raise RuntimeError("not support for kineto.") +# else: +# assert self.function_events is not None +# return self.function_events.export_chrome_trace(path) +# export_chrome_trace.__doc__ = EventList.export_chrome_trace.__doc__ + +# def export_stacks(self, path: str, metric: str = "self_cpu_time_total"): +# self._check_finish() +# assert self.function_events is not None, "Expected profiling results" +# assert self.with_stack, "export_stacks() requires with_stack=True" +# return self.function_events.export_stacks(path, metric) + +# def key_averages(self, group_by_input_shape=False, group_by_stack_n=0): +# self._check_finish() +# assert self.function_events is not None, "Expected profiling results" +# return self.function_events.key_averages(group_by_input_shape, group_by_stack_n) +# key_averages.__doc__ = EventList.key_averages.__doc__ + +# def total_average(self): +# self._check_finish() +# assert self.function_events is not None, "Expected profiling results" +# return self.function_events.total_average() +# total_average.__doc__ = EventList.total_average.__doc__ + +# @property +# def self_cpu_time_total(self): +# """ Returns total time spent on CPU obtained as a sum of +# all self times across all the events. +# """ +# self._check_finish() +# assert self.function_events is not None +# return self.function_events.self_cpu_time_total + + +# class record_function(ContextDecorator): +# """Context manager/function decorator that adds a label to a block of +# Python code (or function) when running autograd profiler. It is +# useful when tracing the code profile. + +# Args: +# name (str): Label assigned to the block of code. +# node_id (int): ID of node, for distributed profiling. Unset in +# non-distributed cases. + +# Example: +# >>> x = torch.randn((1, 1), requires_grad=True) +# >>> with torch.autograd.profiler.profile() as prof: +# ... y = x ** 2 +# ... with torch.autograd.profiler.record_function("label-z"): # label the block +# ... z = y ** 3 +# ... y.backward() +# ... +# >>> # NOTE: some columns were removed for brevity +# >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) +# ----------------------------------- --------------- --------------- --------------- +# Name Self CPU total % CPU time avg Number of Calls +# ----------------------------------- --------------- --------------- --------------- +# pow 60.77% 47.470us 3 +# mul 21.73% 25.465us 2 +# PowBackward0 12.03% 121.891us 1 +# torch::autograd::AccumulateGrad 2.70% 6.324us 1 +# label-z 2.13% 12.421us 1 +# torch::autograd::GraphRoot 0.64% 1.503us 1 +# ----------------------------------- --------------- --------------- --------------- +# Self CPU time total: 234.344us +# CUDA time total: 0.000us + +# """ +# def __init__(self, name: str): +# self.name: str = name +# # Whether or not we should run record function's end callbacks when exiting. +# self.run_callbacks_on_exit: bool = True +# # Stores underlying RecordFunction as a tensor. TODO: move to custom +# # class (https://github.com/pytorch/pytorch/issues/35026). +# self.handle = None + +# def __enter__(self): +# self.handle = torch_npu._C._profiler._record_function_enter(self.name) +# return self + +# def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any): +# if self.run_callbacks_on_exit: +# torch_npu._C._profiler._record_function_exit(self.handle) + +# def _call_end_callbacks_on_future(self, fut): +# """call_end_callbacks_on_future is meant to be used for profiling async +# calls that return a future. Calling this function will extend recording +# beyond this scope, until the future is satisfied. It is useful for profiling +# the end to end time of asynchronous calls. This function should only be called +# once to attach the callback onto the future, and will throw if called multiple +# times. + +# Args: +# fut: (torch._C.Future): future for which to schedule +# callback for. + +# Returns: +# A future that completes with the value of the passed in future when +# the profiling callbacks have ran. + +# """ +# # Throw if we have already attached a callback onto the future. +# if not self.run_callbacks_on_exit: +# raise RuntimeError("_call_end_callbacks_on_future can only be called once.") + +# # We are scheduling to run this RecordFunction's end callbacks when the +# # passed in future completes, so don't run end callbacks on exit. +# self.run_callbacks_on_exit = False +# profiled_future = None +# return profiled_future + + +# def _hook_for_profile(self): +# self._zero_grad_profile_name = "Optimizer.zero_grad#{}.zero_grad".format(self.__class__.__name__) + +# def profile_hook_step(func): + +# @functools.wraps(func) +# def wrapper(*args, **kwargs): +# obj, *_ = args +# profile_name = "Optimizer.step#{}.step".format(obj.__class__.__name__) +# with record_function(profile_name): +# return func(*args, **kwargs) +# return wrapper + +# hooked = getattr(self.__class__.step, "hooked", None) +# if not hooked: +# self.__class__.step = profile_hook_step(self.__class__.step) +# self.__class__.step.hooked = True + +# def load_nvprof(path): +# """Opens an nvprof trace file and parses autograd annotations. + +# Args: +# path (str): path to nvprof trace +# """ +# return EventList(parse_nvprof_trace(path)) + + +# ################################################################################ +# # FunctionEvent + +# def format_time(time_us): +# """Defines how to format time in FunctionEvent""" +# US_IN_SECOND = 1000.0 * 1000.0 +# US_IN_MS = 1000.0 +# if time_us >= US_IN_SECOND: +# return '{:.3f}s'.format(time_us / US_IN_SECOND) +# if time_us >= US_IN_MS: +# return '{:.3f}ms'.format(time_us / US_IN_MS) +# return '{:.3f}us'.format(time_us) + + +# def format_time_share(time_us, total_time_us): +# """Defines how to format time in FunctionEvent""" +# if total_time_us == 0: +# assert time_us == 0, "Expected time_us == 0 but got {}".format(time_us) +# return "NaN" +# return '{:.2f}%'.format(time_us * 100.0 / total_time_us) + +# def format_memory(nbytes): +# """Returns a formatted memory size string""" +# KB = 1024 +# MB = 1024 * KB +# GB = 1024 * MB +# if (abs(nbytes) >= GB): +# return '{:.2f} Gb'.format(nbytes * 1.0 / GB) +# elif (abs(nbytes) >= MB): +# return '{:.2f} Mb'.format(nbytes * 1.0 / MB) +# elif (abs(nbytes) >= KB): +# return '{:.2f} Kb'.format(nbytes * 1.0 / KB) +# else: +# return str(nbytes) + ' b' + +# def attr_formatter(name): +# return property(lambda self: format_time(getattr(self, name))) + + +# class FormattedTimesMixin(object): +# """Helpers for FunctionEvent and FunctionEventAvg. + +# The subclass should define `*_time_total` and `count` attributes. +# """ +# cpu_time_str = attr_formatter('cpu_time') +# cuda_time_str = attr_formatter('cuda_time') +# npu_time_str = attr_formatter('npu_time') +# cpu_time_total_str = attr_formatter('cpu_time_total') +# cuda_time_total_str = attr_formatter('cuda_time_total') +# npu_time_total_str = attr_formatter('npu_time_total') +# self_cpu_time_total_str = attr_formatter('self_cpu_time_total') +# self_cuda_time_total_str = attr_formatter('self_cuda_time_total') +# self_npu_time_total_str = attr_formatter('self_npu_time_total') + +# @property +# def cpu_time(self): +# return 0.0 if self.count == 0 else 1.0 * self.cpu_time_total / self.count # type: ignore + +# @property +# def cuda_time(self): +# return 0.0 if self.count == 0 else 1.0 * self.cuda_time_total / self.count # type: ignore + +# @property +# def npu_time(self): +# return 0.0 if self.count == 0 else 1.0 * self.npu_time_total / self.count # type: ignore + +# class Interval(object): +# def __init__(self, start, end): +# self.start = start +# self.end = end + +# def elapsed_us(self): +# return self.end - self.start + + +# Kernel = namedtuple('Kernel', ['name', 'device', 'interval']) + + +# class FunctionEvent(FormattedTimesMixin): +# """Profiling information about a single function.""" +# def __init__( +# self, id_event, name, thread, start_us, end_us, fwd_thread=None, input_shapes=None, +# stack=None, scope=0, cpu_memory_usage=0, cuda_memory_usage=0, npu_memory_usage=0, +# is_async=False, is_remote=False, sequence_nr=-1, node_id=-1, device_type=DeviceType.CPU, +# device_index=0, is_legacy=False, flops=None, trace_name=None): +# self.id: int = id_event +# self.node_id: int = node_id +# self.name: str = name +# self.trace_name: str = trace_name +# self.time_range: Interval = Interval(start_us, end_us) +# self.thread: int = thread +# self.fwd_thread: Optional[int] = fwd_thread +# self.kernels: List[Kernel] = [] +# self.count: int = 1 +# self.cpu_children: List[FunctionEvent] = [] +# self.cpu_parent: Optional[FunctionEvent] = None +# self.input_shapes: Tuple[int, ...] = input_shapes +# self.stack: List = stack +# self.scope: int = scope +# self.cpu_memory_usage: int = cpu_memory_usage +# self.cuda_memory_usage: int = cuda_memory_usage +# self.npu_memory_usage: int = npu_memory_usage +# self.is_async: bool = is_async +# self.is_remote: bool = is_remote +# self.sequence_nr: int = sequence_nr +# self.device_type: DeviceType = device_type +# self.device_index: int = device_index +# self.is_legacy: bool = is_legacy +# self.flops: Optional[float] = flops + +# def append_kernel(self, name, device, start, end): +# assert self.device_type == DeviceType.CPU +# self.kernels.append(Kernel(name, device, Interval(start, end))) + +# def append_cpu_child(self, child): +# """Append a CPU child of type FunctionEvent. + +# One is supposed to append only direct children to the event to have +# correct self cpu time being reported. +# """ +# assert(self.device_type == DeviceType.CPU) +# assert(isinstance(child, FunctionEvent)) +# assert(child.device_type == DeviceType.CPU) +# self.cpu_children.append(child) + +# def set_cpu_parent(self, parent): +# """Set the immediate CPU parent of type FunctionEvent + +# One profiling FunctionEvent should have only one CPU parent such that +# the child's range interval is completely inside the parent's. We use +# this connection to determine the event is from top-level op or not. +# """ +# assert(self.device_type == DeviceType.CPU) +# assert(isinstance(parent, FunctionEvent)) +# assert(parent.device_type == DeviceType.CPU) +# self.cpu_parent = parent + +# # Note: async events don't have children, are not used when computing 'self' +# # metrics of other events, have only total cpu time +# @property +# def self_cpu_memory_usage(self): +# if self.is_async or self.device_type != DeviceType.CPU: +# return 0 +# return self.cpu_memory_usage - sum( +# [child.cpu_memory_usage for child in self.cpu_children] +# ) + +# @property +# def self_cuda_memory_usage(self): +# if self.is_async or self.device_type != DeviceType.CPU: +# return 0 +# return self.cuda_memory_usage - sum( +# [child.cuda_memory_usage for child in self.cpu_children] +# ) + +# @property +# def self_npu_memory_usage(self): +# if self.is_async or self.device_type != DeviceType.CPU: +# return 0 +# return self.npu_memory_usage - sum( +# [child.npu_memory_usage for child in self.cpu_children] +# ) + +# @property +# def self_cpu_time_total(self): +# if self.is_async or self.device_type != DeviceType.CPU: +# return 0 +# return self.cpu_time_total - sum( +# [child.cpu_time_total for child in self.cpu_children] +# ) + +# @property +# def cuda_time_total(self): +# if self.is_async: +# return 0 +# if self.device_type == DeviceType.CPU: +# if not self.is_legacy: +# # account for the kernels in the children ops +# return (sum(kinfo.interval.elapsed_us() for kinfo in self.kernels) + +# sum(ch.cuda_time_total for ch in self.cpu_children)) +# else: +# # each legacy cpu events has a single (fake) kernel +# return sum(kinfo.interval.elapsed_us() for kinfo in self.kernels) +# else: +# assert self.device_type == DeviceType.CUDA +# return self.time_range.elapsed_us() + +# @property +# def self_cuda_time_total(self): +# if self.is_async: +# return 0 +# if self.device_type == DeviceType.CPU: +# return self.cuda_time_total - \ +# sum([child.cuda_time_total for child in self.cpu_children]) +# else: +# assert(self.device_type == DeviceType.CUDA) +# return self.cuda_time_total + +# @property +# def npu_time_total(self): +# if self.is_async: +# return 0 +# if self.device_type == DeviceType.CPU: +# assert self.is_legacy, "profiling with NPU only support for legacy." +# # each legacy cpu events has a single (fake) kernel +# return sum(kinfo.interval.elapsed_us() for kinfo in self.kernels) +# else: +# assert self.device_type == DeviceType.NPU +# return self.time_range.elapsed_us() + +# @property +# def self_npu_time_total(self): +# if self.is_async: +# return 0 +# if self.device_type == DeviceType.CPU: +# return self.npu_time_total - \ +# sum([child.npu_time_total for child in self.cpu_children]) +# else: +# assert(self.device_type == DeviceType.NPU) +# return self.npu_time_total + +# @property +# def cpu_time_total(self): +# if self.device_type == DeviceType.CPU: +# return self.time_range.elapsed_us() +# else: +# return 0 + +# @property +# def key(self): +# return self.name + +# def __repr__(self): +# return ( +# ''.format( +# self.id, +# self.name, +# self.device_type, +# self.node_id, +# self.cpu_time_str, +# self.time_range.start, +# self.time_range.end, +# str([child.id for child in self.cpu_children]), +# self.cuda_time_str, +# self.npu_time_str, +# self.name, +# self.thread, +# str(self.input_shapes), +# self.cpu_memory_usage, +# self.cuda_memory_usage, +# self.npu_memory_usage, +# self.is_async, +# self.is_remote, +# self.sequence_nr, +# self.is_legacy, +# ) +# ) + + +# class FunctionEventAvg(FormattedTimesMixin): +# """Used to average stats over multiple FunctionEvent objects.""" +# def __init__(self): +# self.key: Optional[str] = None +# self.count: int = 0 +# self.node_id: int = 0 +# self.is_async: bool = False +# self.is_remote: bool = False +# self.use_cuda = True +# self.use_npu = False +# self.cpu_time_total: int = 0 +# self.cuda_time_total: int = 0 +# self.npu_time_total: int = 0 +# self.self_cpu_time_total: int = 0 +# self.self_cuda_time_total: int = 0 +# self.self_npu_time_total: int = 0 +# self.input_shapes: Optional[List[List[int]]] = None +# self.stack: Optional[List] = None +# self.scope: Optional[int] = None +# self.cpu_memory_usage: int = 0 +# self.cuda_memory_usage: int = 0 +# self.npu_memory_usage: int = 0 +# self.self_cpu_memory_usage: int = 0 +# self.self_cuda_memory_usage: int = 0 +# self.self_npu_memory_usage: int = 0 +# self.cpu_children: Optional[List[FunctionEvent]] = None +# self.cpu_parent: Optional[FunctionEvent] = None +# self.device_type: DeviceType = DeviceType.CPU +# self.is_legacy: bool = False +# self.flops: float = 0.0 + +# def add(self, other, use_cuda=True, use_npu=False): +# self.use_cuda = use_cuda +# self.use_npu = use_npu +# if self.key is None: +# # First function being recorded as part of FunctionEventAvg, propagate +# # fields. +# self.key = other.key +# self.node_id = other.node_id +# self.is_async = other.is_async +# self.is_remote = other.is_remote +# self.cpu_parent = other.cpu_parent +# self.cpu_children = other.cpu_children + +# self.input_shapes = other.input_shapes +# self.stack = other.stack +# self.scope = other.scope +# self.device_type = other.device_type +# self.is_legacy = other.is_legacy + +# assert isinstance(other, (FunctionEvent, FunctionEventAvg)) +# assert other.key == self.key +# self.cpu_time_total += other.cpu_time_total +# self.self_cpu_time_total += other.self_cpu_time_total +# self.cpu_memory_usage += other.cpu_memory_usage +# self.self_cpu_memory_usage += other.self_cpu_memory_usage +# self.count += other.count +# if self.use_cuda: +# self.cuda_time_total += other.cuda_time_total +# self.self_cuda_time_total += other.self_cuda_time_total +# self.cuda_memory_usage += other.cuda_memory_usage +# self.self_cuda_memory_usage += other.self_cuda_memory_usage +# elif self.use_npu: +# self.npu_time_total += other.npu_time_total +# self.self_npu_time_total += other.self_npu_time_total +# self.npu_memory_usage += other.npu_memory_usage +# self.self_npu_memory_usage += other.self_npu_memory_usage +# if self.flops is None: +# self.flops = other.flops +# elif other.flops is not None: +# self.flops += other.flops +# return self + +# def __iadd__(self, other): +# return self.add(other) + +# def __repr__(self): +# if self.use_npu: +# return ( +# ''.format( +# self.key, +# self.self_cpu_time_total_str, +# self.cpu_time_str, +# self.self_npu_time_total_str, +# self.npu_time_str, +# str(self.input_shapes), +# self.cpu_memory_usage, +# self.npu_memory_usage, +# ) +# ) +# else: +# return ( +# ''.format( +# self.key, +# self.self_cpu_time_total_str, +# self.cpu_time_str, +# self.self_cuda_time_total_str, +# self.cuda_time_str, +# str(self.input_shapes), +# self.cpu_memory_usage, +# self.cuda_memory_usage, +# ) +# ) + + +# ################################################################################ +# # Utilities + +# class StringTable(defaultdict): +# def __missing__(self, key): +# # manage cases like 't' (demangled to 'unsigned short') separately, +# # for now simply check the length to avoid unexpected results for +# # the short sequences +# self[key] = key +# return self[key] + +# def filter_stack_entry(entry): +# filtered_entries = [ +# ("autograd/__init__", "_make_grads"), +# ("autograd/__init__", "backward"), +# ("torch/tensor", "backward"), +# ("_internal/common_utils", "prof_callable"), +# ("_internal/common_utils", "prof_func_call"), +# ("_internal/common_utils", "prof_meth_call"), +# ] +# return all([not (f[0] in entry and f[1] in entry) for f in filtered_entries]) + +# def filter_name(name): +# # ignoring the following utility ops +# filtered_out_names = [ +# "profiler::_record_function_enter", +# "profiler::_record_function_exit", +# "aten::is_leaf", +# "aten::output_nr", +# "aten::_version", +# ] +# return name in filtered_out_names + +# # Demangles and optionally rewrites the provided event name, +# # with_wildcard - whether to replace certain numbered event names +# # with a wildcard name to aggregate them together in the profiler table +# # output +# def rewrite_name(name, with_wildcard=False): +# string_table = StringTable() +# name = string_table[name] +# if with_wildcard: +# if name.startswith("ProfilerStep#"): +# name = "ProfilerStep*" +# return name + + +# # Parsing of legacy profiler events +# def parse_legacy_records(thread_records): +# def get_record_key(record): +# """ +# Returns a tuple to be used by parse_legacy_records for correlating start and +# end records. +# """ +# return (record.handle(), record.node_id()) + +# next_id = 0 +# start_record = None +# cuda_records = {} +# npu_records = {} +# functions = [] +# record_stack = [] +# profiler_type = DeviceType.CPU + +# # cuda start events and the overall profiler start event don't happen +# # at exactly the same time because we need to record an event on each device +# # and each record takes ~4us. So we adjust here by the difference +# # adding the difference in CPU time between the profiler start event +# # and the CPU time of the cuda start event for the device +# def adjusted_time(device_record, device_records_map): +# assert device_record.device() != -1 +# assert start_record is not None +# if device_record.has_npu(): +# npu_time_0 = device_records_map[(device_record.node_id(), device_record.device())] +# return npu_time_0.npu_elapsed_us(device_record) + start_record.cpu_elapsed_us(npu_time_0) +# else: +# raise RuntimeError("device_record only support for npu") + +# # '__start_profile' is not guaranteed to be first, so we must find it here +# for record in itertools.chain(*thread_records): +# name = record.name() +# if start_record is None and name == '__start_profile': +# start_record = record +# elif '__npu_start_event' in name: +# # N.B.: Each NPU device has its own __npu_start_event. +# assert record.device() != -1 +# # key for npu_records is (node_id, device) in case of multiple nodes +# # having the same device +# npu_records[(record.node_id(), record.device())] = record +# profiler_type = DeviceType.NPU + +# assert start_record is not None and not start_record.is_remote() + +# for thread_record_list in thread_records: +# # accumulated memory allocations per handle +# cpu_memory_allocs = {} +# cuda_memory_allocs = {} +# npu_memory_allocs = {} +# # ranges per handle +# range_starts = {} + +# filtered_handles = set() +# def process_record(functions): +# prev_record = None +# for record in thread_record_list: +# record_key = get_record_key(record) +# if (filter_name(record.name()) or +# record_key in filtered_handles): +# filtered_handles.add(record_key) +# continue +# if record.kind() == 'push': +# def process_push_record(prev_record): +# # workaround to reduce double logging from operator +# # wrappers and redispatch +# if prev_record is not None: +# duplicate = ( +# prev_record.name() == record.name() +# and prev_record.kind() == record.kind() +# and prev_record.node_id() == record.node_id() +# ) +# if duplicate: +# filtered_handles.add(record_key) +# return + +# range_starts[record_key] = record +# cpu_memory_allocs[record_key] = 0 +# cuda_memory_allocs[record_key] = 0 +# npu_memory_allocs[record_key] = 0 +# process_push_record(prev_record) +# elif record.kind() == 'pop': +# def process_op_record(): +# assert ( +# record_key in range_starts +# ), """Expected record with key {} to exist in range_starts. +# This means that the pop event did not have a corresponding push.""".format( +# record_key +# ) + +# start = range_starts[record_key] + +# cpu_memory_usage = cpu_memory_allocs[record_key] +# cuda_memory_usage = cuda_memory_allocs[record_key] +# npu_memory_usage = npu_memory_allocs[record_key] +# is_async = start.thread_id() != record.thread_id() +# is_remote_event = record.is_remote() +# start_flops = start.flops() + +# fe = FunctionEvent( +# id_event=record.handle(), +# node_id=record.node_id(), +# name=rewrite_name(name=start.name(), with_wildcard=True), +# trace_name=rewrite_name(name=start.name(), with_wildcard=False), +# thread=start.thread_id(), +# start_us=start_record.cpu_elapsed_us(start), +# end_us=start_record.cpu_elapsed_us(record), +# fwd_thread=start.fwd_thread_id(), +# input_shapes=start.shapes(), +# stack=[entry for entry in start.stack() if filter_stack_entry(entry)], +# scope=start.scope(), +# cpu_memory_usage=cpu_memory_usage, +# cuda_memory_usage=cuda_memory_usage, +# npu_memory_usage=npu_memory_usage, +# is_async=is_async, +# is_remote=is_remote_event, +# sequence_nr=start.sequence_nr(), +# device_type=DeviceType.CPU, +# is_legacy=True, +# flops=start_flops, +# ) +# # note: async events have only cpu total time +# if not is_async and start.has_npu(): +# npu_start = adjusted_time(start, npu_records) +# npu_end = adjusted_time(record, npu_records) +# if (npu_end - npu_start) > 0: +# fe.append_kernel( +# start.name(), +# start.device(), +# npu_start, +# npu_end) +# functions.append(fe) +# del range_starts[record_key] +# del cpu_memory_allocs[record_key] +# del cuda_memory_allocs[record_key] +# del npu_memory_allocs[record_key] +# process_op_record() +# elif record.kind() == 'memory_alloc': +# def process_memory_alloc_record(): +# num_open_handles_cpu = len(cpu_memory_allocs) +# num_open_handles_cuda = len(cuda_memory_allocs) +# assert num_open_handles_cpu == num_open_handles_cuda +# for handle in cpu_memory_allocs.keys(): +# cpu_memory_allocs[handle] += record.cpu_memory_usage() +# for handle in cuda_memory_allocs.keys(): +# cuda_memory_allocs[handle] += record.cuda_memory_usage() +# for handle in npu_memory_allocs.keys(): +# npu_memory_allocs[handle] += record.npu_memory_usage() +# if num_open_handles_cpu == 0: +# # output event as a top-level memory event +# fe = FunctionEvent( +# id_event=0, +# name="[memory]", +# trace_name=None, +# thread=0, +# start_us=0, +# end_us=0, +# stack=[], +# cpu_memory_usage=record.cpu_memory_usage(), +# cuda_memory_usage=record.cuda_memory_usage(), +# npu_memory_usage=record.npu_memory_usage(), +# is_legacy=True, +# ) +# functions.append(fe) +# process_memory_alloc_record() +# prev_record = record +# return functions +# functions = process_record(functions) +# # Sort functions by start time then by end time ascending. +# # This ensures that--in the case of nested events which +# # have the same start time (which may happen due to the +# # granularity of the given clock tick)--we always show +# # the outermost nested call first. This adds stability +# # in how FunctionEvents appear +# functions.sort(key=lambda evt: [evt.time_range.start, -evt.time_range.end]) +# if profiler_type == DeviceType.NPU: +# for record in itertools.chain(*thread_records): +# if record.has_npu(): +# record.npu_destropy_event() +# return functions + + +# ################################################################################ +# # CUDA checkpoints + +# class EnforceUnique(object): +# """Raises an error if a key is seen more than once.""" +# def __init__(self): +# self.seen = set() + +# def see(self, *key): +# if key in self.seen: +# raise RuntimeError('duplicate key: ' + str(key)) +# self.seen.add(key) + + +# ################################################################################ +# # Pretty printer + + +# def build_table( +# events, +# sort_by=None, +# header=None, +# row_limit=100, +# max_src_column_width=75, +# with_flops=False, +# profile_memory=False, +# top_level_events_only=False, +# use_cuda=False, +# use_npu=False): +# """Prints a summary of events (which can be a list of FunctionEvent or FunctionEventAvg).""" +# if len(events) == 0: +# return "" +# if use_cuda: +# raise RuntimeError("not support for CUDA.") +# has_cuda_time = False +# has_npu_time = any([event.self_npu_time_total > 0 for event in events]) and use_npu +# has_npu_mem = any([event.self_npu_memory_usage > 0 for event in events]) and use_npu +# has_input_shapes = any( +# [(event.input_shapes is not None and len(event.input_shapes) > 0) for event in events]) + +# if sort_by is not None: +# events = EventList(sorted( +# events, key=lambda evt: getattr(evt, sort_by), reverse=True +# ), use_cuda=has_cuda_time, use_npu=has_npu_time, profile_memory=profile_memory, with_flops=with_flops) +# def get_column_width(): +# MAX_NAME_COLUMN_WIDTH = 55 +# name_column_width = max([len(evt.key) for evt in events]) + 4 +# name_column_width = min(name_column_width, MAX_NAME_COLUMN_WIDTH) + +# DEFAULT_COLUMN_WIDTH = 12 +# shapes_column_width = max([len(str(evt.input_shapes)) for evt in events]) + 4 +# shapes_column_width = min(shapes_column_width, 45) +# MAX_NAME_COLUMN_WIDTH, DEFAULT_COLUMN_WIDTH, name_column_width, shapes_column_width = get_column_width() + +# src_column_width = None +# def get_headers(): +# headers = [ +# 'Name', +# 'Self CPU %', +# 'Self CPU', +# 'CPU total %', +# 'CPU total', +# 'CPU time avg', +# ] +# if has_npu_time: +# headers.extend([ +# 'Self NPU', +# 'Self NPU %', +# 'NPU total', +# 'NPU time avg', +# ]) +# if profile_memory: +# headers.extend([ +# 'CPU Mem', +# 'Self CPU Mem', +# ]) +# if has_npu_mem: +# headers.extend([ +# 'NPU Mem', +# 'Self NPU Mem', +# ]) +# headers.append( +# '# of Calls' +# ) +# # Only append Node ID if any event has a valid (>= 0) Node ID +# append_node_id = any([evt.node_id != -1 for evt in events]) +# if append_node_id: +# headers.append('Node ID') +# return headers, append_node_id +# headers, append_node_id = get_headers() +# # Have to use a list because nonlocal is Py3 only... +# SPACING_SIZE = 2 +# row_format_lst = [""] +# header_sep_lst = [""] +# line_length_lst = [-SPACING_SIZE] +# MAX_STACK_ENTRY = 5 + +# def add_column(padding, text_dir='>'): +# row_format_lst[0] += '{: ' + text_dir + str(padding) + '}' + (' ' * SPACING_SIZE) +# header_sep_lst[0] += '-' * padding + (' ' * SPACING_SIZE) +# line_length_lst[0] += padding + SPACING_SIZE + +# def auto_scale_flops(flops): +# flop_headers = [ +# 'FLOPS', +# 'KFLOPS', +# 'MFLOPS', +# 'GFLOPS', +# 'TFLOPS', +# 'PFLOPS', +# ] +# assert flops > 0 +# log_flops = max(0, min(math.log10(flops) / 3, float(len(flop_headers) - 1))) +# assert log_flops >= 0 and log_flops < len(flop_headers) +# return (pow(10, (math.floor(log_flops) * -3.0)), flop_headers[int(log_flops)]) + +# add_column(name_column_width) +# for _ in headers[1:]: +# add_column(DEFAULT_COLUMN_WIDTH) + +# if has_input_shapes: +# headers.append('Input Shapes') +# add_column(shapes_column_width) + +# row_format = row_format_lst[0] +# header_sep = header_sep_lst[0] +# line_length = line_length_lst[0] +# add_column = None # type: ignore + +# # Have to use a list because nonlocal is Py3 only... +# result = [] + +# def append(s): +# result.append(s) +# result.append('\n') # Yes, newline after the end as well +# def get_time_total(): +# sum_self_cpu_time_total = sum([event.self_cpu_time_total for event in events]) +# sum_self_cuda_time_total = 0 +# sum_self_npu_time_total = 0 +# for evt in events: +# if evt.device_type == DeviceType.CPU: +# # in legacy profiler, kernel info is stored in cpu events +# if evt.is_legacy: +# sum_self_cuda_time_total += evt.self_cuda_time_total +# sum_self_npu_time_total += evt.self_npu_time_total +# elif evt.device_type == DeviceType.NPU: +# # in kineto profiler, there're events with the correct device type (e.g. CUDA) +# sum_self_npu_time_total += evt.self_npu_time_total +# else: +# raise RuntimeError("only support for NPU or CPU") +# return sum_self_cpu_time_total, sum_self_npu_time_total +# sum_self_cpu_time_total, sum_self_npu_time_total = get_time_total() + +# # Actual printing +# def process_print(): +# if header is not None: +# append('=' * line_length) +# append(header) +# if top_level_events_only: +# append('=' * line_length) +# append('This report only display top-level ops statistics') +# append(header_sep) +# append(row_format.format(*headers)) + +# append(header_sep) +# process_print() + +# event_limit = 0 +# def get_result(): +# for evt in events: +# if event_limit == row_limit: +# break +# if top_level_events_only and evt.cpu_parent is not None: +# continue +# else: +# event_limit += 1 +# name = evt.key +# if len(name) >= MAX_NAME_COLUMN_WIDTH - 3: +# name = name[:(MAX_NAME_COLUMN_WIDTH - 3)] + "..." +# row_values = [ +# name, +# # Self CPU total %, 0 for async events. +# format_time_share(evt.self_cpu_time_total, +# sum_self_cpu_time_total), +# evt.self_cpu_time_total_str, # Self CPU total +# # CPU total %, 0 for async events. +# format_time_share(evt.cpu_time_total, sum_self_cpu_time_total) if not evt.is_async else 0, +# evt.cpu_time_total_str, # CPU total +# evt.cpu_time_str, # CPU time avg +# ] +# if has_npu_time: +# row_values.extend([ +# evt.self_npu_time_total_str, +# # NPU time total % +# format_time_share(evt.self_npu_time_total, sum_self_npu_time_total), +# evt.npu_time_total_str, +# evt.npu_time_str, # Npu time avg +# ]) +# if profile_memory: +# row_values.extend([ +# # CPU Mem Total +# format_memory(evt.cpu_memory_usage), +# # Self CPU Mem Total +# format_memory(evt.self_cpu_memory_usage), +# ]) +# if has_npu_mem: +# row_values.extend([ +# # NPU Mem Total +# format_memory(evt.npu_memory_usage), +# # Self NPU Mem Total +# format_memory(evt.self_npu_memory_usage), +# ]) +# row_values.append( +# evt.count, # Number of calls +# ) + +# if append_node_id: +# row_values.append(evt.node_id) +# if has_input_shapes: +# row_values.append(str(evt.input_shapes)[:shapes_column_width]) +# get_result() +# append(header_sep) +# append("Self CPU time total: {}".format(format_time(sum_self_cpu_time_total))) +# if has_npu_time: +# append("Self NPU time total: {}".format(format_time(sum_self_npu_time_total))) +# return ''.join(result) diff --git a/torch_npu/npu/random.py b/torch_npu/npu/random.py index 0e2cf39563..3e68f9a3ef 100644 --- a/torch_npu/npu/random.py +++ b/torch_npu/npu/random.py @@ -14,76 +14,14 @@ # See the License for the specific language governing permissions and # limitations under the License. -import torch import torch_npu from .utils import _lazy_init, _lazy_call, device_count, current_device -__all__ = ['get_rng_state', 'set_rng_state', - 'get_rng_state_all', 'set_rng_state_all', - 'manual_seed', 'manual_seed_all', +__all__ = ['manual_seed', 'manual_seed_all', 'seed', 'seed_all', 'initial_seed'] -def get_rng_state(device='npu'): - r"""Returns the random number generator state of the specified NPU as a ByteTensor. - - Args: - device (torch.device or int, optional): The device to return the RNG state of. - Default: ``'npu'`` (i.e., ``torch.device('npu')``, the current NPU device). - - .. warning:: - This function eagerly initializes NPU. - """ - _lazy_init() - device = torch.device(device) - idx = device.index - if idx is None: - idx = current_device() - default_generator = torch_npu.npu.default_generators[idx] - return default_generator.get_state() - - -def get_rng_state_all(): - r"""Returns a list of ByteTensor representing the random number states of all devices.""" - - results = [] - for i in range(device_count()): - results.append(get_rng_state(i)) - return results - - -def set_rng_state(new_state, device='npu'): - r"""Sets the random number generator state of the specified NPU. - - Args: - new_state (torch.ByteTensor): The desired state - device (torch.device or int, optional): The device to set the RNG state. - Default: ``'npu'`` (i.e., ``torch.device('npu')``, the current NPU device). - """ - new_state_copy = new_state.clone(memory_format=torch.contiguous_format) - device = torch.device(device) - - def cb(): - idx = device.index - if idx is None: - idx = current_device() - default_generator = torch_npu.npu.default_generators[idx] - default_generator.set_state(new_state_copy) - - _lazy_call(cb) - - -def set_rng_state_all(new_states): - r"""Sets the random number generator state of all devices. - - Args: - new_states (Iterable of torch.ByteTensor): The desired state for each device - """ - for i, state in enumerate(new_states): - set_rng_state(state, i) - - def manual_seed(seed): r"""Sets the seed for generating random numbers for the current NPU. It's safe to call this function if NPU is not available; in that diff --git a/torch_npu/npu/utils.py b/torch_npu/npu/utils.py index 54c8b98b2b..d2acf641a0 100644 --- a/torch_npu/npu/utils.py +++ b/torch_npu/npu/utils.py @@ -156,19 +156,6 @@ def current_device(): torch_npu.npu._lazy_init() return torch_npu._C._npu_getDevice() -def get_device_name(device_id: int): - if device_id < 0 or device_id >= device_count(): - raise AssertionError("Invalid device id") - torch_npu.npu._lazy_init() - device_prop = torch_npu._C._npu_getDeviceProperties(device_id) - return device_prop.name - -def get_device_properties(device_id: int): - if device_id < 0 or device_id >= device_count(): - raise AssertionError("Invalid device id") - torch_npu.npu._lazy_init() - return torch_npu._C._npu_getDeviceProperties(device_id) - def _get_device_index(device, optional=False): r"""Gets the device index from :attr:`device`, which can be a torch.device object, a Python integer, or ``None``. diff --git a/torch_npu/testing/common_utils.py b/torch_npu/testing/common_utils.py index 00998b6ca2..48d05122bb 100644 --- a/torch_npu/testing/common_utils.py +++ b/torch_npu/testing/common_utils.py @@ -77,6 +77,7 @@ def is_iterable(obj): def set_npu_device(): npu_device = get_npu_device() torch.npu.set_device(npu_device) + print(f"Your device is {npu_device}") return npu_device diff --git a/torch_npu/testing/decorator.py b/torch_npu/testing/decorator.py index 99fa1eae4f..746e26f24c 100644 --- a/torch_npu/testing/decorator.py +++ b/torch_npu/testing/decorator.py @@ -16,7 +16,6 @@ from functools import wraps -import os import logging import inspect import itertools @@ -76,19 +75,14 @@ def instantiate_tests(arg=None, **kwargs): return wrapper(arg) def graph_mode(func): - if os.getenv("GRAPH_MODE_TEST") == '1': - logging.basicConfig(level=logging.INFO, format="%(message)s") - logging.info("graph mode on") - def wrapper(*args, **kw): - logging.info("runing: {}".format(func.__name__)) - torch.npu.enable_graph_mode() - func(*args, **kw) - logging.info("graph mode off") - torch.npu.disable_graph_mode() - return wrapper - + logging.basicConfig(level=logging.INFO, format="%(message)s") + logging.info("graph mode on") def wrapper(*args, **kw): + logging.info("runing: {}".format(func.__name__)) + torch.npu.enable_graph_mode() func(*args, **kw) + logging.info("graph mode off") + torch.npu.disable_graph_mode() return wrapper class Dtypes(object): diff --git a/torch_npu/utils/_tensor_str.py b/torch_npu/utils/_tensor_str.py index 5841116681..f69a3c1a74 100644 --- a/torch_npu/utils/_tensor_str.py +++ b/torch_npu/utils/_tensor_str.py @@ -14,14 +14,11 @@ # limitations under the License. import torch - from torch._tensor_str import _Formatter as SrcFormatter from torch._tensor_str import PRINT_OPTS, _tensor_str_with_formatter, _add_suffixes, get_summarized_data from torch.overrides import has_torch_function_unary, handle_torch_function - import torch_npu - class _Formatter(SrcFormatter): def __init__(self, tensor): self.floating_dtype = tensor.dtype.is_floating_point @@ -46,10 +43,19 @@ def _tensor_str(self, indent): self = self.rename(None) summarize = self.numel() > PRINT_OPTS.threshold + if self._is_zerotensor(): + self = self.clone() + + # handle the negative bit + if self.is_neg(): + self = self.resolve_neg() + if self.dtype is torch.float16 or self.dtype is torch.bfloat16: self = self.float() if self.dtype.is_complex: + # handle the conjugate bit + self = self.resolve_conj() real_formatter = _Formatter(get_summarized_data(self.real) if summarize else self.real) imag_formatter = _Formatter(get_summarized_data(self.imag) if summarize else self.imag) return _tensor_str_with_formatter(self, indent, summarize, real_formatter, imag_formatter) diff --git a/torch_npu/utils/cpp_extension.py b/torch_npu/utils/cpp_extension.py deleted file mode 100644 index cc41d88f00..0000000000 --- a/torch_npu/utils/cpp_extension.py +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (c) 2022 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. - - -import os -import setuptools -import torch.utils.cpp_extension as TorchExtension -import torch_npu - - -def NpuExtension(name, sources, *args, **kwargs): - r''' - Creates a :class:`setuptools.Extension` for C++. - - Convenience method that creates a :class:`setuptools.Extension` with the - bare minimum (but often sufficient) arguments to build a C++ extension. - - All arguments are forwarded to the :class:`setuptools.Extension` - constructor. - - Example: - >>> from setuptools import setup - >>> from torch_npu.utils.cpp_extension import NpuExtension - >>> setup( - name='extension', - ext_modules=[ - NpuExtension( - name='extension', - sources=['extension.cpp'], - extra_compile_args=['-g']), - ], - cmdclass={ - 'build_ext': BuildExtension - }) - ''' - - torch_npu_dir = os.path.dirname(os.path.abspath(torch_npu.__file__)) - include_dirs = kwargs.get('include_dirs', []) - include_dirs.append(os.path.join(torch_npu_dir, 'include')) - include_dirs += TorchExtension.include_paths() - kwargs['include_dirs'] = include_dirs - - library_dirs = kwargs.get('library_dirs', []) - library_dirs.append(os.path.join(torch_npu_dir, 'lib')) - library_dirs += TorchExtension.library_paths() - kwargs['library_dirs'] = library_dirs - - libraries = kwargs.get('libraries', []) - libraries.append('c10') - libraries.append('torch') - libraries.append('torch_cpu') - libraries.append('torch_python') - libraries.append('torch_npu') - kwargs['libraries'] = libraries - - kwargs['language'] = 'c++' - return setuptools.Extension(name, sources, *args, **kwargs) diff --git a/torch_npu/utils/dataloader.py b/torch_npu/utils/dataloader.py index 48e2802e3b..4b8f9e7703 100644 --- a/torch_npu/utils/dataloader.py +++ b/torch_npu/utils/dataloader.py @@ -23,7 +23,8 @@ from torch.utils.data.dataloader import DataLoader as SrcDataLoader from torch.utils.data.dataloader import _DatasetKind from torch._utils import ExceptionWrapper import torch.multiprocessing as multiprocessing -from torch._six import queue, string_classes +from torch._six import string_classes +import queue import torch_npu MP_STATUS_CHECK_INTERVAL = 5.0 @@ -124,7 +125,7 @@ class _MultiProcessingDataLoaderIter(SrcMultiProcessingDataLoaderIter): args=(self._dataset_kind, self._dataset, index_queue, self._worker_result_queue, self._workers_done_event, self._auto_collation, self._collate_fn, self._drop_last, - self._base_seed + i, self._worker_init_fn, i, self._num_workers, + self._base_seed, self._worker_init_fn, i, self._num_workers, self._persistent_workers)) w.daemon = True w.start() @@ -151,11 +152,35 @@ class _MultiProcessingDataLoaderIter(SrcMultiProcessingDataLoaderIter): else: self._data_queue = self._worker_result_queue + # In some rare cases, persistent workers (daemonic processes) + # would be terminated before `__del__` of iterator is invoked + # when main process exits + # It would cause failure when pin_memory_thread tries to read + # corrupted data from worker_result_queue + # atexit is used to shutdown thread and child processes in the + # right sequence before main process exits + if self._persistent_workers and self._pin_memory: + import atexit + for w in self._workers: + atexit.register(_MultiProcessingDataLoaderIter._clean_up_worker, w) + # .pid can be None only before process is spawned (not the case, so ignore) _utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self._workers)) # type: ignore _utils.signal_handling._set_SIGCHLD_handler() self._worker_pids_set = True self._reset(loader, first_iter=True) + # staticmethod is used to remove reference to `_MultiProcessingDataLoaderIter` + @staticmethod + def _clean_up_worker(w): + try: + w.join(timeout=_utils.MP_STATUS_CHECK_INTERVAL) + finally: + if w.is_alive(): + w.terminate() + + def __del__(self): + self._shutdown_workers() + def add_dataloader_method(): torch.utils.data.DataLoader = DataLoader \ No newline at end of file diff --git a/torch_npu/utils/module.py b/torch_npu/utils/module.py index 415c2c82d3..3762e5ee95 100644 --- a/torch_npu/utils/module.py +++ b/torch_npu/utils/module.py @@ -17,13 +17,10 @@ from statistics import mode import warnings import logging import torch - +import torch_npu from torch.nn.modules._functions import SyncBatchNorm as sync_batch_norm from torch_npu.utils.tensor_methods import torch_device_guard -import torch_npu - - def npu(self, device=None): r"""Moves all model parameters and buffers to the npu. @@ -127,9 +124,7 @@ def cast_weight(self, device): module.v_proj_weight.data = module.v_proj_weight.data.to(device) module.v_proj_weight.data = torch_npu.npu_format_cast(module.v_proj_weight.data, 29) - # supported devices list: "npu"(from module.npu), "xla"(from module.to) - support_cast_devices = [torch_npu.npu.native_device, torch_npu.npu.npu_device] - if device is None or not any(support_cast_device in str(device) for support_cast_device in support_cast_devices): + if device is None or torch_npu.npu.native_device not in str(device): return current_class = self.__class__ @@ -176,7 +171,6 @@ def ddp_forward(self, *inputs, **kwargs): if self.ddp_uneven_inputs_config.ddp_join_enabled: # Notify joined ranks whether they should sync in backwards pass or not. self._check_global_requires_backward_grad_sync(is_joined_rank=False) - # Note: module.device_type was builded from device.type("npu") inside Class Module if self.device_ids and self.device_type != torch_npu.npu.npu_device: if len(self.device_ids) == 1: inputs, kwargs = self.to_kwargs(inputs, kwargs, self.device_ids[0]) diff --git a/torch_npu/utils/serialization.py b/torch_npu/utils/serialization.py index 373816ee6e..60cb922b1e 100644 --- a/torch_npu/utils/serialization.py +++ b/torch_npu/utils/serialization.py @@ -20,81 +20,56 @@ import copy import torch import torch.nn as nn import torch.serialization as se -from torch._six import container_abcs, string_classes - +import collections.abc as container_abcs +from torch._six import string_classes import torch_npu - DEFAULT_PROTOCOL = 2 - -def is_device(data): - if isinstance(data, torch_npu.utils.device_guard.device): - return True - return False - - -def module_to_cpu(module): - cpu_module = copy.deepcopy(module).cpu() - for attr in dir(cpu_module): - attr_item = getattr(cpu_module, attr) - if isinstance(attr_item, torch.Tensor): - setattr(cpu_module, attr, attr_item.cpu()) - return cpu_module - - def to_cpu(data): - if isinstance(data, string_classes): - return data - - if isinstance(data, torch.Tensor): - return data.cpu() - - if isinstance(data, nn.Module): - return module_to_cpu(data) - - if isinstance(data, argparse.Namespace): - dict_obj = vars(data) - return argparse.Namespace(**to_cpu(dict_obj)) - - if isinstance(data, container_abcs.Sequence) and not is_device(data): - copy_data = list([None] * len(data)) + if isinstance(data, container_abcs.Sequence): + copy_data = type(data)([None] * len(data)) for i, value in enumerate(data): if isinstance(value, tuple): list_value = list(value) cpu_list_value = to_cpu(list_value) - copy_data[i] = type(value)(cpu_list_value) + copy_data[i] = tuple(cpu_list_value) elif isinstance(value, string_classes): - copy_data[i] = value + continue elif isinstance(value, (container_abcs.Sequence, container_abcs.Mapping)): copy_data[i] = to_cpu(value) elif isinstance(value, torch.Tensor): copy_data[i] = value.cpu() elif isinstance(value, nn.Module): - copy_data[i] = module_to_cpu(value) + copy_data[i] = copy.deepcopy(value).cpu() else: copy_data[i] = value - return type(data)(copy_data) + return copy_data if isinstance(data, container_abcs.Mapping): copy_data = type(data)() for key, value in data.items(): - if isinstance(value, tuple) and not is_device(value): + if isinstance(value, tuple): list_value = list(value) cpu_list_value = to_cpu(list_value) - copy_data[key] = type(value)(cpu_list_value) + copy_data[key] = tuple(cpu_list_value) elif isinstance(value, (container_abcs.Sequence, container_abcs.Mapping)): copy_data[key] = to_cpu(value) elif isinstance(value, torch.Tensor): copy_data[key] = value.cpu() elif isinstance(value, nn.Module): - copy_data[key] = module_to_cpu(value) + copy_data[key] = copy.deepcopy(value).cpu() else: copy_data[key] = value return copy_data - return data + if isinstance(value, torch.Tensor): + return data.cpu() + if isinstance(value, nn.Module): + return copy.deepcopy(value).cpu() + + return data def save(obj, f, pickle_module=pickle, pickle_protocol=DEFAULT_PROTOCOL, _use_new_zipfile_serialization=False): """Saves the input data into a file. @@ -111,8 +86,30 @@ def save(obj, f, pickle_module=pickle, pickle_protocol=DEFAULT_PROTOCOL, _use_ne path: The destination file for the data saving operation. all the writes from the same host will override each other. """ - se.save(to_cpu(obj), f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) + if isinstance(obj, torch.Tensor): + cpu_obj = obj.cpu() + se.save(cpu_obj, f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) + + elif isinstance(obj, tuple): + list_obj = list(obj) + cpu_obj = tuple(to_cpu(list_obj)) + se.save(cpu_obj, f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) + + elif isinstance(obj, (container_abcs.Sequence, container_abcs.Mapping)): + cpu_obj = to_cpu(obj) + se.save(cpu_obj, f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) + + elif isinstance(obj, nn.Module): + se.save(copy.deepcopy(obj).cpu(), f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) + + elif isinstance(obj, argparse.Namespace): + dict_obj = vars(obj) + cpu_obj = argparse.Namespace(**to_cpu(dict_obj)) + se.save(cpu_obj, f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) + + else: + se.save(obj, f, pickle_module, pickle_protocol, _use_new_zipfile_serialization) def load(f, map_location=None, pickle_module=pickle, **pickle_load_args): """Loads data previously saved with the `save()` API. diff --git a/torch_npu/utils/storage.py b/torch_npu/utils/storage.py index 69050b71c1..4e157e610f 100644 --- a/torch_npu/utils/storage.py +++ b/torch_npu/utils/storage.py @@ -18,6 +18,22 @@ import torch import torch._C as _C import torch_npu +def _rebuild_npu_tensor(storage, npu_format, storage_offset, size, stride): + t = torch.tensor([0], dtype=storage.dtype).to(storage.device) + return t.npu_set_(storage, storage_offset, npu_format, size, stride) + +def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks, npu_format=2): + if storage.device.type == 'npu': + tensor = _rebuild_npu_tensor(storage, npu_format, storage_offset, size, stride) + else: + tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride) + tensor.requires_grad = requires_grad + # NB: This line exists only for backwards compatibility; the + # general expectation is that backward_hooks is an empty + # OrderedDict. See Note [Don't serialize hooks] + tensor._backward_hooks = backward_hooks + return tensor + class _StorageBase(torch.storage._StorageBase): _cdata: Any is_cuda: bool = False @@ -44,90 +60,5 @@ class _StorageBase(torch.storage._StorageBase): self._share_fd_() return self -class DoubleStorage(_C.DoubleStorageBase, _StorageBase): - pass - - -class FloatStorage(_C.FloatStorageBase, _StorageBase): - pass - - -class HalfStorage(_C.HalfStorageBase, _StorageBase): - pass - - -class LongStorage(_C.LongStorageBase, _StorageBase): - pass - - -class IntStorage(_C.IntStorageBase, _StorageBase): - pass - - -class ShortStorage(_C.ShortStorageBase, _StorageBase): - pass - - -class CharStorage(_C.CharStorageBase, _StorageBase): - pass - - -class ByteStorage(_C.ByteStorageBase, _StorageBase): - pass - - -class BoolStorage(_C.BoolStorageBase, _StorageBase): - pass - - -class BFloat16Storage(_C.BFloat16StorageBase, _StorageBase): - pass - -class ComplexDoubleStorage(_C.ComplexDoubleStorageBase, _StorageBase): - pass - -class ComplexFloatStorage(_C.ComplexFloatStorageBase, _StorageBase): - pass - -class QUInt8Storage(_C.QUInt8StorageBase, _StorageBase): - pass - -class QInt8Storage(_C.QInt8StorageBase, _StorageBase): - pass - -class QInt32Storage(_C.QInt32StorageBase, _StorageBase): - pass - -class QUInt4x2Storage(_C.QUInt4x2StorageBase, _StorageBase): - pass - -_storage_classes = { - DoubleStorage, FloatStorage, LongStorage, IntStorage, ShortStorage, - CharStorage, ByteStorage, HalfStorage, BoolStorage, QUInt8Storage, QInt8Storage, - QInt32Storage, BFloat16Storage, ComplexFloatStorage, ComplexDoubleStorage, QUInt4x2Storage -} - - -torch._storage_classes.add(DoubleStorage) -torch._storage_classes.add(FloatStorage) -torch._storage_classes.add(LongStorage) -torch._storage_classes.add(IntStorage) -torch._storage_classes.add(ShortStorage) -torch._storage_classes.add(CharStorage) -torch._storage_classes.add(ByteStorage) -torch._storage_classes.add(HalfStorage) -torch._storage_classes.add(BoolStorage) -torch._storage_classes.add(BFloat16Storage) -torch._storage_classes.add(ComplexDoubleStorage) -torch._storage_classes.add(ComplexFloatStorage) - -def is_storage(obj): - r"""Returns True if `obj` is a PyTorch storage object. - - Args: - obj (Object): Object to test - """ - return type(obj) in torch._storage_classes - def add_storage_methods(): - torch.is_storage = is_storage \ No newline at end of file + torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2 \ No newline at end of file diff --git a/torch_npu/utils/tensor_methods.py b/torch_npu/utils/tensor_methods.py index 9ad9e3bee8..f23d1b0c4c 100644 --- a/torch_npu/utils/tensor_methods.py +++ b/torch_npu/utils/tensor_methods.py @@ -19,7 +19,6 @@ import torch import torch_npu from torch_npu.utils.device_guard import torch_device_guard, device - warnings.filterwarnings(action="once") warning_str = "The tensor methods of custom operators would cause performance drop." + \ " Suggest to use torch.{0} or torch_npu.{0} instead." @@ -59,7 +58,6 @@ def npu_confusion_transpose(self, perm, shape, transpose_first): warnings.warn(warning_str.format("npu_confusion_transpose")) return torch_npu.npu_confusion_transpose(self, perm, shape, transpose_first) - @torch_device_guard def _npu(self, *args, **kwargs): return torch_npu._C.npu(self, *args, **kwargs) @@ -72,7 +70,6 @@ def _is_npu(self): def _type(self, *args, **kwargs): return torch_npu._C.type(self, *args, **kwargs) - @torch_device_guard def _to(self, *args, **kwargs): return torch_npu._C.to(self, *args, **kwargs) @@ -99,32 +96,20 @@ def _storage(self): return storage_impl(self) - @torch_device_guard def _new_empty(self, *args, **kwargs): - if isinstance(args[0], int): - list_args = list(args) - sizes = [] - for item in list_args: - if not isinstance(item, int): - break - sizes.append(item) - args = tuple([tuple(sizes)] + list_args[len(sizes):]) return torch_npu._C.new_empty(self, *args, **kwargs) - @torch_device_guard def _new_empty_strided(self, *args, **kwargs): return torch_npu._C.new_empty_strided(self, *args, **kwargs) - @property def _device(self): if torch_npu._C.is_npu(self): return device(type='npu', index=self.get_device()) return torch.device("cpu") - def add_tensor_methods(): torch.Tensor.npu_format_cast_ = npu_format_cast_ torch.Tensor.npu_format_cast = npu_format_cast @@ -141,4 +126,4 @@ def add_tensor_methods(): torch.Tensor.storage = _storage torch.Tensor.new_empty = _new_empty torch.Tensor.new_empty_strided = _new_empty_strided - torch.Tensor.device = _device \ No newline at end of file + torch.Tensor.device = _device diff --git a/scripts/codegen/templates/torch_funcs.py b/torch_npu/utils/torch_funcs.py similarity index 90% rename from scripts/codegen/templates/torch_funcs.py rename to torch_npu/utils/torch_funcs.py index 4e4d53bf4d..85799a5b9e 100644 --- a/scripts/codegen/templates/torch_funcs.py +++ b/torch_npu/utils/torch_funcs.py @@ -27,9 +27,14 @@ def _device(*args, **kwargs): return new_device -@torch_device_guard +# @torch_device_guard +# def _tensor(*args, **kwargs): +# return torch_npu.tensor(*args, **kwargs) + def _tensor(*args, **kwargs): - return torch_npu.tensor(*args, **kwargs) + if kwargs and kwargs.get("device", None) == 'npu': + kwargs['device'] = torch_npu.npu.npu_device + return torch._C._VariableFunctions.tensor(*args, **kwargs) @torch_device_guard @@ -66,7 +71,6 @@ def jit_script(obj, optimize=None, _frames_up=0, _rcb=None): # (Ascend) Disable extension of torch.jit.script return obj - def _as_tensor(*args, **kwargs): if kwargs and "device" in kwargs: dst_device = kwargs.get("device") @@ -78,8 +82,6 @@ def _as_tensor(*args, **kwargs): return torch._C._VariableFunctions.as_tensor(*args, **kwargs) -${device_methods_def_py_dispatch} - def add_torch_funcs(): torch.device = _device torch.tensor = _tensor @@ -91,5 +93,3 @@ def add_torch_funcs(): torch.npu_dropout_gen_mask = _npu_dropout_gen_mask torch.jit.script = jit_script torch.as_tensor = _as_tensor - -${device_methods_def_py} \ No newline at end of file