Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61a88f2d9c |
@@ -3,12 +3,11 @@ approvers:
|
||||
- weili10
|
||||
- you-ansheng
|
||||
- yskhhh
|
||||
- guxinxin2@hisilicon.com
|
||||
- clinglai
|
||||
- lvpeiyuan
|
||||
- wangkai86@huawei.com
|
||||
- guoyafeng1@huawei.com
|
||||
- xiepeng20
|
||||
- xiong05
|
||||
- guang-jun-zhang2
|
||||
- shibo19
|
||||
reviewers:
|
||||
- shibo19
|
||||
- xiaxia3
|
||||
@@ -51,8 +50,4 @@ reviewers:
|
||||
- huangyunlong2022
|
||||
- misty-rain-typhoid
|
||||
- du-jin-hang
|
||||
- xqiangx1991
|
||||
- zhan-jun
|
||||
- wujianping996
|
||||
- geekgaoxiang
|
||||
- jiangpengfei712
|
||||
- xqiangx1991
|
||||
+22
-32
@@ -22,13 +22,14 @@ from abc import ABCMeta, abstractmethod
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).absolute().parent.parent
|
||||
TEST_DIR = BASE_DIR / 'test'
|
||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
||||
TEST_DIR = os.path.join(BASE_DIR, 'test')
|
||||
TEST_OPS = os.path.join(BASE_DIR, 'test/test_ops.py')
|
||||
|
||||
|
||||
class AccurateTest(metaclass=ABCMeta):
|
||||
@abstractmethod
|
||||
def identify(self, modify_file):
|
||||
def identify(self, modify_files):
|
||||
"""
|
||||
该接口提供代码对应的UT的路径信息
|
||||
"""
|
||||
@@ -37,7 +38,7 @@ class AccurateTest(metaclass=ABCMeta):
|
||||
@staticmethod
|
||||
def find_ut_by_regex(regex):
|
||||
ut_files = []
|
||||
cmd = "find {} -name {}".format(str(TEST_DIR), regex)
|
||||
cmd = "find {} -name {}".format(os.path.join(BASE_DIR, 'test'), regex)
|
||||
status, output = subprocess.getstatusoutput(cmd)
|
||||
if status or not output:
|
||||
pass # 对于找不到的暂时不作处理
|
||||
@@ -61,7 +62,7 @@ class OpStrategy(AccurateTest):
|
||||
然后,获取其正则表达式*binary*cross*entropy*with*logits*backward*识别到符合要求的测试用例
|
||||
具体方法:通过大写字母切分关键字,再识别包含所有这些关键字的测试文件名。
|
||||
"""
|
||||
filename = Path(modify_file).name
|
||||
filename = os.path.basename(modify_file)
|
||||
if filename.find('KernelNpu') >= 0:
|
||||
feature_line = filename.split('KernelNpu')[0]
|
||||
features = re.findall('[A-Z][^A-Z]*', feature_line)
|
||||
@@ -72,24 +73,13 @@ class OpStrategy(AccurateTest):
|
||||
|
||||
class DirectoryStrategy(AccurateTest):
|
||||
"""
|
||||
Determine whether the modified files are test cases
|
||||
通过识别测试文件的目录确认需要进行UT的文件
|
||||
"""
|
||||
def identify(self, modify_file):
|
||||
is_test_file = str(Path(modify_file).parts[0]) == "test" \
|
||||
and re.match("test_(.+).py", Path(modify_file).name)
|
||||
return [(str(BASE_DIR / modify_file))] if is_test_file else []
|
||||
is_test_file = modify_file.split("/")[0] == "test" \
|
||||
and re.match("test_(.+).py", os.path.basename(modify_file))
|
||||
return [os.path.join(BASE_DIR, modify_file)] if is_test_file else []
|
||||
|
||||
class CoreTestStrategy(AccurateTest):
|
||||
"""
|
||||
Determine whether the core tests should be runned
|
||||
"""
|
||||
block_list = ['test', 'docs']
|
||||
core_test_cases = [str(i) for i in (BASE_DIR / 'test/test_npu').rglob('test_*.py')]
|
||||
def identify(self, modify_file):
|
||||
modified_module = str(Path(modify_file).parts[0])
|
||||
if modified_module not in self.block_list:
|
||||
return self.core_test_cases
|
||||
return []
|
||||
|
||||
class CopyOptStrategy(AccurateTest):
|
||||
"""
|
||||
@@ -121,10 +111,11 @@ class DirectoryMappingStrategy(AccurateTest):
|
||||
def identify(self, modify_file):
|
||||
current_all_ut_path = []
|
||||
if str(Path(modify_file).parts[0]) == 'torch_npu':
|
||||
CORE_TEST_LIST = [str(i) for i in (Path(BASE_DIR) / 'test/test_npu').rglob('test_*.py')]
|
||||
current_all_ut_path = CORE_TEST_LIST
|
||||
|
||||
mapped_ut_path = []
|
||||
module_name = str(Path(modify_file).parts[1])
|
||||
if module_name == 'csrc':
|
||||
module_name = str(Path(modify_file).parts[2])
|
||||
if module_name in self.mapping_list:
|
||||
mapped_ut_path.append(self.mapping_list[module_name])
|
||||
file_name = str(Path(modify_file).stem)
|
||||
@@ -132,10 +123,10 @@ class DirectoryMappingStrategy(AccurateTest):
|
||||
mapped_ut_path.append(self.mapping_list[file_name])
|
||||
|
||||
for mapped_path in mapped_ut_path:
|
||||
if Path.is_file(BASE_DIR / mapped_path):
|
||||
current_all_ut_path.append(str(BASE_DIR / mapped_path))
|
||||
if Path.is_file(Path(BASE_DIR) / mapped_path):
|
||||
current_all_ut_path.append(str(Path(BASE_DIR) / mapped_path))
|
||||
else:
|
||||
current_all_ut_path += [str(i) for i in (BASE_DIR / mapped_path).rglob('test_*.py')]
|
||||
current_all_ut_path += [str(i) for i in (Path(BASE_DIR) / mapped_path).rglob('test_*.py')]
|
||||
return current_all_ut_path
|
||||
|
||||
class TestMgr():
|
||||
@@ -159,13 +150,12 @@ class TestMgr():
|
||||
self.test_files['ut_files'] += OpStrategy().identify(modify_file)
|
||||
self.test_files['op_ut_files'] += OpStrategy().identify(modify_file)
|
||||
self.test_files['ut_files'] += DirectoryMappingStrategy().identify(modify_file)
|
||||
self.test_files['ut_files'] += CoreTestStrategy().identify(modify_file)
|
||||
unique_files = sorted(set(self.test_files['ut_files']))
|
||||
unique_files = set(self.test_files['ut_files'])
|
||||
|
||||
exist_ut_file = [
|
||||
changed_file
|
||||
for changed_file in unique_files
|
||||
if Path(changed_file).exists()
|
||||
if os.path.exists(changed_file)
|
||||
]
|
||||
self.test_files['ut_files'] = exist_ut_file
|
||||
|
||||
@@ -196,7 +186,7 @@ def exec_ut(files):
|
||||
return ut_file.split('/')[-1].split('.')[0].lstrip('test_')
|
||||
|
||||
def get_ut_name(ut_file):
|
||||
return str(Path(ut_file).relative_to(TEST_DIR))[:-3]
|
||||
return os.path.relpath(ut_file, TEST_DIR)[:-3]
|
||||
|
||||
def get_ut_cmd(ut_type, ut_file):
|
||||
cmd = [sys.executable, "run_test.py", "-v", "-i"]
|
||||
@@ -205,7 +195,7 @@ def exec_ut(files):
|
||||
return cmd + [get_ut_name(ut_file)]
|
||||
|
||||
def run_cmd_with_timeout(cmd):
|
||||
os.chdir(str(TEST_DIR))
|
||||
os.chdir(TEST_DIR)
|
||||
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
||||
|
||||
try:
|
||||
@@ -219,7 +209,7 @@ def exec_ut(files):
|
||||
p.kill()
|
||||
p.terminate()
|
||||
ret = 1
|
||||
print("Timeout: Command '{}' timed out after 2000 seconds".format(" ".join(cmd)))
|
||||
print(f"Timeout: Command '{cmd}' timed out after 2000 seconds")
|
||||
except Exception as err:
|
||||
ret = 1
|
||||
print(err)
|
||||
@@ -249,7 +239,7 @@ def exec_ut(files):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cur_modify_files = str(BASE_DIR / 'modify_files.txt')
|
||||
cur_modify_files = os.path.join(BASE_DIR, 'modify_files.txt')
|
||||
test_mgr = TestMgr()
|
||||
test_mgr.load(cur_modify_files)
|
||||
test_mgr.analyze()
|
||||
|
||||
@@ -112,10 +112,11 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
|
||||
bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
|
||||
for e in es:
|
||||
funcs = e.get('func')
|
||||
for op in custom_data['supported'] or custom_data['custom'] or custom_data['custom_autograd']:
|
||||
if op['func'] == funcs.split('(')[0]:
|
||||
op['func'] = funcs
|
||||
e.update(op)
|
||||
if custom_data['supported']:
|
||||
for op in custom_data['supported']:
|
||||
if op['func'] == funcs.split('(')[0]:
|
||||
op['func'] = funcs
|
||||
e.update(op)
|
||||
with context(lambda: f'in {path}:\n {funcs}'):
|
||||
func, m = NativeFunction.from_yaml(e)
|
||||
rs.append(func)
|
||||
|
||||
@@ -22,13 +22,12 @@ import torch_npu
|
||||
from torch_npu.utils.device_guard import torch_device_guard
|
||||
|
||||
|
||||
def wrap_torch_warning_func(func):
|
||||
def wrap_ewf_warning_func(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
if not wrapper.warned:
|
||||
func_name = func.__name__[1:]
|
||||
print(f"Warning: torch.{func_name} is deprecated and will be removed in future version. "
|
||||
f"Use torch_npu.{func_name} instead.")
|
||||
print(f"Warning: torch.empty_with_format is deprecated and will be removed in future version. "
|
||||
f"Use torch_npu.empty_with_format instead.")
|
||||
wrapper.warned = True
|
||||
return func(*args, **kwargs)
|
||||
wrapper.warned = False
|
||||
@@ -60,28 +59,17 @@ def _arange(*args, **kwargs):
|
||||
return torch_npu.arange(*args, **kwargs)
|
||||
|
||||
|
||||
@wrap_ewf_warning_func
|
||||
@torch_device_guard
|
||||
@wrap_torch_warning_func
|
||||
def _empty_with_format(*args, **kwargs):
|
||||
return torch_npu.empty_with_format(*args, **kwargs)
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
def _custom_empty_with_format(*args, **kwargs):
|
||||
return torch_npu._C._VariableFunctions.empty_with_format(*args, **kwargs)
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
@wrap_torch_warning_func
|
||||
def _npu_dropout_gen_mask(*args, **kwargs):
|
||||
return torch_npu.npu_dropout_gen_mask(*args, **kwargs)
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
def _custom_npu_dropout_gen_mask(*args, **kwargs):
|
||||
return torch_npu._C._VariableFunctions.npu_dropout_gen_mask(*args, **kwargs)
|
||||
|
||||
|
||||
@torch_device_guard
|
||||
def _new_device(*args, **kwargs):
|
||||
return torch_npu._C.device(*args, **kwargs)
|
||||
@@ -147,9 +135,7 @@ def add_torch_funcs():
|
||||
torch.range = _range
|
||||
torch.arange = _arange
|
||||
torch.empty_with_format = _empty_with_format
|
||||
torch_npu.empty_with_format = _custom_empty_with_format
|
||||
torch.npu_dropout_gen_mask = _npu_dropout_gen_mask
|
||||
torch_npu.npu_dropout_gen_mask = _custom_npu_dropout_gen_mask
|
||||
torch.jit.script = jit_script
|
||||
torch.as_tensor = _as_tensor
|
||||
torch.new_device = _new_device
|
||||
|
||||
@@ -38,7 +38,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.11.0.post1'
|
||||
VERSION = '1.11.0'
|
||||
|
||||
|
||||
def generate_torch_npu_version():
|
||||
@@ -188,7 +188,6 @@ class Clean(distutils.command.clean.clean):
|
||||
'torch_npu/csrc/aten/RegisterCPU.cpp',
|
||||
'torch_npu/csrc/aten/RegisterNPU.cpp',
|
||||
'torch_npu/csrc/aten/RegisterAutogradNPU.cpp',
|
||||
'torch_npu/csrc/aten/RegisterUnsupprotNPU.cpp',
|
||||
'torch_npu/csrc/aten/NPUNativeFunctions.h',
|
||||
'torch_npu/csrc/aten/python_custom_functions.cpp',
|
||||
'torch_npu/utils/torch_funcs.py',
|
||||
|
||||
+6
-61
@@ -17,17 +17,12 @@ import pathlib
|
||||
import os
|
||||
import sys
|
||||
import signal
|
||||
import tempfile
|
||||
import shutil
|
||||
import math
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
|
||||
import torch
|
||||
from torch.testing._internal.common_utils import shell
|
||||
|
||||
import torch_npu
|
||||
|
||||
REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||||
|
||||
# https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python
|
||||
@@ -64,18 +59,13 @@ def discover_tests(
|
||||
rc += extra_tests
|
||||
return sorted(rc)
|
||||
|
||||
|
||||
def parse_test_module(test):
|
||||
return pathlib.Path(test).parts[0]
|
||||
|
||||
|
||||
TESTS = discover_tests(
|
||||
blocklisted_patterns=[],
|
||||
blocklisted_tests=[],
|
||||
extra_tests=[]
|
||||
)
|
||||
|
||||
TESTS_MODULE = list(set([parse_test_module(test) for test in TESTS]))
|
||||
TESTS_MODULE = list(set([test.split("/")[0] for test in TESTS]))
|
||||
|
||||
TEST_CHOICES = TESTS + TESTS_MODULE
|
||||
|
||||
@@ -84,16 +74,6 @@ CORE_TEST_LIST = [
|
||||
]
|
||||
|
||||
|
||||
DISTRIBUTED_TESTS_CONFIG = {}
|
||||
|
||||
|
||||
if torch_npu.distributed.is_available():
|
||||
if torch_npu.distributed.is_hccl_available():
|
||||
DISTRIBUTED_TESTS_CONFIG['hccl'] = {
|
||||
'WORLD_SIZE': str(2**math.floor(math.log2(torch.npu.device_count()))),
|
||||
}
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Run the PyTorch unit test suite",
|
||||
@@ -174,8 +154,7 @@ def get_selected_tests(options):
|
||||
selected_tests = []
|
||||
if options.include:
|
||||
for item in options.include:
|
||||
selected_tests.extend(list(filter(lambda test_name: item == test_name \
|
||||
or (item in TESTS_MODULE and test_name.startswith(item)), TESTS)))
|
||||
selected_tests.extend(list(filter(lambda test_name: test_name.startswith(item), TESTS)))
|
||||
else:
|
||||
selected_tests = TESTS
|
||||
|
||||
@@ -196,7 +175,7 @@ def get_selected_tests(options):
|
||||
return selected_tests
|
||||
|
||||
|
||||
def run_test(test, test_directory, options):
|
||||
def run_test(test_module, test_directory, options):
|
||||
unittest_args = options.additional_unittest_args.copy()
|
||||
|
||||
if options.verbose:
|
||||
@@ -206,53 +185,19 @@ def run_test(test, test_directory, options):
|
||||
|
||||
# Can't call `python -m unittest test_*` here because it doesn't run code
|
||||
# in `if __name__ == '__main__': `. So call `python test_*.py` instead.
|
||||
argv = [test + ".py"] + unittest_args
|
||||
argv = [test_module + ".py"] + unittest_args
|
||||
|
||||
command = executable + argv
|
||||
print_to_stderr("Executing {} ... [{}]".format(command, datetime.now()))
|
||||
return shell(command, test_directory)
|
||||
|
||||
|
||||
def run_distributed_test(test, test_directory, options):
|
||||
config = DISTRIBUTED_TESTS_CONFIG
|
||||
for backend, env_vars in config.items():
|
||||
for with_init_file in {True, False}:
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
if options.verbose:
|
||||
with_init = ' with file init_method' if with_init_file else ''
|
||||
print_to_stderr(
|
||||
'Running distributed tests for the {} backend{}'.format(
|
||||
backend, with_init))
|
||||
os.environ['TEMP_DIR'] = tmp_dir
|
||||
os.environ['BACKEND'] = backend
|
||||
os.environ['INIT_METHOD'] = 'env://'
|
||||
os.environ.update(env_vars)
|
||||
if with_init_file:
|
||||
init_method = 'file://{}/shared_init_file'.format(tmp_dir)
|
||||
os.environ['INIT_METHOD'] = init_method
|
||||
try:
|
||||
os.mkdir(os.path.join(tmp_dir, 'barrier'))
|
||||
os.mkdir(os.path.join(tmp_dir, 'test_dir'))
|
||||
return_code = run_test(test, test_directory, options)
|
||||
if return_code != 0:
|
||||
return return_code
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir)
|
||||
return 0
|
||||
|
||||
|
||||
CUSTOM_HANDLERS = {
|
||||
"test_distributed": run_distributed_test,
|
||||
}
|
||||
|
||||
|
||||
def run_test_module(test: str, test_directory: str, options) -> Optional[str]:
|
||||
test_module = parse_test_module(test)
|
||||
test_module = test.split(".")[0]
|
||||
|
||||
print_to_stderr("Running {} ... [{}]".format(test, datetime.now()))
|
||||
handler = CUSTOM_HANDLERS.get(test_module, run_test)
|
||||
|
||||
return_code = handler(test, test_directory, options)
|
||||
return_code = run_test(test_module, test_directory, options)
|
||||
assert isinstance(return_code, int) and not isinstance(return_code, bool), "Return code should be an integer"
|
||||
if return_code == 0:
|
||||
return None
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
# Copyright (c) 2023 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
|
||||
import torch_npu
|
||||
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.contrib import transfer_to_npu
|
||||
|
||||
class TestTransferToNpu(TestCase):
|
||||
|
||||
def test_wrap_isinstance(self):
|
||||
# check builtins isinstance grammar
|
||||
self.assertTrue(isinstance(1, int))
|
||||
self.assertTrue(isinstance(1, (int, str)))
|
||||
self.assertFalse(isinstance(1, str))
|
||||
with self.assertRaises(TypeError):
|
||||
isinstance(1, [str, int])
|
||||
|
||||
# check torch.device
|
||||
self.assertFalse(isinstance(1, torch.device))
|
||||
|
||||
# check torch.cuda.device
|
||||
device = -1
|
||||
torch.cuda.device(device)
|
||||
|
||||
def test_amp_function(self):
|
||||
self.assertEqual(torch.cuda.amp.autocast_mode, torch_npu.npu.amp.autocast_mode)
|
||||
self.assertEqual(torch.cuda.amp.common, torch_npu.npu.amp.common)
|
||||
self.assertEqual(torch.cuda.amp.grad_scaler, torch_npu.npu.amp.grad_scaler)
|
||||
|
||||
def test_wrap_device(self):
|
||||
device = torch.device(f"cuda:{0}")
|
||||
torch.cuda.set_device(device)
|
||||
a = torch.randint(1, 5, (2, 3), device=device)
|
||||
self.assertEqual(a.device.type, 'npu')
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -0,0 +1,477 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
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
|
||||
|
||||
|
||||
PY2 = sys.version_info <= (3,)
|
||||
PY33 = sys.version_info >= (3, 3)
|
||||
PY36 = sys.version_info >= (3, 6)
|
||||
|
||||
TESTS = [
|
||||
'test_distributed'
|
||||
]
|
||||
|
||||
# skip < 3.3 because mock is added in 3.3 and is used in rpc_spawn
|
||||
# skip python2 for rpc and dist_autograd tests that do not support python2
|
||||
if PY33:
|
||||
TESTS.extend([
|
||||
'distributed/rpc/test_rpc_spawn',
|
||||
'distributed/rpc/test_dist_autograd_spawn',
|
||||
'distributed/rpc/test_dist_optimizer_spawn',
|
||||
'distributed/rpc/jit/test_dist_autograd_spawn',
|
||||
])
|
||||
|
||||
# skip < 3.6 b/c fstrings added in 3.6
|
||||
if PY36:
|
||||
TESTS.extend([
|
||||
'test_jit_py3',
|
||||
'test_determination',
|
||||
'distributed/rpc/jit/test_rpc_spawn',
|
||||
])
|
||||
|
||||
WINDOWS_BLACKLIST = [
|
||||
'distributed/test_distributed',
|
||||
'distributed/rpc/test_rpc_spawn',
|
||||
'distributed/rpc/test_dist_autograd_spawn',
|
||||
'distributed/rpc/test_dist_optimizer_spawn',
|
||||
'distributed/rpc/jit/test_rpc_spawn',
|
||||
'distributed/rpc/jit/test_dist_autograd_spawn',
|
||||
]
|
||||
|
||||
ROCM_BLACKLIST = [
|
||||
'test_cpp_extensions_aot_ninja',
|
||||
'test_cpp_extensions_jit',
|
||||
'test_multiprocessing',
|
||||
'distributed/rpc/test_rpc_spawn',
|
||||
'distributed/rpc/test_dist_autograd_spawn',
|
||||
'distributed/rpc/test_dist_optimizer_spawn',
|
||||
'distributed/rpc/jit/test_rpc_spawn',
|
||||
'distributed/rpc/jit/test_dist_autograd_spawn',
|
||||
'test_determination',
|
||||
]
|
||||
|
||||
DISTRIBUTED_TESTS_CONFIG = {}
|
||||
|
||||
|
||||
if dist.is_available():
|
||||
if dist.is_hccl_available():
|
||||
DISTRIBUTED_TESTS_CONFIG['hccl'] = {
|
||||
'WORLD_SIZE': '2' if torch.npu.device_count() == 2 else '4',
|
||||
'TEST_REPORT_SOURCE_OVERRIDE': 'dist-hccl'
|
||||
}
|
||||
else:
|
||||
if not TEST_WITH_ROCM and dist.is_mpi_available():
|
||||
DISTRIBUTED_TESTS_CONFIG['mpi'] = {
|
||||
'WORLD_SIZE': '3',
|
||||
'TEST_REPORT_SOURCE_OVERRIDE': 'dist-mpi'
|
||||
}
|
||||
if dist.is_nccl_available():
|
||||
DISTRIBUTED_TESTS_CONFIG['nccl'] = {
|
||||
'WORLD_SIZE': '2' if torch.cuda.device_count() == 2 else '3',
|
||||
'TEST_REPORT_SOURCE_OVERRIDE': 'dist-nccl'
|
||||
}
|
||||
if not TEST_WITH_ROCM and dist.is_gloo_available():
|
||||
DISTRIBUTED_TESTS_CONFIG['gloo'] = {
|
||||
'WORLD_SIZE': '2' if torch.cuda.device_count() == 2 else '3',
|
||||
'TEST_REPORT_SOURCE_OVERRIDE': 'dist-gloo'
|
||||
}
|
||||
|
||||
# https://stackoverflow.com/questions/2549939/get-signal-names-from-numbers-in-python
|
||||
SIGNALS_TO_NAMES_DICT = {getattr(signal, n): n for n in dir(signal)
|
||||
if n.startswith('SIG') and '_' not in n}
|
||||
|
||||
|
||||
def print_to_stderr(message):
|
||||
print(message, file=sys.stderr)
|
||||
|
||||
|
||||
def run_test(executable, test_module, test_directory, options, *extra_unittest_args):
|
||||
unittest_args = options.additional_unittest_args
|
||||
if options.verbose:
|
||||
unittest_args.append('--verbose')
|
||||
# Can't call `python -m unittest test_*` here because it doesn't run code
|
||||
# in `if __name__ == '__main__': `. So call `python test_*.py` instead.
|
||||
argv = [test_module + '.py'] + unittest_args + list(extra_unittest_args)
|
||||
|
||||
command = executable + argv
|
||||
return shell(command, test_directory)
|
||||
|
||||
def test_distributed_npu(executable, test_module, test_directory, options):
|
||||
config = DISTRIBUTED_TESTS_CONFIG
|
||||
for backend, env_vars in config.items():
|
||||
for with_init_file in {True, False}:
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
if options.verbose:
|
||||
with_init = ' with file init_method' if with_init_file else ''
|
||||
print_to_stderr(
|
||||
'Running distributed tests for the {} backend{}'.format(
|
||||
backend, with_init))
|
||||
os.environ['TEMP_DIR'] = tmp_dir
|
||||
os.environ['BACKEND'] = backend
|
||||
os.environ['INIT_METHOD'] = 'env://'
|
||||
os.environ.update(env_vars)
|
||||
if with_init_file:
|
||||
init_method = 'file://{}/shared_init_file'.format(tmp_dir)
|
||||
os.environ['INIT_METHOD'] = init_method
|
||||
try:
|
||||
os.mkdir(os.path.join(tmp_dir, 'barrier'))
|
||||
os.mkdir(os.path.join(tmp_dir, 'test_dir'))
|
||||
return_code = run_test(executable, test_module, test_directory,
|
||||
options)
|
||||
if return_code != 0:
|
||||
return return_code
|
||||
finally:
|
||||
shutil.rmtree(tmp_dir)
|
||||
return 0
|
||||
|
||||
CUSTOM_HANDLERS = {
|
||||
'test_distributed': test_distributed_npu
|
||||
}
|
||||
|
||||
|
||||
def parse_test_module(test):
|
||||
return test.split('.')[0]
|
||||
|
||||
|
||||
class TestChoices(list):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(TestChoices, self).__init__(args[0])
|
||||
|
||||
def __contains__(self, item):
|
||||
return list.__contains__(self, parse_test_module(item))
|
||||
|
||||
FAILURE_FILE_NAME = 'pytorch_org_failures.txt'
|
||||
ERROR_FILE_NAME = 'pytorch_org_errors.txt'
|
||||
def htmlReport_load_failure_error_cases(file_name):
|
||||
data = []
|
||||
if os.path.isfile(file_name):
|
||||
with open(file_name, 'r') as f:
|
||||
lines = f.readlines()
|
||||
for line in lines:
|
||||
temp = line.strip('\n').strip('\t')
|
||||
data.append(temp)
|
||||
else:
|
||||
print("Invlid filename:",file_name)
|
||||
return data
|
||||
|
||||
def htmlReport_analyse_failure_error_cases(result):
|
||||
new_failures = []
|
||||
new_errors = []
|
||||
|
||||
if len(result.failures) > 0:
|
||||
print("====================================== failed cases count: ", len(result.failures))
|
||||
for failure in result.failures:
|
||||
print(failure[0])
|
||||
print("============================================================\n")
|
||||
orig_failures = htmlReport_load_failure_error_cases(FAILURE_FILE_NAME)
|
||||
for failure in result.failures:
|
||||
if str(failure[0]) not in orig_failures:
|
||||
new_failures.append(str(failure[0]))
|
||||
|
||||
if len(result.errors) > 0:
|
||||
print("====================================== error cases count: ", len(result.errors))
|
||||
for error_case in result.errors:
|
||||
print(error_case[0])
|
||||
print("============================================================\n")
|
||||
orig_errors = htmlReport_load_failure_error_cases(ERROR_FILE_NAME)
|
||||
for error_case in result.errors:
|
||||
if str(error_case[0]) not in orig_errors:
|
||||
new_errors.append(str(error_case[0]))
|
||||
print("====================================== new failed cases count: ", len(new_failures))
|
||||
for case in new_failures:
|
||||
print(case)
|
||||
print("====================================== new error cases count: ", len(new_errors))
|
||||
for case in new_errors:
|
||||
print(case)
|
||||
return new_failures, new_errors
|
||||
|
||||
def htmlReport_RunTests(suite):
|
||||
|
||||
ENABLE_HTML = bool(os.environ.get('ENABLE_HTML'))
|
||||
ENABLE_HTML_MX = bool(os.environ.get('ENABLE_HTML_MX'))
|
||||
ENABLE_CASE_PATH = os.environ.get('ENABLE_CASE_PATH')
|
||||
ENABLE_OUTPUT_PATH = os.environ.get('ENABLE_OUTPUT_PATH')
|
||||
WHITE_LIST_PATH = os.environ.get('WHITE_LIST_PATH')
|
||||
|
||||
test_case_path = './'
|
||||
if ENABLE_CASE_PATH is not None:
|
||||
if not os.path.exists(ENABLE_CASE_PATH):
|
||||
print('path is not exists: ', ENABLE_CASE_PATH)
|
||||
else:
|
||||
test_case_path = ENABLE_CASE_PATH
|
||||
|
||||
test_report_path = test_case_path+'ReportResult'
|
||||
|
||||
if ENABLE_OUTPUT_PATH is not None:
|
||||
if not os.path.exists(ENABLE_OUTPUT_PATH):
|
||||
print('path is not exists: ', ENABLE_OUTPUT_PATH)
|
||||
else:
|
||||
test_report_path = ENABLE_OUTPUT_PATH
|
||||
|
||||
if not os.path.exists(test_report_path):
|
||||
os.mkdir(test_report_path)
|
||||
print(test_report_path)
|
||||
|
||||
now = time.strftime("%Y_%m_%d_%H_%M_%S")
|
||||
htmlFileName = os.path.join(test_report_path, 'pytorch-unittest-report-'+now+'.html')
|
||||
txtFileName = os.path.join(test_report_path, 'pytorch-unittest-report-'+now+'.txt')
|
||||
|
||||
print('start pytorch HTML unittest testset...')
|
||||
import HTMLTestRunner
|
||||
with os.fdopen(os.open(htmlFileName, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=0o600), "wb") as report_file:
|
||||
runner = HTMLTestRunner.HTMLTestRunner(
|
||||
stream=report_file, title='AllTest', description='all npu test case', verbosity=2)
|
||||
result = runner.run(suite)
|
||||
new_failures, new_errors = htmlReport_analyse_failure_error_cases(result)
|
||||
if len(new_failures) + len(new_errors) > 0:
|
||||
print(" RuntimeError: new error or failed cases found!")
|
||||
print('report files path', htmlFileName)
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(
|
||||
description='Run the PyTorch unit test suite',
|
||||
epilog='where TESTS is any of: {}'.format(', '.join(TESTS)))
|
||||
parser.add_argument(
|
||||
'--error-continue',
|
||||
action='store_true',
|
||||
help='run test continue when error or failure.')
|
||||
parser.add_argument(
|
||||
'--html-test-runner',
|
||||
action='store_true',
|
||||
help='run test case by HTML Test Runner.')
|
||||
parser.add_argument(
|
||||
'-v',
|
||||
'--verbose',
|
||||
action='store_true',
|
||||
help='print verbose information and test-by-test results')
|
||||
parser.add_argument(
|
||||
'--jit',
|
||||
'--jit',
|
||||
action='store_true',
|
||||
help='run all jit tests')
|
||||
parser.add_argument(
|
||||
'-pt', '--pytest', action='store_true',
|
||||
help='If true, use `pytest` to execute the tests. E.g., this runs '
|
||||
'TestTorch with pytest in verbose and coverage mode: '
|
||||
'python run_test.py -vci torch -pt')
|
||||
parser.add_argument(
|
||||
'-c', '--coverage', action='store_true', help='enable coverage')
|
||||
parser.add_argument(
|
||||
'-i',
|
||||
'--include',
|
||||
nargs='+',
|
||||
choices=TestChoices(TESTS),
|
||||
default=TESTS,
|
||||
metavar='TESTS',
|
||||
help='select a set of tests to include (defaults to ALL tests).'
|
||||
' tests can be specified with module name, module.TestClass'
|
||||
' or module.TestClass.test_method')
|
||||
parser.add_argument(
|
||||
'-x',
|
||||
'--exclude',
|
||||
nargs='+',
|
||||
choices=TESTS,
|
||||
metavar='TESTS',
|
||||
default=[],
|
||||
help='select a set of tests to exclude')
|
||||
parser.add_argument(
|
||||
'-f',
|
||||
'--first',
|
||||
choices=TESTS,
|
||||
metavar='TESTS',
|
||||
help='select the test to start from (excludes previous tests)')
|
||||
parser.add_argument(
|
||||
'-l',
|
||||
'--last',
|
||||
choices=TESTS,
|
||||
metavar='TESTS',
|
||||
help='select the last test to run (excludes following tests)')
|
||||
parser.add_argument(
|
||||
'--bring-to-front',
|
||||
nargs='+',
|
||||
choices=TestChoices(TESTS),
|
||||
default=[],
|
||||
metavar='TESTS',
|
||||
help='select a set of tests to run first. This can be used in situations'
|
||||
' where you want to run all tests, but care more about some set, '
|
||||
'e.g. after making a change to a specific component')
|
||||
parser.add_argument(
|
||||
'--ignore-win-blacklist',
|
||||
action='store_true',
|
||||
help='always run blacklisted windows tests')
|
||||
parser.add_argument(
|
||||
'--determine-from',
|
||||
help='File of affected source filenames to determine which tests to run.')
|
||||
parser.add_argument(
|
||||
'additional_unittest_args',
|
||||
nargs='*',
|
||||
help='additional arguments passed through to unittest, e.g., '
|
||||
'python run_test.py -i sparse -- TestSparse.test_factory_size_check')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def get_executable_command(options):
|
||||
if options.coverage:
|
||||
executable = ['coverage', 'run', '--parallel-mode', '--source torch']
|
||||
else:
|
||||
executable = [sys.executable]
|
||||
if options.pytest:
|
||||
executable += ['-m', 'pytest']
|
||||
return executable
|
||||
|
||||
|
||||
def find_test_index(test, selected_tests, find_last_index=False):
|
||||
"""Find the index of the first or last occurrence of a given test/test module in the list of selected tests.
|
||||
|
||||
This function is used to determine the indices when slicing the list of selected tests when
|
||||
``options.first``(:attr:`find_last_index`=False) and/or ``options.last``(:attr:`find_last_index`=True) are used.
|
||||
|
||||
:attr:`selected_tests` can be a list that contains multiple consequent occurrences of tests
|
||||
as part of the same test module, e.g.:
|
||||
|
||||
```
|
||||
selected_tests = ['autograd', 'cuda', **'torch.TestTorch.test_acos',
|
||||
'torch.TestTorch.test_tan', 'torch.TestTorch.test_add'**, 'utils']
|
||||
```
|
||||
|
||||
If :attr:`test`='torch' and :attr:`find_last_index`=False, result should be **2**.
|
||||
If :attr:`test`='torch' and :attr:`find_last_index`=True, result should be **4**.
|
||||
|
||||
Arguments:
|
||||
test (str): Name of test to lookup
|
||||
selected_tests (list): List of tests
|
||||
find_last_index (bool, optional): should we lookup the index of first or last
|
||||
occurrence (first is default)
|
||||
|
||||
Returns:
|
||||
index of the first or last occurrence of the given test
|
||||
"""
|
||||
idx = 0
|
||||
found_idx = -1
|
||||
for t in selected_tests:
|
||||
if t.startswith(test):
|
||||
found_idx = idx
|
||||
if not find_last_index:
|
||||
break
|
||||
idx += 1
|
||||
return found_idx
|
||||
|
||||
|
||||
def exclude_tests(exclude_list, selected_tests, exclude_message=None):
|
||||
for exclude_test in exclude_list:
|
||||
tests_copy = selected_tests[:]
|
||||
for test in tests_copy:
|
||||
if test.startswith(exclude_test):
|
||||
if exclude_message is not None:
|
||||
print_to_stderr('Excluding {} {}'.format(test, exclude_message))
|
||||
selected_tests.remove(test)
|
||||
return selected_tests
|
||||
|
||||
|
||||
def get_selected_tests(options):
|
||||
selected_tests = options.include
|
||||
|
||||
if options.bring_to_front:
|
||||
to_front = set(options.bring_to_front)
|
||||
selected_tests = options.bring_to_front + list(filter(lambda name: name not in to_front,
|
||||
selected_tests))
|
||||
|
||||
if options.first:
|
||||
first_index = find_test_index(options.first, selected_tests)
|
||||
selected_tests = selected_tests[first_index:]
|
||||
|
||||
if options.last:
|
||||
last_index = find_test_index(options.last, selected_tests, find_last_index=True)
|
||||
selected_tests = selected_tests[:last_index + 1]
|
||||
|
||||
selected_tests = exclude_tests(options.exclude, selected_tests)
|
||||
|
||||
if sys.platform == 'win32' and not options.ignore_win_blacklist:
|
||||
target_arch = os.environ.get('VSCMD_ARG_TGT_ARCH')
|
||||
if target_arch != 'x64':
|
||||
WINDOWS_BLACKLIST.append('cpp_extensions_aot_no_ninja')
|
||||
WINDOWS_BLACKLIST.append('cpp_extensions_aot_ninja')
|
||||
WINDOWS_BLACKLIST.append('cpp_extensions_jit')
|
||||
WINDOWS_BLACKLIST.append('jit')
|
||||
WINDOWS_BLACKLIST.append('jit_fuser')
|
||||
|
||||
selected_tests = exclude_tests(WINDOWS_BLACKLIST, selected_tests, 'on Windows')
|
||||
|
||||
elif TEST_WITH_ROCM:
|
||||
selected_tests = exclude_tests(ROCM_BLACKLIST, selected_tests, 'on ROCm')
|
||||
|
||||
return selected_tests
|
||||
|
||||
def main():
|
||||
options = parse_args()
|
||||
executable = get_executable_command(options) # this is a list
|
||||
print_to_stderr('Test executor: {}'.format(executable))
|
||||
test_directory = os.path.dirname(os.path.abspath(__file__))
|
||||
selected_tests = get_selected_tests(options)
|
||||
|
||||
if options.verbose:
|
||||
print_to_stderr('Selected tests: {}'.format(', '.join(selected_tests)))
|
||||
|
||||
if options.coverage:
|
||||
shell(['coverage', 'erase'])
|
||||
|
||||
if options.jit:
|
||||
selected_tests = filter(lambda test_name: "jit" in test_name, TESTS)
|
||||
|
||||
if options.determine_from is not None and os.path.exists(options.determine_from):
|
||||
pass
|
||||
|
||||
htmlReport_suite = unittest.TestSuite()
|
||||
htmlReport_loader = unittest.TestLoader()
|
||||
|
||||
for test in selected_tests:
|
||||
|
||||
test_module = parse_test_module(test)
|
||||
|
||||
# Printing the date here can help diagnose which tests are slow
|
||||
print_to_stderr('Running {} ... [{}]'.format(test, datetime.now()))
|
||||
handler = CUSTOM_HANDLERS.get(test, run_test)
|
||||
if options.html_test_runner:
|
||||
testfileName = test_module + '.py'
|
||||
testCase = unittest.defaultTestLoader.discover("./", pattern=testfileName)
|
||||
|
||||
rtn = htmlReport_suite.addTest(testCase)
|
||||
else:
|
||||
return_code = handler(executable, test_module, test_directory, options)
|
||||
assert isinstance(return_code, int) and not isinstance(
|
||||
return_code, bool), 'Return code should be an integer'
|
||||
if return_code != 0:
|
||||
message = '{} failed!'.format(test)
|
||||
if return_code < 0:
|
||||
# subprocess.Popen returns the child process' exit signal as
|
||||
# return code -N, where N is the signal number.
|
||||
signal_name = SIGNALS_TO_NAMES_DICT[-return_code]
|
||||
message += ' Received signal: {}'.format(signal_name)
|
||||
if not options.error_continue:
|
||||
raise RuntimeError(message)
|
||||
if options.html_test_runner:
|
||||
htmlReport_RunTests(htmlReport_suite)
|
||||
if options.coverage:
|
||||
shell(['coverage', 'combine'])
|
||||
shell(['coverage', 'html'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -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");
|
||||
@@ -14,51 +14,82 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
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
|
||||
from torch_npu.testing.decorator import graph_mode
|
||||
|
||||
|
||||
class TestMaxPool2dWithIndices(TestCase):
|
||||
def cpu_op_exec(self, inputCpu, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
dataCpu, argMaxCpu = F.max_pool2d_with_indices(inputCpu, kernel_size = kernel_size,
|
||||
stride = stride, padding = padding, dilation = dilation,
|
||||
ceil_mode = ceil_mode, return_indices=True)
|
||||
return dataCpu,argMaxCpu
|
||||
|
||||
def cpu_op_exec(self, input1, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
output, _ = F.max_pool2d_with_indices(input1, kernel_size=kernel_size,
|
||||
stride=stride, padding=padding, dilation=dilation,
|
||||
ceil_mode=ceil_mode, return_indices=True)
|
||||
return output
|
||||
|
||||
def npu_op_exec(self, input1, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
output, _ = F.max_pool2d_with_indices(input1, kernel_size=kernel_size,
|
||||
stride=stride, padding=padding, dilation=dilation,
|
||||
ceil_mode=ceil_mode, return_indices=True)
|
||||
return output.cpu()
|
||||
def npu_op_exec(self, inputNpu, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
dataNpu, argMaxNpu = F.max_pool2d_with_indices(inputNpu, kernel_size = kernel_size,
|
||||
stride = stride, padding = padding, dilation = dilation,
|
||||
ceil_mode = ceil_mode, return_indices=True)
|
||||
output1 = dataNpu.to("cpu").detach()
|
||||
output2 = argMaxNpu.to("cpu").detach()
|
||||
return output1, output2
|
||||
|
||||
@graph_mode
|
||||
def test_max_pool2d_with_indices(self):
|
||||
dtype_list = [np.float16, np.float32]
|
||||
format_list = [0, 3, 4]
|
||||
shape_list = [[256, 64, 112, 112], [1024, 24, 112, 112],
|
||||
[1024, 24, 56, 112], [1024, 24, 112, 56],
|
||||
[1234, 48, 56], [26, 16, 43]]
|
||||
def test_max_pool2d_with_indices_fp16(self):
|
||||
shape_format = [
|
||||
[[i, j, k], [3, 3], [2, 2], 1, 1, False] for i in dtype_list for j in format_list for k in shape_list
|
||||
[[np.float16, 0, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 0, [1024, 24, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 0, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 0, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 4, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 4, [1024, 24, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 4, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 4, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False]
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input, npu_input = create_common_tensor(item[0], 0, 100)
|
||||
if item[0][0] == np.float16:
|
||||
if cpu_input.dtype == torch.float16:
|
||||
cpu_input = cpu_input.to(torch.float32)
|
||||
cpu_output = self.cpu_op_exec(cpu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
npu_output = self.npu_op_exec(npu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
if item[0][0] == np.float16:
|
||||
cpu_output = cpu_output.to(npu_output.dtype)
|
||||
self.assertRtolEqual(cpu_output, npu_output, prec=1.e-3)
|
||||
cpu_output, cpu_arg = self.cpu_op_exec(cpu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
npu_output, npu_arg = self.npu_op_exec(npu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
cpu_output = cpu_output.to(npu_output.dtype)
|
||||
cpu_arg = cpu_arg.to(npu_arg.dtype)
|
||||
|
||||
self.assertRtolEqual(cpu_output.numpy(), npu_output.numpy())
|
||||
|
||||
@graph_mode
|
||||
def test_max_pool2d_with_indices_fp32(self):
|
||||
shape_format = [
|
||||
[[np.float32, 0, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 0, [1024, 24, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 0, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 0, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 3, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 3, [1024, 24, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 3, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 3, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 4, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 4, [1024, 24, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 4, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float32, 4, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False]
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input, npu_input = create_common_tensor(item[0], 0, 100)
|
||||
cpu_output, cpu_arg = self.cpu_op_exec(cpu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
npu_output, npu_arg = self.npu_op_exec(npu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
|
||||
self.assertRtolEqual(cpu_output.numpy(), npu_output.numpy(), prec=1.e-3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -14,63 +14,80 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
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
|
||||
from torch_npu.testing.decorator import graph_mode
|
||||
|
||||
|
||||
class TestMaxPool2dWithIndicesBackward(TestCase):
|
||||
def cpu_op_exec(self, inputCpu, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
inputCpu.requires_grad = True
|
||||
dataCpu, argMaxCpu = F.max_pool2d_with_indices(inputCpu, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation,
|
||||
ceil_mode=ceil_mode, return_indices=True)
|
||||
z1 = torch.sum(dataCpu)
|
||||
z1.backward()
|
||||
cpu_grad = inputCpu.grad
|
||||
output1 = dataCpu.detach()
|
||||
return output1, cpu_grad
|
||||
|
||||
def cpu_op_exec(self, input1, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
input1.requires_grad = True
|
||||
output, _ = F.max_pool2d_with_indices(input1, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation,
|
||||
ceil_mode=ceil_mode, return_indices=True)
|
||||
res = torch.sum(output)
|
||||
res.backward()
|
||||
cpu_grad = input1.grad
|
||||
output = output.detach()
|
||||
return output, cpu_grad
|
||||
|
||||
def npu_op_exec(self, input1, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
input1.requires_grad = True
|
||||
output, _ = F.max_pool2d_with_indices(input1, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation,
|
||||
ceil_mode=ceil_mode, return_indices=True)
|
||||
res = torch.sum(output)
|
||||
res.backward()
|
||||
npu_grad = input1.grad.cpu()
|
||||
output = output.cpu().detach()
|
||||
return output, npu_grad
|
||||
def npu_op_exec(self, inputNpu, kernel_size, stride, padding, dilation, ceil_mode):
|
||||
inputNpu.requires_grad = True
|
||||
dataNpu, argMaxNpu = F.max_pool2d_with_indices(inputNpu, kernel_size=kernel_size, stride=stride,
|
||||
padding=padding, dilation=dilation,
|
||||
ceil_mode=ceil_mode, return_indices=True)
|
||||
z2 = torch.sum(dataNpu)
|
||||
z2.backward()
|
||||
npu_grad = inputNpu.grad
|
||||
npu_grad = npu_grad.to("cpu")
|
||||
output1 = dataNpu.to("cpu").detach()
|
||||
return output1, npu_grad
|
||||
|
||||
@graph_mode
|
||||
def test_max_pool2d_with_indices_backward(self):
|
||||
dtype_list = [np.float32, np.float16]
|
||||
shape_list = [[256, 64, 112, 112], [1024, 24, 56, 112],
|
||||
[1024, 24, 112, 56], [48, 48, 56], [32, 16, 43]]
|
||||
def test_max_pool2d_with_indices_backward_fp16(self):
|
||||
shape_format = [
|
||||
[[i, 3, j], [3, 3], [2, 2], 1, 1, False] for i in dtype_list for j in shape_list
|
||||
[[np.float16, 3, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False],
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input, npu_input = create_common_tensor(item[0], 0, 100)
|
||||
if item[0][0] == np.float16:
|
||||
if cpu_input.dtype == torch.float16:
|
||||
cpu_input = cpu_input.to(torch.float32)
|
||||
cpu_output, cpu_grad = self.cpu_op_exec(cpu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
if item[0][0] == np.float16:
|
||||
cpu_output = cpu_output.to(torch.float16)
|
||||
cpu_grad = cpu_grad.to(torch.float16)
|
||||
cpu_output = cpu_output.to(npu_output.dtype)
|
||||
cpu_grad = cpu_grad.to(npu_grad.dtype)
|
||||
|
||||
self.assertRtolEqual(cpu_output, npu_output, prec=1.e-3)
|
||||
self.assertRtolEqual(cpu_grad, npu_grad, prec=1.e-3)
|
||||
self.assertRtolEqual(cpu_output.numpy(), npu_output.numpy())
|
||||
self.assertRtolEqual(cpu_grad.numpy(), npu_grad.numpy())
|
||||
|
||||
@graph_mode
|
||||
def test_max_pool2d_with_indices_backward_fp32(self):
|
||||
shape_format = [
|
||||
[[np.float16, 3, [256, 64, 112, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 56, 112]], [3, 3], [2, 2], 1, 1, False],
|
||||
[[np.float16, 3, [1024, 24, 112, 56]], [3, 3], [2, 2], 1, 1, False],
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input, npu_input = create_common_tensor(item[0], 0, 100)
|
||||
if cpu_input.dtype == torch.float16:
|
||||
cpu_input = cpu_input.to(torch.float32)
|
||||
cpu_output, cpu_grad = self.cpu_op_exec(cpu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input, item[1], item[2], item[3], item[4], item[5])
|
||||
cpu_output = cpu_output.to(npu_output.dtype)
|
||||
cpu_grad = cpu_grad.to(npu_grad.dtype)
|
||||
|
||||
self.assertRtolEqual(cpu_output.numpy(), npu_output.numpy(), prec=1.e-3)
|
||||
self.assertRtolEqual(cpu_grad.numpy(), npu_grad.numpy(), prec=1.e-3)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
# Copyright (c) 2023, 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 TestReflectionPad1dBackward(TestCase):
|
||||
|
||||
def cpu_op_exec(self, input1, pad):
|
||||
m = torch.nn.ReflectionPad1d(pad)
|
||||
input1.requires_grad = True
|
||||
output = m(input1)
|
||||
output.backward(torch.ones_like(output))
|
||||
cpu_grad = input1.grad
|
||||
output = output.detach().numpy()
|
||||
cpu_grad = cpu_grad.detach().numpy()
|
||||
return output, cpu_grad
|
||||
|
||||
def npu_op_exec(self, input1, pad):
|
||||
m = torch.nn.ReflectionPad1d(pad).npu()
|
||||
input1.requires_grad = True
|
||||
output = m(input1)
|
||||
output.backward(torch.ones_like(output))
|
||||
output = output.to("cpu")
|
||||
npu_grad = input1.grad
|
||||
npu_grad = npu_grad.to("cpu")
|
||||
output = output.detach().numpy()
|
||||
npu_grad = npu_grad.detach().numpy()
|
||||
return output, npu_grad
|
||||
|
||||
def test_reflection_pad1d_backward_shape_format(self):
|
||||
shape_format = [
|
||||
[[np.float16, 0, (16, 16, 4)], [3, 1]],
|
||||
[[np.float16, 2, (1, 2, 4)], [3, 1]],
|
||||
[[np.float32, 0, (16, 16, 4)], [3, 1]],
|
||||
[[np.float32, 2, (1, 2, 4)], [3, 1]],
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100)
|
||||
if item[0][0] == np.float16:
|
||||
cpu_input1 = cpu_input1.to(torch.float32)
|
||||
cpu_output, cpu_grad = self.cpu_op_exec(cpu_input1, item[1])
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input1, item[1])
|
||||
if item[0][0] == np.float16:
|
||||
cpu_output = cpu_output.astype(np.float16)
|
||||
cpu_grad = cpu_grad.astype(np.float16)
|
||||
self.assertRtolEqual(cpu_output, npu_output)
|
||||
self.assertRtolEqual(cpu_grad, npu_grad)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -29,7 +29,7 @@ class TestReflectionPad2dBackward(TestCase):
|
||||
output = m(input1)
|
||||
output.backward(torch.ones_like(output))
|
||||
input_grad = input1.grad
|
||||
output = output.detach().numpy()
|
||||
output = output.numpy()
|
||||
input_grad = input_grad.numpy()
|
||||
return output, input_grad
|
||||
|
||||
@@ -44,33 +44,31 @@ class TestReflectionPad2dBackward(TestCase):
|
||||
input_grad = input_grad.cpu().numpy()
|
||||
return output, input_grad
|
||||
|
||||
def test_reflectionPad2d_backward_shape_format(self):
|
||||
def test_reflectionPad2d_backward_shape_format_fp16(self):
|
||||
shape_format = [
|
||||
[[np.float16, 0, (1, 1, 37, 37)], [2, 2, 2, 2]],
|
||||
[[np.float16, 3, (1, 1, 4, 3)], 2],
|
||||
[[np.float16, 0, (1, 1, 17, 17)], [1, 2, 2, 2]],
|
||||
[[np.float16, 0, (2, 4, 3)], 2],
|
||||
[[np.float16, 0, (4, 17, 17)], [1, 2, 2, 2]],
|
||||
[[np.float16, 0, (1, 1, 17, 17)], [0, 0, 0, 0]],
|
||||
[[np.float16, 0, (1, 1, 4, 3)], 0],
|
||||
[[np.float32, 0, (1, 1, 37, 37)], [2, 2, 2, 2]],
|
||||
[[np.float32, 3, (1, 1, 4, 3)], 2],
|
||||
[[np.float32, 0, (1, 1, 17, 17)], [1, 2, 2, 2]],
|
||||
[[np.float32, 0, (2, 4, 3)], 2],
|
||||
[[np.float32, 0, (4, 17, 17)], [1, 2, 2, 2]],
|
||||
[[np.float32, 0, (1, 1, 17, 17)], [0, 0, 0, 0]],
|
||||
[[np.float32, 0, (1, 1, 4, 3)], 0],
|
||||
[[np.float16, 0, (4, 17, 17)], [1, 2, 2, 2]]
|
||||
]
|
||||
|
||||
def cpu_op_exec_fp16(input1, pad):
|
||||
input1 = input1.to(torch.float32)
|
||||
input1.requires_grad = True
|
||||
m = torch.nn.ReflectionPad2d(pad)
|
||||
output = m(input1)
|
||||
output.backward(torch.ones_like(output))
|
||||
output = output.detach().numpy()
|
||||
input_grad = input1.grad
|
||||
input_grad = input_grad.numpy().astype(np.float16)
|
||||
output = output.astype(np.float16)
|
||||
return output, input_grad
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100)
|
||||
if item[0][0] == np.float16:
|
||||
cpu_input1 = cpu_input1.to(torch.float32)
|
||||
cpu_output, cpu_grad = self.cpu_op_exec(cpu_input1, item[1])
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input1, item[1])
|
||||
if item[0][0] == np.float16:
|
||||
cpu_output = cpu_output.astype(np.float16)
|
||||
cpu_grad = cpu_grad.astype(np.float16)
|
||||
cpu_output, cpu_grad = cpu_op_exec_fp16(cpu_input1, item[1])
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input1, item[1])
|
||||
self.assertRtolEqual(cpu_output, npu_output)
|
||||
self.assertRtolEqual(cpu_grad, npu_grad)
|
||||
|
||||
|
||||
@@ -45,26 +45,19 @@ class TestReplicationPad1dBackward(TestCase):
|
||||
npu_grad = npu_grad.detach().numpy()
|
||||
return output, npu_grad
|
||||
|
||||
def test_replication_pad1d_backward_shape_format(self):
|
||||
def test_replication_pad1d_backward_shape_format_fp16(self):
|
||||
shape_format = [
|
||||
[[np.float16, 0, (16, 16, 4)], [3, 1]],
|
||||
[[np.float16, 2, (1, 2, 4)], [3, 1]],
|
||||
[[np.float16, 2, (20, 4)], [3, 1]],
|
||||
[[np.float16, 2, (1, 2, 4)], [0, 0]],
|
||||
[[np.float32, 0, (16, 16, 4)], [3, 1]],
|
||||
[[np.float32, 2, (1, 2, 4)], [3, 1]],
|
||||
[[np.float32, 2, (20, 4)], [3, 1]],
|
||||
[[np.float32, 2, (1, 2, 4)], [0, 0]]
|
||||
[[np.float16, 2, (20, 4)], [3, 1]]
|
||||
]
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100)
|
||||
if item[0][0] == np.float16:
|
||||
cpu_input1 = cpu_input1.to(torch.float32)
|
||||
cpu_input1 = cpu_input1.to(torch.float32)
|
||||
cpu_output, cpu_grad = self.cpu_op_exec(cpu_input1, item[1])
|
||||
if item[0][0] == np.float16:
|
||||
cpu_output = cpu_output.astype(np.float16)
|
||||
cpu_grad = cpu_grad.astype(np.float16)
|
||||
cpu_output = cpu_output.astype(np.float16)
|
||||
cpu_grad = cpu_grad.astype(np.float16)
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input1, item[1])
|
||||
self.assertRtolEqual(cpu_output, npu_output)
|
||||
self.assertRtolEqual(cpu_grad, npu_grad)
|
||||
|
||||
@@ -33,38 +33,28 @@ class TestReplicationPad2dBackward(TestCase):
|
||||
output = output.detach().numpy()
|
||||
return output, npu_grad.cpu().numpy()
|
||||
|
||||
def cpu_op_exec(self, input1, pad):
|
||||
m = torch.nn.ReplicationPad2d(pad)
|
||||
input1.requires_grad = True
|
||||
output = m(input1)
|
||||
output.backward(torch.ones_like(output))
|
||||
cpu_grad = input1.grad
|
||||
output = output.detach().numpy()
|
||||
return output, cpu_grad.numpy()
|
||||
|
||||
def test_replicationPad2d_backward_shape_format(self):
|
||||
def test_replicationPad2d_backward_shape_format_fp16(self):
|
||||
shape_format = [
|
||||
[[np.float16, 0, (1, 1, 27, 27)], [2, 2, 2, 2]],
|
||||
[[np.float16, 0, (1, 1, 27, 27)], 3],
|
||||
[[np.float16, 0, (4, 27, 27)], 3],
|
||||
[[np.float16, 0, (2, 3, 27, 27)], 0],
|
||||
[[np.float16, 0, (1, 1, 27, 27)], [0, 0, 0, 0]],
|
||||
[[np.float32, 0, (20, 1, 23, 27)], [2, 2, 2, 2]],
|
||||
[[np.float32, 0, (13, 1, 27, 27)], 3],
|
||||
[[np.float32, 0, (4, 27, 27)], 3],
|
||||
[[np.float32, 0, (21, 3, 27, 27)], 0],
|
||||
[[np.float32, 0, (1, 1, 27, 27)], [0, 0, 0, 0]]
|
||||
[[np.float16, 0, (4, 27, 27)], 3]
|
||||
]
|
||||
|
||||
def cpu_op_exec_fp16(input1, pad):
|
||||
input1 = input1.to(torch.float32)
|
||||
m = torch.nn.ReplicationPad2d(pad)
|
||||
input1.requires_grad = True
|
||||
output = m(input1)
|
||||
output.backward(torch.ones_like(output))
|
||||
cpu_grad = input1.grad
|
||||
output = output.detach().numpy()
|
||||
output = output.astype(np.float16)
|
||||
return output, cpu_grad.numpy().astype(np.float16)
|
||||
|
||||
for item in shape_format:
|
||||
cpu_input1, npu_input1 = create_common_tensor(item[0], 1, 100)
|
||||
if item[0][0] == np.float16:
|
||||
cpu_input1 = cpu_input1.to(torch.float32)
|
||||
cpu_output, cpu_grad = self.cpu_op_exec(cpu_input1, item[1])
|
||||
cpu_output, cpu_grad = cpu_op_exec_fp16(cpu_input1, item[1])
|
||||
npu_output, npu_grad = self.npu_op_exec(npu_input1, item[1])
|
||||
if item[0][0] == np.float16:
|
||||
cpu_output = cpu_output.astype(np.float16)
|
||||
cpu_grad = cpu_grad.astype(np.float16)
|
||||
self.assertRtolEqual(cpu_output, npu_output)
|
||||
self.assertRtolEqual(cpu_grad, npu_grad)
|
||||
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
# 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 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 TestSum(TestCase):
|
||||
|
||||
def cpu_op_exec(self, input1):
|
||||
output = input1.sum()
|
||||
output = output.numpy()
|
||||
return output
|
||||
|
||||
def npu_op_exec(self, input1):
|
||||
output = input1.sum()
|
||||
output = output.to("cpu")
|
||||
output = output.numpy()
|
||||
return output
|
||||
|
||||
def cpu_op_exec_dim(self, input1, dim, dtype):
|
||||
output = torch.sum(input1, dim, keepdim=True, dtype=dtype)
|
||||
output = output.numpy()
|
||||
return output
|
||||
|
||||
def npu_op_exec_dim(self, input1, dim, dtype):
|
||||
output = torch.sum(input1, dim, keepdim=True, dtype=dtype)
|
||||
output = output.to("cpu")
|
||||
output = output.numpy()
|
||||
return output
|
||||
|
||||
def cpu_op_dim_exec_out(self, input1, dim, keepdim):
|
||||
out = torch.tensor(0).to(input1.dtype)
|
||||
torch.sum(input1, dim=dim, keepdim=keepdim, out=out)
|
||||
out = out.numpy()
|
||||
return out
|
||||
|
||||
def npu_op_dim_exec_out(self, input1, dim, keepdim):
|
||||
out = torch.tensor(0).to(input1.dtype).npu()
|
||||
torch.sum(input1, dim=dim, keepdim=keepdim, out=out)
|
||||
out = out.to("cpu").numpy()
|
||||
output = torch.sum(input1, dim=dim, keepdim=keepdim)
|
||||
output = output.to("cpu").numpy()
|
||||
return out, output
|
||||
|
||||
def sum_result(self, shape_format):
|
||||
for item in shape_format:
|
||||
cpu_input1, npu_input1 = create_common_tensor(item, -1, 1)
|
||||
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 = cpu_output.astype(npu_output.dtype)
|
||||
self.assertRtolEqual(cpu_output, npu_output)
|
||||
|
||||
def sum_dim_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, -1, 1)
|
||||
if cpu_input1.dtype == torch.float16:
|
||||
cpu_input1 = cpu_input1.to(torch.float32)
|
||||
|
||||
cpu_out_dim = self.cpu_op_dim_exec_out(cpu_input1, dim=[0], keepdim=True)
|
||||
npu_out_dim, npu_output_dim = self.npu_op_dim_exec_out(npu_input1, dim=[0], keepdim=True)
|
||||
cpu_out_dim = cpu_out_dim.astype(npu_out_dim.dtype)
|
||||
if npu_out_dim.dtype != np.float16:
|
||||
self.assertRtolEqual(npu_out_dim, cpu_out_dim)
|
||||
else:
|
||||
self.assertRtolEqual(npu_out_dim, npu_output_dim)
|
||||
|
||||
cpu_output_dim = self.cpu_op_exec_dim(cpu_input1, dim, cpu_input1.dtype)
|
||||
npu_output_dim = self.npu_op_exec_dim(npu_input1, dim, npu_input1.dtype)
|
||||
cpu_output_dim = cpu_output_dim.astype(npu_output_dim.dtype)
|
||||
self.assertRtolEqual(cpu_output_dim, npu_output_dim)
|
||||
|
||||
def test_sum_shape_format_fp16_1d(self):
|
||||
format_list = [0, 3]
|
||||
shape_format = [
|
||||
[np.float16, i, [18]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp32_1d(self):
|
||||
format_list = [0, 3]
|
||||
shape_format = [
|
||||
[np.float32, i, [18]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp16_2d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float16, i, [256, 1000]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp32_2d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float32, i, [256, 1000]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp16_3d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float16, i, [32, 48, 64]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp32_3d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float32, i, [32, 48, 64]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp16_4d(self):
|
||||
format_list = [0, 4, 29]
|
||||
shape_format = [
|
||||
[np.float16, i, [32, 24, 18, 18]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_fp32_4d(self):
|
||||
format_list = [0, 3, 4, 29]
|
||||
shape_format = [
|
||||
[np.float32, i, [32, 24, 18, 18]] for i in format_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_shape_format_int32(self):
|
||||
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):
|
||||
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)
|
||||
|
||||
def test_sum_shape_format_bool(self):
|
||||
format_list = [0, 2, 30]
|
||||
shape_list = [[18], [256, 1000], [32, 48, 64], [32, 24, 18, 18]]
|
||||
shape_format = [
|
||||
[np.bool, i, j] for i in format_list for j in shape_list
|
||||
]
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp16_1d(self):
|
||||
format_list = [0, 3]
|
||||
shape_format = [
|
||||
[np.float16, i, [18]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp32_1d(self):
|
||||
format_list = [0, 3]
|
||||
shape_format = [
|
||||
[np.float32, i, [18]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp16_2d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float16, i, [256, 1000]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp32_2d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float32, i, [256, 1000]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp16_3d(self):
|
||||
# TODO(ascend): Insufficient precision
|
||||
# format=29精度不满足 format_list = [0, 3, 29]
|
||||
format_list = [0, 3]
|
||||
shape_format = [
|
||||
[np.float16, i, [32, 48, 64]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp32_3d(self):
|
||||
format_list = [0, 3, 29]
|
||||
shape_format = [
|
||||
[np.float32, i, [32, 48, 64]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp16_4d(self):
|
||||
format_list = [0, 3]
|
||||
shape_format = [
|
||||
[np.float16, i, [16, 16, 9, 9]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_fp32_4d(self):
|
||||
format_list = [0, 3, 4]
|
||||
shape_format = [
|
||||
[np.float32, i, [32, 24, 18, 18]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
|
||||
def test_sum_dim_shape_format_int32(self):
|
||||
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):
|
||||
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_shape_format_bool(self):
|
||||
format_list = [0, 2, 30]
|
||||
shape_list = [[18], [256, 1000], [32, 48, 64], [32, 24, 18, 18]]
|
||||
shape_format = [
|
||||
[np.bool, 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):
|
||||
format_list = [0, 3, 4]
|
||||
shape_format = [
|
||||
[np.float32, i, [2, 0, 3]] for i in format_list
|
||||
]
|
||||
self.sum_dim_result(shape_format)
|
||||
self.sum_result(shape_format)
|
||||
|
||||
def test_sum_same_dim(self):
|
||||
npu_input = torch.randn(128, 256).npu()
|
||||
dim = [1, -1]
|
||||
try:
|
||||
torch.sum(npu_input, dim=dim)
|
||||
except RuntimeError as e:
|
||||
self.assertRegex(str(e), "dim 1 appears multiple times in the list of dims")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -43,30 +43,6 @@ class TestDropoutLayers(TestCase):
|
||||
output = m(input1)
|
||||
self.assertEqual(output is not None, True)
|
||||
|
||||
def test_native_dropout(self):
|
||||
for train in [True, False]:
|
||||
for p in [0.0, 1.0, 0.5]:
|
||||
cpu_x = torch.randn(5, 5)
|
||||
x = cpu_x.npu()
|
||||
x_ref = cpu_x.npu()
|
||||
x.requires_grad = True
|
||||
x_ref.requires_grad = True
|
||||
grad = torch.rand(5, 5).npu()
|
||||
torch.manual_seed(123)
|
||||
npu_o = torch.native_dropout(x, p, train)
|
||||
o = npu_o[0]
|
||||
o.backward(grad)
|
||||
torch.manual_seed(123)
|
||||
o_ref = torch.dropout(x_ref, p, train)
|
||||
o_ref.backward(grad)
|
||||
self.assertRtolEqual(o.cpu().detach(), o_ref.cpu().detach())
|
||||
self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())
|
||||
if p in [0.0, 1.0]:
|
||||
cpu_o = torch.native_dropout(cpu_x, p, train)
|
||||
self.assertRtolEqual(cpu_o[0], npu_o[0].cpu())
|
||||
self.assertRtolEqual(cpu_o[1], npu_o[1].cpu())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
torch.npu.set_device(0)
|
||||
run_tests()
|
||||
run_tests()
|
||||
@@ -365,12 +365,6 @@ class TestAmp(TestCase):
|
||||
loss = output.sum()
|
||||
loss.backward()
|
||||
|
||||
def test_autocast_enabled(self):
|
||||
output1 = torch.npu.amp.autocast()
|
||||
self.assertTrue(output1._enabled)
|
||||
output2 = torch.npu.amp.autocast(False)
|
||||
self.assertFalse(output2._enabled)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -30,28 +30,6 @@ class GeneratorTest(TestCase):
|
||||
gen.manual_seed(1234)
|
||||
self.assertEqual(gen.initial_seed(), 1234)
|
||||
|
||||
def test_generator_device(self):
|
||||
gen = torch_npu._C.Generator()
|
||||
self.assertEqual(gen.device.type, "cpu")
|
||||
|
||||
device_id = 0
|
||||
torch.npu.set_device(device_id)
|
||||
npu_device = torch.randn(2).npu(device_id).device
|
||||
device_types = [
|
||||
"npu",
|
||||
"npu:"+str(device_id),
|
||||
torch.device("npu:"+str(device_id)),
|
||||
torch.device("npu:"+str(device_id)).type,
|
||||
npu_device,
|
||||
0
|
||||
]
|
||||
for device_type in device_types:
|
||||
gen = torch_npu._C.Generator(device_type)
|
||||
self.assertEqual(gen.device.type, "npu")
|
||||
|
||||
gen = torch_npu._C.Generator(device=device_type)
|
||||
self.assertEqual(gen.device.type, "npu")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_tests()
|
||||
|
||||
@@ -372,17 +372,6 @@ class TestNpu(TestCase):
|
||||
self.assertEqual(src, dst)
|
||||
self.assertFalse(dst.is_pinned())
|
||||
|
||||
def test_pin_memory(self):
|
||||
x = torch.randn(10, 20)
|
||||
self.assertFalse(x.is_pinned())
|
||||
pinned = x.pin_memory()
|
||||
self.assertTrue(pinned.is_pinned())
|
||||
self.assertEqual(pinned, x)
|
||||
self.assertNotEqual(pinned.data_ptr(), x.data_ptr())
|
||||
# test that pin_memory on already pinned tensor has no effect
|
||||
self.assertIs(pinned, pinned.pin_memory())
|
||||
self.assertEqual(pinned.data_ptr(), pinned.pin_memory().data_ptr())
|
||||
|
||||
def test_torch_manual_seed_seeds_npu_devices(self):
|
||||
with freeze_rng_state():
|
||||
x = torch.zeros(4, 4).float() # Not support device RNG (.npu()).
|
||||
@@ -637,10 +626,6 @@ class TestNpu(TestCase):
|
||||
self.assertRtolEqual(cpu_out.numpy(), npu_output3.cpu().numpy())
|
||||
self.assertRtolEqual(cpu_out.numpy(), npu_output4.cpu().numpy())
|
||||
self.assertRtolEqual(cpu_out.numpy(), npu_output5.cpu().numpy())
|
||||
|
||||
cpu_out = x_cpu.new_ones(2)
|
||||
npu_output6 = x.new_ones(torch.tensor(2), device='npu', requires_grad=False)
|
||||
self.assertRtolEqual(cpu_out.numpy(), npu_output6.cpu().numpy())
|
||||
|
||||
def test_function_tensor_new_tensor(self):
|
||||
x_cpu = torch.tensor((), dtype=torch.float32)
|
||||
|
||||
@@ -555,37 +555,6 @@ class TestOnnxOps(TestCase):
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
def test_wrapper_npu_fused_attention_layernorm_qkv_fwd(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.q_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).to(dtype=to_dtype).npu()
|
||||
self.k_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).to(dtype=to_dtype).npu()
|
||||
self.v_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).to(dtype=to_dtype).npu()
|
||||
self.q_bias = torch.rand(1024).to(dtype=to_dtype).npu()
|
||||
self.k_bias = torch.rand(1024).to(dtype=to_dtype).npu()
|
||||
self.v_bias = torch.rand(1024).to(dtype=to_dtype).npu()
|
||||
|
||||
def forward(self, input_, gamma, beta):
|
||||
return torch_npu.npu_fused_attention_layernorm_qkv_fwd(input_,
|
||||
self.q_weight, self.k_weight, self.v_weight,
|
||||
gamma, beta,
|
||||
self.q_bias, self.k_bias, self.v_bias,
|
||||
seq_len=512, num_heads=16, eps=1e-05)
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
input_ = torch.rand(12288, 1024).uniform_(-6, 6).to(dtype=to_dtype).npu()
|
||||
gamma = torch.rand(1024).to(dtype=to_dtype).npu()
|
||||
beta = torch.rand(1024).to(dtype=to_dtype).npu()
|
||||
model = Model().to("npu")
|
||||
self.onnx_export(model, (input_, gamma, beta), onnx_model_name,
|
||||
["input_", "gamma", "beta"], ["o_1", "o_2", "o_3", "o_4", "o_5", "o_6"])
|
||||
|
||||
to_dtype = torch.float16
|
||||
onnx_model_name = "model_npu_fused_attention_layernorm_qkv_fwd.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -513,6 +513,42 @@ class TestOnnxOps(TestCase):
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
def test_wrapper_npu_fused_attention_layernorm_qkv_fwd(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
super(Model, self).__init__()
|
||||
q_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).half()
|
||||
k_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).half()
|
||||
v_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).half()
|
||||
self.fused_q_w = q_weight.npu().t().contiguous().npu_format_cast(29)
|
||||
self.fused_k_w = k_weight.npu().t().contiguous().npu_format_cast(29)
|
||||
self.fused_v_w = v_weight.npu().t().contiguous().npu_format_cast(29)
|
||||
self.q_bias = torch.rand(1024).half().npu()
|
||||
self.k_bias = torch.rand(1024).half().npu()
|
||||
self.v_bias = torch.rand(1024).half().npu()
|
||||
|
||||
def forward(self, input_, gamma, beta):
|
||||
return torch_npu.npu_fused_attention_layernorm_qkv_fwd(input_,
|
||||
self.fused_q_w, self.fused_k_w, self.fused_v_w, gamma, beta,
|
||||
self.q_bias, self.k_bias, self.v_bias, 512, 16)
|
||||
|
||||
def export_onnx(onnx_model_name):
|
||||
ln_input = torch.rand(12288, 1024).uniform_(-6, 6).half()
|
||||
input_ = ln_input.npu().npu_format_cast(29)
|
||||
gamma = torch.rand(1024).half().npu()
|
||||
beta = torch.rand(1024).half().npu()
|
||||
|
||||
model = Model().to("npu")
|
||||
model(input_, gamma, beta)
|
||||
self.onnx_export(model, (input_, gamma, beta), onnx_model_name,
|
||||
["input_", "gamma", "beta"], ["o_1", "o_2", "o_3",
|
||||
"o_4", "o_5", "o_6"])
|
||||
|
||||
onnx_model_name = "model_npu_fused_attention_layernorm_qkv_fwd.onnx"
|
||||
export_onnx(onnx_model_name)
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
def test_wrapper_npu_fused_attention_score_fwd(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
@@ -655,6 +691,7 @@ class TestOnnxOps(TestCase):
|
||||
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
|
||||
onnx_model_name)))
|
||||
|
||||
|
||||
def test_wrapper_npu_bounding_box_encode(self):
|
||||
class Model(torch.nn.Module):
|
||||
def __init__(self):
|
||||
|
||||
@@ -12,14 +12,13 @@
|
||||
# WITHOUT 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 shutil
|
||||
|
||||
import torch
|
||||
|
||||
import torch_npu
|
||||
from torch_npu.testing.testcase import TestCase, run_tests
|
||||
from torch_npu.testing.testcase import TestCase
|
||||
|
||||
worker_id = 1
|
||||
|
||||
@@ -60,9 +59,8 @@ class TrainModel:
|
||||
class TestNpuProfiler(TestCase):
|
||||
TRACE_FILE_NAME = "trace_view.json"
|
||||
KERNEL_FILE_NAME = "kernel_details.csv"
|
||||
OPERATOR_FILE_NAME = "operator_details.csv"
|
||||
OPERATOR_MEMORY = "operator_memory.csv"
|
||||
MEMORY_RECORD = "memory_record.csv"
|
||||
MEMORY_FORM_NAME = "memory_view_form.csv"
|
||||
MEMORY_LINE_CHART_NAME = "memory_view_line_chart.csv"
|
||||
results_path = "./results"
|
||||
model_train = TrainModel()
|
||||
small_steps = 1
|
||||
@@ -87,10 +85,10 @@ class TestNpuProfiler(TestCase):
|
||||
) as prof:
|
||||
for step in range(self.small_steps):
|
||||
self.model_train.train_one_step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.TRACE_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.KERNEL_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.OPERATOR_FILE_NAME))
|
||||
self.assertEqual(True, self._check_trace_view_keywords(worker_name, ["torch_to_npu", "acl_to_npu"]))
|
||||
self.assertEqual(True, self._has_trace_view(worker_name))
|
||||
self.assertEqual(True, self._has_kernel_details(worker_name))
|
||||
self.assertEqual(True,
|
||||
self._check_trace_view_keywords(worker_name, ["torch_to_acl", "torch_to_npu", "acl_to_npu"]))
|
||||
|
||||
def test_activities_cpu(self):
|
||||
worker_name = self.worker_name
|
||||
@@ -100,11 +98,10 @@ class TestNpuProfiler(TestCase):
|
||||
) as prof:
|
||||
for step in range(self.small_steps):
|
||||
self.model_train.train_one_step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.TRACE_FILE_NAME))
|
||||
self.assertEqual(False, self._has_view_result(worker_name, self.KERNEL_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.OPERATOR_FILE_NAME))
|
||||
self.assertEqual(True, self._has_trace_view(worker_name))
|
||||
self.assertEqual(False, self._has_kernel_details(worker_name))
|
||||
self.assertEqual(False,
|
||||
self._check_trace_view_keywords(worker_name, ["torch_to_npu", "acl_to_npu"]))
|
||||
self._check_trace_view_keywords(worker_name, ["torch_to_acl", "torch_to_npu", "acl_to_npu"]))
|
||||
|
||||
def test_activities_npu(self):
|
||||
worker_name = self.worker_name
|
||||
@@ -114,11 +111,10 @@ class TestNpuProfiler(TestCase):
|
||||
) as prof:
|
||||
for step in range(self.small_steps):
|
||||
self.model_train.train_one_step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.TRACE_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.KERNEL_FILE_NAME))
|
||||
self.assertEqual(False, self._has_view_result(worker_name, self.OPERATOR_FILE_NAME))
|
||||
self.assertEqual(True, self._has_trace_view(worker_name))
|
||||
self.assertEqual(True, self._has_kernel_details(worker_name))
|
||||
self.assertEqual(True, self._check_trace_view_keywords(worker_name, ["acl_to_npu"]))
|
||||
self.assertEqual(False, self._check_trace_view_keywords(worker_name, ["torch_to_npu"]))
|
||||
self.assertEqual(False, self._check_trace_view_keywords(worker_name, ["torch_to_acl", "torch_to_npu"]))
|
||||
|
||||
def test_record_shapes(self):
|
||||
worker_name = self.worker_name
|
||||
@@ -128,9 +124,8 @@ class TestNpuProfiler(TestCase):
|
||||
) as prof:
|
||||
for step in range(self.small_steps):
|
||||
self.model_train.train_one_step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.TRACE_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.KERNEL_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.OPERATOR_FILE_NAME))
|
||||
self.assertEqual(True, self._has_trace_view(worker_name))
|
||||
self.assertEqual(True, self._has_kernel_details(worker_name))
|
||||
self.assertEqual(True, self._check_trace_view_keywords(worker_name, ["Input Dims", "Input type"]))
|
||||
|
||||
def test_with_stack(self):
|
||||
@@ -141,9 +136,8 @@ class TestNpuProfiler(TestCase):
|
||||
) as prof:
|
||||
for step in range(self.small_steps):
|
||||
self.model_train.train_one_step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.TRACE_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.KERNEL_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.OPERATOR_FILE_NAME))
|
||||
self.assertEqual(True, self._has_trace_view(worker_name))
|
||||
self.assertEqual(True, self._has_kernel_details(worker_name))
|
||||
self.assertEqual(True, self._check_trace_view_keywords(worker_name, ["Call stack"]))
|
||||
|
||||
def test_schedule(self):
|
||||
@@ -155,9 +149,8 @@ class TestNpuProfiler(TestCase):
|
||||
for step in range(self.large_steps):
|
||||
self.model_train.train_one_step()
|
||||
prof.step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.TRACE_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.KERNEL_FILE_NAME))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.OPERATOR_FILE_NAME))
|
||||
self.assertEqual(True, self._has_trace_view(worker_name))
|
||||
self.assertEqual(True, self._has_kernel_details(worker_name))
|
||||
|
||||
def test_export_chrome_trace(self):
|
||||
trace_path = f"{self.results_path}/chrome_trace.json"
|
||||
@@ -175,8 +168,8 @@ class TestNpuProfiler(TestCase):
|
||||
) as prof:
|
||||
for step in range(self.small_steps):
|
||||
self.model_train.train_one_step()
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.OPERATOR_MEMORY))
|
||||
self.assertEqual(True, self._has_view_result(worker_name, self.MEMORY_RECORD))
|
||||
self.assertEqual(True, self._has_memory_view_form(worker_name))
|
||||
self.assertEqual(True, self._has_memory_view_line_chart(worker_name))
|
||||
|
||||
def _get_tensorboard_output(self, worker_name: str) -> str:
|
||||
sub_dirs = os.listdir(os.path.realpath(self.results_path))
|
||||
@@ -185,14 +178,32 @@ class TestNpuProfiler(TestCase):
|
||||
return os.path.join(self.results_path, sub_dir, "ASCEND_PROFILER_OUTPUT")
|
||||
return ""
|
||||
|
||||
def _has_view_result(self, worker_name: str, view_name: str) -> bool:
|
||||
def _has_trace_view(self, worker_name: str) -> bool:
|
||||
output_path = self._get_tensorboard_output(worker_name)
|
||||
if os.path.isdir(output_path):
|
||||
return os.path.isfile(os.path.join(output_path, view_name))
|
||||
return os.path.isfile(os.path.join(output_path, self.TRACE_FILE_NAME))
|
||||
return False
|
||||
|
||||
def _has_kernel_details(self, worker_name: str) -> bool:
|
||||
output_path = self._get_tensorboard_output(worker_name)
|
||||
if os.path.isdir(output_path):
|
||||
return os.path.isfile(os.path.join(output_path, self.KERNEL_FILE_NAME))
|
||||
return False
|
||||
|
||||
def _has_memory_view_form(self, worker_name: str) -> bool:
|
||||
output_path = self._get_tensorboard_output(worker_name)
|
||||
if os.path.isdir(output_path):
|
||||
return os.path.isfile(os.path.join(output_path, self.MEMORY_FORM_NAME))
|
||||
return False
|
||||
|
||||
def _has_memory_view_line_chart(self, worker_name: str) -> bool:
|
||||
output_path = self._get_tensorboard_output(worker_name)
|
||||
if os.path.isdir(output_path):
|
||||
return os.path.isfile(os.path.join(output_path, self.MEMORY_LINE_CHART_NAME))
|
||||
return False
|
||||
|
||||
def _check_trace_view_keywords(self, worker_name: str, keywords: list) -> bool:
|
||||
if not self._has_view_result(worker_name, self.TRACE_FILE_NAME):
|
||||
if not self._has_trace_view(worker_name):
|
||||
return False
|
||||
trace_path = os.path.join(self._get_tensorboard_output(worker_name), self.TRACE_FILE_NAME)
|
||||
file_size = os.path.getsize(trace_path)
|
||||
@@ -201,8 +212,3 @@ class TestNpuProfiler(TestCase):
|
||||
with open(trace_path, "rt") as file:
|
||||
all_data = file.read()
|
||||
return all(all_data.find(keyword) != -1 for keyword in keywords)
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# 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
|
||||
|
||||
device = 'npu:0'
|
||||
torch.npu.set_device(device)
|
||||
|
||||
def get_npu_type(type_name):
|
||||
if isinstance(type_name, type):
|
||||
type_name = '{}.{}'.format(type_name.__module__, type_name.__name__)
|
||||
module, name = type_name.rsplit('.', 1)
|
||||
assert module == 'torch'
|
||||
return getattr(torch.npu, name)
|
||||
|
||||
class TestGenerators(TestCase):
|
||||
def test_generator(self):
|
||||
g_npu = torch.Generator(device=device)
|
||||
print(g_npu.device)
|
||||
self.assertExpectedInline(str(g_npu.device), '''npu:0''')
|
||||
|
||||
def test_default_generator(self):
|
||||
output = torch.default_generator
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run_tests()
|
||||
@@ -25,11 +25,11 @@ torch.npu.set_device(device)
|
||||
class TestPointwiseOps(TestCase):
|
||||
|
||||
def test_real(self):
|
||||
cpu_input = torch.randn(4, dtype=torch.float32)
|
||||
npu_input = cpu_input.npu()
|
||||
cpu_output = torch.real(cpu_input)
|
||||
npu_output = torch.real(npu_input)
|
||||
self.assertEqual(cpu_output, npu_output)
|
||||
input1 = torch.randn(4, dtype=torch.float32)
|
||||
input1 = input1.npu()
|
||||
with self.assertRaisesRegex(RuntimeError,
|
||||
r'real is not implemented for tensors with non-complex dtypes.'):
|
||||
cpu_output = torch.real(input1)
|
||||
|
||||
def test_square(self):
|
||||
input1 = torch.randn(4)
|
||||
@@ -113,7 +113,7 @@ class TestOtherOps(TestCase):
|
||||
|
||||
def test_rot90(self):
|
||||
x = torch.arange(4, device=device).view(2, 2)
|
||||
output = torch.rot90(x, 1, [0, 1]).int()
|
||||
output = torch.rot90(x, 1, [0, 1])
|
||||
output_expected = torch.tensor([[1, 3], [0, 2]]).int()
|
||||
self.assertRtolEqual(output.cpu(), output_expected)
|
||||
|
||||
@@ -166,8 +166,8 @@ class TestBLOps(TestCase):
|
||||
c = torch.randn(5, 6)
|
||||
d = torch.randn(6, 7)
|
||||
cpu_output = torch.chain_matmul(a, b, c, d)
|
||||
npu_output = torch.chain_matmul(a.half().npu(), b.half().npu(), c.half().npu(), d.half().npu())
|
||||
self.assertEqual(cpu_output, npu_output, prec = 1e-2)
|
||||
npu_output = torch.chain_matmul(a.npu(), b.npu(), c.npu(), d.npu())
|
||||
self.assertEqual(cpu_output, npu_output)
|
||||
|
||||
def test_trapz(self):
|
||||
def test_dx(sizes, dim, dx):
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import unittest
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
|
||||
@@ -23,7 +21,6 @@ device = 'npu:0'
|
||||
torch.npu.set_device(device)
|
||||
|
||||
class TestUtilities(TestCase):
|
||||
@unittest.skip("Different compile parameters will cause different results")
|
||||
def test_compiled_with_cxx11_abi(self):
|
||||
output = torch.compiled_with_cxx11_abi()
|
||||
self.assertTrue(output)
|
||||
|
||||
Vendored
+1
-3
@@ -165,9 +165,7 @@ typedef enum {
|
||||
ACL_FORMAT_FRACTAL_NZ = 29,
|
||||
ACL_FORMAT_NCDHW = 30,
|
||||
ACL_FORMAT_NDC1HWC0 = 32,
|
||||
ACL_FRACTAL_Z_3D = 33,
|
||||
ACL_FORMAT_NC = 35,
|
||||
ACL_FORMAT_NCL = 47
|
||||
ACL_FRACTAL_Z_3D = 33
|
||||
} aclFormat;
|
||||
|
||||
typedef enum {
|
||||
|
||||
Vendored
-91
@@ -1,91 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Huawei Technologies Co., Ltd. 2023. All rights reserved.
|
||||
*
|
||||
* 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 OP_API_ACL_OP_API_H
|
||||
#define OP_API_ACL_OP_API_H
|
||||
|
||||
#include <acl/acl_base.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct aclOpExecutor aclOpExecutor;
|
||||
typedef struct aclTensor aclTensor;
|
||||
typedef struct aclScalar aclScalar;
|
||||
typedef struct aclIntArray aclIntArray;
|
||||
typedef struct aclFloatArray aclFloatArray;
|
||||
typedef struct aclBoolArray aclBoolArray;
|
||||
typedef struct aclTensorList aclTensorList;
|
||||
|
||||
constexpr int OK = 0;
|
||||
constexpr int ERROR = 1;
|
||||
|
||||
enum aclnnTensorPlacement {
|
||||
ACLNN_MEMTYPE_DEVICE, ///< Tensor位于Device上的HBM内存
|
||||
ACLNN_MEMTYPE_HOST, ///< Tensor位于Host
|
||||
ACLNN_MEMTYPE_HOST_COMPILE_INDEPENDENT, ///< Tensor位于Host,且数据紧跟在结构体后面
|
||||
ACLNN_MEMTYPE_END
|
||||
};
|
||||
|
||||
#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
|
||||
|
||||
ACL_FUNC_VISIBILITY aclTensor *aclCreateTensor(const int64_t *view_dims, uint64_t view_dims_num, aclDataType data_type,
|
||||
const int64_t *stride, int64_t offset, aclFormat format,
|
||||
const int64_t *storage_dims, uint64_t storage_dims_num,
|
||||
void *tensor_data);
|
||||
|
||||
ACL_FUNC_VISIBILITY aclScalar *aclCreateScalar(void *value, aclDataType data_type);
|
||||
ACL_FUNC_VISIBILITY aclIntArray *aclCreateIntArray(const int64_t *value, uint64_t size);
|
||||
ACL_FUNC_VISIBILITY aclFloatArray *aclCreateFloatArray(const float *value, uint64_t size);
|
||||
ACL_FUNC_VISIBILITY aclBoolArray *aclCreateBoolArray(const bool *value, uint64_t size);
|
||||
ACL_FUNC_VISIBILITY aclTensorList *aclCreateTensorList(const aclTensor *const *value, uint64_t size);
|
||||
|
||||
ACL_FUNC_VISIBILITY int aclDestroyTensor(const aclTensor *tensor);
|
||||
ACL_FUNC_VISIBILITY int aclDestroyScalar(const aclScalar *scalar);
|
||||
ACL_FUNC_VISIBILITY int aclDestroyIntArray(const aclIntArray *array);
|
||||
ACL_FUNC_VISIBILITY int aclDestroyFloatArray(const aclFloatArray *array);
|
||||
ACL_FUNC_VISIBILITY int aclDestroyBoolArray(const aclBoolArray *array);
|
||||
ACL_FUNC_VISIBILITY int aclDestroyTensorList(const aclTensorList *array);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // OP_API_ACL_OP_API_H
|
||||
Vendored
-3
@@ -32,8 +32,6 @@ extern "C" {
|
||||
#define ACL_PROF_TRAINING_TRACE 0x0040ULL
|
||||
#define ACL_PROF_MSPROFTX 0x0080ULL
|
||||
#define ACL_PROF_RUNTIME_API 0x0100ULL
|
||||
#define ACL_PROF_TASK_TIME_L0 0x0800ULL
|
||||
#define ACL_PROF_TASK_MEMORY 0x1000ULL
|
||||
|
||||
/**
|
||||
* @deprecated please use aclprofGetOpTypeLen and aclprofGetOpTNameLen instead
|
||||
@@ -48,7 +46,6 @@ typedef enum {
|
||||
ACL_AICORE_L0B_AND_WIDTH = 3,
|
||||
ACL_AICORE_RESOURCE_CONFLICT_RATIO = 4,
|
||||
ACL_AICORE_MEMORY_UB = 5,
|
||||
ACL_AICORE_L2_CACHE = 6,
|
||||
ACL_AICORE_NONE = 0xFF
|
||||
} aclprofAicoreMetrics;
|
||||
|
||||
|
||||
Vendored
-16
@@ -913,22 +913,6 @@ ACL_FUNC_VISIBILITY aclError aclrtCreateStreamWithConfig(aclrtStream *stream, ui
|
||||
*/
|
||||
ACL_FUNC_VISIBILITY aclError aclrtDestroyStream(aclrtStream stream);
|
||||
|
||||
/**
|
||||
* @ingroup AscendCL
|
||||
* @brief destroy stream instance by force
|
||||
*
|
||||
* @par Function
|
||||
* Can only destroy streams created through the aclrtCreateStream interface
|
||||
*
|
||||
* @param stream [IN] the stream to destroy
|
||||
*
|
||||
* @retval ACL_SUCCESS The function is successfully executed.
|
||||
* @retval OtherValues Failure
|
||||
*
|
||||
* @see aclrtCreateStream
|
||||
*/
|
||||
ACL_FUNC_VISIBILITY aclError aclrtDestroyStreamForce(aclrtStream stream);
|
||||
|
||||
/**
|
||||
* @ingroup AscendCL
|
||||
* @brief block the host until all tasks
|
||||
|
||||
Vendored
-1
@@ -37,7 +37,6 @@ aclError aclrtSetStreamFailureMode(aclrtStream stream, uint64_t mode) { return 0
|
||||
aclError aclrtSetOpWaitTimeout(uint32_t timeout) { return 0; }
|
||||
aclError aclrtCreateStreamWithConfig(aclrtStream *stream, uint32_t priority, uint32_t flag) { return 0; }
|
||||
aclError aclrtDestroyStream(aclrtStream stream){return 0;}
|
||||
aclError aclrtDestroyStreamForce(aclrtStream stream){return 0;}
|
||||
aclError aclrtSynchronizeStream(aclrtStream stream){return 0;}
|
||||
aclError aclrtSynchronizeStreamWithTimeout(aclrtStream stream, int32_t timeout){return 0;}
|
||||
|
||||
|
||||
+15
-27
@@ -15,13 +15,13 @@
|
||||
|
||||
import os
|
||||
import re
|
||||
import gc
|
||||
import sys
|
||||
import builtins
|
||||
import inspect
|
||||
import types
|
||||
import atexit
|
||||
import traceback
|
||||
import warnings
|
||||
|
||||
from builtins import isinstance as builtin_isinstance
|
||||
from typing import Set, Type
|
||||
@@ -34,22 +34,12 @@ try:
|
||||
import torch_npu.npu
|
||||
except ImportError as e:
|
||||
if "libhccl.so" in str(e):
|
||||
ei = sys.exc_info()
|
||||
if ("ASCEND_OPP_PATH" in os.environ):
|
||||
newErr = ImportError(str(ei[1]) + ". Please check that the compiler package is installed. " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
else :
|
||||
newErr = ImportError(str(ei[1]) + ". Please check that the cann package is installed. " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
traceback.print_exception(ei[0], newErr, ei[2])
|
||||
sys.exit()
|
||||
|
||||
raise Exception(f"Please check that the cann package is installed, " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
if "libascendcl.so" in str(e):
|
||||
ei = sys.exc_info()
|
||||
newErr = ImportError(str(ei[1]) + ". Please check that the runtime package is installed. " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
traceback.print_exception(ei[0], newErr, ei[2])
|
||||
sys.exit()
|
||||
raise Exception(f"Please check that the runtime package is installed, " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
else:
|
||||
traceback.print_exc()
|
||||
@@ -73,10 +63,9 @@ from .version import __version__ as __version__
|
||||
|
||||
|
||||
cann_pytorch_version_map = {
|
||||
"6.3.RC2" : ["1.8.1.post2", "1.11.0.post1", "2.0.0.rc1"],
|
||||
"6.3.RC1" : ["1.8.1.post1", "1.11.0"],
|
||||
"6.1.RC1" : ["1.8.1.post1", "1.11.0"],
|
||||
"6.0.1" : ["1.8.1", "1.11.0.rc2"],
|
||||
"6.0.1" : ["1.5.0.post8", "1.8.1", "1.11.0.rc2"],
|
||||
"6.0.RC1" : ["1.8.1", "1.11.0.rc1"]
|
||||
}
|
||||
|
||||
@@ -99,27 +88,27 @@ def cann_package_check():
|
||||
if "ASCEND_HOME_PATH" in os.environ:
|
||||
ascend_home_path = os.environ["ASCEND_HOME_PATH"]
|
||||
if not os.path.exists(ascend_home_path):
|
||||
raise Exception(f"ASCEND_HOME_PATH : {ascend_home_path} does not exist. " \
|
||||
raise Exception(f"ASCEND_HOME_PATH : {ascend_home_path} does not exist." \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
# check whether environment variables are correctly configured
|
||||
if "ASCEND_OPP_PATH" not in os.environ:
|
||||
raise Exception(f"ASCEND_OPP_PATH environment variable is not set. " \
|
||||
raise Exception(f"ASCEND_OPP_PATH environment variable is not set." \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
ascend_opp_path = os.environ["ASCEND_OPP_PATH"]
|
||||
if not os.path.exists(ascend_opp_path):
|
||||
raise Exception(f"ASCEND_OPP_PATH : {ascend_opp_path} does not exist. " \
|
||||
raise Exception(f"ASCEND_OPP_PATH : {ascend_opp_path} does not exist." \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
ascend_runtime_path = os.path.join(ascend_home_path, "runtime")
|
||||
if not os.path.exists(ascend_runtime_path):
|
||||
raise Exception(f"{ascend_runtime_path} does not exist. " \
|
||||
raise Exception(f"{ascend_runtime_path} does not exist, " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
ascend_compiler_path = os.path.join(ascend_home_path, "compiler")
|
||||
if not os.path.exists(ascend_compiler_path):
|
||||
raise Exception(f"{ascend_compiler_path} does not exist. " \
|
||||
raise Exception(f"{ascend_compiler_path} does not exist, " \
|
||||
"Please run 'source set_env.sh' in the CANN installation path.")
|
||||
|
||||
# get the cann version
|
||||
@@ -128,10 +117,10 @@ def cann_package_check():
|
||||
# check whether the CANN package version matches the pytorch version
|
||||
if cann_version in cann_pytorch_version_map and \
|
||||
torch_npu.__version__ not in cann_pytorch_version_map[cann_version]:
|
||||
print(f"Warning : CANN package version {cann_version} and PyTorch version {torch_npu.__version__} " \
|
||||
"is not matched, please check the README in repo of https://gitee.com/ascend/pytorch")
|
||||
warnings.warn(f"CANN package version {cann_version} and PyTorch version {torch_npu.__version__}" \
|
||||
"is not matched, please check the README in repo of https://gitee.com/ascend/pytorch")
|
||||
else:
|
||||
print(f"Warning : ASCEND_HOME_PATH environment variable is not set.")
|
||||
warnings.warn(f"ASCEND_HOME_PATH environment variable is not set.")
|
||||
|
||||
cann_package_check()
|
||||
|
||||
@@ -253,7 +242,6 @@ torch_npu._C._initExtension()
|
||||
|
||||
# NPU exit, need to synchronize devices
|
||||
def _npu_shutdown():
|
||||
gc.collect()
|
||||
torch_npu._C._npu_shutdown()
|
||||
|
||||
|
||||
|
||||
@@ -160,7 +160,7 @@ class NpuPreGenDropout(torch.nn.Dropout):
|
||||
return return_obj
|
||||
|
||||
if self.p not in NpuPreGenDropout.task_dict:
|
||||
raise RuntimeError(f"NpuPreGenDropout input prob error! "
|
||||
raise RuntimeError("NpuPreGenDropout input prob error! "
|
||||
"You Only Register prob:{NpuPreGenDropout.task_dict.keys()}")
|
||||
|
||||
tmp_len = reduce(lambda a, b: a * b, x.shape)
|
||||
|
||||
@@ -118,7 +118,6 @@ def wrapper_hccl(fn):
|
||||
def patch_cuda():
|
||||
patchs = [
|
||||
['cuda', torch_npu.npu], ['cuda.amp', torch_npu.npu.amp],
|
||||
['cuda.random', torch_npu.npu.random],
|
||||
['cuda.amp.autocast_mode', torch_npu.npu.amp.autocast_mode],
|
||||
['cuda.amp.common', torch_npu.npu.amp.common],
|
||||
['cuda.amp.grad_scaler', torch_npu.npu.amp.grad_scaler]
|
||||
|
||||
@@ -58,44 +58,27 @@ PyObject * THPModule_npu_shutdown(PyObject * /* unused */)
|
||||
// on the current device, while aclrtFree Free device memory immediately.
|
||||
// aclrtSynchronizeDevice should be called before aclrtFree to ensure that
|
||||
// all of op tasks completed before device memory free.
|
||||
ASCEND_LOGI("NPU shutdown begin.");
|
||||
if (!c10_npu::NpuSysCtrl::GetInstance().GetInitFlag()) {
|
||||
Py_RETURN_NONE;
|
||||
if (c10_npu::NpuSysCtrl::GetInstance().GetInitFlag()) {
|
||||
try {
|
||||
c10_npu::npuSynchronizeDevice();
|
||||
} catch (std::exception& e) {
|
||||
NPU_LOGE("npuSynchronizeDevice failed err=:%s", e.what());
|
||||
}
|
||||
at_npu::native::GraphExecutor::GetInstance().Finalize();
|
||||
at_npu::native::TdtChannelForPrint::GetInstance().Finalize();
|
||||
THNPUCachingHostAllocator_emptyCache();
|
||||
try {
|
||||
c10_npu::NPUCachingAllocator::emptyCache();
|
||||
} catch (std::exception& e) {
|
||||
NPU_LOGE("NPUCachingAllocator::emptyCache failed err=:%s", e.what());
|
||||
}
|
||||
c10_npu::NpuSysCtrl::SysStatus status = c10_npu::NpuSysCtrl::GetInstance().Finalize();
|
||||
if (status != c10_npu::NpuSysCtrl::SysStatus::FINALIZE_SUCC) {
|
||||
fprintf(stdout, "THPModule_npu_shutdown failed.\n");
|
||||
} else {
|
||||
fprintf(stdout, "THPModule_npu_shutdown success.\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Return aclrtSynchronizeDevice result. If sync device fails, release host
|
||||
// resources forcibly, only record WARN logs when acl interface of stream
|
||||
// or event fails.
|
||||
bool success = true;
|
||||
try {
|
||||
ASCEND_LOGI("NPU shutdown synchronize device.");
|
||||
success = c10_npu::npuSynchronizeDevice(false);
|
||||
} catch (std::exception& e) {
|
||||
ASCEND_LOGE("npuSynchronizeDevice failed err=:%s", e.what());
|
||||
success = false;
|
||||
}
|
||||
if (!success) {
|
||||
ASCEND_LOGE("NPU shutdown synchronize device failed.");
|
||||
}
|
||||
ASCEND_LOGI("NPU shutdown GraphExecutor Finalize.");
|
||||
at_npu::native::GraphExecutor::GetInstance().Finalize();
|
||||
ASCEND_LOGI("NPU shutdown TdtChannelForPrint Finalize.");
|
||||
at_npu::native::TdtChannelForPrint::GetInstance().Finalize();
|
||||
THNPUCachingHostAllocator_emptyCache();
|
||||
try {
|
||||
ASCEND_LOGI("NPU shutdown NPUCachingAllocator emptyCache.");
|
||||
c10_npu::NPUCachingAllocator::emptyCache(success);
|
||||
} catch (std::exception& e) {
|
||||
ASCEND_LOGE("NPUCachingAllocator::emptyCache failed err=:%s", e.what());
|
||||
}
|
||||
ASCEND_LOGI("NPU shutdown NpuSysCtrl Finalize.");
|
||||
c10_npu::NpuSysCtrl::SysStatus status = c10_npu::NpuSysCtrl::GetInstance().Finalize();
|
||||
if (status != c10_npu::NpuSysCtrl::SysStatus::FINALIZE_SUCC) {
|
||||
ASCEND_LOGE("NPU shutdown failed.");
|
||||
} else {
|
||||
ASCEND_LOGI("NPU shutdown success.");
|
||||
}
|
||||
|
||||
Py_RETURN_NONE;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,7 @@ FILE(GLOB _ATEN_SRCS
|
||||
ops/loss/*.cpp
|
||||
ops/normalization/*.cpp
|
||||
ops/pooling/*.cpp
|
||||
ops/hcom/*.cpp
|
||||
ops/op_api/*.cpp)
|
||||
ops/hcom/*.cpp)
|
||||
|
||||
FILE(GLOB _EXCLUDE
|
||||
VariableTypeEverything.cpp
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
#include "torch_npu/csrc/aten/OverrideOperators.h"
|
||||
#include "torch_npu/csrc/core/npu/NPURunMode.h"
|
||||
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#ifndef BUILD_LIBTORCH
|
||||
#include "torch_npu/csrc/profiler/utils.h"
|
||||
#endif
|
||||
@@ -46,11 +42,7 @@ at::Tensor wrapper__argmax(const at::Tensor & self, c10::optional<int64_t> dim,
|
||||
#ifndef BUILD_LIBTORCH
|
||||
torch_npu::profiler::NPURecordFunction guard;
|
||||
#endif
|
||||
if (c10_npu::NpuRunMode::IsGraphMode() || !at_npu::native::env::CheckForbidInternalFormat()) {
|
||||
return at_npu::native::NPUNativeFunctions::argmax(self, dim, keepdim);
|
||||
} else {
|
||||
return at_npu::native::NPUNativeOpApiFunctions::argmax(self, dim, keepdim);
|
||||
}
|
||||
return at_npu::native::NPUNativeFunctions::argmax(self, dim, keepdim);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -28,10 +28,9 @@ namespace native {
|
||||
|
||||
c10::Scalar NPUNativeFunctions::_local_scalar_dense(const at::Tensor& self) {
|
||||
c10::Scalar r;
|
||||
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(
|
||||
AT_DISPATCH_ALL_TYPES_AND2(
|
||||
at::ScalarType::Half,
|
||||
at::ScalarType::Bool,
|
||||
at::ScalarType::BFloat16,
|
||||
self.scalar_type(),
|
||||
"_local_scalar_dense_npu",
|
||||
[&] {
|
||||
|
||||
@@ -20,7 +20,7 @@ bool NPUNativeFunctions::is_pinned(const at::Tensor& self, c10::optional<at::Dev
|
||||
return false;
|
||||
}
|
||||
|
||||
return THNPUCachingHostAllocator_isPinndPtr(self.storage().data());
|
||||
return false;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::_pin_memory(const at::Tensor& self, c10::optional<at::Device> device) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -76,9 +76,9 @@ at::Tensor &add_out_npu_nocheck(
|
||||
const at::Tensor &other,
|
||||
at::Scalar alpha) {
|
||||
auto unified_result = OpPreparation::binary_op_check(result, self, other, true);
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
adds_out_npu_nocheck(result, self, other.item(), alpha);
|
||||
} else if (OpPreparation::IsCPUScalar(self)) {
|
||||
} else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) {
|
||||
adds_out_npu_nocheck(result, other, self.item(), alpha);
|
||||
} else {
|
||||
alpha_check_npu(self.scalar_type(), alpha);
|
||||
@@ -209,7 +209,7 @@ at::Tensor &NPUNativeFunctions::add_(at::Tensor &self, const at::Tensor &other,
|
||||
c10::SmallVector<at::Tensor, N> outputs = {self_cp};
|
||||
CalcuOpUtil::CheckMemoryOverLaps(inputs, outputs);
|
||||
if (!NpuUtils::check_match(&self_cp)) {
|
||||
at::Tensor contiguous_self = NpuUtils::format_contiguous(self_cp);
|
||||
at::Tensor contiguous_self = NpuUtils::format_contiguous_add_copy_optimize(self_cp);
|
||||
at::Tensor result = add_out_npu_nocheck(contiguous_self, contiguous_self, other_cp, alpha);
|
||||
NpuUtils::format_fresh_view(self_cp, result);
|
||||
} else {
|
||||
@@ -226,7 +226,7 @@ at::Tensor &NPUNativeFunctions::add_(at::Tensor &self, const at::Tensor &other,
|
||||
|
||||
at::Tensor &NPUNativeFunctions::add_(at::Tensor &self, const at::Scalar &other, const at::Scalar &alpha) {
|
||||
if (!NpuUtils::check_match(&self)) {
|
||||
at::Tensor contiguous_self = NpuUtils::format_contiguous(self);
|
||||
at::Tensor contiguous_self = NpuUtils::format_contiguous_add_copy_optimize(self);
|
||||
at::Tensor result = adds_out_npu_nocheck(contiguous_self, contiguous_self, other, alpha);
|
||||
NpuUtils::format_fresh_view(self, result);
|
||||
} else {
|
||||
|
||||
@@ -54,9 +54,9 @@ at::Tensor& bitwise_and_out_npu_nocheck(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& other) {
|
||||
auto unified_result = OpPreparation::binary_op_check(result, self, other, true);
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
NPUNativeFunctions::bitwise_and_out(self, other.item(), result);
|
||||
} else if (OpPreparation::IsCPUScalar(self)) {
|
||||
} else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) {
|
||||
NPUNativeFunctions::bitwise_and_out(other, self.item(), result);
|
||||
} else {
|
||||
// executing the NPU operator
|
||||
|
||||
@@ -54,9 +54,9 @@ at::Tensor& bitwise_or_out_npu_nocheck(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& other) {
|
||||
auto unified_result = OpPreparation::binary_op_check(result, self, other, true);
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
NPUNativeFunctions::bitwise_or_out(self, other.item(), result);
|
||||
} else if (OpPreparation::IsCPUScalar(self)) {
|
||||
} else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) {
|
||||
NPUNativeFunctions::bitwise_or_out(other, self.item(), result);
|
||||
} else {
|
||||
// executing the NPU operator
|
||||
|
||||
@@ -60,9 +60,9 @@ at::Tensor& bitwise_xor_out_npu_nocheck(
|
||||
at::Tensor otherInput = (other.dtype() == at::ScalarType::Bool) ? NPUNativeFunctions::npu_dtype_cast(other, at::ScalarType::Int) : other;
|
||||
result = (result.dtype() == at::ScalarType::Bool) ? NPUNativeFunctions::npu_dtype_cast(result, at::ScalarType::Int) : result;
|
||||
|
||||
if (OpPreparation::IsCPUScalar(otherInput)) {
|
||||
if (otherInput.dim() == 0 && !at_npu::key::isDeviceTensor(otherInput)) {
|
||||
NPUNativeFunctions::bitwise_xor_out(selfInput, otherInput.item(), result);
|
||||
} else if (OpPreparation::IsCPUScalar(selfInput)) {
|
||||
} else if (selfInput.dim() == 0 && !at_npu::key::isDeviceTensor(selfInput)) {
|
||||
NPUNativeFunctions::bitwise_xor_out(otherInput, selfInput.item(), result);
|
||||
} else {
|
||||
// executing the NPU operator
|
||||
|
||||
@@ -27,8 +27,8 @@ at::Tensor& bmm_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, cons
|
||||
bool is_self_t = CalcuOpUtil::IsTransposeLastTwoDims(self);
|
||||
bool is_mat2_t = CalcuOpUtil::IsTransposeLastTwoDims(mat2);
|
||||
|
||||
at::Tensor contiguous_self = is_self_t ? self : NpuUtils::format_contiguous(self);
|
||||
at::Tensor contiguous_mat2 = is_mat2_t ? mat2 : NpuUtils::format_contiguous(mat2);
|
||||
at::Tensor contiguous_self = is_self_t ? self : NpuUtils::format_contiguous_add_copy_optimize(self);
|
||||
at::Tensor contiguous_mat2 = is_mat2_t ? mat2 : NpuUtils::format_contiguous_add_copy_optimize(mat2);
|
||||
|
||||
OpCommand cmd;
|
||||
cmd.Name("BatchMatMul")
|
||||
@@ -42,11 +42,6 @@ at::Tensor& bmm_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, cons
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeFunctions::bmm_out(const at::Tensor& self, const at::Tensor& mat2, at::Tensor& result) {
|
||||
TORCH_CHECK(self.device() == mat2.device(),
|
||||
"Expected all tensors to be on the same device, but found at least two devices, ",
|
||||
(self.device().type() == at_npu::key::NativeDeviceType ? "npu" : "cpu"),
|
||||
" and ",
|
||||
(mat2.device().type() == at_npu::key::NativeDeviceType ? "npu! " : "cpu! "));
|
||||
auto output_size = {self.size(0), self.size(1), mat2.size(2)};
|
||||
|
||||
OpPreparation::CheckOut(
|
||||
@@ -67,11 +62,6 @@ at::Tensor& NPUNativeFunctions::bmm_out(const at::Tensor& self, const at::Tensor
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::bmm(const at::Tensor& self, const at::Tensor& mat2) {
|
||||
TORCH_CHECK(self.device() == mat2.device(),
|
||||
"Expected all tensors to be on the same device, but found at least two devices, ",
|
||||
(self.device().type() == at_npu::key::NativeDeviceType ? "npu" : "cpu"),
|
||||
" and ",
|
||||
(mat2.device().type() == at_npu::key::NativeDeviceType ? "npu! " : "cpu! "));
|
||||
auto output_size = {self.size(0), self.size(1), mat2.size(2)};
|
||||
|
||||
at::Tensor result;
|
||||
|
||||
@@ -85,13 +85,5 @@ at::Tensor& NPUNativeFunctions::cumsum_out(const at::Tensor& self, at::Dimname d
|
||||
return NPUNativeFunctions::cumsum_out(self, dimname_to_position(self, dim), dtype, result);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::cumsum(const at::Tensor& self, int64_t dim,
|
||||
c10::optional<at::ScalarType> dtype) {
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
|
||||
NPUNativeFunctions::cumsum_out(self, dim, dtype, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
|
||||
@@ -38,7 +38,7 @@ at::Tensor &div_scalar_out_npu(const at::Tensor &self, const at::Scalar other, a
|
||||
at::Tensor &div_out_npu_nocheck(const at::Tensor &self, const at::Tensor &other, at::Tensor &result)
|
||||
{
|
||||
// executing the NPU operator
|
||||
if (OpPreparation::IsCPUScalar(other))
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other))
|
||||
{
|
||||
div_scalar_out_npu(self, other.item(), result);
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ at::Tensor& NPUNativeFunctions::fill_(at::Tensor& self, const at::Tensor& other)
|
||||
auto other_dim = other.dim();
|
||||
TORCH_CHECK(other_dim <= 1, "fill_ only supports 0 or 1 dimension value tensor but got tensor with ",
|
||||
other_dim, " dimension.");
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other_dim == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
fill_out_npu(self, self, other.item());
|
||||
} else {
|
||||
fill_out_npu(self, self, other);
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
// Copyright (c) 2023 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/csrc/autograd/custom_function.h>
|
||||
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
std::vector<at::Tensor> NPUNativeFunctions::npu_flash_attention_score_grad(
|
||||
const at::Tensor &query,
|
||||
const at::Tensor &key,
|
||||
const at::Tensor &value,
|
||||
const at::Tensor &dy,
|
||||
const c10::optional<at::Tensor> &pse,
|
||||
const c10::optional<at::Tensor> &drop_mask,
|
||||
const c10::optional<at::Tensor> &padding_mask,
|
||||
const c10::optional<at::Tensor> &atten_mask,
|
||||
const c10::optional<at::Tensor> &softmax_max,
|
||||
const c10::optional<at::Tensor> &softmax_sum,
|
||||
const c10::optional<at::Tensor> &softmax_in,
|
||||
const c10::optional<at::Tensor> &attention_in,
|
||||
double scale_value,
|
||||
double keep_prob,
|
||||
bool query_transpose,
|
||||
bool key_transpose,
|
||||
bool value_transpose,
|
||||
bool dy_transpose,
|
||||
bool is_transpose_attention,
|
||||
int64_t pre_tockens,
|
||||
int64_t next_tockens)
|
||||
{
|
||||
return NPUNativeOpApiFunctions::npu_flash_attention_score_grad(query,
|
||||
key, value, dy, pse, drop_mask, padding_mask, atten_mask,
|
||||
softmax_max, softmax_sum, softmax_in, attention_in, scale_value,
|
||||
keep_prob, query_transpose, key_transpose, value_transpose,
|
||||
dy_transpose, is_transpose_attention, pre_tockens, next_tockens);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,41 +0,0 @@
|
||||
// Copyright (c) 2023 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/csrc/autograd/custom_function.h>
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
using torch::autograd::AutogradContext;
|
||||
using torch::autograd::Function;
|
||||
|
||||
std::vector<at::Tensor> NPUNativeFunctions::npu_flash_attention_score(
|
||||
const at::Tensor &query_layer, const at::Tensor &key_layer,
|
||||
const at::Tensor &value_layer, const c10::optional<at::Tensor> &pse,
|
||||
const c10::optional<at::Tensor> &drop_mask, const c10::optional<at::Tensor> &padding_mask,
|
||||
const c10::optional<at::Tensor> &atten_mask, bool query_transpose, bool key_transpose, bool value_transpose,
|
||||
double scale, double keep_prob, bool is_transpose_out, int64_t pre_tockens, int64_t next_tockens)
|
||||
{
|
||||
return NPUNativeOpApiFunctions::npu_flash_attention_score(
|
||||
query_layer, key_layer, value_layer, pse, drop_mask, padding_mask,
|
||||
atten_mask, query_transpose, key_transpose, value_transpose, scale, keep_prob,
|
||||
is_transpose_out, pre_tockens, next_tockens);
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -27,6 +27,13 @@ at::Tensor& gather_out_npu_nocheck(
|
||||
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 = OpPreparation::ApplyTensor(result, result.options().dtype(at::kFloat));
|
||||
}
|
||||
|
||||
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!");
|
||||
@@ -34,11 +41,12 @@ at::Tensor& gather_out_npu_nocheck(
|
||||
|
||||
OpCommand cmd;
|
||||
cmd.Name("GatherElements")
|
||||
.Input(self)
|
||||
.Input(dtypeCastOfSelf)
|
||||
.Input(index)
|
||||
.Attr("dim", dim)
|
||||
.Output(result)
|
||||
.Output(dtypeCastOfResult)
|
||||
.Run();
|
||||
result.copy_(dtypeCastOfResult);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -85,10 +85,10 @@ at::Tensor& NPUNativeFunctions::ge_out(const at::Tensor& self, const at::Scalar&
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::ge(const at::Tensor& self, const at::Tensor& other) {
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
return NPUNativeFunctions::ge(self, other.item());
|
||||
}
|
||||
else if (OpPreparation::IsCPUScalar(self)) {
|
||||
else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) {
|
||||
return NPUNativeFunctions::lt(other, self.item());
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -18,27 +18,16 @@
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeFunctions::gelu_out(const at::Tensor& self, at::Tensor& result) {
|
||||
OpPreparation::CheckOut({self}, result, self);
|
||||
|
||||
OpCommand cmd;
|
||||
cmd.Name("Gelu")
|
||||
.Input(self)
|
||||
.Output(result)
|
||||
.Run();
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::gelu(const at::Tensor& self) {
|
||||
at::Tensor result = OpPreparation::ApplyTensor(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;
|
||||
OpCommand cmd;
|
||||
cmd.Name("Gelu")
|
||||
.Input(self)
|
||||
.Output(result)
|
||||
.Run();
|
||||
|
||||
return result;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
|
||||
@@ -14,60 +14,48 @@
|
||||
// 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/CalcuOpUtil.h"
|
||||
#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/framework/utils/KernelNpuOutputSize.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor &glu_backward_npu_nocheck(const at::Tensor &grad_output,
|
||||
const at::Tensor &self, at::Tensor &result,
|
||||
int64_t dim) {
|
||||
OpCommand cmd;
|
||||
cmd.Name("GLUGrad")
|
||||
.Input(grad_output)
|
||||
.Input(self)
|
||||
.Output(result)
|
||||
.Attr("dim", dim)
|
||||
.Run();
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor &NPUNativeFunctions::glu_backward_out(const at::Tensor &grad_output,
|
||||
const at::Tensor &self,
|
||||
int64_t dim,
|
||||
at::Tensor &result) {
|
||||
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);
|
||||
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);
|
||||
wrap_dim, " is size ", nIn);
|
||||
|
||||
auto chunkedInput = self.chunk(2, dim);
|
||||
at::Tensor firstHalf = chunkedInput[0];
|
||||
at::Tensor secondHalf = chunkedInput[1];
|
||||
|
||||
glu_backward_npu_nocheck(grad_output, self, result, dim);
|
||||
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) {
|
||||
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);
|
||||
|
||||
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);
|
||||
glu_backward_npu_nocheck(grad_output, self, result, dim);
|
||||
NPUNativeFunctions::glu_backward_out(grad_output, self, dim, result);
|
||||
return result;
|
||||
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -14,54 +14,39 @@
|
||||
// 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/CalcuOpUtil.h"
|
||||
#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/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);
|
||||
|
||||
at::Tensor &glu_out_npu_nocheck(const at::Tensor &self, at::Tensor &result,
|
||||
int64_t dim) {
|
||||
OpCommand cmd;
|
||||
cmd.Name("GLU")
|
||||
.Input(self)
|
||||
.Output(result)
|
||||
.Attr("dim", dim)
|
||||
.Run();
|
||||
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_out(const at::Tensor &self, int64_t dim,
|
||||
at::Tensor &result) {
|
||||
auto outputSize = glu_npu_output_size(self, dim);
|
||||
OpPreparation::CheckOut({self},
|
||||
result,
|
||||
self,
|
||||
outputSize);
|
||||
|
||||
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);
|
||||
|
||||
glu_out_npu_nocheck(self, result, dim);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::glu(const at::Tensor &self, int64_t dim) {
|
||||
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);
|
||||
|
||||
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);
|
||||
glu_out_npu_nocheck(self, result, dim);
|
||||
NPUNativeFunctions::glu_out(self, dim, result);
|
||||
return result;
|
||||
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -56,15 +56,5 @@ at::Tensor& NPUNativeFunctions::_log_softmax_backward_data_out(
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::_log_softmax_backward_data(
|
||||
const at::Tensor& grad_output,
|
||||
const at::Tensor& output,
|
||||
int64_t dim,
|
||||
c10::ScalarType input_dtype) {
|
||||
at::Tensor result = OpPreparation::ApplyTensor(grad_output);
|
||||
log_softmax_backward_data_out_npu_nocheck(result, grad_output, output, dim, input_dtype);
|
||||
|
||||
return result;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -22,6 +22,7 @@
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
namespace {
|
||||
@@ -60,7 +61,7 @@ at::Tensor log_softmax_nocheck(
|
||||
log_softmax_nocheck(result, self.toType(dstType), dim);
|
||||
return result;
|
||||
}
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
at::Tensor NPUNativeFunctions::log_softmax(
|
||||
const at::Tensor& self,
|
||||
@@ -97,22 +98,6 @@ at::Tensor NPUNativeFunctions::_log_softmax(const at::Tensor& self, int64_t dim,
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeFunctions::_log_softmax_out(
|
||||
const at::Tensor& self,
|
||||
int64_t dim,
|
||||
bool half_to_float,
|
||||
at::Tensor& out) {
|
||||
// calculate the output result of the NPU
|
||||
c10::ScalarType outType = out.scalar_type();
|
||||
|
||||
if (half_to_float) {
|
||||
log_softmax_nocheck(out, self, dim, c10::ScalarType::Float);
|
||||
} else {
|
||||
log_softmax_nocheck(out, self, dim, outType);
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -81,7 +81,7 @@ at::Tensor& masked_fill_out_npu_nocheck(const at::Tensor& self, const at::Tensor
|
||||
|
||||
at::Tensor& NPUNativeFunctions::masked_fill_(at::Tensor& self, const at::Tensor& mask, const at::Tensor& value) {
|
||||
//Handle the situation when the second input is a scalar and placed on cpu.
|
||||
if (OpPreparation::IsCPUScalar(value)) {
|
||||
if (value.dim() == 0 && !at_npu::key::isDeviceTensor(value)) {
|
||||
return NPUNativeFunctions::masked_fill_(self, mask, value.item());
|
||||
}
|
||||
if (!NpuUtils::check_match(&self)) {
|
||||
|
||||
@@ -175,28 +175,9 @@ at::Tensor& NPUNativeFunctions::maximum_out(
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& max_out_npu_nocheck(
|
||||
const at::Tensor& self,
|
||||
const at::Scalar& other,
|
||||
at::Tensor& result) {
|
||||
OpCommand cmd;
|
||||
cmd.Name("Maximum")
|
||||
.Input(self)
|
||||
.Input(other, self.scalar_type())
|
||||
.Output(result)
|
||||
.Run();
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::maximum(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& other) {
|
||||
auto output_size_diff = self.sizes();
|
||||
at::Tensor result_diff = OpPreparation::ApplyTensor(self, output_size_diff);
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
max_out_npu_nocheck(self, other.item(), result_diff);
|
||||
return result_diff;
|
||||
}
|
||||
auto outputSize = broadcast_ops_npu_output_size(self, other);
|
||||
at::ScalarType high_type = at::native::result_type(self, other);
|
||||
at::Tensor self_copy = (self.scalar_type() != high_type && !CalcuOpUtil::IsScalarWrappedToTensor(self)) ?
|
||||
|
||||
@@ -109,7 +109,7 @@ at::Tensor &NPUNativeFunctions::mm_out(const at::Tensor &self,
|
||||
set_transposed_npu_desc(contiguousSelf);
|
||||
}
|
||||
} else {
|
||||
contiguousSelf = NpuUtils::format_contiguous(self);
|
||||
contiguousSelf = NpuUtils::format_contiguous_add_copy_optimize(self);
|
||||
}
|
||||
|
||||
if (isMat2T_flex) {
|
||||
@@ -122,7 +122,7 @@ at::Tensor &NPUNativeFunctions::mm_out(const at::Tensor &self,
|
||||
set_transposed_npu_desc(contiguousMat2);
|
||||
}
|
||||
} else {
|
||||
contiguousMat2 = NpuUtils::format_contiguous(mat2);
|
||||
contiguousMat2 = NpuUtils::format_contiguous_add_copy_optimize(mat2);
|
||||
}
|
||||
|
||||
// executing the NPU operator
|
||||
|
||||
@@ -49,9 +49,9 @@ at::Tensor& muls_out_npu(at::Tensor& result, const at::Tensor& self, const at::S
|
||||
}
|
||||
|
||||
at::Tensor& mul_out_npu_nocheck(at::Tensor& result, const at::Tensor& self, const at::Tensor& other) {
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
muls_out_npu(result, self, other.item());
|
||||
} else if (OpPreparation::IsCPUScalar(self)) {
|
||||
} else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) {
|
||||
muls_out_npu(result, other, self.item());
|
||||
} else {
|
||||
auto unified_result = OpPreparation::binary_op_check(result, self, other, true);
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
// Copyright (c) 2023 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<at::Tensor, at::Tensor> NPUNativeFunctions::native_dropout(
|
||||
const at::Tensor& input,
|
||||
double p,
|
||||
c10::optional<bool> train) {
|
||||
if (input.numel() == 0) {
|
||||
return std::make_tuple(input, at::empty_like(input, input.options()));
|
||||
}
|
||||
|
||||
bool dropout_train = !train.has_value() ? true : train.value();
|
||||
|
||||
at::TensorOptions options = input.options();
|
||||
if (p == 0 || !dropout_train) {
|
||||
at::Tensor mask = NPUNativeFunctions::ones(
|
||||
input.sizes(),
|
||||
optTypeMetaToScalarType(options.dtype_opt()),
|
||||
options.layout(),
|
||||
options.device(),
|
||||
options.pinned_memory());
|
||||
return std::make_tuple(input.clone(), mask);
|
||||
}
|
||||
if (p == 1) {
|
||||
at::Tensor output = NPUNativeFunctions::zeros(
|
||||
input.sizes(),
|
||||
optTypeMetaToScalarType(options.dtype_opt()),
|
||||
options.layout(),
|
||||
options.device(),
|
||||
options.pinned_memory());
|
||||
at::Tensor mask = NPUNativeFunctions::zeros(
|
||||
input.sizes(),
|
||||
optTypeMetaToScalarType(options.dtype_opt()),
|
||||
options.layout(),
|
||||
options.device(),
|
||||
options.pinned_memory());
|
||||
return std::make_tuple(output, mask);
|
||||
}
|
||||
|
||||
return NPUNativeFunctions::_npu_dropout(input, p);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::native_dropout_backward(
|
||||
const at::Tensor& grad_output,
|
||||
const at::Tensor& mask,
|
||||
double scale) {
|
||||
double p = (scale == 0.0) ? 1 : (1 - 1 / scale);
|
||||
at::TensorOptions options = grad_output.options();
|
||||
if (p == 0) {
|
||||
return grad_output;
|
||||
}
|
||||
if (p == 1) {
|
||||
return NPUNativeFunctions::zeros(
|
||||
grad_output.sizes(),
|
||||
optTypeMetaToScalarType(options.dtype_opt()),
|
||||
options.layout(),
|
||||
options.device(),
|
||||
options.pinned_memory());
|
||||
}
|
||||
return NPUNativeFunctions::npu_dropout_backward(grad_output, mask, p);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2023, 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::reflection_pad1d_backward_out(
|
||||
const at::Tensor& grad_output,
|
||||
const at::Tensor& input,
|
||||
at::IntArrayRef padding,
|
||||
at::Tensor& grad_input) {
|
||||
c10::SmallVector<int64_t, N> paddings = {padding[0], padding[1], 0, 0};
|
||||
at::Tensor input_cp = input.unsqueeze(0);
|
||||
at::Tensor grad_output_cp = grad_output.unsqueeze(0);
|
||||
NPUNativeFunctions::reflection_pad2d_backward_out(grad_output_cp, input_cp, paddings, grad_input);
|
||||
grad_input.squeeze_(0);
|
||||
return grad_input;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::reflection_pad1d_backward(
|
||||
const at::Tensor& grad_output,
|
||||
const at::Tensor& input,
|
||||
at::IntArrayRef padding) {
|
||||
c10::SmallVector<int64_t, N> paddings = {padding[0], padding[1], 0, 0};
|
||||
at::Tensor input_cp = input.unsqueeze(0);
|
||||
at::Tensor grad_output_cp = grad_output.unsqueeze(0);
|
||||
at::Tensor grad_input = NPUNativeFunctions::reflection_pad2d_backward(grad_output_cp, input_cp, paddings);
|
||||
grad_input.squeeze_(0);
|
||||
return grad_input;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -19,16 +19,6 @@
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
namespace {
|
||||
bool check_padding(at::IntArrayRef padding) {
|
||||
for (int64_t i = 0; i < padding.size(); i++) {
|
||||
if (padding[i] != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
at::Tensor& reflection_pad2d_backward_out_npu_nocheck(
|
||||
const at::Tensor& grad_output,
|
||||
@@ -69,11 +59,6 @@ at::Tensor& NPUNativeFunctions::reflection_pad2d_backward_out(
|
||||
const at::Tensor& input,
|
||||
at::IntArrayRef padding,
|
||||
at::Tensor& grad_input) {
|
||||
if (check_padding(padding)) {
|
||||
grad_input.copy_(grad_output);
|
||||
return grad_input;
|
||||
}
|
||||
|
||||
OpPreparation::CheckOut(
|
||||
{input, grad_output},
|
||||
grad_input,
|
||||
@@ -90,11 +75,6 @@ at::Tensor NPUNativeFunctions::reflection_pad2d_backward(
|
||||
const at::Tensor& input,
|
||||
at::IntArrayRef padding) {
|
||||
at::Tensor grad_input = OpPreparation::ApplyTensor(input);
|
||||
if (check_padding(padding)) {
|
||||
grad_input.copy_(grad_output);
|
||||
return grad_input;
|
||||
}
|
||||
|
||||
reflection_pad2d_backward_out_npu_nocheck(grad_output, input, padding, grad_input);
|
||||
return grad_input;
|
||||
}
|
||||
|
||||
@@ -50,13 +50,23 @@ at::Tensor& reflection_pad2d_out_npu_nocheck(
|
||||
}
|
||||
c10::SmallVector<int64_t, N> value_tensor = {(int64_t)0};
|
||||
OpCommand cmd;
|
||||
cmd.Name("MirrorPad")
|
||||
.Input(self_cp)
|
||||
.Input(vector_int, at::kInt)
|
||||
.Output(result)
|
||||
.Attr("mode", (string)"REFLECT")
|
||||
.Run();
|
||||
|
||||
if(self.dtype() == at::kHalf) {
|
||||
cmd.Name("PadV3")
|
||||
.Input(self_cp)
|
||||
.Input(vector_int, at::kInt)
|
||||
.Input(value_tensor, self.scalar_type())
|
||||
.Output(result)
|
||||
.Attr("mode", (string)"reflect")
|
||||
.Attr("paddings_contiguous", true)
|
||||
.Run();
|
||||
} else {
|
||||
cmd.Name("MirrorPad")
|
||||
.Input(self_cp)
|
||||
.Input(vector_int, at::kInt)
|
||||
.Output(result)
|
||||
.Attr("mode", (string)"REFLECT")
|
||||
.Run();
|
||||
}
|
||||
if (self.dim() == 3) {
|
||||
result.squeeze_(0);
|
||||
}
|
||||
|
||||
@@ -17,16 +17,6 @@
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
namespace {
|
||||
bool check_padding(at::IntArrayRef padding) {
|
||||
for (int64_t i = 0; i < padding.size(); i++) {
|
||||
if (padding[i] != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
at::Tensor& replication_pad2d_backward_out_npu_nocheck(
|
||||
at::Tensor& grad_input,
|
||||
@@ -68,11 +58,6 @@ at::Tensor& NPUNativeFunctions::replication_pad2d_backward_out(
|
||||
const at::Tensor& input,
|
||||
at::IntArrayRef padding,
|
||||
at::Tensor& grad_input) {
|
||||
if (check_padding(padding)) {
|
||||
grad_input.copy_(grad_output);
|
||||
return grad_input;
|
||||
}
|
||||
|
||||
OpPreparation::CheckOut(
|
||||
{input, grad_output},
|
||||
grad_input,
|
||||
@@ -86,10 +71,6 @@ at::Tensor NPUNativeFunctions::replication_pad2d_backward(
|
||||
const at::Tensor& input,
|
||||
at::IntArrayRef padding) {
|
||||
at::Tensor grad_input = OpPreparation::ApplyTensor(input);
|
||||
if (check_padding(padding)) {
|
||||
grad_input.copy_(grad_output);
|
||||
return grad_input;
|
||||
}
|
||||
replication_pad2d_backward_out_npu_nocheck(grad_input, grad_output, input, padding);
|
||||
return grad_input;
|
||||
}
|
||||
|
||||
@@ -24,15 +24,13 @@ at::Tensor& scatter_add_out_npu_nocheck(
|
||||
int64_t dim,
|
||||
const at::Tensor& index,
|
||||
const at::Tensor& src) {
|
||||
std::string reduction = "add";
|
||||
OpCommand cmd;
|
||||
cmd.Name("ScatterElements")
|
||||
cmd.Name("ScatterAddWithAxis")
|
||||
.Input(self)
|
||||
.Input(index)
|
||||
.Input(src)
|
||||
.Output(result)
|
||||
.Attr("axis", dim)
|
||||
.Attr("reduction", reduction)
|
||||
.Run();
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -98,28 +98,5 @@ at::Tensor& NPUNativeFunctions::scatter_out(
|
||||
scatter_npu_src_impl(result, dim, index, srcTensor_broadcast);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeFunctions::scatter_out(
|
||||
const at::Tensor& self,
|
||||
int64_t dim,
|
||||
const at::Tensor& index,
|
||||
const at::Tensor& src,
|
||||
c10::string_view reduce,
|
||||
at::Tensor& result) {
|
||||
TORCH_CHECK(false, "scatter.reduce_out is not supported.");
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeFunctions::scatter_out(
|
||||
const at::Tensor& self,
|
||||
int64_t dim,
|
||||
const at::Tensor& index,
|
||||
const at::Scalar& value,
|
||||
c10::string_view reduce,
|
||||
at::Tensor& result) {
|
||||
TORCH_CHECK(false, "scatter.value_reduce_out is not supported.");
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
|
||||
@@ -45,10 +45,6 @@ at::Tensor& NPUNativeFunctions::sgn_out(const at::Tensor& self, at::Tensor& resu
|
||||
return NPUNativeFunctions::sign_out(self, result);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::sgn(const at::Tensor& self) {
|
||||
return NPUNativeFunctions::sign(self);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::sign(const at::Tensor& self) {
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
|
||||
@@ -18,80 +18,77 @@
|
||||
#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
namespace at_npu
|
||||
{
|
||||
namespace native
|
||||
{
|
||||
|
||||
at::Tensor NPUNativeFunctions::softmax(
|
||||
const at::Tensor& self,
|
||||
int64_t dim,
|
||||
c10::optional<at::ScalarType> dtype) {
|
||||
auto result = [&]() {
|
||||
at::NoNamesGuard guard;
|
||||
at::Tensor converted = dtype.has_value() ? NPUNativeFunctions::npu_dtype_cast(self, dtype.value()) : self;
|
||||
return at::_softmax(converted, dim, false);
|
||||
}();
|
||||
at::namedinference::propagate_names(result, self);
|
||||
at::Tensor NPUNativeFunctions::softmax(
|
||||
const at::Tensor &self,
|
||||
int64_t dim,
|
||||
c10::optional<at::ScalarType> dtype)
|
||||
{
|
||||
auto result = [&]()
|
||||
{
|
||||
at::NoNamesGuard guard;
|
||||
at::Tensor converted = dtype.has_value() ? NPUNativeFunctions::npu_dtype_cast(self, dtype.value()) : self;
|
||||
return at::_softmax(converted, dim, false);
|
||||
}();
|
||||
at::namedinference::propagate_names(result, self);
|
||||
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::softmax(
|
||||
const at::Tensor& self,
|
||||
at::Dimname dim,
|
||||
c10::optional<at::ScalarType> dtype) {
|
||||
return NPUNativeFunctions::softmax(self, dimname_to_position(self, dim), dtype);
|
||||
}
|
||||
at::Tensor NPUNativeFunctions::softmax(
|
||||
const at::Tensor &self,
|
||||
at::Dimname dim,
|
||||
c10::optional<at::ScalarType> dtype)
|
||||
{
|
||||
return NPUNativeFunctions::softmax(self, dimname_to_position(self, dim), dtype);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeFunctions::_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) {
|
||||
result = OpPreparation::ApplyTensor(self, self.options().dtype(at::ScalarType::Float));
|
||||
} else {
|
||||
result = OpPreparation::ApplyTensor(self);
|
||||
}
|
||||
at::Tensor NPUNativeFunctions::_softmax(const at::Tensor &self, int64_t dim, bool half_to_float)
|
||||
{
|
||||
|
||||
// calculate the output result of the NPU
|
||||
c10::optional<at::ScalarType> dtype = result.scalar_type();
|
||||
at::ScalarType dstType;
|
||||
if (dtype.has_value()) {
|
||||
dstType = dtype.value();
|
||||
} else if (result.defined()) {
|
||||
dstType = result.scalar_type();
|
||||
} else {
|
||||
dstType = self.scalar_type();
|
||||
}
|
||||
at::Tensor converted = dstType == self.scalar_type() ? self : NPUNativeFunctions::npu_dtype_cast(self, dstType);
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result;
|
||||
if (half_to_float)
|
||||
{
|
||||
result = OpPreparation::ApplyTensor(self, self.options().dtype(at::ScalarType::Float));
|
||||
}
|
||||
else
|
||||
{
|
||||
result = OpPreparation::ApplyTensor(self);
|
||||
}
|
||||
|
||||
c10::SmallVector<int64_t, N> dimList = {dim};
|
||||
OpCommand cmd;
|
||||
cmd.Name("SoftmaxV2")
|
||||
.Input(converted)
|
||||
.Output(result)
|
||||
.Attr("axes", dimList)
|
||||
.Run();
|
||||
// calculate the output result of the NPU
|
||||
c10::optional<at::ScalarType> dtype = result.scalar_type();
|
||||
at::ScalarType dstType;
|
||||
if (dtype.has_value())
|
||||
{
|
||||
dstType = dtype.value();
|
||||
}
|
||||
else if (result.defined())
|
||||
{
|
||||
dstType = result.scalar_type();
|
||||
}
|
||||
else
|
||||
{
|
||||
dstType = self.scalar_type();
|
||||
}
|
||||
at::Tensor converted =
|
||||
dstType == self.scalar_type() ? self : NPUNativeFunctions::npu_dtype_cast(self, dstType);
|
||||
|
||||
return result;
|
||||
}
|
||||
c10::SmallVector<int64_t, N> dimList = {dim};
|
||||
OpCommand cmd;
|
||||
cmd.Name("SoftmaxV2")
|
||||
.Input(converted)
|
||||
.Output(result)
|
||||
.Attr("axes", dimList)
|
||||
.Run();
|
||||
|
||||
at::Tensor& NPUNativeFunctions::_softmax_out(
|
||||
const at::Tensor& self,
|
||||
int64_t dim,
|
||||
bool half_to_float,
|
||||
at::Tensor& out) {
|
||||
// calculate the output result of the NPU
|
||||
c10::SmallVector<int64_t, N> dimList = {dim};
|
||||
OpCommand cmd;
|
||||
cmd.Name("SoftmaxV2")
|
||||
.Input(self)
|
||||
.Output(out)
|
||||
.Attr("axes", dimList)
|
||||
.Run();
|
||||
return result;
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
|
||||
@@ -106,30 +106,5 @@ tuple<at::Tensor, at::Tensor> NPUNativeFunctions::sort(
|
||||
return NPUNativeFunctions::sort(self, dimname_to_position(self, dim), descending);
|
||||
}
|
||||
|
||||
tuple<at::Tensor, at::Tensor> NPUNativeFunctions::sort(
|
||||
const at::Tensor& self,
|
||||
c10::optional<bool> stable,
|
||||
int64_t dim,
|
||||
bool descending) {
|
||||
TORCH_CHECK(false, "sort.stable is not supported.");
|
||||
auto outputSize = input_same_output_size(self);
|
||||
auto format = CalcuOpUtil::GetTensorNpuFormat(self);
|
||||
at::Tensor values = OpPreparation::ApplyTensor(self);
|
||||
at::Tensor indices = OpPreparation::ApplyTensorWithFormat(outputSize, self.options().dtype(at::kLong), format);
|
||||
|
||||
return std::tie(values, indices);
|
||||
}
|
||||
|
||||
tuple<at::Tensor&, at::Tensor&> NPUNativeFunctions::sort_out(
|
||||
const at::Tensor& self,
|
||||
c10::optional<bool> stable,
|
||||
int64_t dim,
|
||||
bool descending,
|
||||
at::Tensor& values,
|
||||
at::Tensor& indices) {
|
||||
TORCH_CHECK(false, "sort.stable is not supported.");
|
||||
return std::tie(values, indices);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
|
||||
@@ -47,7 +47,7 @@ at::Tensor &sub_out_npu_nocheck(
|
||||
const at::Tensor &other,
|
||||
at::Scalar alpha) {
|
||||
auto unified_result = OpPreparation::binary_op_check(result, self, other, true);
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
sub_scalar_out_npu(result, self, other.item(), alpha);
|
||||
} else {
|
||||
at::Tensor otherMulResult = other;
|
||||
|
||||
@@ -60,7 +60,7 @@ at::Tensor &NPUNativeFunctions::sum_out(
|
||||
auto selfSize = self.sizes();
|
||||
for (int64_t i = 0; i < selfSize.size(); i++) {
|
||||
if (selfSize[i] == 0) {
|
||||
at::Tensor result_cast = at::empty(outputSize, self.options().dtype(res_type));
|
||||
at::Tensor result_cast = at::empty(outputSize);
|
||||
result.copy_(result_cast);
|
||||
return result;
|
||||
}
|
||||
@@ -109,7 +109,7 @@ at::Tensor NPUNativeFunctions::sum(
|
||||
|
||||
for (int64_t i = 0; i < selfSize.size(); i++) {
|
||||
if (selfSize[i] == 0) {
|
||||
return at::zeros(outputSize, self_cp.options().dtype(out_type));
|
||||
return at::zeros(outputSize, self_cp.options());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor NPUNativeFunctions::_reshape_alias(const at::Tensor& self, at::IntArrayRef sizes, at::IntArrayRef strides) {
|
||||
|
||||
return self.view(sizes);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -49,9 +49,9 @@ at::Tensor& and_out_npu_nocheck(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& other,
|
||||
at::Tensor& result) {
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
and_out_npu_nocheck(self, other.item(),result);
|
||||
} else if (OpPreparation::IsCPUScalar(self)) {
|
||||
} else if (self.dim() == 0 && !at_npu::key::isDeviceTensor(self)) {
|
||||
and_out_npu_nocheck(other, self.item(),result);
|
||||
} else {
|
||||
OpCommand cmd;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// 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::IsScalarWrappedToTensor(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, const at::Scalar& other) {
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
or___out_scalar_npu(result, self, other);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/CalcuOpUtil.h"
|
||||
#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::abs_out(const at::Tensor& self, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAbs, NPUNativeFunctions::abs_out(self, result));
|
||||
OpPreparation::CheckOut({self}, result, self);
|
||||
|
||||
EXEC_NPU_CMD(aclnnAbs, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::abs(const at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnAbs, NPUNativeFunctions::abs(self));
|
||||
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnAbs, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::abs_(at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnAbs, NPUNativeFunctions::abs_(self));
|
||||
NPUNativeOpApiFunctions::abs_out(self, self);
|
||||
return self;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,36 +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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::_adaptive_avg_pool2d_backward(const at::Tensor& grad_output,
|
||||
const at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnAdaptiveAvgPool2dBackward,
|
||||
NPUNativeFunctions::_adaptive_avg_pool2d_backward(grad_output, self));
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
EXEC_NPU_CMD(aclnnAdaptiveAvgPool2dBackward, grad_output, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::adaptive_avg_pool2d_out(const at::Tensor& self, at::IntArrayRef output_size,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAdaptiveAvgPool2d, NPUNativeFunctions::adaptive_avg_pool2d_out(self, output_size, result));
|
||||
EXEC_NPU_CMD(aclnnAdaptiveAvgPool2d, self, output_size, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::adaptive_avg_pool2d(const at::Tensor& self, at::IntArrayRef output_size) {
|
||||
DO_COMPATIBILITY(aclnnAdaptiveAvgPool2d, NPUNativeFunctions::adaptive_avg_pool2d(self, output_size));
|
||||
// The logic is a little different from CPU_impl
|
||||
return NPUNativeOpApiFunctions::_adaptive_avg_pool2d(self, output_size);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::_adaptive_avg_pool2d(const at::Tensor& self, at::IntArrayRef output_size) {
|
||||
DO_COMPATIBILITY(aclnnAdaptiveAvgPool2d, NPUNativeFunctions::_adaptive_avg_pool2d(self, output_size));
|
||||
|
||||
TORCH_CHECK((self.dim() == 3 || self.dim() == 4), "non-empty 3D or 4D (batch mode) tensor expected for input");
|
||||
auto outputSize = array_to_small_vector(self.sizes());
|
||||
outputSize[self.dim() - 1] = output_size[1];
|
||||
outputSize[self.dim() - 2] = output_size[0];
|
||||
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self, outputSize);
|
||||
|
||||
NPUNativeOpApiFunctions::adaptive_avg_pool2d_out(self, output_size, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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 <ATen/Tensor.h>
|
||||
#include <c10/util/SmallVector.h>
|
||||
|
||||
#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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/core/NPUBridge.h"
|
||||
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h"
|
||||
#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h"
|
||||
#include "torch_npu/csrc/framework/utils/OpPreparation.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
inline void alpha_check_npu(const at::ScalarType dtype, at::Scalar alpha) {
|
||||
TORCH_CHECK(!alpha.isBoolean() || dtype == at::ScalarType::Bool, "Boolean alpha only supported for Boolean results.");
|
||||
TORCH_CHECK(isFloatingType(dtype) || alpha.isIntegral(true),
|
||||
"For integral input tensors, argument alpha must not be a floating point number.");
|
||||
}
|
||||
|
||||
static at::Tensor& add_out_npu_nocheck(const at::Tensor& self, const at::Tensor& other, const at::Scalar& alpha,
|
||||
at::Tensor& result) {
|
||||
// executing the NPU operator
|
||||
if (other.dim() == 0 && !at_npu::key::isDeviceTensor(other)) {
|
||||
c10::Scalar others = at_npu::native::CalcuOpUtil::ConvertTensorToScalar(other);
|
||||
EXEC_NPU_CMD(aclnnAdds, self, others, alpha, result);
|
||||
} else {
|
||||
EXEC_NPU_CMD(aclnnAdd, self, other, alpha, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static at::Tensor self_tensor_to_device(const at::Tensor& tensor, const at::ScalarType result_type) {
|
||||
if (at_npu::native::CalcuOpUtil::IsScalarWrappedToTensor(tensor)) {
|
||||
at::Scalar scalar = CalcuOpUtil::ConvertTensorToScalar(tensor);
|
||||
return CalcuOpUtil::CopyScalarToDevice(scalar, result_type);
|
||||
}
|
||||
return tensor;
|
||||
}
|
||||
|
||||
static at::Tensor add_dest_output(const at::Tensor& self, const at::Tensor& other) {
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
return isSelfWrapped ? other : self;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::add(const at::Tensor& self, const at::Tensor& other, const at::Scalar& alpha) {
|
||||
DO_COMPATIBILITY(aclnnAdd, NPUNativeFunctions::add(self, other, alpha));
|
||||
DO_COMPATIBILITY(aclnnAdds, NPUNativeFunctions::add(self, other, alpha));
|
||||
alpha_check_npu(self.scalar_type(), alpha);
|
||||
// calculate the output size
|
||||
at::Tensor output_tensor = add_dest_output(self, other);
|
||||
auto output_size = broadcast_ops_npu_output_size(self, other);
|
||||
at::ScalarType result_type = at::native::result_type(self, other);
|
||||
at::Tensor self_cp = self_tensor_to_device(self, result_type);
|
||||
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithFormat(output_size, output_tensor.options().dtype(result_type),
|
||||
CalcuOpUtil::GetTensorNpuFormat(output_tensor));
|
||||
|
||||
// calculate the output result of the NPU
|
||||
add_out_npu_nocheck(self_cp, other, alpha, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::add(const at::Tensor& self, const at::Scalar& other, const at::Scalar& alpha) {
|
||||
DO_COMPATIBILITY(aclnnAdds, NPUNativeFunctions::add(self, other, alpha));
|
||||
alpha_check_npu(self.scalar_type(), alpha);
|
||||
// calculate the output size
|
||||
auto output_size = input_same_output_size(self);
|
||||
at::ScalarType result_type = at::native::result_type(self, other);
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithFormat(output_size, self.options().dtype(result_type),
|
||||
CalcuOpUtil::GetTensorNpuFormat(self));
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnAdds, self, other, alpha, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::add_out(const at::Tensor& self, const at::Tensor& other, const at::Scalar& alpha,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAdd, NPUNativeFunctions::add_out(self, other, alpha, result));
|
||||
DO_COMPATIBILITY(aclnnAdds, NPUNativeFunctions::add_out(self, other, alpha, result));
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
at::Tensor output_tensor = isSelfWrapped ? other : self;
|
||||
auto output_size = broadcast_ops_npu_output_size(self, other);
|
||||
at::ScalarType result_type = at::native::result_type(self, other);
|
||||
at::Tensor self_cp = self_tensor_to_device(self, result_type);
|
||||
|
||||
OpPreparation::CheckOut({self}, result, CalcuOpUtil::GetTensorNpuFormat(output_tensor), result.scalar_type(),
|
||||
output_size);
|
||||
|
||||
CalcuOpUtil::CheckMemoryOverLaps({self, other}, {result});
|
||||
add_out_npu_nocheck(self_cp, other, alpha, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,53 +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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::addcdiv_out(const at::Tensor& self, const at::Tensor& tensor1,
|
||||
const at::Tensor& tensor2, const at::Scalar& value,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAddcdiv, NPUNativeFunctions::addcdiv_out(self, tensor1, tensor2, value, result));
|
||||
EXEC_NPU_CMD(aclnnAddcdiv, self, tensor1, tensor2, value, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::addcdiv(const at::Tensor& self, const at::Tensor& tensor1,
|
||||
const at::Tensor& tensor2, const at::Scalar& value) {
|
||||
DO_COMPATIBILITY(aclnnAddcdiv, NPUNativeFunctions::addcdiv(self, tensor1, tensor2, 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);
|
||||
|
||||
EXEC_NPU_CMD(aclnnAddcdiv, self, tensor1, tensor2, value, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::addcdiv_(at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2,
|
||||
const at::Scalar& value) {
|
||||
DO_COMPATIBILITY(aclnnInplaceAddcdiv, NPUNativeFunctions::addcdiv_(self, tensor1, tensor2, value));
|
||||
EXEC_NPU_CMD(aclnnInplaceAddcdiv, self, tensor1, tensor2, value);
|
||||
return self;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,53 +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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::addcmul_out(const at::Tensor& self, const at::Tensor& tensor1,
|
||||
const at::Tensor& tensor2, const at::Scalar& value,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAddcmul, NPUNativeFunctions::addcmul_out(self, tensor1, tensor2, value, result));
|
||||
EXEC_NPU_CMD(aclnnAddcmul, self, tensor1, tensor2, value, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::addcmul(const at::Tensor& self, const at::Tensor& tensor1,
|
||||
const at::Tensor& tensor2, const at::Scalar& value) {
|
||||
DO_COMPATIBILITY(aclnnAddcmul, NPUNativeFunctions::addcmul(self, tensor1, tensor2, value));
|
||||
auto mulOutputSize = broadcast_ops_npu_output_size(tensor1, tensor2);
|
||||
auto outputSize = broadcast_ops_npu_output_size(self.sizes(), mulOutputSize);
|
||||
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self, outputSize);
|
||||
|
||||
EXEC_NPU_CMD(aclnnAddcmul, self, tensor1, tensor2, value, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::addcmul_(at::Tensor& self, const at::Tensor& tensor1, const at::Tensor& tensor2,
|
||||
const at::Scalar& value) {
|
||||
DO_COMPATIBILITY(aclnnInplaceAddcmul, NPUNativeFunctions::addcmul_(self, tensor1, tensor2, value));
|
||||
EXEC_NPU_CMD(aclnnInplaceAddcmul, self, tensor1, tensor2, value);
|
||||
return self;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,40 +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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor &NPUNativeOpApiFunctions::addmm_out(
|
||||
const at::Tensor &self,
|
||||
const at::Tensor &mat1,
|
||||
const at::Tensor &mat2,
|
||||
const at::Scalar &beta,
|
||||
const at::Scalar &alpha,
|
||||
at::Tensor &result)
|
||||
{
|
||||
DO_COMPATIBILITY(aclnnAddmm,
|
||||
NPUNativeFunctions::addmm_out(self, mat1, mat2, beta, alpha, result));
|
||||
int8_t cubeMathType = 1;
|
||||
EXEC_NPU_CMD(aclnnAddmm, self, mat1, mat2, beta, alpha, result, cubeMathType);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,73 +0,0 @@
|
||||
// Copyright (c) 2023, 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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.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 {
|
||||
|
||||
static at::Tensor& AddmvOutOpApi(const at::Tensor& self,
|
||||
const at::Tensor& mat,
|
||||
const at::Tensor& vec,
|
||||
const at::Scalar& beta,
|
||||
const at::Scalar& alpha,
|
||||
at::Tensor& result) {
|
||||
int8_t cube_math_type = 1;
|
||||
EXEC_NPU_CMD(aclnnAddmv, self, mat, vec, alpha, beta, result, cube_math_type);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::addmv_out(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& mat,
|
||||
const at::Tensor& vec,
|
||||
const at::Scalar& beta,
|
||||
const at::Scalar& alpha,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAddmv, NPUNativeFunctions::addmv_out(self, mat, vec, beta, alpha, result));
|
||||
AddmvOutOpApi(self, mat, vec, beta, alpha, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::addmv(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& mat,
|
||||
const at::Tensor& vec,
|
||||
const at::Scalar& beta,
|
||||
const at::Scalar& alpha) {
|
||||
DO_COMPATIBILITY(aclnnAddmv, NPUNativeFunctions::addmv(self, mat, vec, beta, alpha));
|
||||
auto output_size = addmv_npu_output_size(self, mat, vec, beta, alpha);
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self, output_size);
|
||||
AddmvOutOpApi(self, mat, vec, beta, alpha, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::addmv_(
|
||||
at::Tensor& self,
|
||||
const at::Tensor& mat,
|
||||
const at::Tensor& vec,
|
||||
const at::Scalar& beta,
|
||||
const at::Scalar& alpha) {
|
||||
DO_COMPATIBILITY(aclnnAddmv, NPUNativeFunctions::addmv_(self, mat, vec, beta, alpha));
|
||||
OpPreparation::CheckMemory({self, mat, vec}, {self});
|
||||
AddmvOutOpApi(self, mat, vec, beta, alpha, self);
|
||||
return self;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/aten/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::all_out(const at::Tensor& self, int64_t dim, bool keepdim, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnAll, NPUNativeFunctions::all_out(self, dim, keepdim, result));
|
||||
c10::SmallVector<int64_t, N> dimList = {dim};
|
||||
|
||||
// check result for return
|
||||
auto output_size = reduce_ops_npu_output_size(self, dimList, keepdim);
|
||||
OpPreparation::CheckOut({self}, result, result, output_size);
|
||||
// calculate the output result of the NPU
|
||||
at::IntArrayRef dims(dim);
|
||||
EXEC_NPU_CMD(aclnnAll, self, dims, keepdim, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::all(const at::Tensor& self, int64_t dim, bool keepdim) {
|
||||
DO_COMPATIBILITY(aclnnAll, NPUNativeFunctions::all(self, dim, keepdim));
|
||||
|
||||
// calculate the output size
|
||||
at::IntArrayRef dims(dim);
|
||||
auto output_size = reduce_ops_npu_output_size(self, dims, keepdim);
|
||||
auto output_dtype = self.scalar_type() == at::ScalarType::Byte ? at::ScalarType::Byte : at::ScalarType::Bool;
|
||||
auto options = self.options().dtype(output_dtype);
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(output_size, options, self);
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnAll, self, dims, keepdim, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::all(const at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnAll, NPUNativeFunctions::all(self));
|
||||
// calculate the output size
|
||||
at::IntArrayRef dims;
|
||||
auto output_size = reduce_ops_npu_output_size(self, dims, false);
|
||||
auto output_dtype = self.scalar_type() == at::ScalarType::Byte ? at::ScalarType::Byte : at::ScalarType::Bool;
|
||||
auto options = self.options().dtype(output_dtype);
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(output_size, options, self);
|
||||
|
||||
at::IntArrayRef dimList(CalcuOpUtil::GetDimlistForTensor(self));
|
||||
bool keepdim = false;
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnAll, self, dimList, keepdim, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,123 +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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.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 {
|
||||
|
||||
// bool inputs are considered integral
|
||||
static inline bool allIntegral(std::initializer_list<std::reference_wrapper<at::Scalar>> l) {
|
||||
for (at::Scalar& s : l) {
|
||||
if (!s.isIntegral(true)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static at::Tensor& ArangeOutOpApi(at::Scalar start, at::Scalar end, at::Scalar step, at::Tensor& result) {
|
||||
EXEC_NPU_CMD(aclnnArange, start, end, step, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
static int64_t GetResultSize(const at::Scalar& start, const at::Scalar& end, const at::Scalar& step,
|
||||
at::ScalarType resultType) {
|
||||
double size_arange = 0;
|
||||
// calculate the output size
|
||||
if (isFloatingType(resultType)) {
|
||||
if (step.toDouble() != 0) {
|
||||
size_arange = std::ceil(static_cast<double>(end.toDouble() - start.toDouble()) / step.toDouble());
|
||||
}
|
||||
} else {
|
||||
if (step.toLong() != 0) {
|
||||
size_arange = std::ceil(static_cast<double>(end.toLong() - start.toLong()) / step.toLong());
|
||||
}
|
||||
}
|
||||
return static_cast<int64_t>(size_arange);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::arange(const at::Scalar& start, const at::Scalar& end, const at::Scalar& step,
|
||||
c10::optional<at::ScalarType> dtype_opt,
|
||||
c10::optional<at::Layout> layout_opt, c10::optional<at::Device> device_opt,
|
||||
c10::optional<bool> pin_memory_opt) {
|
||||
DO_COMPATIBILITY(aclnnArange,
|
||||
NPUNativeFunctions::arange(start, end, step, dtype_opt, layout_opt, device_opt, pin_memory_opt));
|
||||
c10::TensorOptions option =
|
||||
c10::TensorOptions().dtype(dtype_opt).device(device_opt).layout(layout_opt).pinned_memory(pin_memory_opt);
|
||||
|
||||
at::Scalar start_opt = start;
|
||||
at::Scalar end_opt = end;
|
||||
at::Scalar step_opt = step;
|
||||
bool set_to_integral_dtype = !option.has_dtype() && allIntegral({start_opt, end_opt, step_opt});
|
||||
|
||||
if (set_to_integral_dtype) {
|
||||
option = option.dtype(at::ScalarType::Long);
|
||||
}
|
||||
|
||||
int64_t size_value = GetResultSize(start, end, step, c10::typeMetaToScalarType(option.dtype()));
|
||||
at::SmallVector<int64_t, SIZE> outputSize = {size_value};
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithSizes(outputSize, option);
|
||||
|
||||
ArangeOutOpApi(start, end, step, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::arange(const at::Scalar& start, const at::Scalar& end,
|
||||
c10::optional<at::ScalarType> dtype_opt,
|
||||
c10::optional<at::Layout> layout_opt, c10::optional<at::Device> device_opt,
|
||||
c10::optional<bool> pin_memory_opt) {
|
||||
DO_COMPATIBILITY(aclnnArange,
|
||||
NPUNativeFunctions::arange(start, end, dtype_opt, layout_opt, device_opt, pin_memory_opt));
|
||||
return NPUNativeOpApiFunctions::arange(start, end, 1, dtype_opt, layout_opt, device_opt, pin_memory_opt);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::arange(const at::Scalar& end, c10::optional<at::ScalarType> dtype_opt,
|
||||
c10::optional<at::Layout> layout_opt, c10::optional<at::Device> device_opt,
|
||||
c10::optional<bool> pin_memory_opt) {
|
||||
DO_COMPATIBILITY(aclnnArange, NPUNativeFunctions::arange(end, dtype_opt, layout_opt, device_opt, pin_memory_opt));
|
||||
return NPUNativeOpApiFunctions::arange(0, end, dtype_opt, layout_opt, device_opt, pin_memory_opt); // start = 0
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::arange_out(const at::Scalar& start, const at::Scalar& end, const at::Scalar& step,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnArange, NPUNativeFunctions::arange_out(start, end, step, result));
|
||||
|
||||
int64_t size_value = GetResultSize(start, end, step, result.scalar_type());
|
||||
at::SmallVector<int64_t, SIZE> outputSize = {size_value};
|
||||
result.resize_(outputSize);
|
||||
|
||||
ArangeOutOpApi(start, end, step, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& ArangeStartEndOut(at::Scalar start, at::Scalar end, at::Tensor& result) {
|
||||
at::Scalar step = 1;
|
||||
return NPUNativeOpApiFunctions::arange_out(start, end, step, result);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::arange_out(const at::Scalar& end, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnArange, NPUNativeFunctions::arange_out(end, result));
|
||||
return ArangeStartEndOut(0, end, result);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,51 +0,0 @@
|
||||
// Copyright (c) 2023 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"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::argmax(const at::Tensor& self, at::optional<int64_t> dim, bool keepdim) {
|
||||
DO_COMPATIBILITY(aclnnArgMax, NPUNativeFunctions::argmax(self, dim, keepdim));
|
||||
|
||||
if (self.numel() == 0) {
|
||||
return self;
|
||||
}
|
||||
|
||||
at::Tensor input = self.reshape({-1});
|
||||
int64_t realDim = 0;
|
||||
bool realKeepDim = false;
|
||||
if (dim.has_value()) {
|
||||
input = self;
|
||||
realDim = dim.value();
|
||||
realKeepDim = keepdim;
|
||||
}
|
||||
|
||||
// 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::kLong));
|
||||
|
||||
EXEC_NPU_CMD(aclnnArgMax, input, realDim, realKeepDim, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,59 +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 <ATen/Tensor.h>
|
||||
#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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/framework/FormatHelper.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
tuple<at::Tensor, at::Tensor, at::Tensor> NPUNativeOpApiFunctions::native_batch_norm_backward(
|
||||
const at::Tensor& grad_out, const at::Tensor& self, const c10::optional<at::Tensor>& weight_opt,
|
||||
const c10::optional<at::Tensor>& running_mean_opt, const c10::optional<at::Tensor>& running_var_opt,
|
||||
const c10::optional<at::Tensor>& save_mean_opt, const c10::optional<at::Tensor>& save_invstd_opt, bool train,
|
||||
double eps, std::array<bool, 3> grad_input_mask) {
|
||||
if (self.dim() == 5) {
|
||||
return NPUNativeFunctions::native_batch_norm_backward(grad_out, self, weight_opt, running_mean_opt, running_var_opt,
|
||||
save_mean_opt, save_invstd_opt, train, eps, grad_input_mask);
|
||||
}
|
||||
DO_COMPATIBILITY(aclnnBatchNormBackward, NPUNativeFunctions::native_batch_norm_backward(grad_out, self, weight_opt, running_mean_opt, running_var_opt, save_mean_opt, save_invstd_opt, train, eps, grad_input_mask));
|
||||
// grad_input_mask
|
||||
at::Tensor grad_input;
|
||||
at::Tensor grad_weight;
|
||||
at::Tensor grad_bias;
|
||||
if (grad_input_mask[0]) {
|
||||
grad_input = OpPreparation::ApplyTensor(self.sizes(), self.options(), self);
|
||||
}
|
||||
if (grad_input_mask[1]) {
|
||||
grad_weight = OpPreparation::ApplyTensor({self.size(1)}, self.options().dtype(at::kFloat), self);
|
||||
}
|
||||
if (grad_input_mask[2]) {
|
||||
grad_bias = OpPreparation::ApplyTensor({self.size(1)}, self.options().dtype(at::kFloat), self);
|
||||
}
|
||||
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnBatchNormBackward, grad_out, self, weight_opt, running_mean_opt, running_var_opt, save_mean_opt,
|
||||
save_invstd_opt, train, eps, grad_input_mask, grad_input, grad_weight, grad_bias);
|
||||
|
||||
return std::make_tuple(grad_input, grad_weight, grad_bias);
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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 <ATen/Tensor.h>
|
||||
#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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/framework/FormatHelper.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
tuple<at::Tensor, at::Tensor, at::Tensor> NPUNativeOpApiFunctions::native_batch_norm(
|
||||
const at::Tensor& self, const c10::optional<at::Tensor>& weight_opt, const c10::optional<at::Tensor>& bias_opt,
|
||||
const c10::optional<at::Tensor>& running_mean_opt, const c10::optional<at::Tensor>& running_var_opt, bool train,
|
||||
double momentum, double eps) {
|
||||
if (self.dim() == 5) {
|
||||
return NPUNativeFunctions::native_batch_norm(self, weight_opt, bias_opt, running_mean_opt, running_var_opt, train,
|
||||
momentum, eps);
|
||||
}
|
||||
DO_COMPATIBILITY(aclnnBatchNorm, NPUNativeFunctions::native_batch_norm(self, weight_opt, bias_opt, running_mean_opt,
|
||||
running_var_opt, train, momentum, eps));
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self.sizes(), self.options(), self);
|
||||
at::Tensor save_mean;
|
||||
at::Tensor save_invstd;
|
||||
if (train) {
|
||||
save_mean = OpPreparation::ApplyTensor({self.size(1)}, self.options().dtype(at::kFloat), self);
|
||||
save_invstd = OpPreparation::ApplyTensor({self.size(1)}, self.options().dtype(at::kFloat), self);
|
||||
} else {
|
||||
save_mean = at::empty({0}, self.options());
|
||||
save_invstd = at::empty({0}, self.options());
|
||||
}
|
||||
|
||||
EXEC_NPU_CMD(aclnnBatchNorm, self, weight_opt, bias_opt, running_mean_opt, running_var_opt, train, momentum, eps,
|
||||
result, save_mean, save_invstd);
|
||||
|
||||
return std::tie(result, save_mean, save_invstd);
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/aten/ops/op_api/op_api_common.h"
|
||||
#include <limits.h>
|
||||
#include <ATen/NamedTensorUtils.h>
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/core/npu/NPUCachingAllocator.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/framework/utils/CalcuOpUtil.h"
|
||||
#include "torch_npu/csrc/aten/NPUGeneratorImpl.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bernoulli_(at::Tensor& self, double p, c10::optional<at::Generator> gen) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBernoulli, NPUNativeFunctions::bernoulli_(self, p, gen));
|
||||
auto gen_ = at::get_generator_or_default<NPUGeneratorImpl>(gen, at_npu::detail::getDefaultNPUGenerator());
|
||||
auto pair = gen_->philox_engine_inputs(10);
|
||||
const int64_t seed = pair.first;
|
||||
const int64_t offset = pair.second;
|
||||
|
||||
const c10::Scalar& pScalar = at::Scalar(p);
|
||||
EXEC_NPU_CMD(aclnnInplaceBernoulli, self, pScalar, seed, offset);
|
||||
return self;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bernoulli_(at::Tensor& self, const at::Tensor& p,
|
||||
c10::optional<at::Generator> gen) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBernoulliTensor, NPUNativeFunctions::bernoulli_(self, p, gen));
|
||||
auto gen_ = at::get_generator_or_default<NPUGeneratorImpl>(gen, at_npu::detail::getDefaultNPUGenerator());
|
||||
auto pair = gen_->philox_engine_inputs(10);
|
||||
const int64_t seed = pair.first;
|
||||
const int64_t offset = pair.second;
|
||||
|
||||
EXEC_NPU_CMD(aclnnInplaceBernoulliTensor, self, p, seed, offset);
|
||||
return self;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bernoulli(const at::Tensor& self, c10::optional<at::Generator> gen) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBernoulliTensor, NPUNativeFunctions::bernoulli(self, gen));
|
||||
at::Tensor self_copy = OpPreparation::ApplyTensor(self);
|
||||
return NPUNativeOpApiFunctions::bernoulli_(self_copy, self, gen);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bernoulli(const at::Tensor& self, double p, c10::optional<at::Generator> gen) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBernoulli, NPUNativeFunctions::bernoulli(self, p, gen));
|
||||
return at::empty_like(self, LEGACY_CONTIGUOUS_MEMORY_FORMAT).bernoulli_(p, gen);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bernoulli_out(const at::Tensor& self, c10::optional<at::Generator> gen,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBernoulliTensor, NPUNativeFunctions::bernoulli_out(self, gen, result));
|
||||
result.resize_(self.sizes()).bernoulli_(self, gen);
|
||||
at::namedinference::propagate_names(result, self);
|
||||
return result;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.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 &NPUNativeOpApiFunctions::binary_cross_entropy_out(
|
||||
const at::Tensor &self,
|
||||
const at::Tensor &target,
|
||||
const c10::optional<at::Tensor> &weight_opt,
|
||||
int64_t reduction,
|
||||
at::Tensor &result) {
|
||||
DO_COMPATIBILITY(aclnnBinaryCrossEntropy,
|
||||
NPUNativeFunctions::binary_cross_entropy_out(self, target, weight_opt, reduction, result));
|
||||
EXEC_NPU_CMD(aclnnBinaryCrossEntropy, self, target, weight_opt, reduction, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::binary_cross_entropy(
|
||||
const at::Tensor &self,
|
||||
const at::Tensor &target,
|
||||
const c10::optional<at::Tensor> &weight_opt,
|
||||
int64_t reduction) {
|
||||
DO_COMPATIBILITY(aclnnBinaryCrossEntropy,
|
||||
NPUNativeFunctions::binary_cross_entropy(self, target, weight_opt, 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<int64_t>();
|
||||
}
|
||||
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self, outputSize);
|
||||
EXEC_NPU_CMD(aclnnBinaryCrossEntropy, self, target, weight_opt, reduction, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_and_out(const at::Tensor& self, const at::Scalar& other,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseAndTensorOut, NPUNativeFunctions::bitwise_and_out(self, other, result));
|
||||
OpPreparation::CheckOut({self}, result, self);
|
||||
|
||||
auto other_tensor = CalcuOpUtil::CopyScalarToDevice(other, self.scalar_type());
|
||||
EXEC_NPU_CMD(aclnnBitwiseAndTensorOut, self, other_tensor, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_and_out(const at::Tensor& self, const at::Tensor& other,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseAndTensorOut, NPUNativeFunctions::bitwise_and_out(self, other, result));
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
|
||||
at::Tensor ref_tensor;
|
||||
if (isSelfWrapped) {
|
||||
ref_tensor = other;
|
||||
} else {
|
||||
ref_tensor = self;
|
||||
}
|
||||
|
||||
auto output_size = broadcast_ops_npu_output_size(self, other);
|
||||
|
||||
OpPreparation::CheckOut({self}, result, ref_tensor, output_size);
|
||||
|
||||
EXEC_NPU_CMD(aclnnBitwiseAndTensorOut, self, other, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bitwise_and(const at::Tensor& self, const at::Tensor& other) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseAndTensorOut, NPUNativeFunctions::bitwise_and(self, other));
|
||||
// calculate the output size
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
|
||||
at::Tensor ref_tensor;
|
||||
if (isSelfWrapped) {
|
||||
ref_tensor = other;
|
||||
} else {
|
||||
ref_tensor = self;
|
||||
}
|
||||
|
||||
auto output_size = broadcast_ops_npu_output_size(self, other);
|
||||
|
||||
// construct the output at::Tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(ref_tensor, output_size);
|
||||
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnBitwiseAndTensorOut, self, other, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bitwise_and(const at::Tensor& self, const at::Scalar& other) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseAndTensorOut, NPUNativeFunctions::bitwise_and(self, other));
|
||||
// calculate the output size
|
||||
auto output_size = input_same_output_size(self);
|
||||
|
||||
// construct the output at::Tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self, output_size);
|
||||
|
||||
auto other_tensor = CalcuOpUtil::CopyScalarToDevice(other, self.scalar_type());
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnBitwiseAndTensorOut, self, other_tensor, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_and_(at::Tensor& self, const at::Tensor& other) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBitwiseAndTensorOut, NPUNativeFunctions::bitwise_and_(self, other));
|
||||
EXEC_NPU_CMD(aclnnInplaceBitwiseAndTensorOut, self, other);
|
||||
return self;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_and_(at::Tensor& self, const at::Scalar& other) {
|
||||
DO_COMPATIBILITY(aclnnInplaceBitwiseAndTensorOut, NPUNativeFunctions::bitwise_and_(self, other));
|
||||
auto other_tensor = CalcuOpUtil::CopyScalarToDevice(other, self.scalar_type());
|
||||
EXEC_NPU_CMD(aclnnInplaceBitwiseAndTensorOut, self, other_tensor);
|
||||
return self;
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,49 +0,0 @@
|
||||
// Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
// Copyright (c) 2023, 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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_not_out(const at::Tensor& self, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseNot, NPUNativeFunctions::bitwise_not_out(self, result));
|
||||
OpPreparation::CheckOut(
|
||||
{self},
|
||||
result,
|
||||
self);
|
||||
|
||||
EXEC_NPU_CMD(aclnnBitwiseNot, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bitwise_not(const at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseNot, NPUNativeFunctions::bitwise_not(self));
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
EXEC_NPU_CMD(aclnnBitwiseNot, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_not_(at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseNot, NPUNativeFunctions::bitwise_not_(self));
|
||||
EXEC_NPU_CMD(aclnnBitwiseNot, self, self);
|
||||
return self;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,113 +0,0 @@
|
||||
// Copyright (c) 2023, 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/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_or_out(
|
||||
const at::Tensor& self,
|
||||
const at::Scalar& other,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseOrScalar, NPUNativeFunctions::bitwise_or_out(self, other, result));
|
||||
|
||||
OpPreparation::CheckOut({self}, result, result, self.sizes());
|
||||
EXEC_NPU_CMD(aclnnBitwiseOrScalar, self, other, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bitwise_or(const at::Tensor& self, const at::Scalar& other) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseOrScalar, NPUNativeFunctions::bitwise_or(self, other));
|
||||
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnBitwiseOrScalar, self, other, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& bitwise_or_op_api_out_npu_nocheck(
|
||||
at::Tensor& result,
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& other) {
|
||||
if (OpPreparation::IsCPUScalar(other)) {
|
||||
const at::Scalar other_value = other.item();
|
||||
EXEC_NPU_CMD(aclnnBitwiseOrScalar, self, other_value, result);
|
||||
} else if (OpPreparation::IsCPUScalar(self)) {
|
||||
const at::Scalar self_value = self.item();
|
||||
EXEC_NPU_CMD(aclnnBitwiseOrScalar, other, self_value, result);
|
||||
} else {
|
||||
EXEC_NPU_CMD(aclnnBitwiseOrTensor, self, other, result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bitwise_or_out(
|
||||
const at::Tensor& self,
|
||||
const at::Tensor& other,
|
||||
at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseOrScalar, NPUNativeFunctions::bitwise_or_out(self, other, result));
|
||||
DO_COMPATIBILITY(aclnnBitwiseOrTensor, NPUNativeFunctions::bitwise_or_out(self, other, result));
|
||||
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
|
||||
|
||||
at::Tensor outputTensor;
|
||||
if (isSelfWrapped) {
|
||||
outputTensor = other;
|
||||
} else {
|
||||
outputTensor = self;
|
||||
}
|
||||
auto outputSize = broadcast_ops_npu_output_size(self, other);
|
||||
OpPreparation::CheckOut(
|
||||
{self},
|
||||
result,
|
||||
outputTensor,
|
||||
outputSize);
|
||||
|
||||
bitwise_or_op_api_out_npu_nocheck(result, self, other);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bitwise_or(const at::Tensor& self, const at::Tensor& other) {
|
||||
DO_COMPATIBILITY(aclnnBitwiseOrScalar, NPUNativeFunctions::bitwise_or(self, other));
|
||||
DO_COMPATIBILITY(aclnnBitwiseOrTensor, NPUNativeFunctions::bitwise_or(self, other));
|
||||
|
||||
// calculate the output size
|
||||
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(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 NPUitwiseOrKerne
|
||||
at::Tensor result = OpPreparation::ApplyTensor(outputTensor, outputSize);
|
||||
// calculate the output result of the NPU
|
||||
bitwise_or_op_api_out_npu_nocheck(result, self, other);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,58 +0,0 @@
|
||||
// Copyright (c) 2023 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/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::bmm_out(const at::Tensor& self, const at::Tensor& mat2, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnBatchMatMul,
|
||||
NPUNativeFunctions::bmm_out(self, mat2, result));
|
||||
|
||||
auto output_size = {self.size(0), self.size(1), mat2.size(2)};
|
||||
OpPreparation::CheckOut({self, mat2}, result, CalcuOpUtil::GetTensorNpuFormat(result),
|
||||
self.scalar_type(), output_size);
|
||||
|
||||
// cube_math_type, an enumeration value of type int8 that determines which calculation logic the CUBE unit should use
|
||||
// and functions such as hfloat32 can be enabled through this switch
|
||||
int cube_math_type = 1;
|
||||
EXEC_NPU_CMD(aclnnBatchMatMul, self, mat2, result, cube_math_type);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::bmm(const at::Tensor& self, const at::Tensor& mat2) {
|
||||
DO_COMPATIBILITY(aclnnBatchMatMul,
|
||||
NPUNativeFunctions::bmm(self, mat2));
|
||||
|
||||
// calculate the output size
|
||||
auto output_size = {self.size(0), self.size(1), mat2.size(2)};
|
||||
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensorWithSizes(
|
||||
output_size, self.options());
|
||||
|
||||
// cube_math_type, an enumeration value of type int8 that determines which calculation logic the CUBE unit should use
|
||||
// and functions such as hfloat32 can be enabled through this switch
|
||||
int cube_math_type = 1;
|
||||
EXEC_NPU_CMD(aclnnBatchMatMul, self, mat2, result, cube_math_type);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
// Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
// Copyright (c) 2023, 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/csrc/autograd/custom_function.h>
|
||||
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
using torch::autograd::AutogradContext;
|
||||
using torch::autograd::Function;
|
||||
using tensor_list = std::vector<at::Tensor>;
|
||||
|
||||
at::Tensor npu_dtype_cast_impl_op_api(const at::Tensor& self, at::ScalarType dtype) {
|
||||
if (self.dtype() == dtype) {
|
||||
return self.clone();
|
||||
}
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self.sizes(), self.options().dtype(dtype), self);
|
||||
|
||||
// calculate the output result of the NPU
|
||||
EXEC_NPU_CMD(aclnnCast, self, dtype, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
class NPUDtypeCastOpApiFunction : public torch::autograd::Function<NPUDtypeCastOpApiFunction> {
|
||||
public:
|
||||
static at::Tensor forward(AutogradContext* ctx, at::Tensor self, at::ScalarType dtype) {
|
||||
at::AutoNonVariableTypeMode g;
|
||||
ctx->saved_data["dtype"] = self.scalar_type();
|
||||
return npu_dtype_cast_impl_op_api(self, dtype);
|
||||
}
|
||||
|
||||
static tensor_list backward(AutogradContext* ctx, tensor_list grad_outputs) {
|
||||
auto dtype = ctx->saved_data["dtype"].toScalarType();
|
||||
grad_outputs[0].requires_grad_();
|
||||
return {NPUDtypeCastOpApiFunction::apply(grad_outputs[0], dtype), at::Tensor()};
|
||||
}
|
||||
};
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::npu_dtype_cast(const at::Tensor& self, at::ScalarType dtype) {
|
||||
DO_COMPATIBILITY(aclnnCast, NPUNativeFunctions::npu_dtype_cast(self, dtype));
|
||||
return NPUDtypeCastOpApiFunction::apply(self, dtype);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,142 +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/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
c10::SmallVector<at::Tensor, N> cat_dest_tensor_list_opapi(at::TensorList tensors) {
|
||||
c10::SmallVector<at::Tensor, N> dst_tensor_list;
|
||||
// pytorch supports empty tensors, which needs to be removed from the NPU.
|
||||
for (at::Tensor tensor : tensors) {
|
||||
if (tensor.dim() == 1 && tensor.sizes()[0] == 0) {
|
||||
continue;
|
||||
}
|
||||
dst_tensor_list.emplace_back(tensor);
|
||||
}
|
||||
return dst_tensor_list;
|
||||
}
|
||||
|
||||
c10::SmallVector<int64_t, SIZE> cat_npu_output_size_opapi(c10::SmallVector<at::Tensor, N_SIZE>& tensors,
|
||||
int64_t dimension) {
|
||||
bool allSkipped = true;
|
||||
int64_t nDims = 0;
|
||||
at::Tensor* notSkippedTensor;
|
||||
int numInputs = tensors.size();
|
||||
auto should_skip = [](const at::Tensor* t) { return t->nbytes() == 0 && t->dim() == 1; };
|
||||
for (int i = 0; i < numInputs; i++) {
|
||||
if (should_skip((at::Tensor*)&tensors[i])) {
|
||||
continue;
|
||||
}
|
||||
// found a non-empty tensor
|
||||
allSkipped = false;
|
||||
notSkippedTensor = (at::Tensor*)&tensors[i];
|
||||
nDims = notSkippedTensor->dim();
|
||||
break;
|
||||
}
|
||||
|
||||
if (allSkipped) {
|
||||
c10::SmallVector<int64_t, SIZE> size = {0};
|
||||
return size;
|
||||
}
|
||||
|
||||
// Compute size of the result in the cat dimension
|
||||
int64_t cat_dim_size = 0;
|
||||
for (int i = 0; i < numInputs; i++) {
|
||||
at::Tensor* tensor = (at::Tensor*)&tensors[i];
|
||||
if (should_skip(tensor)) {
|
||||
continue;
|
||||
}
|
||||
cat_dim_size += tensor->size(dimension);
|
||||
}
|
||||
|
||||
// Compute the size of the result
|
||||
c10::SmallVector<int64_t, SIZE> size;
|
||||
size.resize(nDims);
|
||||
for (int dim = 0; dim < nDims; dim++) {
|
||||
int64_t result_dim_size = notSkippedTensor->size(dim);
|
||||
if (dim == dimension) {
|
||||
result_dim_size = cat_dim_size;
|
||||
}
|
||||
size[dim] = result_dim_size;
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::_cat_out(at::TensorList tensors, int64_t dim, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnCat, NPUNativeFunctions::_cat_out(tensors, dim, result));
|
||||
EXEC_NPU_CMD(aclnnCat, tensors, dim, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::cat_out(at::TensorList tensors, int64_t dim, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnCat, NPUNativeFunctions::cat_out(tensors, dim, result));
|
||||
c10::SmallVector<at::Tensor, N> inputTensors = cat_dest_tensor_list_opapi(tensors);
|
||||
|
||||
int64_t dim_post_expr = 0;
|
||||
if (inputTensors.size() > 0) {
|
||||
dim_post_expr = inputTensors[0].dim();
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
dim = CalcuOpUtil::MakeWrapDim(dim, dim_post_expr);
|
||||
auto outputSize = cat_npu_output_size_opapi(inputTensors, dim);
|
||||
OpPreparation::CheckOut({tensors[0]}, result, ACL_FORMAT_ND, tensors[0].scalar_type(), outputSize);
|
||||
return at::_cat_out(result, tensors, dim);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::cat_out(at::TensorList tensors, at::Dimname dim, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnCat, NPUNativeFunctions::cat_out(tensors, dim, result));
|
||||
return at::cat_out(result, tensors, dimname_to_position(tensors[0], dim));
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::_cat(at::TensorList tensors, int64_t dim) {
|
||||
DO_COMPATIBILITY(aclnnCat, NPUNativeFunctions::_cat(tensors, dim));
|
||||
c10::SmallVector<at::Tensor, N> inputTensors = cat_dest_tensor_list_opapi(tensors);
|
||||
|
||||
int64_t dim_post_expr = 0;
|
||||
if (inputTensors.size() > 0) {
|
||||
dim_post_expr = inputTensors[0].dim();
|
||||
} else {
|
||||
at::Tensor result = OpPreparation::ApplyTensor(tensors[0]);
|
||||
return result;
|
||||
}
|
||||
dim = CalcuOpUtil::MakeWrapDim(dim, dim_post_expr);
|
||||
|
||||
// calculate the output size
|
||||
auto outputSize = cat_npu_output_size_opapi(inputTensors, dim);
|
||||
at::Tensor result = OpPreparation::ApplyTensor(inputTensors[0], outputSize);
|
||||
NPUNativeOpApiFunctions::_cat_out(tensors, dim, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::cat(at::TensorList tensors, int64_t dim) {
|
||||
DO_COMPATIBILITY(aclnnCat, NPUNativeFunctions::cat(tensors, dim));
|
||||
return at::_cat(tensors, dim);
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::cat(at::TensorList tensors, at::Dimname dim) {
|
||||
DO_COMPATIBILITY(aclnnCat, NPUNativeFunctions::cat(tensors, dim));
|
||||
return at::cat(tensors, dimname_to_position(tensors[0], dim));
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,44 +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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/framework/utils/OpAdapter.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::ceil_out(const at::Tensor& self, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnCeil, NPUNativeFunctions::ceil_out(self, result));
|
||||
EXEC_NPU_CMD(aclnnCeil, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::ceil(const at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnCeil, NPUNativeFunctions::ceil(self));
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
EXEC_NPU_CMD(aclnnCeil, self, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::ceil_(at::Tensor& self) {
|
||||
DO_COMPATIBILITY(aclnnCeil, NPUNativeFunctions::ceil_(self));
|
||||
NPUNativeOpApiFunctions::ceil_out(self, self);
|
||||
return self;
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -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/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
#include "torch_npu/csrc/aten/ops/op_api/op_api_common.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
at::Tensor& NPUNativeOpApiFunctions::clamp_out(const at::Tensor& self, const c10::optional<at::Scalar>& min,
|
||||
const c10::optional<at::Scalar>& max, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnClamp, NPUNativeFunctions::clamp_out(self, min, max, result));
|
||||
OpPreparation::CheckOut({self}, result, self);
|
||||
EXEC_NPU_CMD(aclnnClamp, self, min, max, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::clamp(const at::Tensor& self, const c10::optional<at::Scalar>& min,
|
||||
const c10::optional<at::Scalar>& max) {
|
||||
DO_COMPATIBILITY(aclnnClamp, NPUNativeFunctions::clamp(self, min, max));
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
return NPUNativeOpApiFunctions::clamp_out(self, min, max, result);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::clamp_(
|
||||
at::Tensor& self,
|
||||
const c10::optional<at::Scalar>& min,
|
||||
const c10::optional<at::Scalar>& max) {
|
||||
DO_COMPATIBILITY(aclnnClamp, NPUNativeFunctions::clamp_(self, min, max));
|
||||
return NPUNativeOpApiFunctions::clamp_out(self, min, max, self);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::clamp_out(const at::Tensor& self, const c10::optional<at::Tensor>& min,
|
||||
const c10::optional<at::Tensor>& max, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnClampTensor, NPUNativeFunctions::clamp_out(self, min, max, result));
|
||||
EXEC_NPU_CMD(aclnnClampTensor, self, min, max, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::clamp(const at::Tensor& self, const c10::optional<at::Tensor>& min,
|
||||
const c10::optional<at::Tensor>& max) {
|
||||
DO_COMPATIBILITY(aclnnClampTensor, NPUNativeFunctions::clamp(self, min, max));
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
return NPUNativeOpApiFunctions::clamp_out(self, min, max, result);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::clamp_min_out(const at::Tensor& self, const at::Scalar& min, at::Tensor& result) {
|
||||
DO_COMPATIBILITY(aclnnClampMin, NPUNativeFunctions::clamp_min_out(self, min, result));
|
||||
OpPreparation::CheckOut({self}, result, self);
|
||||
EXEC_NPU_CMD(aclnnClampMin, self, min, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
at::Tensor NPUNativeOpApiFunctions::clamp_min(const at::Tensor& self, const at::Scalar& min) {
|
||||
DO_COMPATIBILITY(aclnnClampMin, NPUNativeFunctions::clamp_min(self, min));
|
||||
at::Tensor result = OpPreparation::ApplyTensor(self);
|
||||
return NPUNativeOpApiFunctions::clamp_min_out(self, min, result);
|
||||
}
|
||||
|
||||
at::Tensor& NPUNativeOpApiFunctions::clamp_min_(at::Tensor& self, const at::Scalar& min) {
|
||||
DO_COMPATIBILITY(aclnnClampMin, NPUNativeFunctions::clamp_min_(self, min));
|
||||
return NPUNativeOpApiFunctions::clamp_min_out(self, min, self);
|
||||
}
|
||||
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
@@ -1,121 +0,0 @@
|
||||
// Copyright (c) 2023 Huawei Technologies Co., Ltd
|
||||
// Copyright (c) 2023, 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/ops/op_api/op_api_common.h"
|
||||
#include "torch_npu/csrc/framework/utils/KernelNpuOutputSize.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
|
||||
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
|
||||
|
||||
namespace at_npu {
|
||||
namespace native {
|
||||
|
||||
static inline c10::SmallVector<int64_t, N> expand_dim_if_needed(
|
||||
at::IntArrayRef list_param,
|
||||
const char* param_name,
|
||||
int64_t expected_dim)
|
||||
{
|
||||
if (list_param.size() == 1) {
|
||||
c10::SmallVector<int64_t, N> expand_dim_param_vec;
|
||||
for (int64_t i = 0; i < expected_dim; i++) {
|
||||
expand_dim_param_vec.emplace_back(list_param[0]);
|
||||
}
|
||||
return expand_dim_param_vec;
|
||||
} else {
|
||||
return CalcuOpUtil::ConvertIntArrayRefToSmallVector(list_param);
|
||||
}
|
||||
}
|
||||
|
||||
// length of output_mask is 3
|
||||
std::tuple<at::Tensor, at::Tensor, at::Tensor> NPUNativeOpApiFunctions::convolution_backward(
|
||||
const at::Tensor & grad_output, const at::Tensor & input, const at::Tensor & weight,
|
||||
c10::optional<at::IntArrayRef> bias_sizes_opt, at::IntArrayRef stride, at::IntArrayRef padding,
|
||||
at::IntArrayRef dilation, bool transposed, at::IntArrayRef output_padding, int64_t groups,
|
||||
::std::array<bool, 3> output_mask)
|
||||
{
|
||||
DO_COMPATIBILITY(aclnnConvolutionBackward,
|
||||
NPUNativeFunctions::convolution_backward(grad_output, input, weight, bias_sizes_opt, stride, padding,
|
||||
dilation, transposed, output_padding, groups, output_mask));
|
||||
|
||||
int64_t k = weight.ndimension();
|
||||
int64_t dim = k - 2;
|
||||
int8_t cubeMathType = 1;
|
||||
|
||||
/* k == 5 and groups > 3 currently unsupported by the binary file, CCB concludes to use path 3 to maintain
|
||||
the current function in hostapi
|
||||
*/
|
||||
if (k == 5 || groups > 1) {
|
||||
return at_npu::native::NPUNativeFunctions::convolution_backward(grad_output, input, weight, bias_sizes_opt,
|
||||
stride, padding, dilation, transposed, output_padding, groups, output_mask);
|
||||
}
|
||||
|
||||
c10::SmallVector<int64_t, N> stride_expand = expand_dim_if_needed(stride, "stride", dim);
|
||||
stride = at::IntArrayRef(stride_expand);
|
||||
|
||||
c10::SmallVector<int64_t, N> padding_expand = expand_dim_if_needed(padding, "padding", dim);
|
||||
padding = at::IntArrayRef(padding_expand);
|
||||
|
||||
c10::SmallVector<int64_t, N> dilation_expand = expand_dim_if_needed(dilation, "dilation", dim);
|
||||
dilation = at::IntArrayRef(dilation_expand);
|
||||
|
||||
c10::SmallVector<int64_t, N> output_padding_expand = expand_dim_if_needed(
|
||||
output_padding, "output_padding", dim);
|
||||
output_padding = at::IntArrayRef(output_padding_expand);
|
||||
|
||||
auto outputSizes = conv2d_backward_npu_output_size(
|
||||
input, grad_output, weight, stride, padding, dilation, groups);
|
||||
|
||||
// construct the output tensor of the NPU
|
||||
at::Tensor gradInput;
|
||||
at::Tensor gradWeight;
|
||||
at::Tensor gradBias;
|
||||
|
||||
gradInput = OpPreparation::ApplyTensorWithSizes(
|
||||
std::get<0>(outputSizes), input.options());
|
||||
|
||||
if (groups > 1) {
|
||||
gradWeight = OpPreparation::ApplyTensorWithSizes(
|
||||
std::get<1>(outputSizes), weight.options());
|
||||
} else {
|
||||
gradWeight = OpPreparation::ApplyTensorWithSizes(
|
||||
std::get<1>(outputSizes), weight.options());
|
||||
}
|
||||
|
||||
// use 2nd dimension of outputSizes
|
||||
gradBias = OpPreparation::ApplyTensorWithSizes(
|
||||
std::get<2>(outputSizes), grad_output.options());
|
||||
|
||||
int64_t input_dim = input.ndimension();
|
||||
|
||||
EXEC_NPU_CMD(aclnnConvolutionBackward,
|
||||
grad_output,
|
||||
input,
|
||||
weight,
|
||||
bias_sizes_opt,
|
||||
stride,
|
||||
padding,
|
||||
dilation,
|
||||
transposed,
|
||||
output_padding,
|
||||
groups,
|
||||
output_mask,
|
||||
cubeMathType,
|
||||
gradInput,
|
||||
gradWeight,
|
||||
gradBias);
|
||||
return std::make_tuple(std::move(gradInput), std::move(gradWeight), std::move(gradBias));
|
||||
}
|
||||
} // namespace native
|
||||
} // namespace at_npu
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user