ZTWHHH commited on
Commit
2b4cc9f
·
verified ·
1 Parent(s): 8eb303d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp +73 -0
  2. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h +29 -0
  3. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp +13 -0
  4. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Function.h +26 -0
  5. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.cpp +103 -0
  6. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyIr.h +19 -0
  7. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h +11 -0
  8. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h +24 -0
  9. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h +33 -0
  10. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h +23 -0
  11. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp +29 -0
  12. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp +110 -0
  13. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp +13 -0
  14. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h +4 -0
  15. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp +61 -0
  16. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp +14 -0
  17. minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu +21 -0
  18. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/BUILD.bazel +4 -0
  19. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/__init__.cpython-310.pyc +0 -0
  20. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/context.cpython-310.pyc +0 -0
  21. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_annotated_fn_args.cpython-310.pyc +0 -0
  22. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd.cpython-310.pyc +0 -0
  23. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd_functions.cpython-310.pyc +0 -0
  24. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_inplace_or_view_type.cpython-310.pyc +0 -0
  25. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_python_functions.cpython-310.pyc +0 -0
  26. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_trace_type.cpython-310.pyc +0 -0
  27. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_factories.cpython-310.pyc +0 -0
  28. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_type.cpython-310.pyc +0 -0
  29. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_view_funcs.cpython-310.pyc +0 -0
  30. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/load_derivatives.cpython-310.pyc +0 -0
  31. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/build.bzl +14 -0
  32. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/derivatives.yaml +0 -0
  33. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py +132 -0
  34. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_python_functions.py +1402 -0
  35. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_factories.py +116 -0
  36. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_view_funcs.py +340 -0
  37. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/load_derivatives.py +1014 -0
  38. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp +65 -0
  39. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp +14 -0
  40. minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h +28 -0
  41. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Central +0 -0
  42. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain +0 -0
  43. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland +0 -0
  44. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/__pycache__/__init__.cpython-310.pyc +0 -0
  45. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 +0 -0
  46. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 +0 -0
  47. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 +0 -0
  48. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 +0 -0
  49. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 +0 -0
  50. minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 +0 -0
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/CompositeViewCopyKernels.cpp ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
2
+ // ${generated_comment}
3
+
4
+ #include <ATen/InferSize.h>
5
+ #include <ATen/Tensor.h>
6
+ #include <ATen/native/Resize.h>
7
+
8
+ #ifndef AT_PER_OPERATOR_HEADERS
9
+ #include <ATen/Operators.h>
10
+ #else
11
+ #include <ATen/ops/clone.h>
12
+ $ops_headers
13
+ #endif
14
+
15
+ namespace at {
16
+ namespace native {
17
+
18
+ // This file contains a number of kernels for aten functions that are fully code-generated.
19
+ // TODO: rename this file to something more generic.
20
+
21
+ namespace {
22
+ at::Tensor clone_arg(const at::Tensor& t) {
23
+ return t.clone();
24
+ }
25
+
26
+ std::vector<at::Tensor> clone_arg(const at::TensorList& t_list) {
27
+ std::vector<at::Tensor> out(t_list.size());
28
+ for (const auto& i : c10::irange(t_list.size())) {
29
+ out[i] = t_list[i].clone();
30
+ }
31
+ return out;
32
+ }
33
+
34
+ // duped with gen_resize_out_helper from structured kernels
35
+ void copy_arg(const at::Tensor& dst, const at::Tensor& src) {
36
+ TORCH_CHECK(src.dtype() == dst.dtype(),
37
+ "Expected out tensor to have dtype ", src.dtype(), ", but got ", dst.dtype(), " instead");
38
+ TORCH_CHECK(src.device() == dst.device(),
39
+ "Expected out tensor to have device ", src.device(), ", but got ", dst.device(), " instead");
40
+ dst.copy_(src);
41
+ }
42
+
43
+ void copy_arg(const at::TensorList& dst, const at::TensorList& src) {
44
+ TORCH_INTERNAL_ASSERT(dst.size() == src.size());
45
+ for (const auto& i : c10::irange(dst.size())) {
46
+ copy_arg(dst[i], src[i]);
47
+ }
48
+ }
49
+
50
+ // TODO: this doesn't handle restriding empty tensors correctly; see
51
+ // gen_resize_out_helper for the correct algorithm
52
+
53
+ void resize_out_helper(const at::Tensor& dst, const at::Tensor& src) {
54
+ at::native::resize_output(dst, src.sizes());
55
+ }
56
+
57
+ void resize_out_helper(const at::TensorList& dst, const at::TensorList& src) {
58
+ TORCH_INTERNAL_ASSERT(dst.size() == src.size());
59
+ for (const auto& i : c10::irange(dst.size())) {
60
+ at::native::resize_output(dst[i], src[i].sizes());
61
+ }
62
+ }
63
+ }
64
+
65
+
66
+ ${CompositeViewCopyKernel_Definitions}
67
+
68
+ ${GeneratedCompositeFunctional_Definitions}
69
+
70
+ ${GeneratedCompositeOut_Definitions}
71
+
72
+ } // namespace native
73
+ } // namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyFunctions.h ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/TensorBody.h>
2
+
3
+ // TODO Undo all logic introduced for Note [Avoiding Include Cycles In Static Dispatch]
4
+ // Code introduced to avoid cyclic dependency in static dispatch is no longer
5
+ // needed as static dispatch logic is moved from TensorBody.h, which caused cycles in the first place,
6
+ // to Operators.cpp for supporting multiple backends with multiple kernels.
7
+ //
8
+ // Note [Avoiding Include Cycles In Static Dispatch]
9
+ // In order to avoid #include cycles in the static dispatch build, we've carefully split out
10
+ // the static function definition files into {DispatchKey}Functions.h and {DispatchKey}Functions_inl.h.
11
+ //
12
+ // Without this split, the include cycle looks like TensorBody.h -> CPUFunctions.h -> TensorBody.h.
13
+ // - TensorBody.h #includes CPUFunctions.h in the static dispatch build, because the tensor methods
14
+ // all need to call into the fastpath C++ API defined in CPUFunctions.h. The methods are also all
15
+ // directly inlined into TensorBody.h.
16
+ // - CPUFunctions.h #includes TensorBody.h because it contains function declarations for the entire C++ API,
17
+ // which include functions that have defaultable std::optional<Tensor> arguments.
18
+ // That requires knowing the full Tensor class definition.
19
+ //
20
+ // We break the cycle by doing the following:
21
+ // - Split out CPUFunction.h into two files: CPUFunctions.h and CPUFunctions_inl.h
22
+ // - CPUFunction.h is a dummy file that just includes the Tensor class and includes CPUFunctions_inl.,
23
+ // - CPUFunctions_inl.h includes everything else
24
+ // - (only in the static dispatch build) TensorBody.h makes sure to finish defining the Tensor class,
25
+ // and then it includes CPUFunctions_inl.h.
26
+ // - All other files that want the cpu fastpath functions can include CPUFunctions.h directly.
27
+ // - This also means that static dispatch build, CPUFunctions.h only needs to
28
+ // #include TensorBody.h, and it will automatically bring in CPUFunctions_inl.h.
29
+ ${inline_headers}
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/DispatchKeyNativeFunctions.cpp ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ${generated_comment}
2
+ ${includes}
3
+ ${native_functions_include}
4
+
5
+ namespace {
6
+ ${helper_fns}
7
+ } // namespace
8
+
9
+ ${namespace_prologue}
10
+
11
+ ${native_function_definitions}
12
+
13
+ ${namespace_epilogue}
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Function.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // ${generated_comment}
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+ ${static_dispatch_ops_headers}
19
+
20
+ ${operator_includes}
21
+
22
+ namespace at {
23
+
24
+ ${function_definitions}
25
+
26
+ }
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/Functions.cpp ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <array>
2
+
3
+ #include <ATen/Functions.h>
4
+ #include <ATen/Utils.h>
5
+ #include <c10/core/Allocator.h>
6
+
7
+ namespace at {
8
+
9
+ Tensor TensorMaker::make_tensor() {
10
+ AutoDispatchBelowADInplaceOrView guard{}; // TODO: Remove.
11
+ tracer::impl::NoTracerDispatchMode tracer_guard{};
12
+
13
+ check_size_nonnegative(sizes_);
14
+
15
+ TORCH_CHECK_VALUE(
16
+ !deleter_ || !ctx_,
17
+ "The deleter and context arguments are mutually exclusive.");
18
+
19
+ if (device_ == std::nullopt) {
20
+ device_ = globalContext().getDeviceFromPtr(data_, opts_.device().type());
21
+ }
22
+
23
+ if (opts_.device().has_index()) {
24
+ // clang-format off
25
+ TORCH_CHECK_VALUE(
26
+ opts_.device() == *device_,
27
+ "Specified device ", opts_.device(), " does not match device of data ", *device_);
28
+ // clang-format on
29
+ }
30
+
31
+ std::size_t size_bytes = computeStorageSize();
32
+
33
+ DataPtr data_ptr{};
34
+ if (deleter_) {
35
+ data_ptr = makeDataPtrFromDeleter();
36
+ } else {
37
+ data_ptr = makeDataPtrFromContext();
38
+ }
39
+
40
+ TORCH_CHECK(!resizeable_ || allocator_ != nullptr, "Must specify an allocator with allocator() if you want to use resizeable_storage()");
41
+ Storage storage{Storage::use_byte_size_t{}, size_bytes, std::move(data_ptr), /*allocator=*/allocator_, /*resizable=*/resizeable_};
42
+
43
+ Tensor tensor = detail::make_tensor<TensorImpl>(
44
+ std::move(storage), opts_.computeDispatchKey(), opts_.dtype());
45
+
46
+ TensorImpl* tensor_impl = tensor.unsafeGetTensorImpl();
47
+ if (strides_) {
48
+ tensor_impl->set_sizes_and_strides(sizes_, *strides_);
49
+ } else {
50
+ tensor_impl->set_sizes_contiguous(sizes_);
51
+ }
52
+ if (storage_offset_) {
53
+ tensor_impl->set_storage_offset(*storage_offset_);
54
+ }
55
+
56
+ return tensor;
57
+ }
58
+
59
+ std::size_t TensorMaker::computeStorageSize() const noexcept {
60
+ std::size_t itemsize = opts_.dtype().itemsize();
61
+
62
+ if (strides_) {
63
+ auto storage_size = detail::computeStorageNbytes(sizes_, *strides_, itemsize);
64
+ if (storage_offset_) {
65
+ storage_size += storage_offset_.value();
66
+ }
67
+ return storage_size;
68
+ }
69
+
70
+ std::size_t size = 1;
71
+ for (std::int64_t s : sizes_) {
72
+ size *= static_cast<std::size_t>(s);
73
+ }
74
+ auto storage_size = size * itemsize;
75
+ if (storage_offset_) {
76
+ storage_size += storage_offset_.value();
77
+ }
78
+ return storage_size;
79
+ }
80
+
81
+ inline DataPtr TensorMaker::makeDataPtrFromDeleter() noexcept {
82
+ return InefficientStdFunctionContext::makeDataPtr(data_, std::move(deleter_), *device_);
83
+ }
84
+
85
+ inline DataPtr TensorMaker::makeDataPtrFromContext() noexcept {
86
+ return DataPtr{data_, ctx_.release(), ctx_.get_deleter(), *device_};
87
+ }
88
+
89
+ IntArrayRef TensorMaker::makeTempSizes() const noexcept {
90
+ static std::int64_t zeros[5] = {0, 0, 0, 0, 0};
91
+ if (opts_.has_memory_format()) {
92
+ MemoryFormat format = *opts_.memory_format_opt();
93
+ if (format == MemoryFormat::ChannelsLast) {
94
+ return IntArrayRef(zeros, 4);
95
+ }
96
+ if (format == MemoryFormat::ChannelsLast3d) {
97
+ return IntArrayRef(zeros, 5);
98
+ }
99
+ }
100
+ return IntArrayRef(zeros, 1);
101
+ }
102
+
103
+ } // namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyIr.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // This file contains autogenerated LazyTensor IR nodes
4
+ ${lazy_ir_sysinc}
5
+ ${lazy_ir_inc}
6
+
7
+ ${namespace_prologue}
8
+ using at::operator<<;
9
+
10
+ // kNullValue is used to contribute a static hash value any time
11
+ // a node has an Optional<Value> input that is nullopt. It is important
12
+ // to differentiate between HASH(std::nullopt, something) and HASH(something, std::nullopt),
13
+ // and using kNullValue in the hash function in the order of arguments
14
+ // serves this purpose.
15
+ static const torch::lazy::Value kNullValue = torch::lazy::Value();
16
+
17
+ ${ir_declarations}
18
+
19
+ ${namespace_epilogue}
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/LazyNonNativeIr.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ ${lazy_non_native_ir_inc}
4
+
5
+ // This file contains autogenerated LazyTensor Non Native IR nodes
6
+
7
+ ${namespace_prologue}
8
+
9
+ ${non_native_ir_nodes}
10
+
11
+ ${namespace_epilogue}
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/MethodOperators.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // ${generated_comment}
4
+
5
+ #ifdef TORCH_ASSERT_NO_OPERATORS
6
+ #error This change adds a dependency on native_functions.yaml, \
7
+ meaning the file will need to be re-compiled every time an operator \
8
+ is changed or added. Consider if your change would be better placed in \
9
+ another file, or if a more specific header might achieve the same goal. \
10
+ See NOTE: [Tensor vs. TensorBase]
11
+ #endif
12
+
13
+ // Forward declarations of any types needed in the operator signatures.
14
+ // We can't directly include these classes because it will cause circular include dependencies.
15
+ // This file is included by TensorBody.h, which defines the Tensor class.
16
+ #include <ATen/core/ATen_fwd.h>
17
+
18
+ ${MethodOperators_includes}
19
+
20
+ namespace at {
21
+ namespace _ops {
22
+ ${MethodOperators_declarations}
23
+ } // namespace _ops
24
+ } // namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeFunctions.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // ${generated_comment}
4
+
5
+ #ifdef TORCH_ASSERT_NO_OPERATORS
6
+ #error This change adds a dependency on native_functions.yaml, \
7
+ meaning the file will need to be re-compiled every time an operator \
8
+ is changed or added. Consider if your change would be better placed in \
9
+ another file, or if a more specific header might achieve the same goal. \
10
+ See NOTE: [Tensor vs. TensorBase]
11
+ #endif
12
+
13
+ #if defined(AT_PER_OPERATOR_HEADERS) && defined(TORCH_ASSERT_ONLY_METHOD_OPERATORS)
14
+ #error This change adds a dependency on all pytorch operators, meaning the \
15
+ file will need to be re-compiled every time an operator is changed or added. \
16
+ Consider including a specific operator from <ATen/ops/{my_operator}_native.h> \
17
+ and see NOTE [TORCH_ASSERT_ONLY_METHOD_OPERATORS].
18
+ #endif
19
+
20
+ #include <c10/core/Scalar.h>
21
+ #include <c10/core/Storage.h>
22
+ #include <c10/core/TensorOptions.h>
23
+ #include <c10/util/Deprecated.h>
24
+ #include <optional>
25
+ #include <c10/core/QScheme.h>
26
+ #include <ATen/core/Reduction.h>
27
+ #include <ATen/core/Tensor.h>
28
+ #include <tuple>
29
+ #include <vector>
30
+
31
+ ${NativeFunctions_includes}
32
+
33
+ ${NativeFunctions_declarations}
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/NativeMetaFunction.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // ${generated_comment}
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/TensorIterator.h>
13
+ #include <ATen/TensorMeta.h>
14
+ #include <tuple>
15
+ #include <vector>
16
+
17
+ namespace at {
18
+ namespace meta {
19
+
20
+ ${meta_function_declarations}
21
+
22
+ } // namespace native
23
+ } // namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterBackendSelect.cpp ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // We register ops with a higher priority dispatch key (BackendSelect) than the usual backend-specific keys (e.g. CPU)
2
+ // which makes calls to the factory functions dispatch to here.
3
+ // We then 'manually' compute a lower-priority to re-dispatch to (e.g. CPU) to get to the eventually correct backend.
4
+ // ${generated_comment}
5
+
6
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
7
+ #include <ATen/core/Tensor.h>
8
+ #include <ATen/core/dispatch/DispatchKeyExtractor.h>
9
+ #include <torch/library.h>
10
+
11
+ #ifndef AT_PER_OPERATOR_HEADERS
12
+ #include <ATen/Operators.h>
13
+ #else
14
+
15
+ ${ops_headers}
16
+ #endif
17
+
18
+ namespace at {
19
+
20
+ namespace {
21
+
22
+ ${backend_select_method_definitions}
23
+
24
+ TORCH_LIBRARY_IMPL(aten, BackendSelect, m) {
25
+ ${backend_select_function_registrations};
26
+ }
27
+
28
+ } // namespace
29
+ } // at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterFunctionalization.cpp ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
2
+ // ${generated_comment}
3
+
4
+ #include <ATen/core/LegacyTypeDispatch.h>
5
+ #include <ATen/EmptyTensor.h>
6
+ #include <ATen/FunctionalTensorWrapper.h>
7
+ #include <ATen/FunctionalInverses.h>
8
+ #include <ATen/MemoryOverlap.h>
9
+ #include <torch/library.h>
10
+
11
+ #ifndef AT_PER_OPERATOR_HEADERS
12
+ #include <ATen/Operators.h>
13
+ #include <ATen/NativeFunctions.h>
14
+ #else
15
+ // needed for the meta tensor calls to get stride info in functionalization
16
+ #include <ATen/ops/empty_strided_native.h>
17
+ // needed for special handling of copy_().
18
+ // See Note [functionalizating copy_() and not preserving strides]
19
+ #include <ATen/ops/to_ops.h>
20
+ #include <ATen/ops/expand_copy_ops.h>
21
+
22
+ $ops_headers
23
+ #endif
24
+
25
+ namespace at {
26
+ namespace functionalization {
27
+
28
+ // This keyset is used by functionalization when it calls into meta kernels
29
+ // to accurately propagate stride metadata.
30
+ // Exclude any modes: the purpose of calling into meta kernels is only as an implementation
31
+ // detail to perform shape inference, and we don't want any modal keys to run.
32
+ // Specifically, we want to prevent functionalization and Python modes from running.
33
+ constexpr auto exclude_keys_for_meta_dispatch =
34
+ c10::functorch_transforms_ks |
35
+ c10::DispatchKeySet({
36
+ c10::DispatchKey::FuncTorchDynamicLayerBackMode,
37
+ c10::DispatchKey::FuncTorchDynamicLayerFrontMode,
38
+ c10::DispatchKey::Python,
39
+ c10::DispatchKey::PreDispatch,
40
+
41
+ });
42
+
43
+ // Helper around at::has_internal_overlap.
44
+ // The ATen util is used in hot-path eager mode: it's always fast,
45
+ // but might return TOO_HARD sometimes.
46
+ // During functionalization, we're ok taking a bit longer
47
+ // to detect memory overlap.
48
+ inline bool has_internal_overlap_helper(const at::Tensor t) {
49
+ auto has_overlap = at::has_internal_overlap(t);
50
+ if (has_overlap == at::MemOverlap::Yes) return true;
51
+ if (has_overlap == at::MemOverlap::No) return false;
52
+ return false;
53
+ }
54
+
55
+
56
+ inline Tensor to_meta(const Tensor& t) {
57
+ if (!t.defined()) return t;
58
+ return at::native::empty_strided_meta_symint(t.sym_sizes(), t.sym_strides(),
59
+ /*dtype=*/std::make_optional(t.scalar_type()), /*layout=*/std::make_optional(t.layout()),
60
+ /*device=*/std::make_optional(c10::Device(kMeta)), /*pin_memory=*/std::nullopt);
61
+ }
62
+
63
+ inline std::optional<Tensor> to_meta(const std::optional<Tensor>& t) {
64
+ if (t.has_value()) {
65
+ return std::make_optional<Tensor>(to_meta(*t));
66
+ }
67
+ return std::nullopt;
68
+ }
69
+
70
+ inline std::vector<Tensor> to_meta(at::ITensorListRef t_list) {
71
+ std::vector<Tensor> outputs;
72
+ outputs.reserve(t_list.size());
73
+ for (const auto& tensor : t_list) {
74
+ outputs.push_back(to_meta(tensor));
75
+ }
76
+ return outputs;
77
+ }
78
+
79
+ inline c10::List<Tensor> to_meta(const c10::List<Tensor>& t_list) {
80
+ c10::List<Tensor> outputs;
81
+ outputs.reserve(t_list.size());
82
+ for (const auto i : c10::irange(t_list.size())) {
83
+ outputs.push_back(to_meta(t_list[i]));
84
+ }
85
+ return outputs;
86
+ }
87
+
88
+ inline c10::List<::std::optional<Tensor>> to_meta(const c10::List<::std::optional<Tensor>>& t_list) {
89
+ c10::List<::std::optional<Tensor>> outputs;
90
+ outputs.reserve(t_list.size());
91
+ for (const auto i : c10::irange(t_list.size())) {
92
+ outputs.push_back(to_meta(t_list[i]));
93
+ }
94
+ return outputs;
95
+ }
96
+
97
+
98
+ ${func_definitions}
99
+
100
+ } // namespace functionalization
101
+
102
+ namespace {
103
+
104
+ TORCH_LIBRARY_IMPL(aten, Functionalize, m) {
105
+ ${func_registrations};
106
+ }
107
+
108
+ } // namespace
109
+
110
+ } // namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegisterSchema.cpp ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ${generated_comment}
2
+ #define TORCH_ASSERT_ONLY_METHOD_OPERATORS
3
+ #include <torch/library.h>
4
+
5
+ namespace at {
6
+ TORCH_LIBRARY(aten, m) {
7
+ ${aten_schema_registrations};
8
+ // Distributed Ops
9
+ // Implementations located in torch/csrc/jit/runtime/register_distributed_ops.cpp
10
+ m.def("get_gradients(int context_id) -> Dict(Tensor, Tensor)");
11
+ }
12
+ ${schema_registrations}
13
+ } // namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/RegistrationDeclarations.h ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ // This file contains all native_functions that can be registered to
2
+ // and the schema string that they should be registered with
3
+
4
+ ${registration_declarations}
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/TensorMethods.cpp ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <c10/core/Scalar.h>
2
+ #include <ATen/core/TensorBody.h>
3
+
4
+ #include <c10/util/string_view.h>
5
+
6
+ namespace at {
7
+
8
+ namespace {
9
+
10
+ // Verifies the requested type is the same as the Tensor's type.
11
+ void check_type(const TensorBase& tensor, ScalarType type, c10::string_view type_name) {
12
+ TORCH_CHECK(
13
+ tensor.scalar_type() == type
14
+ || (isQIntType(tensor.scalar_type())
15
+ && toUnderlying(tensor.scalar_type()) == type),
16
+ "expected scalar type ", type_name, " but found ", tensor.scalar_type());
17
+ }
18
+
19
+ } // namespace
20
+
21
+ #define DEFINE_CAST(T, name) \
22
+ template <> \
23
+ TORCH_API const T* TensorBase::const_data_ptr() const { \
24
+ check_type(*this, ScalarType::name, #name); \
25
+ return this->unsafeGetTensorImpl()->data_ptr_impl<T>(); \
26
+ } \
27
+ \
28
+ template <> \
29
+ TORCH_API const T* TensorBase::const_data_ptr<const T>() const { \
30
+ check_type(*this, ScalarType::name, #name); \
31
+ return this->unsafeGetTensorImpl()->data_ptr_impl<std::remove_const_t<T>>(); \
32
+ } \
33
+ \
34
+ template <> \
35
+ TORCH_API T* TensorBase::mutable_data_ptr() const { \
36
+ check_type(*this, ScalarType::name, #name); \
37
+ return this->unsafeGetTensorImpl()->mutable_data_ptr_impl<T>(); \
38
+ } \
39
+ \
40
+ template <> \
41
+ TORCH_API T* TensorBase::data_ptr() const { \
42
+ return mutable_data_ptr<T>(); \
43
+ } \
44
+
45
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_CAST)
46
+ AT_FORALL_QINT_TYPES(DEFINE_CAST)
47
+ DEFINE_CAST(uint16_t, UInt16)
48
+ DEFINE_CAST(uint32_t, UInt32)
49
+ DEFINE_CAST(uint64_t, UInt64)
50
+ #undef DEFINE_CAST
51
+
52
+ #define DEFINE_ITEM(T, name) \
53
+ template <> \
54
+ TORCH_API T Tensor::item() const { \
55
+ return item().to##name(); \
56
+ }
57
+
58
+ AT_FORALL_SCALAR_TYPES_WITH_COMPLEX(DEFINE_ITEM)
59
+ #undef DEFINE_ITEM
60
+
61
+ } //namespace at
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCPUKernel.cpp ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define TORCH_ASSERT_NO_OPERATORS
2
+
3
+ #include <ATen/native/ufunc/${name}.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <ATen/TensorIterator.h>
6
+ #include <ATen/native/cpu/Loops.h>
7
+ #include <ATen/cpu/vec/vec.h>
8
+ #include <ATen/Dispatch.h>
9
+ #include <c10/core/Scalar.h>
10
+
11
+ namespace at {
12
+ namespace native {
13
+ ${native_definitions}
14
+ }} // namespace at::native
minigpt2/lib/python3.10/site-packages/torchgen/packaged/ATen/templates/UfuncCUDA.cu ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #define TORCH_ASSERT_NO_OPERATORS
2
+
3
+ #include <ATen/native/ufunc/${name}.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <c10/core/Scalar.h>
7
+ ${cuda_headers}
8
+
9
+ namespace at {
10
+
11
+ // NB: this is explicitly copied here (via codegen) rather than
12
+ // included via NativeFunctions.h to avoid recompiling this file when
13
+ // NativeFunctions.h changes
14
+ namespace meta {
15
+ ${meta_declaration}
16
+ }
17
+
18
+ namespace native {
19
+ ${native_declaration}
20
+ ${native_definitions}
21
+ }} // namespace at::native
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/BUILD.bazel ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ load("//:tools/bazel.bzl", "rules")
2
+ load(":build.bzl", "define_targets")
3
+
4
+ define_targets(rules = rules)
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (180 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/context.cpython-310.pyc ADDED
Binary file (1.41 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_annotated_fn_args.cpython-310.pyc ADDED
Binary file (4.35 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd.cpython-310.pyc ADDED
Binary file (3.34 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_autograd_functions.cpython-310.pyc ADDED
Binary file (21 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_inplace_or_view_type.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_python_functions.cpython-310.pyc ADDED
Binary file (28.7 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_trace_type.cpython-310.pyc ADDED
Binary file (12 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_factories.cpython-310.pyc ADDED
Binary file (3.98 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_variable_type.cpython-310.pyc ADDED
Binary file (46.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/gen_view_funcs.cpython-310.pyc ADDED
Binary file (9.99 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/__pycache__/load_derivatives.cpython-310.pyc ADDED
Binary file (24.9 kB). View file
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/build.bzl ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def define_targets(rules):
2
+ rules.py_library(
3
+ name = "autograd",
4
+ srcs = rules.glob(["*.py"]),
5
+ data = rules.glob([
6
+ "*.yaml",
7
+ "templates/*",
8
+ ]),
9
+ visibility = ["//:__subpackages__"],
10
+ deps = [
11
+ rules.requirement("PyYAML"),
12
+ "//torchgen",
13
+ ],
14
+ )
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/derivatives.yaml ADDED
The diff for this file is too large to render. See raw diff
 
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_annotated_fn_args.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ For procedural tests needed for __torch_function__, we use this function
3
+ to export method names and signatures as needed by the tests in
4
+ test/test_overrides.py.
5
+
6
+ python -m tools.autograd.gen_annotated_fn_args \
7
+ aten/src/ATen/native/native_functions.yaml \
8
+ aten/src/ATen/native/tags.yaml \
9
+ $OUTPUT_DIR \
10
+ tools/autograd
11
+
12
+ Where $OUTPUT_DIR is where you would like the files to be
13
+ generated. In the full build system, OUTPUT_DIR is
14
+ torch/testing/_internal/generated
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import os
21
+ import textwrap
22
+ from collections import defaultdict
23
+ from typing import Any, Sequence, TYPE_CHECKING
24
+
25
+ import torchgen.api.python as python
26
+ from torchgen.context import with_native_function
27
+ from torchgen.gen import parse_native_yaml
28
+ from torchgen.utils import FileManager
29
+
30
+ from .gen_python_functions import (
31
+ is_py_fft_function,
32
+ is_py_linalg_function,
33
+ is_py_nn_function,
34
+ is_py_special_function,
35
+ is_py_torch_function,
36
+ is_py_variable_method,
37
+ should_generate_py_binding,
38
+ )
39
+
40
+
41
+ if TYPE_CHECKING:
42
+ from torchgen.model import Argument, BaseOperatorName, NativeFunction
43
+
44
+
45
+ def gen_annotated(
46
+ native_yaml_path: str, tags_yaml_path: str, out: str, autograd_dir: str
47
+ ) -> None:
48
+ native_functions = parse_native_yaml(
49
+ native_yaml_path, tags_yaml_path
50
+ ).native_functions
51
+ mappings = (
52
+ (is_py_torch_function, "torch._C._VariableFunctions"),
53
+ (is_py_nn_function, "torch._C._nn"),
54
+ (is_py_linalg_function, "torch._C._linalg"),
55
+ (is_py_special_function, "torch._C._special"),
56
+ (is_py_fft_function, "torch._C._fft"),
57
+ (is_py_variable_method, "torch.Tensor"),
58
+ )
59
+ annotated_args: list[str] = []
60
+ for pred, namespace in mappings:
61
+ groups: dict[BaseOperatorName, list[NativeFunction]] = defaultdict(list)
62
+ for f in native_functions:
63
+ if not should_generate_py_binding(f) or not pred(f):
64
+ continue
65
+ groups[f.func.name.name].append(f)
66
+ for group in groups.values():
67
+ for f in group:
68
+ annotated_args.append(f"{namespace}.{gen_annotated_args(f)}")
69
+
70
+ template_path = os.path.join(autograd_dir, "templates")
71
+ fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
72
+ fm.write_with_template(
73
+ "annotated_fn_args.py",
74
+ "annotated_fn_args.py.in",
75
+ lambda: {
76
+ "annotated_args": textwrap.indent("\n".join(annotated_args), " "),
77
+ },
78
+ )
79
+
80
+
81
+ @with_native_function
82
+ def gen_annotated_args(f: NativeFunction) -> str:
83
+ def _get_kwargs_func_exclusion_list() -> list[str]:
84
+ # functions that currently don't work with kwargs in test_overrides.py
85
+ return [
86
+ "diagonal",
87
+ "round_",
88
+ "round",
89
+ "scatter_",
90
+ ]
91
+
92
+ def _add_out_arg(
93
+ out_args: list[dict[str, Any]], args: Sequence[Argument], *, is_kwarg_only: bool
94
+ ) -> None:
95
+ for arg in args:
96
+ if arg.default is not None:
97
+ continue
98
+ out_arg: dict[str, Any] = {}
99
+ out_arg["is_kwarg_only"] = str(is_kwarg_only)
100
+ out_arg["name"] = arg.name
101
+ out_arg["simple_type"] = python.argument_type_str(
102
+ arg.type, simple_type=True
103
+ )
104
+ size_t = python.argument_type_size(arg.type)
105
+ if size_t:
106
+ out_arg["size"] = size_t
107
+ out_args.append(out_arg)
108
+
109
+ out_args: list[dict[str, Any]] = []
110
+ _add_out_arg(out_args, f.func.arguments.flat_positional, is_kwarg_only=False)
111
+ if f"{f.func.name.name}" not in _get_kwargs_func_exclusion_list():
112
+ _add_out_arg(out_args, f.func.arguments.flat_kwarg_only, is_kwarg_only=True)
113
+
114
+ return f"{f.func.name.name}: {repr(out_args)},"
115
+
116
+
117
+ def main() -> None:
118
+ parser = argparse.ArgumentParser(description="Generate annotated_fn_args script")
119
+ parser.add_argument(
120
+ "native_functions", metavar="NATIVE", help="path to native_functions.yaml"
121
+ )
122
+ parser.add_argument("tags", metavar="TAGS", help="path to tags.yaml")
123
+ parser.add_argument("out", metavar="OUT", help="path to output directory")
124
+ parser.add_argument(
125
+ "autograd", metavar="AUTOGRAD", help="path to template directory"
126
+ )
127
+ args = parser.parse_args()
128
+ gen_annotated(args.native_functions, args.tags, args.out, args.autograd)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ main()
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_python_functions.py ADDED
@@ -0,0 +1,1402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generates Python bindings for ATen functions
2
+ #
3
+ # The bindings are generated as methods on python_variable or functions on the
4
+ # torch._C._nn. torch._C._fft, torch._C._linalg, torch._C._nested, torch._C._sparse
5
+ # or torch._C._special objects.
6
+ #
7
+
8
+ # Code tries to stick to the following rules:
9
+ #
10
+ # - templates should be colocated with the functions that use them.
11
+ # no templates are currently shared between functions, but if that
12
+ # happens, maybe put the template with the first one
13
+ #
14
+ # - don't use environment dictionaries when calling template.substitute().
15
+ # pass named arguments directly for everything, otherwise it's much too
16
+ # hard to track what's actually being used and by who
17
+ #
18
+ # - colocate any new hacks/adjustments with existing ones of the same kind.
19
+ # ideally in a data structure rather than code if possible. See e.g.
20
+ # SCHEMA_DEFAULT_CONVERSION_HACKS, etc.
21
+ #
22
+ # - similarly, conversions from one format to another should ideally happen
23
+ # all at once in a single place.
24
+ #
25
+ # - no nontrivial nested functions. couple-liners are ok but please no more.
26
+ # especially avoid functions that read/write outer variables defined far away.
27
+ #
28
+ # - raise RuntimeError instead of asserting, and put as much
29
+ # information as is available into the message. I.e. no need to
30
+ # plumb in new params whose only purpose is to fill out an error
31
+ # message, but use what's there
32
+ #
33
+
34
+ from __future__ import annotations
35
+
36
+ import itertools
37
+ import re
38
+ from collections import defaultdict
39
+ from typing import Callable, Iterable, Sequence
40
+
41
+ import yaml
42
+
43
+ from torchgen.api import cpp
44
+ from torchgen.api.python import (
45
+ arg_parser_output_exprs,
46
+ cpp_dispatch_exprs,
47
+ cpp_dispatch_target,
48
+ dispatch_lambda_args,
49
+ dispatch_lambda_exprs,
50
+ dispatch_lambda_return_str,
51
+ has_tensor_options,
52
+ PythonSignature,
53
+ PythonSignatureDeprecated,
54
+ PythonSignatureGroup,
55
+ PythonSignatureNativeFunctionPair,
56
+ signature,
57
+ signature_from_schema,
58
+ structseq_fieldnames,
59
+ )
60
+ from torchgen.code_template import CodeTemplate
61
+ from torchgen.context import with_native_function
62
+ from torchgen.gen import cpp_string, parse_native_yaml, parse_tags_yaml
63
+ from torchgen.model import (
64
+ Argument,
65
+ BaseOperatorName,
66
+ FunctionSchema,
67
+ NativeFunction,
68
+ SchemaKind,
69
+ Type,
70
+ Variant,
71
+ )
72
+ from torchgen.utils import FileManager, split_name_params
73
+ from torchgen.yaml_utils import YamlLoader
74
+
75
+ from .gen_inplace_or_view_type import is_tensor_list_type
76
+ from .gen_trace_type import should_trace
77
+
78
+
79
+ #
80
+ # declarations blocklist
81
+ # We skip codegen for these functions, for various reasons.
82
+ # Future PRs will categorize this list and eliminate or hoist
83
+ # them out of eager-only codegen.
84
+ # See https://github.com/pytorch/pytorch/issues/30788
85
+ #
86
+
87
+ # These functions require manual Python bindings or are not exposed to Python
88
+ _SKIP_PYTHON_BINDINGS = [
89
+ "alias",
90
+ "contiguous",
91
+ "is_cuda",
92
+ "is_sparse",
93
+ "is_sparse_csr",
94
+ "size",
95
+ "stride",
96
+ "sym_size",
97
+ "sym_stride",
98
+ "sym_storage_offset",
99
+ "sym_numel",
100
+ ".*_backward",
101
+ ".*_backward_(out|input|weight|bias)",
102
+ ".*_forward",
103
+ ".*_forward_out",
104
+ ".*_jvp",
105
+ "_unsafe_view",
106
+ "tensor",
107
+ "_?sparse_(coo|compressed|csr|csc|bsr|bsc)_tensor.*",
108
+ "_range.*",
109
+ "_sparse_add_out",
110
+ "_sparse_div.*",
111
+ "_sparse_mul.*",
112
+ "_sparse_sub.*",
113
+ "_sparse_dense_add_out",
114
+ "index",
115
+ "index_out",
116
+ "unique_dim_consecutive",
117
+ "_cumsum.*",
118
+ "_cumprod.*",
119
+ "_sum.*",
120
+ "_prod.*",
121
+ "_th_.*",
122
+ "_thnn_.*",
123
+ "range.*",
124
+ "_solve.*",
125
+ "_inverse.*",
126
+ "_cholesky.*",
127
+ "_triangular_solve.*",
128
+ "_qr.*",
129
+ "_svd.*",
130
+ "slice",
131
+ "item",
132
+ "_local_scalar_dense",
133
+ "to",
134
+ "_to_copy",
135
+ "_to_copy_out",
136
+ "_reshape_copy",
137
+ "_reshape_copy_out",
138
+ "copy_sparse_to_sparse_",
139
+ "copy_",
140
+ "_foreach_copy",
141
+ "numpy_T",
142
+ "matrix_H",
143
+ "mT",
144
+ "mH", # these need to be an attributes in Python, not functions
145
+ "nonzero(_(out|numpy))?",
146
+ "set_data",
147
+ ".*_overrideable", # overrideable functions for backend extension
148
+ "data",
149
+ "is_leaf",
150
+ "output_nr",
151
+ "_version",
152
+ "requires_grad_",
153
+ "retains_grad",
154
+ "set_",
155
+ "_fw_primal",
156
+ "fake_quantize_per_tensor_affine_cachemask",
157
+ "fake_quantize_per_channel_affine_cachemask",
158
+ "_new_zeros_with_same_feature_meta",
159
+ "_has_same_storage_numel", # used for forward AD internals
160
+ "_reshape_alias",
161
+ "replace_", # only used by the functionalization pass, doesn't need to be exposed to python
162
+ "copy", # only used by the functionalization pass
163
+ "fill.Tensor", # only used by the functionalization pass
164
+ "fill.Scalar", # only used by the functionalization pass
165
+ "lift.*",
166
+ "normal_functional", # only used by the functionalization pass
167
+ "nbytes",
168
+ "itemsize",
169
+ "_batch_norm_with_update",
170
+ "_batch_norm_with_update_out",
171
+ "_batch_norm_no_update",
172
+ ]
173
+
174
+ SKIP_PYTHON_BINDINGS = [
175
+ re.compile(rf"^{pattern}$") for pattern in _SKIP_PYTHON_BINDINGS
176
+ ]
177
+
178
+ # These function signatures are not exposed to Python. Note that this signature
179
+ # list does not support regex.
180
+ SKIP_PYTHON_BINDINGS_SIGNATURES = [
181
+ "add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor",
182
+ "add_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)",
183
+ "sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor",
184
+ "sub_.Scalar(Tensor(a!) self, Scalar other, Scalar alpha=1) -> Tensor(a!)",
185
+ "mul.Scalar(Tensor self, Scalar other) -> Tensor",
186
+ "mul_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)",
187
+ "div.Scalar(Tensor self, Scalar other) -> Tensor",
188
+ "div_.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)",
189
+ ]
190
+
191
+
192
+ @with_native_function
193
+ def should_generate_py_binding(f: NativeFunction) -> bool:
194
+ # NativeFunctions that are entirely code-generated should not get python bindings
195
+ # because these codegen implementations are often inefficient. A handful of
196
+ # view_copy style ops were exposed accidentally when they were handwritten and now
197
+ # that we are moving them to codegen for bc reasons we need to keep them exposed in
198
+ # python.
199
+ if "generated" in f.tags and "view_copy" not in f.tags:
200
+ return False
201
+
202
+ name = cpp.name(f.func)
203
+ for skip_regex in SKIP_PYTHON_BINDINGS:
204
+ if skip_regex.match(name):
205
+ return False
206
+
207
+ signature = str(f.func)
208
+ for pattern in SKIP_PYTHON_BINDINGS_SIGNATURES:
209
+ if pattern == signature:
210
+ return False
211
+ return True
212
+
213
+
214
+ def get_pycname(name: BaseOperatorName) -> str:
215
+ return f"THPVariable_{name}"
216
+
217
+
218
+ def is_noarg(overloads: Sequence[PythonSignatureNativeFunctionPair]) -> bool:
219
+ return len(overloads) == 1 and overloads[0].signature.arguments_count() == 0
220
+
221
+
222
+ def is_py_variable_method(f: NativeFunction) -> bool:
223
+ return f.python_module is None and Variant.method in f.variants
224
+
225
+
226
+ def is_py_torch_function(f: NativeFunction) -> bool:
227
+ return f.python_module is None and Variant.function in f.variants
228
+
229
+
230
+ def is_py_nn_function(f: NativeFunction) -> bool:
231
+ return f.python_module == "nn"
232
+
233
+
234
+ def is_py_fft_function(f: NativeFunction) -> bool:
235
+ return f.python_module == "fft"
236
+
237
+
238
+ def is_py_linalg_function(f: NativeFunction) -> bool:
239
+ return f.python_module == "linalg"
240
+
241
+
242
+ def is_py_nested_function(f: NativeFunction) -> bool:
243
+ return f.python_module == "nested"
244
+
245
+
246
+ def is_py_sparse_function(f: NativeFunction) -> bool:
247
+ return f.python_module == "sparse"
248
+
249
+
250
+ def is_py_special_function(f: NativeFunction) -> bool:
251
+ return f.python_module == "special"
252
+
253
+
254
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
255
+ #
256
+ # Main Function
257
+ #
258
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
259
+
260
+
261
+ def gen(
262
+ out: str,
263
+ native_yaml_path: str,
264
+ tags_yaml_path: str,
265
+ deprecated_yaml_path: str,
266
+ template_path: str,
267
+ *,
268
+ symint: bool = True,
269
+ ) -> None:
270
+ fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
271
+ native_functions = parse_native_yaml(
272
+ native_yaml_path, tags_yaml_path
273
+ ).native_functions
274
+ native_functions = list(filter(should_generate_py_binding, native_functions))
275
+
276
+ methods = load_signatures(native_functions, deprecated_yaml_path, method=True)
277
+ create_python_bindings(
278
+ fm,
279
+ methods,
280
+ is_py_variable_method,
281
+ None,
282
+ "python_variable_methods.cpp",
283
+ method=True,
284
+ symint=symint,
285
+ )
286
+
287
+ # NOTE: num_shards here must be synced with gatherTorchFunctions in
288
+ # torch/csrc/autograd/python_torch_functions_manual.cpp
289
+ functions = load_signatures(native_functions, deprecated_yaml_path, method=False)
290
+ create_python_bindings_sharded(
291
+ fm,
292
+ functions,
293
+ is_py_torch_function,
294
+ "torch",
295
+ "python_torch_functions.cpp",
296
+ method=False,
297
+ num_shards=3,
298
+ symint=symint,
299
+ )
300
+
301
+ create_python_bindings(
302
+ fm,
303
+ functions,
304
+ is_py_nn_function,
305
+ "torch.nn",
306
+ "python_nn_functions.cpp",
307
+ method=False,
308
+ symint=symint,
309
+ )
310
+
311
+ create_python_bindings(
312
+ fm,
313
+ functions,
314
+ is_py_fft_function,
315
+ "torch.fft",
316
+ "python_fft_functions.cpp",
317
+ method=False,
318
+ symint=symint,
319
+ )
320
+
321
+ create_python_bindings(
322
+ fm,
323
+ functions,
324
+ is_py_linalg_function,
325
+ "torch.linalg",
326
+ "python_linalg_functions.cpp",
327
+ method=False,
328
+ symint=symint,
329
+ )
330
+
331
+ create_python_bindings(
332
+ fm,
333
+ functions,
334
+ is_py_nested_function,
335
+ "torch.nested",
336
+ "python_nested_functions.cpp",
337
+ method=False,
338
+ )
339
+
340
+ create_python_bindings(
341
+ fm,
342
+ functions,
343
+ is_py_sparse_function,
344
+ "torch.sparse",
345
+ "python_sparse_functions.cpp",
346
+ method=False,
347
+ symint=symint,
348
+ )
349
+
350
+ create_python_bindings(
351
+ fm,
352
+ functions,
353
+ is_py_special_function,
354
+ "torch.special",
355
+ "python_special_functions.cpp",
356
+ method=False,
357
+ symint=symint,
358
+ )
359
+
360
+ # Currently, we only use `functions` to generate `return_types` bindings.
361
+ # All methods which return structseq have function variant at this point.
362
+ # If any method only operator with structseq is added in the future,
363
+ # we will have to address that.
364
+ create_python_return_type_bindings(
365
+ fm, functions, lambda fn: True, "python_return_types.cpp"
366
+ )
367
+ create_python_return_type_bindings_header(
368
+ fm, functions, lambda fn: True, "python_return_types.h"
369
+ )
370
+
371
+ valid_tags = parse_tags_yaml(tags_yaml_path)
372
+
373
+ def gen_tags_enum() -> dict[str, str]:
374
+ return {
375
+ "enum_of_valid_tags": (
376
+ "".join(
377
+ [f'\n.value("{tag}", at::Tag::{tag})' for tag in sorted(valid_tags)]
378
+ )
379
+ )
380
+ }
381
+
382
+ fm.write("python_enum_tag.cpp", gen_tags_enum)
383
+
384
+
385
+ def group_filter_overloads(
386
+ pairs: Sequence[PythonSignatureNativeFunctionPair],
387
+ pred: Callable[[NativeFunction], bool],
388
+ ) -> dict[BaseOperatorName, list[PythonSignatureNativeFunctionPair]]:
389
+ grouped: dict[
390
+ BaseOperatorName, list[PythonSignatureNativeFunctionPair]
391
+ ] = defaultdict(list)
392
+ for pair in pairs:
393
+ if pred(pair.function):
394
+ grouped[pair.function.func.name.name].append(pair)
395
+ return grouped
396
+
397
+
398
+ def create_python_bindings(
399
+ fm: FileManager,
400
+ pairs: Sequence[PythonSignatureNativeFunctionPair],
401
+ pred: Callable[[NativeFunction], bool],
402
+ module: str | None,
403
+ filename: str,
404
+ *,
405
+ method: bool,
406
+ symint: bool = True,
407
+ ) -> None:
408
+ """Generates Python bindings to ATen functions"""
409
+ py_methods: list[str] = []
410
+ ops_headers: list[str] = []
411
+ py_method_defs: list[str] = []
412
+ py_forwards: list[str] = []
413
+
414
+ grouped = group_filter_overloads(pairs, pred)
415
+
416
+ for name in sorted(grouped.keys(), key=str):
417
+ overloads = grouped[name]
418
+ py_methods.append(
419
+ method_impl(name, module, overloads, method=method, symint=symint)
420
+ )
421
+ py_method_defs.append(method_def(name, module, overloads, method=method))
422
+ py_forwards.extend(forward_decls(name, overloads, method=method))
423
+ ops_headers.append(f"#include <ATen/ops/{name.base}.h>")
424
+
425
+ fm.write_with_template(
426
+ filename,
427
+ filename,
428
+ lambda: {
429
+ "generated_comment": "@"
430
+ + f"generated from {fm.template_dir_for_comments()}/{filename}",
431
+ "ops_headers": ops_headers,
432
+ "py_forwards": py_forwards,
433
+ "py_methods": py_methods,
434
+ "py_method_defs": py_method_defs,
435
+ },
436
+ )
437
+
438
+
439
+ def create_python_return_type_bindings(
440
+ fm: FileManager,
441
+ pairs: Sequence[PythonSignatureNativeFunctionPair],
442
+ pred: Callable[[NativeFunction], bool],
443
+ filename: str,
444
+ ) -> None:
445
+ """
446
+ Generate function to initialize and return named tuple for native functions
447
+ which returns named tuple and registration invocations in `python_return_types.cpp`.
448
+ """
449
+ py_return_types_definition: list[str] = []
450
+ py_return_types_registrations: list[str] = []
451
+
452
+ grouped = group_filter_overloads(pairs, pred)
453
+
454
+ for name in sorted(grouped.keys(), key=str):
455
+ overloads = grouped[name]
456
+ definitions, registrations = generate_return_type_definition_and_registrations(
457
+ overloads
458
+ )
459
+ py_return_types_definition.append(
460
+ "" if not definitions else "\n".join(definitions)
461
+ )
462
+ py_return_types_registrations.append(
463
+ "" if not registrations else "\n".join(registrations)
464
+ )
465
+
466
+ fm.write_with_template(
467
+ filename,
468
+ filename,
469
+ lambda: {
470
+ "generated_comment": "@"
471
+ + f"generated from {fm.template_dir_for_comments()}/{filename}",
472
+ "py_return_types": py_return_types_definition,
473
+ "py_return_types_registrations": py_return_types_registrations,
474
+ },
475
+ )
476
+
477
+
478
+ def create_python_return_type_bindings_header(
479
+ fm: FileManager,
480
+ pairs: Sequence[PythonSignatureNativeFunctionPair],
481
+ pred: Callable[[NativeFunction], bool],
482
+ filename: str,
483
+ ) -> None:
484
+ """
485
+ Generate function to initialize and return named tuple for native functions
486
+ which returns named tuple and relevant entry for the map in `python_return_types.cpp`.
487
+ """
488
+ py_return_types_declarations: list[str] = []
489
+
490
+ grouped = group_filter_overloads(pairs, pred)
491
+
492
+ for name in sorted(grouped.keys(), key=str):
493
+ overloads = grouped[name]
494
+ declarations = generate_return_type_declarations(overloads)
495
+ py_return_types_declarations.append(
496
+ "" if not declarations else "\n".join(declarations)
497
+ )
498
+
499
+ fm.write_with_template(
500
+ filename,
501
+ filename,
502
+ lambda: {
503
+ "generated_comment": "@"
504
+ + f"generated from {fm.template_dir_for_comments()}/{filename}",
505
+ "py_return_types_declarations": py_return_types_declarations,
506
+ },
507
+ )
508
+
509
+
510
+ def create_python_bindings_sharded(
511
+ fm: FileManager,
512
+ pairs: Sequence[PythonSignatureNativeFunctionPair],
513
+ pred: Callable[[NativeFunction], bool],
514
+ module: str | None,
515
+ filename: str,
516
+ *,
517
+ method: bool,
518
+ num_shards: int,
519
+ symint: bool = True,
520
+ ) -> None:
521
+ """Generates Python bindings to ATen functions"""
522
+ grouped = group_filter_overloads(pairs, pred)
523
+
524
+ def key_func(
525
+ kv: tuple[BaseOperatorName, list[PythonSignatureNativeFunctionPair]]
526
+ ) -> str:
527
+ return kv[0].base
528
+
529
+ def env_func(
530
+ kv: tuple[BaseOperatorName, list[PythonSignatureNativeFunctionPair]]
531
+ ) -> dict[str, list[str]]:
532
+ name, fn_pairs = kv
533
+ return {
534
+ "ops_headers": [f"#include <ATen/ops/{name.base}.h>"],
535
+ "py_forwards": list(forward_decls(name, fn_pairs, method=method)),
536
+ "py_methods": [
537
+ method_impl(name, module, fn_pairs, method=method, symint=symint)
538
+ ],
539
+ "py_method_defs": [method_def(name, module, fn_pairs, method=method)],
540
+ }
541
+
542
+ fm.write_sharded(
543
+ filename,
544
+ grouped.items(),
545
+ base_env={
546
+ "generated_comment": "@"
547
+ + f"generated from {fm.template_dir_for_comments()}/{filename}",
548
+ },
549
+ key_fn=key_func,
550
+ env_callable=env_func,
551
+ num_shards=num_shards,
552
+ sharded_keys={"ops_headers", "py_forwards", "py_methods", "py_method_defs"},
553
+ )
554
+
555
+
556
+ def load_signatures(
557
+ native_functions: list[NativeFunction],
558
+ deprecated_yaml_path: str,
559
+ *,
560
+ method: bool,
561
+ skip_deprecated: bool = False,
562
+ pyi: bool = False,
563
+ ) -> Sequence[PythonSignatureNativeFunctionPair]:
564
+ @with_native_function
565
+ def gen_signature_pairs(f: NativeFunction) -> PythonSignatureNativeFunctionPair:
566
+ return PythonSignatureNativeFunctionPair(
567
+ signature=signature(f, method=method, pyi=pyi),
568
+ function=f,
569
+ )
570
+
571
+ pairs = list(map(gen_signature_pairs, native_functions))
572
+ deprecated = load_deprecated_signatures(
573
+ pairs, deprecated_yaml_path, method=method, pyi=pyi
574
+ )
575
+ return pairs if skip_deprecated else pairs + deprecated
576
+
577
+
578
+ def load_deprecated_signatures(
579
+ pairs: Sequence[PythonSignatureNativeFunctionPair],
580
+ deprecated_yaml_path: str,
581
+ *,
582
+ method: bool,
583
+ pyi: bool,
584
+ ) -> list[PythonSignatureNativeFunctionPair]:
585
+ # The deprecated.yaml doesn't have complete type information, we need
586
+ # find and leverage the original ATen signature (to which it delegates
587
+ # the call) to generate the full python signature.
588
+ # We join the deprecated and the original signatures using type-only form.
589
+
590
+ # group the original ATen signatures by name
591
+ grouped: dict[str, list[PythonSignatureNativeFunctionPair]] = defaultdict(list)
592
+ for pair in pairs:
593
+ grouped[pair.signature.name].append(pair)
594
+
595
+ # find matching original signatures for each deprecated signature
596
+ results: list[PythonSignatureNativeFunctionPair] = []
597
+
598
+ with open(deprecated_yaml_path) as f:
599
+ deprecated_defs = yaml.load(f, Loader=YamlLoader)
600
+
601
+ for deprecated in deprecated_defs:
602
+ schema = FunctionSchema.parse(deprecated["name"])
603
+ aten_name, call_args = split_name_params(deprecated["aten"])
604
+ is_out = aten_name.endswith("_out")
605
+ if is_out:
606
+ aten_name = aten_name.replace("_out", "")
607
+
608
+ # HACK: these are fixed constants used to pass the aten function.
609
+ # The type must be known ahead of time
610
+ known_constants = {
611
+ "1": Type.parse("Scalar"),
612
+ }
613
+ schema_args_by_name = {a.name: a for a in schema.arguments.flat_all}
614
+ for name in call_args:
615
+ assert (
616
+ name in schema_args_by_name or name in known_constants
617
+ ), f"deprecation definiton: Unrecognized value {name}"
618
+
619
+ # Map deprecated signature arguments to their aten signature and test
620
+ # if the types and alias annotation match.
621
+ def is_schema_compatible(
622
+ aten_schema: FunctionSchema,
623
+ ) -> bool:
624
+ arguments: Iterable[Argument]
625
+ if is_out:
626
+ arguments = itertools.chain(
627
+ aten_schema.arguments.out, aten_schema.arguments.flat_non_out
628
+ )
629
+ else:
630
+ arguments = aten_schema.arguments.flat_all
631
+
632
+ for i, arg in enumerate(arguments):
633
+ if i < len(call_args):
634
+ arg_name = call_args[i]
635
+ if arg_name in known_constants:
636
+ schema_type = known_constants[arg_name]
637
+ schema_annotation = None
638
+ else:
639
+ schema_arg = schema_args_by_name[arg_name]
640
+ schema_type = schema_arg.type
641
+ schema_annotation = schema_arg.annotation
642
+
643
+ if schema_type != arg.type or schema_annotation != arg.annotation:
644
+ return False
645
+ else:
646
+ if arg.default is None:
647
+ return False
648
+
649
+ return len(schema.returns) == len(aten_schema.returns) and all(
650
+ a == b for a, b in zip(schema.returns, aten_schema.returns)
651
+ )
652
+
653
+ any_schema_found = False
654
+ for pair in grouped[aten_name]:
655
+ if not is_schema_compatible(pair.function.func):
656
+ continue
657
+ any_schema_found = True
658
+
659
+ python_sig = signature_from_schema(
660
+ schema,
661
+ category_override=pair.function.category_override,
662
+ method=method,
663
+ pyi=pyi,
664
+ )
665
+
666
+ results.append(
667
+ PythonSignatureNativeFunctionPair(
668
+ signature=PythonSignatureDeprecated(
669
+ name=python_sig.name,
670
+ input_args=python_sig.input_args,
671
+ input_kwargs=python_sig.input_kwargs,
672
+ output_args=python_sig.output_args,
673
+ tensor_options_args=python_sig.tensor_options_args,
674
+ method=python_sig.method,
675
+ deprecated_schema=schema,
676
+ deprecated_args_exprs=tuple(call_args),
677
+ returns=python_sig.returns,
678
+ ),
679
+ function=pair.function,
680
+ )
681
+ )
682
+ assert (
683
+ any_schema_found
684
+ ), f"No native function with name {aten_name} matched signature:\n {str(schema)}"
685
+
686
+ return results
687
+
688
+
689
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
690
+ #
691
+ # Named Tuple Codegen
692
+ #
693
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
694
+
695
+
696
+ @with_native_function
697
+ def gen_structseq_typename_key(f: NativeFunction) -> str:
698
+ name = cpp.name(f.func)
699
+ fieldnames = structseq_fieldnames(f.func.returns)
700
+ return "_".join([name] + fieldnames)
701
+
702
+
703
+ def emit_structseq_call(
704
+ overloads: Sequence[PythonSignatureNativeFunctionPair],
705
+ ) -> tuple[list[str], dict[str, str]]:
706
+ """
707
+ Generate block of named tuple type def inits, and add typeref snippets
708
+ to declarations that use them
709
+ """
710
+ typenames: dict[
711
+ str, str
712
+ ] = {} # map from unique name + field name lists to typedef name
713
+ typedefs: list[str] = [] # typedef declarations and init code
714
+
715
+ for overload in overloads:
716
+ fieldnames = structseq_fieldnames(overload.function.func.returns)
717
+ if not fieldnames:
718
+ continue
719
+
720
+ name = cpp.name(overload.function.func) # use @with_native_function?
721
+ tn_key = gen_structseq_typename_key(overload.function)
722
+ typename = typenames.get(tn_key)
723
+ if typename is None:
724
+ typename = f'NamedTuple{"" if not typedefs else len(typedefs)}'
725
+ typenames[tn_key] = typename
726
+ typedefs.append(
727
+ f"""\
728
+ static PyTypeObject* {typename} = generated::get_{name}_structseq();"""
729
+ )
730
+
731
+ return typedefs, typenames
732
+
733
+
734
+ def generate_return_type_definition_and_registrations(
735
+ overloads: Sequence[PythonSignatureNativeFunctionPair],
736
+ ) -> tuple[list[str], list[str]]:
737
+ """
738
+ Generate block of function in `python_return_types.cpp` to initialize
739
+ and return named tuple for a native function which returns named tuple
740
+ and registration invocations in same file.
741
+ """
742
+ typenames: dict[
743
+ str, str
744
+ ] = {} # map from unique name + field name lists to typedef name
745
+ definitions: list[str] = [] # function definition to register the typedef
746
+ registrations: list[str] = [] # register call for the typedef
747
+
748
+ for overload in overloads:
749
+ fieldnames = structseq_fieldnames(overload.function.func.returns)
750
+ if not fieldnames:
751
+ continue
752
+
753
+ fields = ", ".join(f'{{"{fn}", ""}}' for fn in fieldnames)
754
+
755
+ name = cpp.name(overload.function.func) # use @with_native_function?
756
+ tn_key = gen_structseq_typename_key(overload.function)
757
+ typename = typenames.get(tn_key)
758
+
759
+ if typename is None:
760
+ typename = f'{name}NamedTuple{"" if not definitions else len(definitions)}'
761
+ typenames[tn_key] = typename
762
+ definitions.append(
763
+ f"""\
764
+ PyTypeObject* get_{name}_structseq() {{
765
+ static PyStructSequence_Field NamedTuple_fields[] = {{ {fields}, {{nullptr}} }};
766
+ static PyTypeObject {typename};
767
+ static bool is_initialized = false;
768
+ static PyStructSequence_Desc desc = {{ "torch.return_types.{name}", nullptr, NamedTuple_fields, {len(fieldnames)} }};
769
+ if (!is_initialized) {{
770
+ PyStructSequence_InitType(&{typename}, &desc);
771
+ {typename}.tp_repr = (reprfunc)torch::utils::returned_structseq_repr;
772
+ is_initialized = true;
773
+ }}
774
+ return &{typename};
775
+ }}
776
+ """
777
+ )
778
+ registrations.append(
779
+ f'addReturnType(return_types_module, "{name}", generated::get_{name}_structseq());'
780
+ )
781
+
782
+ return definitions, registrations
783
+
784
+
785
+ def generate_return_type_declarations(
786
+ overloads: Sequence[PythonSignatureNativeFunctionPair],
787
+ ) -> list[str]:
788
+ """
789
+ Generate block of function declarations in `python_return_types.h` to initialize
790
+ and return named tuple for a native function.
791
+ """
792
+ typenames: dict[
793
+ str, str
794
+ ] = {} # map from unique name + field name lists to typedef name
795
+ declarations: list[str] = [] # function declaration to register the typedef
796
+
797
+ for overload in overloads:
798
+ fieldnames = structseq_fieldnames(overload.function.func.returns)
799
+ if not fieldnames:
800
+ continue
801
+
802
+ name = cpp.name(overload.function.func) # use @with_native_function?
803
+ tn_key = gen_structseq_typename_key(overload.function)
804
+ typename = typenames.get(tn_key)
805
+
806
+ if typename is None:
807
+ typename = (
808
+ f'{name}NamedTuple{"" if not declarations else len(declarations)}'
809
+ )
810
+ typenames[tn_key] = typename
811
+ declarations.append(f"PyTypeObject* get_{name}_structseq();")
812
+
813
+ return declarations
814
+
815
+
816
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
817
+ #
818
+ # Method Impl Codegen
819
+ #
820
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
821
+
822
+ # python binding for all overloads of a particular function/method
823
+ PY_VARIABLE_METHOD_VARARGS = CodeTemplate(
824
+ r"""\
825
+ // ${name}
826
+ static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
827
+ {
828
+ ${method_header}
829
+ static PythonArgParser parser({
830
+ ${signatures}
831
+ }, /*traceable=*/${traceable});
832
+
833
+ ParsedArgs<${max_args}> parsed_args;
834
+ auto _r = parser.parse(${self_}, args, kwargs, parsed_args);
835
+ ${check_has_torch_function}
836
+ switch (_r.idx) {
837
+ ${dispatch}
838
+ }
839
+ ${method_footer}
840
+ }
841
+
842
+ """
843
+ )
844
+
845
+ # handler for a single parsed signature - may be a single overload or
846
+ # a pair of overloads that whose signatures only differ in output params
847
+ # (plugged into PY_VARIABLE_METHOD_VARARGS as an item in ${dispatch})
848
+ PY_VARIABLE_CASE = CodeTemplate(
849
+ """\
850
+ case ${overload_index}: {
851
+ ${body}
852
+ }
853
+ """
854
+ )
855
+
856
+ # python binding for single-overload function/method
857
+ PY_VARIABLE_METHOD_VARARGS_SINGLETON = CodeTemplate(
858
+ """\
859
+ // ${name}
860
+ static PyObject * ${pycname}(PyObject* self_, PyObject* args, PyObject* kwargs)
861
+ {
862
+ ${method_header}
863
+ static PythonArgParser parser({
864
+ ${signatures}
865
+ }, /*traceable=*/${traceable});
866
+
867
+ ParsedArgs<${max_args}> parsed_args;
868
+ auto _r = parser.parse(${self_}, args, kwargs, parsed_args);
869
+ ${check_has_torch_function}
870
+ ${dispatch}
871
+ ${method_footer}
872
+ }
873
+
874
+ """
875
+ )
876
+
877
+ # python binding for a method with no args, shortcuts parsing
878
+ PY_VARIABLE_METHOD_NOARGS = CodeTemplate(
879
+ """\
880
+ // ${name}
881
+ static PyObject * ${pycname}(PyObject* self_, PyObject* args)
882
+ {
883
+ ${method_header}
884
+ ${check_has_torch_function}
885
+ ${dispatch}
886
+ ${method_footer}
887
+ }
888
+
889
+ """
890
+ )
891
+
892
+
893
+ def method_impl(
894
+ name: BaseOperatorName,
895
+ module: str | None,
896
+ overloads: Sequence[PythonSignatureNativeFunctionPair],
897
+ *,
898
+ method: bool,
899
+ symint: bool = True,
900
+ ) -> str:
901
+ """
902
+ Generate a python binding for all overloads of an op.
903
+ """
904
+ pycname = get_pycname(name)
905
+ noarg = is_noarg(overloads)
906
+ structseq_inits, structseq_typenames = emit_structseq_call(overloads)
907
+
908
+ method_header = ["HANDLE_TH_ERRORS"]
909
+ method_header += structseq_inits
910
+ method_header += (
911
+ ["const Tensor& self = THPVariable_Unpack(self_);"] if method else []
912
+ )
913
+
914
+ method_footer = ([] if noarg else ["Py_RETURN_NONE;"]) + ["END_HANDLE_TH_ERRORS"]
915
+
916
+ traceable = "true" if all(should_trace(o.function) for o in overloads) else "false"
917
+
918
+ grouped_overloads: Sequence[PythonSignatureGroup] = group_overloads(
919
+ overloads, symint=symint
920
+ )
921
+ is_singleton = len(grouped_overloads) == 1
922
+ signatures: list[str] = []
923
+ dispatch: list[str] = []
924
+ for overload_index, overload in enumerate(grouped_overloads):
925
+ signature = overload.signature.signature_str(symint=symint)
926
+ signatures.append(f"{cpp_string(str(signature))},")
927
+ dispatch_body = emit_dispatch_case(overload, structseq_typenames, symint=symint)
928
+ dispatch.append(
929
+ PY_VARIABLE_CASE.substitute(
930
+ overload_index=overload_index, body=dispatch_body
931
+ )
932
+ if not is_singleton
933
+ else dispatch_body
934
+ )
935
+
936
+ if noarg:
937
+ template = PY_VARIABLE_METHOD_NOARGS
938
+ elif is_singleton:
939
+ template = PY_VARIABLE_METHOD_VARARGS_SINGLETON
940
+ else:
941
+ template = PY_VARIABLE_METHOD_VARARGS
942
+
943
+ return template.substitute(
944
+ name=name,
945
+ pycname=pycname,
946
+ method_header=method_header,
947
+ max_args=max(o.signature.arguments_count() for o in overloads),
948
+ signatures=signatures,
949
+ traceable=traceable,
950
+ check_has_torch_function=gen_has_torch_function_check(
951
+ name=name,
952
+ module=module,
953
+ noarg=noarg,
954
+ method=method,
955
+ ),
956
+ dispatch=dispatch,
957
+ method_footer=method_footer,
958
+ self_="self_" if method else "nullptr",
959
+ )
960
+
961
+
962
+ def gen_has_torch_function_check(
963
+ name: BaseOperatorName, module: str | None, *, noarg: bool, method: bool
964
+ ) -> str:
965
+ if noarg:
966
+ if method:
967
+ return f"""\
968
+ if(check_has_torch_function(self_)) {{
969
+ return handle_torch_function(self_, "{name}");
970
+ }}
971
+ """
972
+ else:
973
+ return ""
974
+
975
+ self_ = "self_" if method else "nullptr"
976
+ namespace = (
977
+ {
978
+ "torch": "THPVariableFunctionsModule",
979
+ "torch.nn": "THPNNVariableFunctionsModule",
980
+ "torch.fft": "THPFFTVariableFunctionsModule",
981
+ "torch.linalg": "THPLinalgVariableFunctionsModule",
982
+ "torch.nested": "THPNestedVariableFunctionsModule",
983
+ "torch.sparse": "THPSparseVariableFunctionsModule",
984
+ "torch.special": "THPSpecialVariableFunctionsModule",
985
+ }[module]
986
+ if module
987
+ else "THPVariableClass"
988
+ )
989
+
990
+ return f"""\
991
+ if(_r.has_torch_function()) {{
992
+ return handle_torch_function(_r, {self_}, args, kwargs, {namespace}, "{module or "torch.Tensor"}");
993
+ }}
994
+ """
995
+
996
+
997
+ # handler for output/no-output overload pair
998
+ PY_VARIABLE_OUT = CodeTemplate(
999
+ """\
1000
+ if (_r.isNone(${out_idx})) {
1001
+ ${call_dispatch}
1002
+ } else {
1003
+ ${call_dispatch_out}
1004
+ }
1005
+ """
1006
+ )
1007
+
1008
+
1009
+ def emit_dispatch_case(
1010
+ overload: PythonSignatureGroup,
1011
+ structseq_typenames: dict[str, str],
1012
+ *,
1013
+ symint: bool = True,
1014
+ ) -> str:
1015
+ """
1016
+ Emit dispatch code for a single parsed signature. This corresponds to either
1017
+ a single native function, or a pair that differ only in output params. In the
1018
+ latter case, a single python signature is used for both and dispatching
1019
+ switches on the presence/absence of passed output args.
1020
+ """
1021
+ if overload.outplace is not None:
1022
+ # dispatch output and no-output variants, branch on _r.isNone(<out_idx>)
1023
+ return PY_VARIABLE_OUT.substitute(
1024
+ out_idx=overload.signature.output_idx(),
1025
+ call_dispatch=emit_single_dispatch(
1026
+ overload.signature, overload.base, structseq_typenames, symint=symint
1027
+ ),
1028
+ call_dispatch_out=emit_single_dispatch(
1029
+ overload.signature,
1030
+ overload.outplace,
1031
+ structseq_typenames,
1032
+ symint=symint,
1033
+ ),
1034
+ )
1035
+ else:
1036
+ # no-output version only
1037
+ return emit_single_dispatch(
1038
+ overload.signature, overload.base, structseq_typenames, symint=symint
1039
+ )
1040
+
1041
+
1042
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1043
+ #
1044
+ # Forward Declarations Codegen
1045
+ #
1046
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1047
+
1048
+
1049
+ def forward_decls(
1050
+ name: BaseOperatorName,
1051
+ overloads: Sequence[PythonSignatureNativeFunctionPair],
1052
+ *,
1053
+ method: bool,
1054
+ ) -> tuple[str, ...]:
1055
+ if method:
1056
+ return ()
1057
+
1058
+ pycname = get_pycname(name)
1059
+ if is_noarg(overloads):
1060
+ return (
1061
+ f"""\
1062
+ static PyObject * {pycname}(PyObject* self_, PyObject* args);
1063
+ """,
1064
+ )
1065
+ else:
1066
+ return (
1067
+ f"""\
1068
+ static PyObject * {pycname}(PyObject* self_, PyObject* args, PyObject* kwargs);
1069
+ """,
1070
+ )
1071
+
1072
+
1073
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1074
+ #
1075
+ # Method Def (Binding Table Entry) Codegen
1076
+ #
1077
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1078
+
1079
+
1080
+ def method_def(
1081
+ name: BaseOperatorName,
1082
+ module: str | None,
1083
+ overloads: Sequence[PythonSignatureNativeFunctionPair],
1084
+ *,
1085
+ method: bool,
1086
+ ) -> str:
1087
+ """
1088
+ Generate method def entry.
1089
+ """
1090
+ pycname = get_pycname(name)
1091
+
1092
+ if name.dunder_method:
1093
+ # PyMethodDef entry for binary op, throws not implemented error
1094
+ pycname = f"TypeError_to_NotImplemented_<{pycname}>"
1095
+
1096
+ if is_noarg(overloads):
1097
+ flags = "METH_NOARGS" if method else "METH_VARARGS | METH_KEYWORDS"
1098
+ else:
1099
+ pycname = f"castPyCFunctionWithKeywords({pycname})"
1100
+ flags = "METH_VARARGS | METH_KEYWORDS"
1101
+
1102
+ if module == "torch":
1103
+ flags += " | METH_STATIC"
1104
+
1105
+ return f'{{"{name}", {pycname}, {flags}, NULL}},'
1106
+
1107
+
1108
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1109
+ #
1110
+ # Overload Sorting and Grouping
1111
+ #
1112
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1113
+
1114
+
1115
+ def group_overloads(
1116
+ overloads: Sequence[PythonSignatureNativeFunctionPair], *, symint: bool = True
1117
+ ) -> Sequence[PythonSignatureGroup]:
1118
+ bases: dict[str, PythonSignatureNativeFunctionPair] = {}
1119
+ outplaces: dict[str, PythonSignatureNativeFunctionPair] = {}
1120
+
1121
+ # first group by signature ignoring out arguments
1122
+ for overload in overloads:
1123
+ sig = overload.signature.signature_str(skip_outputs=True, symint=symint)
1124
+ if overload.function.func.is_out_fn():
1125
+ if sig in outplaces:
1126
+ raise RuntimeError(
1127
+ f"Found duplicated function definition:\n- {overload.function.func}.\n"
1128
+ f"Existing definition:\n- {outplaces[sig].function.func}."
1129
+ )
1130
+ outplaces[sig] = overload
1131
+ else:
1132
+ if sig in bases:
1133
+ raise RuntimeError(
1134
+ f"Found duplicated function definition:\n- {overload.function.func}.\n"
1135
+ f"Existing definition:\n- {bases[sig].function.func}."
1136
+ )
1137
+ bases[sig] = overload
1138
+
1139
+ for sig, out in outplaces.items():
1140
+ if sig not in bases:
1141
+ candidates: list[str] = []
1142
+ for overload in overloads:
1143
+ if (
1144
+ str(overload.function.func.name.name)
1145
+ == str(out.function.func.name.name)
1146
+ and not overload.function.func.is_out_fn()
1147
+ and not overload.signature.deprecated
1148
+ ):
1149
+ candidates.append(
1150
+ overload.signature.signature_str(
1151
+ skip_outputs=True, symint=symint
1152
+ )
1153
+ )
1154
+ out_sig = out.signature.signature_str(symint=symint)
1155
+ raise RuntimeError(
1156
+ f"While identifying overloads, we found an out schema {out_sig} without a corresponding non-out variant. "
1157
+ f"We expected the non-out variant to have schema: \n- {sig}\nPlease check that you spelled the schema "
1158
+ "correctly in native_functions.yaml. We discovered the following candidate(s): \n"
1159
+ + "\n".join(f"- {candidate}" for candidate in candidates)
1160
+ )
1161
+
1162
+ grouped = [
1163
+ PythonSignatureGroup.from_pairs(
1164
+ functional=base,
1165
+ out=outplaces.get(sig),
1166
+ )
1167
+ for sig, base in bases.items()
1168
+ ]
1169
+ return sort_overloads(grouped, symint=symint)
1170
+
1171
+
1172
+ # This function declares a partial order on declarations, and sorts them according
1173
+ # to its linear extension. This is necessary, because there's some ambiguity in the
1174
+ # choice of overload, and we want a different order.
1175
+ #
1176
+ # See Note[Order of overloads matters]
1177
+ #
1178
+ # A few examples of ambiguous python signature pairs.
1179
+ #
1180
+ # All parameters have the same type, except one taking Tensor the other taking
1181
+ # Scalar. A numeric PyObject can be casted into Tensor, and a zero-dim Tensor
1182
+ # object can be accepted as Scalar type parameter (see python_arg_parser.cpp).
1183
+ # Therefore, same input arguments might be accepted by either python signature.
1184
+ # We want to always parse the one taking Tensor first.
1185
+ #
1186
+ # bitwise_and(Tensor input, Tensor other, *, Tensor out=None)
1187
+ # bitwise_and(Tensor input, Scalar other, *, Tensor out=None)
1188
+ #
1189
+ # If they have different number of parameters then they are not ambiguous - but
1190
+ # the difference on output param can be ignored as it's optional.
1191
+ #
1192
+ # multiply(Tensor input, Tensor other, *, Tensor out=None)
1193
+ # multiply(Tensor input, Scalar other)
1194
+ #
1195
+ # Both positional args and keyword-only args are considered together.
1196
+ #
1197
+ # subtract(Tensor other, *, Scalar alpha=1)
1198
+ # subtract(Scalar other, Scalar alpha=1)
1199
+ #
1200
+ # A few ambiguous cases which it does NOT handle yet.
1201
+ #
1202
+ # If there is any difference in other parameters besides the Tensor/Scalar
1203
+ # difference, then they are not considered ambiguous by this method anymore.
1204
+ # However, the difference could be too trivial to disambiguate.
1205
+ #
1206
+ # foo(Tensor input, Scalar other, Scalar bar)
1207
+ # foo(Tensor input, Tensor other, double bar)
1208
+ #
1209
+ # If they are taking different number of parameters then they are not considered
1210
+ # ambiguous anymore, even if the difference is only on optional kwargs.
1211
+ #
1212
+ # foo(Scalar other, Scalar alpha=1)
1213
+ # foo(Tensor other, *, Scalar alpha=1, Scalar beta=1)
1214
+ #
1215
+
1216
+
1217
+ def sort_overloads(
1218
+ grouped_overloads: Sequence[PythonSignatureGroup], *, symint: bool = True
1219
+ ) -> Sequence[PythonSignatureGroup]:
1220
+ # NB: Smaller here means lower priority
1221
+
1222
+ def is_arg_smaller(t1: Type, t2: Type) -> bool:
1223
+ return (
1224
+ str(t1) == "Scalar"
1225
+ and str(t2) == "Tensor"
1226
+ or str(t1) == "Scalar?"
1227
+ and str(t2) == "Tensor?"
1228
+ or "Dimname" in str(t1)
1229
+ and "Dimname" not in str(t2)
1230
+ or
1231
+ # In the discussion https://github.com/pytorch/pytorch/issues/54555 it has been
1232
+ # discussed why it is important to prioritize int/int? over int[]
1233
+ str(t1) == "int[]"
1234
+ and (str(t2) == "int" or str(t2) == "int?")
1235
+ or
1236
+ # TensorList currently throws an error during argument parsing, that's why it needs to be
1237
+ # last in signature ordering. See discussion: https://github.com/pytorch/pytorch/issues/58087
1238
+ str(t1) == "Tensor[]"
1239
+ and str(t2).find("[]") != -1
1240
+ or
1241
+ # Prioritize IntArrayRef overload over SymIntArrayRef
1242
+ str(t1) == "SymInt[]"
1243
+ and str(t2) == "int[]"
1244
+ or
1245
+ # Make sure both in, SymInt are sorted consistently w.r.t. Tensor since Tensor can be implicitly
1246
+ # converted to either int or SymInt. Prioritize the Tensor overload since it otherwise gets shadowed.
1247
+ (str(t1) == "SymInt" or str(t1) == "int")
1248
+ and str(t2) == "Tensor"
1249
+ )
1250
+
1251
+ def is_smaller(s1: PythonSignature, s2: PythonSignature) -> bool:
1252
+ """Returns True if s1 < s2 in the partial order."""
1253
+ args1, args2 = s1.arguments(skip_outputs=True), s2.arguments(skip_outputs=True)
1254
+ if len(args1) != len(args2):
1255
+ return False
1256
+ # TODO: should use some canonical form instead of 'str(arg.type)' - see comments
1257
+ # above. The old codegen used the deprecated 'dynamic_type(arg.type)', which
1258
+ # ignores the optional annotation, i.e. 'Scalar' and 'Scalar?'.
1259
+ equal = all(arg1.type == arg2.type for arg1, arg2 in zip(args1, args2))
1260
+ smaller_or_equal = all(
1261
+ str(arg1.type) == str(arg2.type) or is_arg_smaller(arg1.type, arg2.type)
1262
+ for arg1, arg2 in zip(args1, args2)
1263
+ )
1264
+ return smaller_or_equal and not equal
1265
+
1266
+ # First sort by signature
1267
+ grouped_overloads = sorted(
1268
+ grouped_overloads, key=lambda x: x.signature.signature_str(symint=symint)
1269
+ )
1270
+
1271
+ # Construct the relation graph
1272
+ larger_than: dict[int, set[int]] = defaultdict(set)
1273
+ for i1, overload1 in enumerate(grouped_overloads):
1274
+ for i2, overload2 in enumerate(grouped_overloads):
1275
+ if is_smaller(overload1.signature, overload2.signature):
1276
+ larger_than[i1].add(i2)
1277
+
1278
+ if not larger_than:
1279
+ return list(grouped_overloads)
1280
+
1281
+ # Use a topological sort to sort overloads according to the partial order.
1282
+ N = len(grouped_overloads)
1283
+ sorted_ids: list[int] = list(filter(lambda x: x not in larger_than, range(N)))
1284
+
1285
+ for idx in range(N):
1286
+ # The size of sorted_ids will grow to N eventually.
1287
+ i = sorted_ids[idx]
1288
+ for j in sorted(larger_than.keys()):
1289
+ larger = larger_than[j]
1290
+ larger.discard(i)
1291
+ if not larger:
1292
+ del larger_than[j]
1293
+ sorted_ids.append(j)
1294
+
1295
+ return [grouped_overloads[x] for x in sorted_ids]
1296
+
1297
+
1298
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1299
+ #
1300
+ # Codegen API Integration
1301
+ #
1302
+ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
1303
+
1304
+
1305
+ def emit_single_dispatch(
1306
+ ps: PythonSignature,
1307
+ f: NativeFunction,
1308
+ structseq_typenames: dict[str, str],
1309
+ *,
1310
+ symint: bool = True,
1311
+ ) -> str:
1312
+ """
1313
+ Emit dispatch code for a single native function.
1314
+ """
1315
+
1316
+ @with_native_function
1317
+ def go(f: NativeFunction) -> str:
1318
+ # header comments
1319
+ if isinstance(ps, PythonSignatureDeprecated):
1320
+ schema_comment = f"// [deprecated] aten::{ps.deprecated_schema}"
1321
+ else:
1322
+ schema_comment = f"// aten::{f.func}"
1323
+
1324
+ deprecated = "[deprecated] " if ps.deprecated else ""
1325
+
1326
+ # dispatch lambda signature
1327
+ name = cpp.name(f.func)
1328
+ lambda_formals = ", ".join(
1329
+ f"{a.type_str} {a.name}" for a in dispatch_lambda_args(ps, f, symint=symint)
1330
+ )
1331
+ lambda_return = dispatch_lambda_return_str(f)
1332
+
1333
+ # dispatch lambda body
1334
+ dispatch_callee = cpp_dispatch_target(f)
1335
+ dispatch_args = ", ".join(cpp_dispatch_exprs(f, python_signature=ps))
1336
+
1337
+ # from arg parser outputs to dispatch lambda arguments
1338
+ parser_outputs = arg_parser_output_exprs(ps, f, symint=symint)
1339
+ lambda_arg_exprs = dispatch_lambda_exprs(ps, f, symint=symint)
1340
+ inits = "\n".join(lambda_arg_exprs.inits)
1341
+ lambda_args = ", ".join(lambda_arg_exprs.exprs)
1342
+
1343
+ # scatter fields
1344
+ # TODO: Checking `ps.method and ('requires_grad' in parser_outputs)` is a hacky
1345
+ # solution for enabling the 'requires_grad' argument for tensor methods
1346
+ # new_full, new_empty, and new_zeros. A much better but more difficult to
1347
+ # implement solution involves refactoring according to Ed's description here:
1348
+ # https://github.com/pytorch/pytorch/issues/36455#issuecomment-614767589
1349
+ need_set_requires_grad = ps.tensor_options_args and (
1350
+ not has_tensor_options(f)
1351
+ or (ps.method and ("requires_grad" in parser_outputs))
1352
+ )
1353
+ set_requires_grad = (
1354
+ f'.set_requires_grad({parser_outputs["requires_grad"].expr})'
1355
+ if need_set_requires_grad
1356
+ else ""
1357
+ )
1358
+
1359
+ if lambda_return == "void":
1360
+ # Make in-place foreach return `self` at python-binding level.
1361
+ # ref: https://github.com/pytorch/pytorch/pull/118622#pullrequestreview-1904804954
1362
+ self_arg = f.func.arguments.self_arg
1363
+ return_stmt: str
1364
+ if (
1365
+ str(f.func.name).startswith("_foreach_")
1366
+ and f.func.kind() == SchemaKind.inplace
1367
+ ):
1368
+ # note(crcrpar): `_foreach_pow.ScalarAndTensor` does NOT have its in-place
1369
+ # variant and it unlikely to have it in the future. Thus it's safe to have the following assert.
1370
+ assert self_arg is not None and is_tensor_list_type(
1371
+ self_arg.argument.type
1372
+ )
1373
+ return_stmt = """PyObject* self_tensorlist = _r.args[0];
1374
+ Py_INCREF(self_tensorlist);
1375
+ return self_tensorlist;
1376
+ """
1377
+ else:
1378
+ return_stmt = "Py_RETURN_NONE;"
1379
+ return f"""\
1380
+ {schema_comment}
1381
+ {inits}
1382
+ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
1383
+ pybind11::gil_scoped_release no_gil;
1384
+ {dispatch_callee}({dispatch_args});
1385
+ }};
1386
+ dispatch_{name}({lambda_args}){set_requires_grad};
1387
+ {return_stmt}
1388
+ """
1389
+ else:
1390
+ typename = structseq_typenames.get(gen_structseq_typename_key(f))
1391
+ structseq_typeref = f"{typename}, " if typename is not None else ""
1392
+ return f"""\
1393
+ {schema_comment}
1394
+ {inits}
1395
+ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
1396
+ pybind11::gil_scoped_release no_gil;
1397
+ return {dispatch_callee}({dispatch_args});
1398
+ }};
1399
+ return wrap({structseq_typeref}dispatch_{name}({lambda_args}){set_requires_grad});
1400
+ """
1401
+
1402
+ return go(f)
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_variable_factories.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables.
2
+ #
3
+ # This writes one file: variable_factories.h
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+
9
+ import torchgen.api.python as python
10
+ from torchgen.api import cpp
11
+ from torchgen.api.types import CppSignatureGroup
12
+ from torchgen.context import with_native_function
13
+ from torchgen.gen import parse_native_yaml
14
+ from torchgen.model import NativeFunction, TensorOptionsArguments, Variant
15
+ from torchgen.utils import FileManager, mapMaybe
16
+
17
+
18
+ OPTIONAL_TYPE_PATTERN = re.compile(r"std::optional<(.+)>")
19
+ TYPE_PATTERN = re.compile(r"(?:const\s+)?([A-Z]\w+)")
20
+
21
+
22
+ # Add 'at::' to types defined in ATen namespace, e.g. Tensor, TensorList, IntArrayRef and etc.
23
+ # TODO: maybe update the cpp argument API to take optional namespace argument?
24
+ def fully_qualified_type(argument_type: str) -> str:
25
+ def maybe_optional_type(type: str, is_opt: bool) -> str:
26
+ return f"std::optional<{type}>" if is_opt else type
27
+
28
+ opt_match = OPTIONAL_TYPE_PATTERN.match(argument_type)
29
+ is_opt = opt_match is not None
30
+ if opt_match:
31
+ argument_type = argument_type[opt_match.start(1) : opt_match.end(1)]
32
+ match = TYPE_PATTERN.match(argument_type)
33
+ if match is None:
34
+ return maybe_optional_type(argument_type, is_opt)
35
+ index = match.start(1)
36
+ qualified_type = f"{argument_type[:index]}at::{argument_type[index:]}"
37
+ return maybe_optional_type(qualified_type, is_opt)
38
+
39
+
40
+ def gen_variable_factories(
41
+ out: str, native_yaml_path: str, tags_yaml_path: str, template_path: str
42
+ ) -> None:
43
+ native_functions = parse_native_yaml(
44
+ native_yaml_path, tags_yaml_path
45
+ ).native_functions
46
+ factory_functions = [fn for fn in native_functions if is_factory_function(fn)]
47
+ fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
48
+ fm.write_with_template(
49
+ "variable_factories.h",
50
+ "variable_factories.h",
51
+ lambda: {
52
+ "generated_comment": "@"
53
+ + f"generated from {fm.template_dir_for_comments()}/variable_factories.h",
54
+ "ops_headers": [
55
+ f"#include <ATen/ops/{fn.root_name}.h>" for fn in factory_functions
56
+ ],
57
+ "function_definitions": list(mapMaybe(process_function, factory_functions)),
58
+ },
59
+ )
60
+
61
+
62
+ @with_native_function
63
+ def is_factory_function(f: NativeFunction) -> bool:
64
+ if Variant.function not in f.variants:
65
+ return False
66
+
67
+ name = cpp.name(f.func)
68
+ has_tensor_options = python.has_tensor_options(f)
69
+ return has_tensor_options or name.endswith("_like")
70
+
71
+
72
+ @with_native_function
73
+ def process_function(f: NativeFunction) -> str | None:
74
+ name = cpp.name(f.func)
75
+ has_tensor_options = python.has_tensor_options(f)
76
+ is_factory = has_tensor_options or name.endswith("_like")
77
+
78
+ if Variant.function not in f.variants or not is_factory:
79
+ return None
80
+
81
+ cpp_sigs = CppSignatureGroup.from_native_function(f, method=False)
82
+ sigs = [cpp_sigs.signature]
83
+ if cpp_sigs.symint_signature is not None:
84
+ sigs.append(cpp_sigs.symint_signature)
85
+ r = ""
86
+ for sig in sigs:
87
+ formals: list[str] = []
88
+ exprs: list[str] = []
89
+ requires_grad = "false"
90
+ for arg in sig.arguments():
91
+ qualified_type = fully_qualified_type(arg.type)
92
+ if arg.default:
93
+ formals.append(f"{qualified_type} {arg.name} = {arg.default}")
94
+ else:
95
+ formals.append(f"{qualified_type} {arg.name}")
96
+
97
+ if isinstance(arg.argument, TensorOptionsArguments):
98
+ # note: we remove the requires_grad setting from the TensorOptions because
99
+ # it is ignored anyways (and we actually have an assertion that it isn't set
100
+ # which would fail otherwise). We handle requires_grad explicitly here
101
+ # instead of passing it through to the kernel.
102
+ exprs.append(
103
+ f"at::TensorOptions({arg.name}).requires_grad(::std::nullopt)"
104
+ )
105
+ # Manually set the requires_grad bit on the result tensor.
106
+ requires_grad = f"{arg.name}.requires_grad()"
107
+ else:
108
+ exprs.append(arg.name)
109
+
110
+ r += f"""\
111
+ inline at::Tensor {sig.name()}({', '.join(formals)}) {{
112
+ at::AutoDispatchBelowADInplaceOrView guard;
113
+ return autograd::make_variable(at::{sig.name()}({', '.join(exprs)}), /*requires_grad=*/{requires_grad});
114
+ }}
115
+ """
116
+ return r
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/gen_view_funcs.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generates ViewFuncs.h/cpp
2
+ #
3
+ # NOTE: If any changes are being made to the ViewFunc codegen please also check
4
+ # if updates are needed in torch/csrc/autograd/autograd_not_implemented_fallback.cpp
5
+ # The fallback is expected to mimic this codegen, so we should keep the two in sync.
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING
10
+
11
+ import torchgen.api.dispatcher as dispatcher
12
+ from torchgen.api.translate import translate
13
+ from torchgen.api.types import (
14
+ BaseCType,
15
+ Binding,
16
+ NamedCType,
17
+ SymIntT,
18
+ tensorT,
19
+ VectorCType,
20
+ )
21
+ from torchgen.code_template import CodeTemplate
22
+ from torchgen.model import Argument, NativeFunction, OptionalType
23
+ from torchgen.utils import FileManager
24
+
25
+ from .gen_inplace_or_view_type import (
26
+ CALL_DISPATCH,
27
+ extract_bindings,
28
+ get_view_info,
29
+ modifies_arguments,
30
+ use_derived,
31
+ )
32
+
33
+
34
+ if TYPE_CHECKING:
35
+ from torchgen.api.autograd import NativeFunctionWithDifferentiabilityInfo
36
+
37
+
38
+ FUNCTION_DECLARATION = CodeTemplate(
39
+ """\
40
+ #define ${uppercase_op}_AVAILABLE
41
+ struct ${op} : public ${superclass} {
42
+ ${op}(${constructor_args}) ${initializer_list}
43
+ {};
44
+ virtual ~${op}() override {};
45
+ virtual std::vector<c10::SymInt> get_symints() const override;
46
+ virtual size_t num_symints() const override;
47
+ virtual std::vector<at::Tensor> get_tensors() const override;
48
+ virtual size_t num_tensors() const override;
49
+ virtual at::Tensor operator()(const at::Tensor&) const override;
50
+ virtual std::unique_ptr<ViewFunc> clone_and_set(
51
+ std::optional<std::vector<c10::SymInt>> = ::std::nullopt,
52
+ std::optional<std::vector<at::Tensor>> = ::std::nullopt) const override;
53
+
54
+ protected:
55
+ virtual void set_symints(std::vector<c10::SymInt>) override;
56
+ virtual void set_tensors(std::vector<at::Tensor>) override;
57
+
58
+ private:
59
+ ${state}
60
+ };
61
+
62
+ """
63
+ )
64
+
65
+ FUNCTION_DEFINITION = CodeTemplate(
66
+ """\
67
+ std::vector<c10::SymInt> ${op}::get_symints() const {
68
+ ${get_symints}
69
+ }
70
+
71
+ size_t ${op}::num_symints() const {
72
+ return static_cast<size_t>(${num_symints});
73
+ }
74
+
75
+ void ${op}::set_symints(std::vector<c10::SymInt> ${symints_vec}) {
76
+ TORCH_INTERNAL_ASSERT(${symints_vec}.size() == num_symints());
77
+ ${set_symints}
78
+ }
79
+
80
+ std::vector<at::Tensor> ${op}::get_tensors() const {
81
+ ${get_tensors}
82
+ }
83
+
84
+ size_t ${op}::num_tensors() const {
85
+ return static_cast<size_t>(${num_tensors});
86
+ }
87
+
88
+ void ${op}::set_tensors(std::vector<at::Tensor> ${tensors_vec}) {
89
+ TORCH_INTERNAL_ASSERT(${tensors_vec}.size() == num_tensors());
90
+ ${set_tensors}
91
+ }
92
+
93
+ at::Tensor ${op}::operator()(const at::Tensor& ${call_input_name}) const {
94
+ return ${op_call};
95
+ }
96
+
97
+ std::unique_ptr<ViewFunc> ${op}::clone_and_set(
98
+ std::optional<std::vector<c10::SymInt>> ${symints_vec},
99
+ std::optional<std::vector<at::Tensor>> ${tensors_vec}) const {
100
+ auto output = std::make_unique<${op}>(${clone_args});
101
+ if (${symints_vec}.has_value()) {
102
+ output->set_symints(std::move(*(${symints_vec})));
103
+ }
104
+ if (${tensors_vec}.has_value()) {
105
+ output->set_tensors(std::move(*(${tensors_vec})));
106
+ }
107
+ return output;
108
+ }
109
+
110
+ """
111
+ )
112
+
113
+
114
+ # e.g. as_strided -> AsStridedViewFunc for camel case or
115
+ # as_strided_view_func otherwise
116
+ def view_func_name(
117
+ f: NativeFunction, include_namespace: bool = False, camel_case: bool = True
118
+ ) -> str:
119
+ name = f.func.name.unambiguous_name()
120
+ view_func_name = f"{name.replace('.', '_')}_view_func"
121
+ if camel_case:
122
+ is_private = view_func_name.startswith("_")
123
+ view_func_name = "".join(
124
+ [p.title() for p in view_func_name.replace(".", "_").split("_")]
125
+ )
126
+ if is_private:
127
+ # put the leading underscore back in
128
+ view_func_name = f"_{view_func_name}"
129
+ namespace = "torch::autograd::generated::" if include_namespace else ""
130
+ return f"{namespace}{view_func_name}"
131
+
132
+
133
+ def is_symint_or_tensor(arg: Argument) -> bool:
134
+ return arg.type.is_tensor_like() or arg.type.is_symint_like()
135
+
136
+
137
+ def remove_const_ref(binding: Binding) -> Binding:
138
+ return Binding(
139
+ name=binding.name,
140
+ nctype=binding.nctype.remove_const_ref(),
141
+ argument=binding.argument,
142
+ default=binding.default,
143
+ )
144
+
145
+
146
+ def returns_multi_tensor(fn: NativeFunction) -> bool:
147
+ returns = fn.func.returns
148
+ assert len(returns) == 1
149
+ returns_list_like = returns[0].type.is_list_like() is not None
150
+ returns_tensor_like = returns[0].type.is_tensor_like()
151
+ return returns_list_like and returns_tensor_like
152
+
153
+
154
+ # Generates strings with logic for getting / setting state of a particular type.
155
+ #
156
+ # Args:
157
+ # bindings (list): List of state bindings of interest (may be empty)
158
+ # state_vec_type (NamedCType): Type of vector to either return or copy from
159
+ #
160
+ # Returns:
161
+ # tuple: (list of getter logic strings, list of setter logic strings, string
162
+ # with num items expression)
163
+ def generate_state_getter_setter(
164
+ bindings: list[Binding],
165
+ state_vec_type: NamedCType,
166
+ ) -> tuple[list[str], list[str], str]:
167
+ getter_logic = []
168
+ setter_logic = []
169
+
170
+ state_vec = state_vec_type.name
171
+ getter_logic.append(f"{state_vec_type.cpp_type()} {state_vec};")
172
+ if len(bindings) > 0:
173
+ setter_logic.append("auto i = 0;")
174
+
175
+ num_exprs = []
176
+ for i, b in enumerate(bindings):
177
+ assert isinstance(b.argument, Argument)
178
+ if b.argument.type.is_list_like():
179
+ # Handle list-likes.
180
+ num_expr = f"{b.name}.size()"
181
+ num_exprs.append(num_expr)
182
+ getter = f"{state_vec}.insert({state_vec}.end(), {b.name}.begin(), {b.name}.end());"
183
+ setter = f"std::copy({state_vec}.begin() + i, {state_vec}.begin() + i + {b.name}.size(), {b.name}.begin());"
184
+ elif isinstance(b.argument.type, OptionalType):
185
+ # Handle optionals.
186
+ num_expr = f"({b.name}.has_value() ? 1 : 0)"
187
+ num_exprs.append(num_expr)
188
+ conditional = f"if({b.name}.has_value())"
189
+ getter = (
190
+ f"{conditional} {state_vec}.insert({state_vec}.end(), *({b.name}));"
191
+ )
192
+ setter = f"{conditional} {b.name} = {state_vec}[i];"
193
+ else:
194
+ num_expr = "1"
195
+ num_exprs.append(num_expr)
196
+ getter = f"{state_vec}.push_back({b.name});"
197
+ setter = f"{b.name} = {state_vec}[i];"
198
+
199
+ getter_logic.append(getter)
200
+ setter_logic.append(setter)
201
+ if i < len(bindings) - 1:
202
+ setter_logic.append(f"i += {num_expr};")
203
+
204
+ # Reserve / assert based on the total number of items expression.
205
+ num_items = "0" if len(num_exprs) == 0 else " + ".join(num_exprs)
206
+ if len(bindings) > 0:
207
+ getter_logic.insert(1, f"{state_vec}.reserve({num_items});")
208
+
209
+ getter_logic.append(f"return {state_vec};")
210
+
211
+ return getter_logic, setter_logic, num_items
212
+
213
+
214
+ def process_function(fn: NativeFunction, template: CodeTemplate) -> str:
215
+ bindings = extract_bindings(fn)
216
+ non_self_bindings = [b for b in bindings if b.name != "self"]
217
+
218
+ non_self_args = fn.func.arguments.flat_all[1:]
219
+ non_self_value_bindings = [
220
+ dispatcher.argument(a, remove_non_owning_ref_types=True) for a in non_self_args
221
+ ]
222
+
223
+ # Generate constructor / clone args for the generated struct.
224
+ constructor_args = [b.defn() for b in non_self_bindings]
225
+ clone_args = [b.name for b in non_self_bindings]
226
+
227
+ # Generate state variable declarations for the generated struct.
228
+ state_variables = [
229
+ f"{remove_const_ref(b).defn()};" for b in non_self_value_bindings
230
+ ]
231
+
232
+ # Generate initializer list expressions for the generated struct.
233
+ # allow_expensive_conversions=True because we need to store e.g. SymIntArrayRefs as
234
+ # vector<SymInt>s.
235
+ init_exprs = translate(
236
+ non_self_bindings, non_self_value_bindings, allow_expensive_conversions=True
237
+ )
238
+ initializers = []
239
+ for b, init_expr in zip(non_self_bindings, init_exprs):
240
+ name = b.nctype.name
241
+ assert isinstance(name, str)
242
+ initializers.append(f"{name}({init_expr.expr})")
243
+
244
+ # Generate call to underlying view op
245
+ call_input_name = "input_base"
246
+ op_call_args = [call_input_name, *(b.name for b in non_self_bindings)]
247
+ op_call = CALL_DISPATCH.substitute(
248
+ unambiguous_name=fn.func.name.unambiguous_name(),
249
+ unpacked_args=op_call_args,
250
+ )
251
+
252
+ # Multi-output views additionally require a view_idx for disambiguation.
253
+ if returns_multi_tensor(fn):
254
+ view_idx_name = "view_idx"
255
+ view_idx_typename = "int64_t"
256
+ view_idx_decl = f"{view_idx_typename} {view_idx_name}"
257
+ constructor_args.append(view_idx_decl)
258
+ clone_args.append(view_idx_name)
259
+ state_variables.append(f"{view_idx_decl};")
260
+ initializers.append(f"{view_idx_name}({view_idx_name})")
261
+ op_call += f"[{view_idx_name}]"
262
+
263
+ # Generate initializer list for the generated struct.
264
+ initializer_list = f": {', '.join(initializers)}" if len(initializers) > 0 else ""
265
+
266
+ # Generate getter / setter logic for any symints.
267
+ symint_bindings = [
268
+ b
269
+ for b in non_self_bindings
270
+ if isinstance(b.argument, Argument) and b.argument.type.is_symint_like()
271
+ ]
272
+ symints_vec_type = NamedCType("symints", VectorCType(BaseCType(SymIntT)))
273
+ get_symints, set_symints, num_symints = generate_state_getter_setter(
274
+ symint_bindings, symints_vec_type
275
+ )
276
+
277
+ # Generate getter / setter logic for any tensors.
278
+ tensor_bindings = [
279
+ b
280
+ for b in non_self_bindings
281
+ if isinstance(b.argument, Argument) and b.argument.type.is_tensor_like()
282
+ ]
283
+ tensors_vec_type = NamedCType("tensors", VectorCType(BaseCType(tensorT)))
284
+ get_tensors, set_tensors, num_tensors = generate_state_getter_setter(
285
+ tensor_bindings, tensors_vec_type
286
+ )
287
+
288
+ return template.substitute(
289
+ op=view_func_name(fn),
290
+ uppercase_op=view_func_name(fn, camel_case=False).upper(),
291
+ superclass="torch::autograd::ViewFunc",
292
+ initializer_list=initializer_list,
293
+ state=state_variables,
294
+ constructor_args=constructor_args,
295
+ clone_args=clone_args,
296
+ symints_vec=symints_vec_type.name,
297
+ get_symints=get_symints,
298
+ set_symints=set_symints,
299
+ num_symints=num_symints,
300
+ tensors_vec=tensors_vec_type.name,
301
+ get_tensors=get_tensors,
302
+ set_tensors=set_tensors,
303
+ num_tensors=num_tensors,
304
+ call_input_name=call_input_name,
305
+ op_call=op_call,
306
+ )
307
+
308
+
309
+ def gen_view_funcs(
310
+ out: str,
311
+ fns_with_infos: list[NativeFunctionWithDifferentiabilityInfo],
312
+ template_path: str,
313
+ ) -> None:
314
+ # don't need the info parts, just the function
315
+ fns = [fn.func for fn in fns_with_infos if use_derived(fn)]
316
+ # only want out-of-place views
317
+ view_fns = [
318
+ fn for fn in fns if get_view_info(fn) is not None and not modifies_arguments(fn)
319
+ ]
320
+
321
+ declarations = [process_function(fn, FUNCTION_DECLARATION) for fn in view_fns]
322
+ definitions = [process_function(fn, FUNCTION_DEFINITION) for fn in view_fns]
323
+ ops_headers = [f"#include <ATen/ops/{fn.root_name}_ops.h>" for fn in view_fns]
324
+
325
+ file_basename = "ViewFuncs"
326
+ fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
327
+ for suffix in [".h", ".cpp"]:
328
+ fname = file_basename + suffix
329
+ fm.write_with_template(
330
+ fname,
331
+ fname,
332
+ lambda: {
333
+ "generated_comment": "@"
334
+ + f"generated from {fm.template_dir_for_comments()}/"
335
+ + fname,
336
+ "view_func_declarations": declarations,
337
+ "view_func_definitions": definitions,
338
+ "ops_headers": ops_headers,
339
+ },
340
+ )
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/load_derivatives.py ADDED
@@ -0,0 +1,1014 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Parses derivatives.yaml into autograd functions
2
+ #
3
+ # Each autograd function is represented by `DifferentiabilityInfo` containing
4
+ # a list of `Derivative`. See `torchgen.api.autograd` for the data models.
5
+
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from collections import defaultdict
10
+ from typing import Any, Counter, Dict, Sequence, Set, Tuple
11
+
12
+ import yaml
13
+
14
+ from torchgen.api import cpp
15
+ from torchgen.api.autograd import (
16
+ Derivative,
17
+ DifferentiabilityInfo,
18
+ ForwardDerivative,
19
+ SavedAttribute,
20
+ )
21
+ from torchgen.api.types import (
22
+ BaseCType,
23
+ Binding,
24
+ boolT,
25
+ CppSignatureGroup,
26
+ layoutT,
27
+ longT,
28
+ NamedCType,
29
+ OptionalCType,
30
+ scalarTypeT,
31
+ SpecialArgName,
32
+ stringT,
33
+ symIntArrayRefT,
34
+ SymIntT,
35
+ tensorGeometryT,
36
+ tensorOptionsT,
37
+ typeAndSizeT,
38
+ VectorCType,
39
+ )
40
+ from torchgen.context import with_native_function
41
+ from torchgen.gen import get_grouped_by_view_native_functions, parse_native_yaml
42
+ from torchgen.model import (
43
+ AUTOGRAD_KEYS,
44
+ FunctionSchema,
45
+ NativeFunction,
46
+ NativeFunctionsViewGroup,
47
+ OperatorName,
48
+ SchemaKind,
49
+ Type,
50
+ Variant,
51
+ )
52
+ from torchgen.utils import concatMap, IDENT_REGEX, split_name_params
53
+ from torchgen.yaml_utils import YamlLoader
54
+
55
+
56
+ DerivativeRet = Tuple[Dict[FunctionSchema, Dict[str, DifferentiabilityInfo]], Set[str]]
57
+
58
+ _GLOBAL_LOAD_DERIVATIVE_CACHE: dict[tuple[str, str], DerivativeRet] = {}
59
+
60
+ _VALID_AUTOGRAD_KEYS = set(AUTOGRAD_KEYS)
61
+
62
+
63
+ # This function directly adds per-dispatchkey derivative entries for {view}_copy variants of each view op.
64
+ # Since every {view} and {view}_copy op shares the same derivative formula,
65
+ # we generate them here instead of duplicating them in the yaml.
66
+ # See Note [Codegen'd {view}_copy Operators]
67
+ def add_view_copy_derivatives(
68
+ infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]],
69
+ view_groups: list[NativeFunctionsViewGroup],
70
+ ) -> None:
71
+ # Get the map from each view op's name to its corresponding view group
72
+ view_name_to_group: dict[OperatorName, NativeFunctionsViewGroup] = {
73
+ g.view.func.name: g for g in view_groups
74
+ }
75
+
76
+ view_infos = {}
77
+
78
+ for info_dispatch_dict in infos.values():
79
+ # maybe_view_group only needs to be calculated once per info_dispatch_dict
80
+ maybe_view_group = None
81
+ view_copy_differentiability_infos = {}
82
+ for dispatch_key, info in info_dispatch_dict.items():
83
+ maybe_view_group = view_name_to_group.get(info.func.func.name, None)
84
+ if maybe_view_group is not None and maybe_view_group.view_copy is not None:
85
+ view_copy_info = info.create_view_copy_from_view_derivative(
86
+ maybe_view_group
87
+ )
88
+ if view_copy_info is not None:
89
+ fn_schema = view_copy_info.func.func
90
+ view_copy_differentiability_infos[dispatch_key] = view_copy_info
91
+ else:
92
+ break
93
+ # prefer manually-defined derivatives if any
94
+ if len(view_copy_differentiability_infos) > 0 and fn_schema not in infos:
95
+ assert fn_schema is not None
96
+ view_infos[fn_schema] = view_copy_differentiability_infos
97
+
98
+ infos.update(view_infos)
99
+
100
+
101
+ def load_derivatives(
102
+ derivatives_yaml_path: str, native_yaml_path: str, tags_yaml_path: str
103
+ ) -> DerivativeRet:
104
+ # Do some caching as this is a deterministic function
105
+ global _GLOBAL_LOAD_DERIVATIVE_CACHE
106
+ key = (derivatives_yaml_path, native_yaml_path)
107
+ if key not in _GLOBAL_LOAD_DERIVATIVE_CACHE:
108
+ with open(derivatives_yaml_path) as f:
109
+ definitions = yaml.load(f, Loader=YamlLoader)
110
+
111
+ funcs = parse_native_yaml(native_yaml_path, tags_yaml_path).native_functions
112
+ # From the parsed native functions, separate out the (generated) view_copy functions,
113
+ # so we can generate derivatives for them separately.
114
+ native_functions_with_view_groups = get_grouped_by_view_native_functions(funcs)
115
+ native_functions = concatMap(
116
+ lambda g: [g]
117
+ if isinstance(g, NativeFunction)
118
+ else list(g.functions(include_copy=True)),
119
+ native_functions_with_view_groups,
120
+ )
121
+ view_groups = [
122
+ g
123
+ for g in native_functions_with_view_groups
124
+ if isinstance(g, NativeFunctionsViewGroup)
125
+ ]
126
+
127
+ # What's the difference between function schema v.s. signature?
128
+ # function schema is the complete declaration including mutability annotation / default value and etc.
129
+ # signature is the canonical schema for a group of functions (in-place/out/functional variants)
130
+ # that are semantically related.
131
+ functions_by_signature: dict[
132
+ FunctionSchema, list[NativeFunction]
133
+ ] = defaultdict(list)
134
+ functions_by_schema: dict[str, NativeFunction] = {}
135
+ for function in native_functions:
136
+ functions_by_signature[function.func.signature()].append(function)
137
+ assert str(function.func) not in functions_by_schema
138
+ functions_by_schema[str(function.func)] = function
139
+
140
+ # Keep track of how many of which ops we've seen so we can
141
+ # disambiguate them with a numeric suffix.
142
+ op_counter = Counter[str]()
143
+
144
+ # infos is a dict that maps FunctionSchema -> a dict of per dispatch key DifferentiabilityInfos
145
+ # this is useful because in tools/autograd/gen_autograd.py:match_differentiability_info
146
+ # we ultimately need to categorize the DifferentiabilityInfos by FunctionSchema
147
+ infos: dict[FunctionSchema, dict[str, DifferentiabilityInfo]] = {}
148
+ used_dispatch_keys: set[str] = set()
149
+ for defn_dict in definitions:
150
+ # Ensure that the old derivatives.yaml schema with no dispatch key can be loaded.
151
+ if "dispatch" not in defn_dict:
152
+ specification = defn_dict.pop("name")
153
+ output_differentiability = defn_dict.pop(
154
+ "output_differentiability", None
155
+ )
156
+ defn_dict = {"name": specification, "dispatch": {"Default": defn_dict}}
157
+ if output_differentiability:
158
+ defn_dict["output_differentiability"] = output_differentiability
159
+ name, per_dispatch_diffinfos = create_differentiability_info(
160
+ defn_dict,
161
+ functions_by_signature,
162
+ functions_by_schema,
163
+ op_counter,
164
+ used_dispatch_keys,
165
+ )
166
+ infos[name] = per_dispatch_diffinfos
167
+
168
+ add_view_copy_derivatives(infos, view_groups)
169
+
170
+ # cache both loaded infos as well a a set of all the dispatch_keys/aliases
171
+ # that appear in derivatives.yaml. used_dispatch_keys is useful for generating
172
+ # VariableType.cpp where we need a TORCH_LIBRARY_IMPL for every autograd dispatch key used
173
+ _GLOBAL_LOAD_DERIVATIVE_CACHE[key] = infos, used_dispatch_keys
174
+
175
+ return _GLOBAL_LOAD_DERIVATIVE_CACHE[key]
176
+
177
+
178
+ # TODO: Why is this going through CppSignatureGroup, that doesn't make sense...
179
+ @with_native_function
180
+ def cpp_arguments(f: NativeFunction) -> Sequence[Binding]:
181
+ sigs = CppSignatureGroup.from_native_function(f, method=False)
182
+ if sigs.symint_signature is not None:
183
+ return sigs.symint_signature.arguments()
184
+ else:
185
+ return sigs.signature.arguments()
186
+
187
+
188
+ def create_derivative(
189
+ f: NativeFunction,
190
+ formula: str,
191
+ var_names: tuple[str, ...],
192
+ available_named_gradients: Sequence[str],
193
+ ) -> Derivative:
194
+ original_formula = formula
195
+ arguments: list[NamedCType] = [
196
+ a.nctype.remove_const_ref() for a in cpp_arguments(f)
197
+ ]
198
+
199
+ return_names = tuple(n if n != "self" else "result" for n in cpp.return_names(f))
200
+ return_types = tuple(
201
+ cpp.return_type(r, symint=True).remove_const_ref() for r in f.func.returns
202
+ )
203
+
204
+ named_returns = [
205
+ NamedCType(name, type) for name, type in zip(return_names, return_types)
206
+ ]
207
+
208
+ formula, saved_inputs = saved_variables(formula, arguments, var_names)
209
+ formula, saved_outputs = saved_variables(formula, named_returns, var_names)
210
+
211
+ used_named_gradients = {
212
+ name
213
+ for name in available_named_gradients
214
+ if re.search(IDENT_REGEX.format(name), formula)
215
+ }
216
+
217
+ # Check that the referenced derivatives in the formula are in bounds
218
+ for i in used_gradient_indices(formula):
219
+ if i >= len(f.func.returns):
220
+ raise RuntimeError(
221
+ f"Out of bounds grads access: derivative formula for {cpp.name(f.func)} "
222
+ f"used grads[{i}], but the forward only returns {len(f.func.returns)} outputs."
223
+ )
224
+
225
+ return Derivative(
226
+ formula=formula,
227
+ original_formula=original_formula,
228
+ var_names=var_names,
229
+ saved_inputs=saved_inputs,
230
+ saved_outputs=saved_outputs,
231
+ named_gradients=used_named_gradients,
232
+ )
233
+
234
+
235
+ def create_forward_derivative(
236
+ f: NativeFunction, formula: str, names: tuple[str, ...]
237
+ ) -> ForwardDerivative:
238
+ var_names = names
239
+ var_types: tuple[Type, ...] | None = None
240
+ for r in f.func.returns:
241
+ if r.name in var_names:
242
+ if var_types is None:
243
+ var_types = ()
244
+ var_types = var_types + (r.type,)
245
+
246
+ # Handle default return names
247
+ if var_types is None:
248
+ if var_names == ("result",):
249
+ assert len(f.func.returns) == 1
250
+ var_types = (f.func.returns[0].type,)
251
+ else:
252
+ for var_name in var_names:
253
+ res = re.findall(r"^result(\d+)$", var_name)
254
+ if len(res) == 1:
255
+ if var_types is None:
256
+ var_types = ()
257
+ arg_idx = int(res[0])
258
+ var_types = var_types + (f.func.returns[arg_idx].type,)
259
+
260
+ assert var_types is not None, "No matching output for forward derivative definition"
261
+ return ForwardDerivative(
262
+ formula=formula,
263
+ var_names=var_names,
264
+ var_types=var_types,
265
+ required_inputs_fw_grad=None,
266
+ required_inputs_primal=None,
267
+ required_original_self_value=False,
268
+ is_reusing_outplace_formula=False,
269
+ )
270
+
271
+
272
+ def postprocess_forward_derivatives(
273
+ f: NativeFunction,
274
+ defn_name: str,
275
+ all_arg_names: list[str],
276
+ derivatives: list[Derivative],
277
+ forward_derivatives: list[ForwardDerivative],
278
+ args_with_derivatives: Sequence[Binding],
279
+ ) -> list[ForwardDerivative]:
280
+ def find_required_inputs(formula: str, postfix: str) -> tuple[str, ...]:
281
+ is_foreach = f.func.name.name.base.startswith("_foreach_")
282
+ required_inputs = set()
283
+ for arg in args_with_derivatives:
284
+ if (
285
+ arg.type in ("at::TensorList", "const at::ITensorListRef &")
286
+ and not is_foreach
287
+ ):
288
+ # The functions taking TensorList handle everything internally
289
+ continue
290
+ arg_name = arg.name
291
+
292
+ found = re.search(IDENT_REGEX.format(arg_name), formula)
293
+ if found:
294
+ raise RuntimeError(
295
+ f"The forward formula for {defn_name} is using the base name of the {arg_name} "
296
+ f"argument which is ambiguous. You should use {arg_name}_p to access the primal "
297
+ f"value and {arg_name}_t to access the tangent."
298
+ )
299
+
300
+ found = re.search(IDENT_REGEX.format(arg_name + postfix), formula)
301
+ if found:
302
+ required_inputs.add(arg_name)
303
+
304
+ return tuple(required_inputs)
305
+
306
+ updated_derivatives: list[ForwardDerivative] = []
307
+
308
+ for defn in forward_derivatives:
309
+ formula = defn.formula
310
+ required_inputs_tangent = find_required_inputs(formula, "_t")
311
+ if formula == "auto_element_wise":
312
+ assert (
313
+ f.func.kind() != SchemaKind.inplace
314
+ ), f"Cannot use auto_element_wise with {f.func.name} because it is an in-place variant"
315
+ if (
316
+ (not len(args_with_derivatives) == 1)
317
+ or len(forward_derivatives) > 1
318
+ or len(forward_derivatives[0].var_names) > 1
319
+ ):
320
+ raise RuntimeError(
321
+ f"Derivative definition of {defn_name} in derivatives.yaml defines the "
322
+ "forward definition of gradient as element_wise but this only "
323
+ "works for functions with a single differentiable input and a "
324
+ "single differentiable output."
325
+ )
326
+ if not len(derivatives) == 1:
327
+ raise RuntimeError(
328
+ f"Derivative definition of {defn_name} in derivatives.yaml defines the "
329
+ "forward definition of gradient as element_wise but it does not "
330
+ "defines the gradient formula for its argument which is required."
331
+ )
332
+ # This transformation is based on the observation that for element-wise functions, the Jacobian
333
+ # matrix is diagonal and thus doing J * v is the same as (v^T J)^T (in practice, we ignore the transpositions)
334
+ # For the complex case, we use hermitian transpose and get (v.conj() J).conj()
335
+ # So here we are going to re-use the backward formula and replace two things:
336
+ # 1) all occurrences of "grad" with "foo_t.conj()", where foo is the name of the unique differentiable input.
337
+ # 2) all usage of an original input "foo" with its primal value "foo_p".
338
+ # 3) conjugate the final result
339
+ # For example, for abs, the backward formula is:
340
+ # grad * self.sgn()
341
+ # And this function generates a forward formula that is:
342
+ # (self_t.conj() * self_p.sgn()).conj()
343
+
344
+ backward_formula = derivatives[0].original_formula
345
+ input_name = args_with_derivatives[0].name
346
+
347
+ # Do replacement 1) of the grad
348
+ def repl(m: Any) -> str:
349
+ return f"{m.group(1)}{input_name}_t.conj(){m.group(2)}"
350
+
351
+ fw_formula = re.sub(IDENT_REGEX.format("grad"), repl, backward_formula)
352
+
353
+ # Do replacement 2) of the input variables
354
+ for arg in args_with_derivatives:
355
+ arg_name = arg.name
356
+
357
+ def repl(m: Any) -> str:
358
+ return f"{m.group(1)}{arg_name}_p{m.group(2)}"
359
+
360
+ fw_formula = re.sub(IDENT_REGEX.format(arg_name), repl, fw_formula)
361
+
362
+ # Do the final conjugate 3)
363
+ fw_formula = f"({fw_formula}).conj()"
364
+
365
+ # Since there is a single differentiable inputs and we necessarily need its tangent we can
366
+ # simply require all differentiable input's tangent.
367
+ required_inputs_tangent = tuple(all_arg_names)
368
+ formula = fw_formula
369
+ elif formula == "auto_linear":
370
+ if (
371
+ len(forward_derivatives) > 1
372
+ or len(forward_derivatives[0].var_names) > 1
373
+ ):
374
+ raise RuntimeError(
375
+ f"Derivative definition of {defn_name} in derivatives.yaml defines the "
376
+ "forward definition of gradient as linear but this only works "
377
+ "for functions with a single differentiable output."
378
+ )
379
+ # This transformation is based on the observation that linear functions can be written as:
380
+ # y = f(x) = A * x
381
+ # For some matrix A and the Jacobian of the function f is also A.
382
+ # So doing J * v = A * v = f(v).
383
+ # Hence to do the jvp, we simply need to evaluate the function at the point v instead of x.
384
+ # We do this by calling the forward again by replacing any occurrence of the differentiable
385
+ # input "foo" by it's tangent "foo_t".
386
+ # Note that multiple inputs are not a problem as long as the function is truly linear wrt to
387
+ # the vector where all the differentiable inputs are stacked.
388
+
389
+ diff_arg_names = [arg.name for arg in args_with_derivatives]
390
+ assert len(diff_arg_names) > 0
391
+
392
+ # Do replacement of input variables
393
+ new_args = []
394
+ for arg_name in all_arg_names:
395
+ if arg_name in diff_arg_names:
396
+ arg_name = arg_name + "_t"
397
+ new_args.append(arg_name)
398
+
399
+ # TODO we are trolling
400
+ if f.func.has_symint():
401
+ defn_name += "_symint"
402
+
403
+ # Call into the forward again. We need two cases here to handle both Tensor methods and at:: functions.
404
+ if Variant.function in f.variants:
405
+ fw_formula = f"at::{defn_name}({', '.join(new_args)})"
406
+ else:
407
+ assert Variant.method in f.variants
408
+ fw_formula = f"{new_args[0]}.{defn_name}({', '.join(new_args[1:])})"
409
+
410
+ # All of the input tangents are always used so all of them are required here.
411
+ required_inputs_tangent = tuple(diff_arg_names)
412
+ formula = fw_formula
413
+
414
+ # At this point, the formula is final and is not modified anymore.
415
+
416
+ # During forward formula, we use the primal instead of the input Tensors.
417
+ # This call inspects the formula to find for which input's primal are used.
418
+ required_inputs_primal = find_required_inputs(formula, "_p")
419
+
420
+ updated_derivatives.append(
421
+ ForwardDerivative(
422
+ formula=formula,
423
+ var_names=defn.var_names,
424
+ var_types=defn.var_types,
425
+ required_inputs_fw_grad=required_inputs_tangent,
426
+ required_inputs_primal=required_inputs_primal,
427
+ required_original_self_value=False,
428
+ is_reusing_outplace_formula=False,
429
+ )
430
+ )
431
+
432
+ return updated_derivatives
433
+
434
+
435
+ def is_forward_derivative_definition(
436
+ all_arg_names: list[str], names: tuple[str, ...]
437
+ ) -> bool:
438
+ for name in names:
439
+ return name not in all_arg_names
440
+ raise RuntimeError("Expected `names` to be non-empty")
441
+
442
+
443
+ def create_differentiability_info(
444
+ defn_dict: dict[Any, Any],
445
+ functions_by_signature: dict[FunctionSchema, list[NativeFunction]],
446
+ functions_by_schema: dict[str, NativeFunction],
447
+ op_counter: Counter[str],
448
+ used_dispatch_keys: set[str],
449
+ ) -> tuple[FunctionSchema, dict[str, DifferentiabilityInfo]]:
450
+ """Processes a single entry `defn` in derivatives.yaml"""
451
+
452
+ def canonical_function(
453
+ functions: Sequence[NativeFunction], name: str
454
+ ) -> NativeFunction:
455
+ for f in functions:
456
+ if (
457
+ not f.func.is_functional_fn()
458
+ and not f.func.is_out_fn()
459
+ and name == str(f.func.name.name)
460
+ ):
461
+ return f
462
+ # some functions only have in-place variants
463
+ assert name + "_" == cpp.name(functions[0].func)
464
+ return functions[0]
465
+
466
+ def split_names(raw_names: str) -> tuple[str, ...]:
467
+ """Given "foo, bar", return ["foo", "bar"]."""
468
+ return tuple(x.strip() for x in raw_names.split(","))
469
+
470
+ def check_grad_usage(defn_name: str, derivatives: Sequence[Derivative]) -> None:
471
+ """
472
+ Check for some subtle mistakes one might make when writing derivatives.
473
+ These mistakes will compile, but will be latent until a function is
474
+ used with double backwards.
475
+ """
476
+
477
+ uses_grad = False # true if any derivative uses "grad"
478
+ num_grads_uses = 0 # count of uses of "grads" or "grads[INDEX]"
479
+ uses_named_grads = False # true if any derivative uses "grad_{name}"
480
+ used_grads_indices: list[int] = [] # which indices of grads are used
481
+ for d in derivatives:
482
+ formula = d.formula
483
+ uses_grad = uses_grad or bool(
484
+ re.findall(IDENT_REGEX.format("grad"), formula)
485
+ )
486
+ num_grads_uses += len(re.findall(IDENT_REGEX.format("grads"), formula))
487
+ uses_named_grads = uses_named_grads or bool(d.named_gradients)
488
+ used_grads_indices.extend(used_gradient_indices(formula))
489
+ # This is a basic sanity check: the number of places we see
490
+ # "grads" should be no fewer than the number of indices we see
491
+ # inside "grads". They may not be equal because we may use
492
+ # "grads" without an index.
493
+ assert num_grads_uses >= len(used_grads_indices)
494
+ # Thus if the number is equal, every use of grads is also
495
+ # indexed.
496
+ only_used_grads_indices = num_grads_uses == len(used_grads_indices)
497
+
498
+ if uses_grad and num_grads_uses > 0:
499
+ raise RuntimeError(
500
+ f"Derivative definition of {defn_name} in derivatives.yaml illegally "
501
+ "mixes use of 'grad' and 'grads'. Consider replacing "
502
+ "occurrences of 'grad' with 'grads[0]'"
503
+ )
504
+
505
+ if only_used_grads_indices and set(used_grads_indices) == {0}:
506
+ raise RuntimeError(
507
+ f"Derivative definition of {defn_name} in derivatives.yaml solely "
508
+ "refers to 'grads[0]'. If the first output is indeed the "
509
+ "only differentiable output, replace 'grads[0]' with 'grad'; "
510
+ "otherwise, there is a likely error in your derivatives "
511
+ "declaration."
512
+ )
513
+
514
+ if uses_named_grads and (uses_grad or num_grads_uses > 0):
515
+ raise RuntimeError(
516
+ f"Derivative definition of {defn_name} in derivatives.yaml illegally "
517
+ 'mixes use of "grad_RETURN_NAME" and "grad" or "grads[x]". Use '
518
+ "only one method for identifying gradients."
519
+ )
520
+
521
+ @with_native_function
522
+ def set_up_derivatives(
523
+ f: NativeFunction,
524
+ ) -> tuple[
525
+ Sequence[Derivative],
526
+ Sequence[ForwardDerivative],
527
+ Sequence[Binding],
528
+ Sequence[str],
529
+ Sequence[str],
530
+ ]:
531
+ # Set up the derivative information
532
+ derivatives: list[Derivative] = []
533
+ forward_derivatives: list[ForwardDerivative] = []
534
+ non_differentiable_arg_names: list[str] = []
535
+ args_with_derivatives_set: set[str] = set()
536
+
537
+ all_arg_names = [a.name for a in cpp_arguments(f)]
538
+ all_ret_names = [
539
+ r.name for r in f.func.returns
540
+ ] # only used for the assert below
541
+ # output_differentiability is captured from the enclosed
542
+ # scope. Don't modify it.
543
+ #
544
+ # If it is not present, then no output is explicitly
545
+ # undifferentiable.
546
+ #
547
+ # It may be present and shorter than the length of return
548
+ # values. If that's the case, any return value that does not
549
+ # have a corresponding entry is considered not differentiable.
550
+ differentiability = output_differentiability or [True] * len(f.func.returns)
551
+ # A return is available as a named gradient ...
552
+ available_named_gradients = [
553
+ f"grad_{ret.name}"
554
+ for ret, differentiable in zip(f.func.returns, differentiability)
555
+ # if it has not been explicitly made undifferentiable
556
+ if differentiable
557
+ # and if it has a name
558
+ and ret.name is not None
559
+ # and if its type is differentiable
560
+ and ret.type.is_tensor_like()
561
+ ]
562
+
563
+ for raw_names in sorted(defn.keys()):
564
+ formula = defn[raw_names]
565
+ names = split_names(raw_names)
566
+
567
+ for name in names:
568
+ assert not (name in all_arg_names and name in all_ret_names), (
569
+ f"While processing the derivative formula for '{f.func.name}' wrt '{name}', "
570
+ f"expected '{name}' to not be both an input arg and named return. "
571
+ )
572
+
573
+ if is_forward_derivative_definition(all_arg_names, names):
574
+ forward_derivatives.append(create_forward_derivative(f, formula, names))
575
+ else:
576
+ if formula.lower().strip() == "non_differentiable":
577
+ non_differentiable_arg_names += names
578
+ else:
579
+ derivative = create_derivative(
580
+ f, formula, names, available_named_gradients
581
+ )
582
+ derivatives.append(derivative)
583
+ args_with_derivatives_set |= set(names)
584
+
585
+ overlap = args_with_derivatives_set.intersection(non_differentiable_arg_names)
586
+ if overlap:
587
+ raise RuntimeError(
588
+ f"derivatives definition for {defn} have overlapped non_differentiable "
589
+ f"and differentiable variables: {overlap}"
590
+ )
591
+
592
+ # Next, let us determine the list of inputs in order.
593
+ # TODO: do we need eagerly calculate and save it here? Can it be derived
594
+ # from NativeFunction and `derivatives` on callsites instead?
595
+ args_with_derivatives = [
596
+ a for a in cpp_arguments(f) if a.name in args_with_derivatives_set
597
+ ]
598
+
599
+ # Postprocess forward derivatives definitions now that we know the differentiable arguments
600
+ forward_derivatives = postprocess_forward_derivatives(
601
+ f,
602
+ defn_name,
603
+ all_arg_names,
604
+ derivatives,
605
+ forward_derivatives,
606
+ args_with_derivatives,
607
+ )
608
+
609
+ # Test to see if the use of 'grads' makes sense.
610
+ check_grad_usage(defn_name, derivatives)
611
+
612
+ return (
613
+ derivatives,
614
+ forward_derivatives,
615
+ args_with_derivatives,
616
+ non_differentiable_arg_names,
617
+ available_named_gradients,
618
+ )
619
+
620
+ # NB: Removes 'name' from defn dictionary
621
+ specification = defn_dict.pop("name")
622
+ defn_name, _ = split_name_params(specification)
623
+ # NB: Removes 'output_differentiability' from defn dictionary
624
+ # `None` means all differentiable.
625
+ output_differentiability = defn_dict.pop("output_differentiability", None)
626
+ output_differentiability_conditions = None
627
+ if output_differentiability and any(
628
+ isinstance(diff, str) for diff in output_differentiability
629
+ ):
630
+ if len(output_differentiability) != 1:
631
+ raise RuntimeError(
632
+ f"Not supported: for {specification},"
633
+ f"output_differentiability must either be "
634
+ f"List[bool] or a List[str] where each str is a "
635
+ f"condition. In the case where it is a condition, "
636
+ f"we only support single-output functions. "
637
+ f"Please file us an issue. "
638
+ )
639
+ output_differentiability_conditions = output_differentiability
640
+ output_differentiability = [True]
641
+
642
+ schema_function = functions_by_schema.get(specification)
643
+ if not schema_function:
644
+ avail = "\n".join(
645
+ k for k, v in functions_by_schema.items() if cpp.name(v.func) == defn_name
646
+ )
647
+ raise RuntimeError(
648
+ f"could not find ATen function for schema: {specification} "
649
+ f". Available signatures:\n{avail}"
650
+ )
651
+
652
+ # now map this to the legacy schema; this isn't technically necessary, but we'd need some logic here
653
+ # to map in-place schemas to the out-of-place variants.
654
+ # TODO: maybe the logic to handle the legacy schema is no longer necessary?
655
+ signature = schema_function.func.signature()
656
+ functions = functions_by_signature[signature]
657
+ if len(functions) == 0:
658
+ avail = "\n".join(
659
+ str(k)
660
+ for k, v in functions_by_signature.items()
661
+ if cpp.name(k) == defn_name
662
+ )
663
+ raise RuntimeError(
664
+ f"could not find ATen function for legacy signature: {signature} "
665
+ f"corresponding to schema {specification}. Please report a bug to PyTorch. "
666
+ f"Available signatures:\n{avail}"
667
+ )
668
+
669
+ canonical = canonical_function(functions, defn_name)
670
+ if "grad_input_mask" in (a.name for a in cpp_arguments(canonical)):
671
+ raise RuntimeError(
672
+ f"Schema for {defn_name} has an argument named grad_input_mask, "
673
+ "but this name would be shadowed by our codegen. "
674
+ "Please use a different name in native_functions.yaml."
675
+ )
676
+
677
+ if "result" in (a.name for a in cpp_arguments(canonical)):
678
+ raise RuntimeError(
679
+ f"Schema for {defn_name} has an argument named result, "
680
+ "but this is only allowed for outputs."
681
+ "Please use a different name in native_functions.yaml."
682
+ )
683
+
684
+ diffinfo_dict = {}
685
+ for key, defn in defn_dict["dispatch"].items():
686
+ if key != "Default" and key not in _VALID_AUTOGRAD_KEYS:
687
+ raise RuntimeError(
688
+ f"Invalid dispatch key {key} in derivatives.yaml for {specification},"
689
+ f" expected key to be one of {_VALID_AUTOGRAD_KEYS}"
690
+ )
691
+ if key not in used_dispatch_keys:
692
+ used_dispatch_keys.add(key)
693
+
694
+ (
695
+ derivatives,
696
+ forward_derivatives,
697
+ args_with_derivatives,
698
+ non_differentiable_arg_names,
699
+ available_named_gradients,
700
+ ) = set_up_derivatives(canonical)
701
+
702
+ used_named_gradients: set[str] = set()
703
+ for d in derivatives:
704
+ used_named_gradients |= d.named_gradients
705
+
706
+ # only assign an op name if we are actually going to calculate a derivative
707
+ op = None
708
+ if args_with_derivatives:
709
+ op_prefix = _create_op_prefix(defn_name)
710
+ if key != "Default":
711
+ op_prefix = op_prefix + key
712
+ op = f"{op_prefix}{op_counter[op_prefix]}"
713
+ op_counter[op_prefix] += 1
714
+
715
+ diffinfo_dict[key] = DifferentiabilityInfo(
716
+ name=defn_name,
717
+ func=canonical,
718
+ op=op,
719
+ derivatives=derivatives,
720
+ forward_derivatives=forward_derivatives,
721
+ all_saved_inputs=dedup_vars(
722
+ [v for d in derivatives for v in d.saved_inputs]
723
+ ),
724
+ all_saved_outputs=dedup_vars(
725
+ [v for d in derivatives for v in d.saved_outputs]
726
+ ),
727
+ available_named_gradients=available_named_gradients,
728
+ used_named_gradients=used_named_gradients,
729
+ args_with_derivatives=args_with_derivatives,
730
+ non_differentiable_arg_names=non_differentiable_arg_names,
731
+ output_differentiability=output_differentiability,
732
+ output_differentiability_conditions=output_differentiability_conditions,
733
+ )
734
+
735
+ return canonical.func, diffinfo_dict
736
+
737
+
738
+ GRAD_INDEX_REGEX = r"(?:^|\W)grads\[(\d+)\]"
739
+
740
+
741
+ def used_gradient_indices(formula: str) -> list[int]:
742
+ """Determine a list of gradient indices (the i in grads[i]) that
743
+ are used by the formula.
744
+
745
+ >>> used_gradient_indices("foo(grads[0], grads[1])")
746
+ [0, 1]
747
+ """
748
+ return [int(i) for i in re.findall(GRAD_INDEX_REGEX, formula)]
749
+
750
+
751
+ def saved_variables(
752
+ formula: str,
753
+ nctypes: list[NamedCType],
754
+ var_names: tuple[str, ...],
755
+ ) -> tuple[str, tuple[SavedAttribute, ...]]:
756
+ def stride_expr(name: str) -> str:
757
+ assert var_names == (name,), (
758
+ 'Replacement for ".strides()" is currently only supported for single derivatives of the same tensor '
759
+ 'that ".strides()" is being called on.'
760
+ )
761
+ return f'strides_or_error({name}, "{name}")'
762
+
763
+ REPLACEMENTS: list[tuple[str, dict[str, Any]]] = [
764
+ # replace self.sym_sizes() with self_sym_sizes
765
+ (
766
+ r"{}.sym_sizes\(\)",
767
+ {
768
+ "suffix": "_sym_sizes",
769
+ "nctype": lambda name: NamedCType(name, BaseCType(symIntArrayRefT)),
770
+ },
771
+ ),
772
+ # replace self->sym_sizes() with self_sym_sizes_opt
773
+ (
774
+ r"{}->sym_sizes\(\)",
775
+ {
776
+ "suffix": "_sym_sizes_opt",
777
+ "nctype": lambda name: NamedCType(
778
+ name, OptionalCType(BaseCType(symIntArrayRefT))
779
+ ),
780
+ "expr": lambda name: f"{name}.has_value() ? std::optional<c10::SymIntArrayRef>({name}->sym_sizes()) : std::nullopt",
781
+ },
782
+ ),
783
+ # replace self.sym_blocksize() with self_sym_blocksize_opt
784
+ (
785
+ r"{}.sym_blocksize\(\)",
786
+ {
787
+ "suffix": "_self_sym_blocksize_opt",
788
+ "nctype": lambda name: NamedCType(
789
+ name, OptionalCType(BaseCType(symIntArrayRefT))
790
+ ),
791
+ "expr": lambda name: f"at::sparse_csr::getSymIntBlockSize({name})",
792
+ },
793
+ ),
794
+ # replace self.options() with self_options
795
+ (
796
+ r"{}.options\(\)",
797
+ {
798
+ "suffix": "_options",
799
+ "nctype": lambda name: NamedCType(name, BaseCType(tensorOptionsT)),
800
+ },
801
+ ),
802
+ # replace zeros_like(self) with self_info
803
+ (
804
+ r"zeros_like\({}\)",
805
+ {
806
+ "suffix": "_info",
807
+ "nctype": lambda name: NamedCType(name, BaseCType(typeAndSizeT)),
808
+ "expr": lambda name: name, # at save-time
809
+ "res": lambda name: name + "_info.zeros()", # at eval-time
810
+ },
811
+ ),
812
+ # replace self.sym_size(2) with self_sym_size_2
813
+ (
814
+ r"{}.sym_size\((-?\w+)\)",
815
+ {
816
+ "suffix": lambda m: f"_sym_argsize_{m.groups()[0].replace('-', 'minus_')}",
817
+ "nctype": lambda name: NamedCType(name, BaseCType(SymIntT)),
818
+ },
819
+ ),
820
+ # replace self.numel() with self_numel
821
+ (
822
+ r"{}.numel\(\)",
823
+ {
824
+ "suffix": "_numel",
825
+ "nctype": lambda name: NamedCType(name, BaseCType(longT)),
826
+ },
827
+ ),
828
+ # replace self.sym_numel() with self_sym_numel
829
+ (
830
+ r"{}.sym_numel\(\)",
831
+ {
832
+ "suffix": "_sym_numel",
833
+ "nctype": lambda name: NamedCType(name, BaseCType(SymIntT)),
834
+ },
835
+ ),
836
+ # replace to_args_sizes(self) with self_args_sizes
837
+ (
838
+ r"to_args_sizes\({}\)",
839
+ {
840
+ "suffix": "_args_sizes",
841
+ "nctype": lambda name: NamedCType(
842
+ name, VectorCType(VectorCType(BaseCType(longT)))
843
+ ),
844
+ },
845
+ ),
846
+ # replace to_args_sizes_symint(self) with self_args_sizes
847
+ (
848
+ r"to_args_sizes_symint\({}\)",
849
+ {
850
+ "suffix": "_args_sizes_symint",
851
+ "nctype": lambda name: NamedCType(
852
+ name, VectorCType(VectorCType(BaseCType(SymIntT)))
853
+ ),
854
+ },
855
+ ),
856
+ # replace to_args_scalartypes(self) with self_args_scalartypes
857
+ (
858
+ r"to_args_scalartypes\({}\)",
859
+ {
860
+ "suffix": "_args_scalartypes",
861
+ "nctype": lambda name: NamedCType(
862
+ name, VectorCType(BaseCType(scalarTypeT))
863
+ ),
864
+ },
865
+ ),
866
+ # replace TensorGeometry(self) with self_geometry
867
+ (
868
+ r"TensorGeometry\({}\)",
869
+ {
870
+ "suffix": "_geometry",
871
+ "nctype": lambda name: NamedCType(name, BaseCType(tensorGeometryT)),
872
+ },
873
+ ),
874
+ (
875
+ r"{}.scalar_type\(\)",
876
+ {
877
+ "suffix": "_scalar_type",
878
+ "nctype": lambda name: NamedCType(name, BaseCType(scalarTypeT)),
879
+ },
880
+ ),
881
+ # replace self.dim() with self_dim
882
+ (
883
+ r"{}.dim\(\)",
884
+ {
885
+ "suffix": "_dim",
886
+ "nctype": lambda name: NamedCType(name, BaseCType(longT)),
887
+ },
888
+ ),
889
+ # replace self.sym_strides() with self_sym_strides
890
+ (
891
+ r"{}.sym_strides\(\)",
892
+ {
893
+ "suffix": "_sym_strides",
894
+ "nctype": lambda name: NamedCType(name, BaseCType(symIntArrayRefT)),
895
+ "expr": stride_expr,
896
+ },
897
+ ),
898
+ # replace self.layout() with self_layout
899
+ (
900
+ r"{}.layout\(\)",
901
+ {
902
+ "suffix": "_layout",
903
+ "nctype": lambda name: NamedCType(name, BaseCType(layoutT)),
904
+ },
905
+ ),
906
+ # replace self.is_conj() with self_conjugate
907
+ (
908
+ r"{}.is_conj\(\)",
909
+ {
910
+ "suffix": "_conjugate",
911
+ "nctype": lambda name: NamedCType(name, BaseCType(boolT)),
912
+ },
913
+ ),
914
+ ]
915
+
916
+ # find which arguments need to be saved
917
+ saved: list[SavedAttribute] = []
918
+
919
+ if ".sizes()" in formula or "->sizes()" in formula:
920
+ raise RuntimeError(
921
+ ".sizes() is not supported in derivative formulas. Instead, please use the SymInt version,"
922
+ + f".sym_sizes(), which returned a c10::SymIntArrayRef. formula={formula}"
923
+ )
924
+ if re.search(r"\.size\([-]?\d+\)", formula) or re.search(
925
+ r"->size\([-]?\d+\)", formula
926
+ ):
927
+ raise RuntimeError(
928
+ ".size(int) is not supported in derivative formulas. Instead, please use the SymInt version,"
929
+ + f".sym_size(int), which returned a c10::SymIntArrayRef. formula={formula}"
930
+ )
931
+ if ".strides()" in formula or "->strides()" in formula:
932
+ raise RuntimeError(
933
+ ".strides() is not supported in derivative formulas. Instead, please use the SymInt version,"
934
+ + f".sym_strides(), which returned a c10::SymIntArrayRef. formula={formula}"
935
+ )
936
+ for nctype in nctypes:
937
+ name = (
938
+ nctype.name.name if isinstance(nctype.name, SpecialArgName) else nctype.name
939
+ )
940
+ # First search the formula for expressions which can be evaluated
941
+ # when the autograd Function is created to avoid saving variables
942
+ for regex, info in REPLACEMENTS:
943
+
944
+ def repl(m: re.Match[str]) -> str:
945
+ suffix: str = (
946
+ info["suffix"](m) if callable(info["suffix"]) else info["suffix"]
947
+ )
948
+ expr: str = info["expr"](name) if "expr" in info else m.group(0)
949
+ saved.append(
950
+ SavedAttribute(
951
+ nctype=info["nctype"](name + suffix),
952
+ expr=expr,
953
+ )
954
+ )
955
+ if "res" in info:
956
+ replacement: str = info["res"](name)
957
+ return replacement
958
+ return name + suffix
959
+
960
+ formula = re.sub(regex.format(name), repl, formula)
961
+
962
+ # std::optional<std::string> types stored in Backward nodes must be
963
+ # converted to std::optional<std::string_view> before being passed into
964
+ # the backward function
965
+ if nctype.type == OptionalCType(BaseCType(stringT)):
966
+ formula = re.sub(
967
+ rf"\b{name}\b",
968
+ f"{name}.has_value() ? std::optional<c10::string_view>({name}.value()) : std::nullopt",
969
+ formula,
970
+ )
971
+
972
+ # Find any variables which remain in the formula and save them
973
+ if re.search(IDENT_REGEX.format(name), formula):
974
+ saved.append(
975
+ SavedAttribute(
976
+ nctype=nctype,
977
+ expr=name,
978
+ )
979
+ )
980
+
981
+ return formula, tuple(saved)
982
+
983
+
984
+ def _create_op_prefix(name: str) -> str:
985
+ """Takes a native function name converts to a op prefix name.
986
+
987
+ Note that the "name" parameter must be the native function name
988
+ without the optional variant suffix, so "add" instead of
989
+ "add.out".
990
+
991
+ OP names correspond to classes, hence the change to title case.
992
+
993
+ Example::
994
+ >>> _create_op_prefix('add')
995
+ 'AddBackward'
996
+ """
997
+ camel_case = "".join([p.title() for p in name.split("_")])
998
+ return (camel_case + "Backward").replace("ForwardBackward", "Backward")
999
+
1000
+
1001
+ def dedup_vars(vars: Sequence[SavedAttribute]) -> Sequence[SavedAttribute]:
1002
+ seen: set[str] = set()
1003
+ saved: list[SavedAttribute] = []
1004
+ for var in vars:
1005
+ name = (
1006
+ var.nctype.name.name
1007
+ if isinstance(var.nctype.name, SpecialArgName)
1008
+ else var.nctype.name
1009
+ )
1010
+ if name in seen:
1011
+ continue
1012
+ seen.add(name)
1013
+ saved.append(var)
1014
+ return saved
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/VariableType.cpp ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "torch/csrc/autograd/VariableTypeUtils.h"
2
+ #include "torch/csrc/autograd/generated/VariableType.h"
3
+ #include "torch/csrc/autograd/FunctionsManual.h"
4
+
5
+ #include <ATen/RedispatchFunctions.h>
6
+ #include <c10/core/impl/TorchDispatchModeTLS.h>
7
+ #include <ATen/core/TorchDispatchUtils.h>
8
+ #include <torch/library.h>
9
+
10
+ #include <ATen/SparseCsrTensorUtils.h>
11
+
12
+
13
+ // ${generated_comment}
14
+
15
+ // NOTE [Sharded File]: on this file's split-into-shards state
16
+ //
17
+ // Back in the good old days, VariableType.cpp was generated as one
18
+ // file with every function in it, and everything was great and
19
+ // simple.
20
+ //
21
+ // However, this file was also very large (over 36,000 lines), and
22
+ // compiling it was very slow, and in fact was a significant
23
+ // bottleneck for incremental rebuilds. To address this, we now
24
+ // generate the file split across multiple shards, named
25
+ // VariableType_0.cpp and so on, which can be compiled in parallel.
26
+ //
27
+ // For ease of inspection and debugging, so that it's not necessary to
28
+ // go rooting around in multiple files, we also generate all the
29
+ // functions together in VariableTypeEverything.cpp. This generated
30
+ // file is only for convenience; it's not actually used in the
31
+ // build. If the file you're looking at now is one of the shards, you
32
+ // may want to switch over to the Everything variant to make you
33
+ // grepping smoother.
34
+
35
+ using namespace at;
36
+ using namespace torch::autograd::generated;
37
+ using namespace torch::autograd::generated::details;
38
+
39
+
40
+ namespace torch::autograd {
41
+
42
+ namespace VariableType {
43
+ namespace{
44
+ C10_UNUSED void reset_grad_accumulator(Variable & self) {
45
+ AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self);
46
+ if (meta != nullptr) {
47
+ meta->grad_accumulator_.reset();
48
+ }
49
+ }
50
+ }
51
+
52
+ namespace {
53
+
54
+
55
+ ${type_derived_method_definitions}
56
+ }
57
+ }
58
+
59
+ namespace {
60
+
61
+ ${wrapper_registrations}
62
+
63
+ }
64
+
65
+ } // namespace torch::autograd
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.cpp ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <torch/csrc/autograd/generated/ViewFuncs.h>
2
+
3
+ // ${generated_comment}
4
+
5
+ using at::Tensor;
6
+ using at::Scalar;
7
+ using at::IntArrayRef;
8
+ using at::TensorList;
9
+
10
+ namespace torch::autograd::generated {
11
+
12
+ ${view_func_definitions}
13
+
14
+ } // namespace torch::autograd::generated
minigpt2/lib/python3.10/site-packages/torchgen/packaged/autograd/templates/ViewFuncs.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // ${generated_comment}
4
+
5
+ #include <torch/library.h>
6
+ #include <torch/csrc/autograd/variable.h>
7
+ #include <c10/core/SymIntArrayRef.h>
8
+
9
+ #ifndef AT_PER_OPERATOR_HEADERS
10
+ #include <ATen/Operators.h>
11
+ #else
12
+ $ops_headers
13
+ #endif
14
+
15
+ namespace torch::autograd::generated {
16
+
17
+ using at::Scalar;
18
+ using at::Tensor;
19
+ using at::IntArrayRef;
20
+ using at::ArrayRef;
21
+ using at::Type;
22
+ using at::ScalarType;
23
+ using std::optional;
24
+ using c10::fmap;
25
+
26
+ ${view_func_declarations}
27
+
28
+ } // namespace torch::autograd::generated
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Central ADDED
Binary file (1.29 kB). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Mountain ADDED
Binary file (970 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/Newfoundland ADDED
Binary file (1.88 kB). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Canada/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+0 ADDED
Binary file (111 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+2 ADDED
Binary file (113 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT+4 ADDED
Binary file (113 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-12 ADDED
Binary file (115 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-14 ADDED
Binary file (115 Bytes). View file
 
minigpt2/lib/python3.10/site-packages/tzdata/zoneinfo/Etc/GMT-6 ADDED
Binary file (114 Bytes). View file