diff --git a/autograd/__init__.py b/autograd/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/codegen/api/python.py b/codegen/api/python.py index a07af176eb..6c168ae410 100644 --- a/codegen/api/python.py +++ b/codegen/api/python.py @@ -992,13 +992,16 @@ def cpp_record_func(f: NativeFunction, custom=False) -> str: return record_func raise RuntimeError(f'could not dispatch, neither function nor method: {f.func}') -def cpp_dispatch_target(f: NativeFunction, custom=False) -> str: +def cpp_dispatch_target(f: NativeFunction, custom=False, is_npu_autograd=False) -> str: name = cpp.name(f.func) if Variant.method in f.variants and not custom: return f'self.{name}' if Variant.function in f.variants: if custom: - namespace = 'at_npu::native::NPUNativeFunctions' + if is_npu_autograd: + namespace = 'at_npu::autograd::VariableType' + else: + namespace = 'at_npu::native::NPUNativeFunctions' elif has_tensor_options(f) or f.func.name.name.base.endswith('_like'): namespace = 'torch' else: diff --git a/codegen/api/types.py b/codegen/api/types.py index 42502537f0..3de8d8b546 100644 --- a/codegen/api/types.py +++ b/codegen/api/types.py @@ -49,6 +49,7 @@ intT = BaseCppType('', 'int64_t') doubleT = BaseCppType('', 'double') boolT = BaseCppType('', 'bool') voidT = BaseCppType('', 'void') +longT = BaseCppType('', 'int64_t') stringT = BaseCppType('c10', 'string_view') generatorT = BaseCppType('at', 'Generator') scalarTypeT = BaseCppType('at', 'ScalarType') diff --git a/codegen/gen.py b/codegen/gen.py index b0277cea52..94a9477dcc 100644 --- a/codegen/gen.py +++ b/codegen/gen.py @@ -18,14 +18,14 @@ import os import stat import functools import hashlib -from typing import List, Dict, Optional, Set, Callable, Any, Union, Sequence, TypeVar, Iterable +from typing import (List, Dict, Optional, Set, Callable, Any, + Union, Sequence, TypeVar, Iterable) from collections import defaultdict from codegen.code_template import CodeTemplate from codegen.model import (FunctionSchema, NativeFunction, NativeFunctionsGroup, OperatorName, SchemaKind, assert_never) - from codegen.utils import concat_map T = TypeVar('T') diff --git a/codegen/gen_python_functions.py b/codegen/gen_python_functions.py index d587156210..73a97887ce 100644 --- a/codegen/gen_python_functions.py +++ b/codegen/gen_python_functions.py @@ -86,6 +86,8 @@ SKIP_PYTHON_BINDINGS_SIGNATURES = [] DONT_RECORD_TRACE = [] +NPU_AUTOGRAD_FUNCTION = [] + def should_trace(f: NativeFunction) -> bool: # Operations involving Storage or Type are not traceable at the moment if any(str(arg.type) in {'Storage', 'Type', 'ConstQuantizerPtr'} @@ -664,9 +666,14 @@ def emit_single_dispatch( init_npu_device = f"//" # dispatch lambda body + is_npu_autograd = str(f.func.name) in NPU_AUTOGRAD_FUNCTION record_func_define = cpp_record_func(f, custom=custom) - dispatch_callee = cpp_dispatch_target(f, custom=custom) + dispatch_key_set = '' if not is_npu_autograd else 'auto ks_set = ' \ + 'c10::DispatchKeySet().add(c10::DispatchKey::AutogradXLA).add(c10::DispatchKey::XLA);' + dispatch_callee = cpp_dispatch_target(f, custom=custom, is_npu_autograd=is_npu_autograd) dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=custom)) + if is_npu_autograd: + dispatch_args = 'ks_set, ' + dispatch_args # from arg parser outputs to dispatch lambda arguments parser_outputs = arg_parser_output_exprs(ps, f) @@ -687,6 +694,7 @@ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{ {init_npu_device} pybind11::gil_scoped_release no_gil; {record_func_define} + {dispatch_key_set} {dispatch_callee}({dispatch_args}); }}; dispatch_{name}({lambda_args}){set_requires_grad}; @@ -702,6 +710,7 @@ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{ {init_npu_device} pybind11::gil_scoped_release no_gil; {record_func_define} + {dispatch_key_set} return {dispatch_callee}({dispatch_args}); }}; return wrap({namedtuple_typeref}dispatch_{name}({lambda_args}){set_requires_grad}); diff --git a/codegen/model.py b/codegen/model.py index 6781dfbb37..9ae14415f8 100644 --- a/codegen/model.py +++ b/codegen/model.py @@ -52,6 +52,15 @@ def assert_never(x: NoReturn) -> NoReturn: # and you're expected to populate information once during # construction. +# Represent a source location; used for better error reporting +@dataclass(frozen=True) +class Location: + file: str + line: int + + def __str__(self) -> str: + return "{}:{}".format(self.file, self.line) + # Valid values of the 'variants' field in native_functions.yaml Variant = Enum('Variant', ('function', 'method')) @@ -457,7 +466,6 @@ class NativeFunction: has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel, tag=tag, bscpp_op=bscpp_op), backend_metadata - def validate_unstructured(self) -> None: # TODO: probably better to accumulate these errors and report them all # at once @@ -505,6 +513,20 @@ class NativeFunction: @property def has_composite_kernel(self) -> bool: return self.has_composite_implicit_autograd_kernel or self.has_composite_explicit_autograd_kernel + + @property + def is_view_op(self) -> bool: + rets = self.func.returns + is_non_mutating_view = len(rets) > 0 and any(r.annotation is not None + and not r.annotation.is_write for r in rets) + is_inplace_view = self.tag is not None and self.tag is Tag.inplace_view + is_wildcard_view = any(inp.annotation is not None and + inp.annotation.alias_set_after != "" for inp in self.func.schema_order_arguments()) + return is_non_mutating_view or is_inplace_view or is_wildcard_view + + @property + def root_name(self) -> str: + return self.func.name.name.base SchemaKind = Enum('SchemaKind', ('functional', 'inplace', 'out')) diff --git a/codegen/utils.py b/codegen/utils.py index c85a05140d..931db5a550 100644 --- a/codegen/utils.py +++ b/codegen/utils.py @@ -20,12 +20,30 @@ from enum import Enum import contextlib import textwrap +# Safely load fast C Yaml loader/dumper if they are available +try: + from yaml import CSafeLoader as Loader +except ImportError: + from yaml import SafeLoader as Loader # type: ignore[misc] + try: from yaml import CSafeDumper as Dumper except ImportError: from yaml import SafeDumper as Dumper # type: ignore[misc] YamlDumper = Dumper +# A custom loader for YAML that errors on duplicate keys. +# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165 +class YamlLoader(Loader): + def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def] + mapping = [] + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call] + assert key not in mapping, f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}" + mapping.append(key) + mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call] + return mapping + # Many of these functions share logic for defining both the definition # and declaration (for example, the function signature is the same), so # we organize them into one function that takes a Target to say which diff --git a/torch_npu/csrc/framework/autograd/FunctionsManual.cpp b/torch_npu/csrc/framework/autograd/FunctionsManual.cpp new file mode 100644 index 0000000000..dec3f0fb08 --- /dev/null +++ b/torch_npu/csrc/framework/autograd/FunctionsManual.cpp @@ -0,0 +1,130 @@ +// 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 +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "torch_npu/csrc/aten/NPUNativeFunctions.h" +#include "FunctionsManual.h" + +// Helper functions for autogenerated code +// These used to be inlined into the codegened Functions.cpp + +namespace at_npu { +namespace autograd { +namespace generated { +namespace details { + +using at::Tensor; +using at::Scalar; +using at::IntArrayRef; +using at::TensorList; +using at::areAnyTensorSubclassLike; + +Tensor apply_loss_reduction(const Tensor& unreduced, int64_t reduction) { + if (reduction == at::Reduction::Mean) { + return unreduced.mean(); + } else if (reduction == at::Reduction::Sum) { + return unreduced.sum(); + } + return unreduced; +} + +bool any_variable_defined(const variable_list& variables) { + for (const auto& variable : variables) { + if (variable.defined()) { + return true; + } + } + return false; +} + +bool isDefined(const c10::optional& t) { + return t.has_value() && t->defined(); +} + +Tensor toNonOptTensor(const c10::optional& t) { + return t.has_value() ? *t : Tensor(); +} + +Tensor toNonOptFwGrad(const c10::optional& t) { + return (t.has_value() && t->defined()) ? t->_fw_grad(/*level */ 0) : Tensor(); +} + +Tensor toNonOptPrimal(const c10::optional& t) { + return (t.has_value() && t->defined()) ? t->_fw_primal(/*level */ 0) : Tensor(); +} + +void copy_range(variable_list& out, IndexRange range, const Tensor& t) { + AT_ASSERT(range.second <= out.size()); + AT_ASSERTM(range.second - range.first == 1, "inconsistent range for Tensor output"); + out[range.first] = t; +} + +void copy_range(variable_list& out, IndexRange range, at::ArrayRef t) { + AT_ASSERT(range.second <= out.size()); + AT_ASSERTM(range.second - range.first == t.size(), "inconsistent range for TensorList output"); + std::copy(t.begin(), t.end(), out.begin() + range.first); +} + +template +T not_implemented_base(const char* name, const char* reason) { + std::string msg = c10::str("the derivative for '", name, "' is not implemented."); + if (strlen(reason) > 0) { + msg = c10::str(msg, " ", reason); + }; + TORCH_CHECK_NOT_IMPLEMENTED(false, msg); +} + +Tensor not_implemented(const char* name, const char* reason) { + return not_implemented_base(name, reason); +} + +std::vector not_implemented_list(const char* name, const char* reason) { + return not_implemented_base>(name, reason); +} + + +} // namespace details +} // namespace generated +} // namespace autograd +} // namespace at_npu diff --git a/torch_npu/csrc/framework/autograd/FunctionsManual.h b/torch_npu/csrc/framework/autograd/FunctionsManual.h new file mode 100644 index 0000000000..b3fc4aed17 --- /dev/null +++ b/torch_npu/csrc/framework/autograd/FunctionsManual.h @@ -0,0 +1,64 @@ +// 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. + +#pragma once + +// NB: Must be at the top of file to avoid including the deprecated "math.h". +// https://stackoverflow.com/questions/6563810/m-pi-works-with-math-h-but-not-with-cmath-in-visual-studio +#ifdef _MSC_VER +#ifndef _USE_MATH_DEFINES +#define _USE_MATH_DEFINES +#endif +#include +#endif + +#include + +#include "torch_npu/csrc/aten/Functions.h" + +namespace at_npu { +namespace autograd { +namespace generated { +namespace details { + +// A simple way to imperatively compute index ranges for slots +// that have been flattened +struct IndexRangeGenerator { + IndexRange range(size_t range_size) { + i += range_size; + return {i - range_size, i}; + } + size_t size() { return i; } + private: + size_t i = 0; +}; + +Tensor toNonOptFwGrad(const c10::optional& t); +Tensor toNonOptPrimal(const c10::optional& t); +Tensor toNonOptTensor(const c10::optional& t); + +Tensor apply_loss_reduction(const Tensor& unreduced, int64_t reduction); +bool any_variable_defined(const variable_list& variables); +void copy_range(variable_list& out, IndexRange range, const at::Tensor& t); +void copy_range(variable_list& out, IndexRange range, at::ArrayRef t); +at::Tensor not_implemented(const char* name, const char* reason=""); +std::vector not_implemented_list(const char* name, const char* reason=""); + + +} // namespace details +} // namespace generated +} // namespace autograd +} // namespace at_npu diff --git a/torch_npu/csrc/framework/autograd/VariableTypeManual.cpp b/torch_npu/csrc/framework/autograd/VariableTypeManual.cpp new file mode 100644 index 0000000000..b1b812f4fd --- /dev/null +++ b/torch_npu/csrc/framework/autograd/VariableTypeManual.cpp @@ -0,0 +1,132 @@ +// 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "torch_npu/csrc/framework/autograd/FunctionsManual.h" + +using namespace at; +using namespace at_npu::autograd::generated; +using torch::autograd::CreationMeta; +using torch::autograd::as_view; + +namespace at_npu { +namespace autograd { +namespace VariableType { + +std::vector allTypesForBackends(at::ArrayRef backends) { + std::vector res; + res.reserve(backends.size()); + for (auto p : backends) { + for(const auto s : c10::irange(static_cast(ScalarType::NumOptions))) { + auto& type = getDeprecatedTypeProperties(static_cast(p), static_cast(s)); + res.emplace_back(&type); + } + } + return res; +} + +C10_EXPORT std::vector allCPUTypes() { + return allTypesForBackends({ Backend::CPU, Backend::SparseCPU }); +} + +namespace { +const Variable& checked_cast_variable(const Tensor& t, const char* name, int pos) { + if (!t.defined()) { + AT_ERROR("Expected a proper Tensor but got None (or an undefined Tensor in C++) ", + "for argument #", pos, " '", name, "'"); + } + return t; +} + +Variable& checked_cast_variable(Tensor& t, const char* name, int pos) { + if (!t.defined()) { + AT_ERROR("Expected a proper Tensor but got None (or an undefined Tensor in C++) ", + "for argument #", pos, " '", name, "'"); + } + return t; +} +} // namespace + +const Tensor& unpack(const Tensor& t, const char* name, int pos) { + return checked_cast_variable(t, name, pos); +} + +Tensor& unpack(Tensor& t, const char* name, int pos) { + return checked_cast_variable(t, name, pos); +} + +Tensor unpack_opt(const Tensor& t, const char* name, int pos) { + if (!t.defined()) { + return Tensor(); + } + return unpack(t, name, pos); +} + +std::vector unpack(at::TensorList tl, const char* name, int pos) { + std::vector ret(tl.size()); + for (const auto i : c10::irange(tl.size())) { + const auto &t = tl[i]; + if (!t.defined()) { + continue; + } + ret[i] = static_cast(t); + } + return ret; +} + +namespace { + +// Taken from codegened version +Tensor _fw_primal(c10::DispatchKeySet ks, const Tensor& self, int64_t level) { + auto& self_ = unpack(self, "self", 0); + std::shared_ptr grad_fn; + if (compute_requires_grad(self)) { + grad_fn = std::make_shared(); + grad_fn->set_next_edges(collect_next_edges(self)); + } + + auto result = ([&]() { + at::AutoDispatchBelowAutograd guard; + return at::redispatch::_fw_primal(ks& c10::after_autograd_keyset, self_, level); + })(); + + if (grad_fn) { + set_history(flatten_tensor_args(result), grad_fn); + } + if (isFwGradDefined(self)) { + // Modified from original codegen + // We explicitly want to ignore the forward grad at the given level + TORCH_CHECK(level == 0, "Invalid level given to _fw_primal"); + // End modified from original codegen + } + return result; +} +} // namespace + +} // namespace VariableType +} // namespace autograd +} // namespace at_npu