jasonfan commited on
Commit
52c956c
·
verified ·
1 Parent(s): e20bd03

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. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/codegen.h +274 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h +103 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h +37 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h +291 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h +105 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h +330 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h +90 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h +498 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h +116 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h +30 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h +62 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h +130 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h +116 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h +217 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h +286 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h +27 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir.h +921 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h +67 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h +67 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_printer.h +137 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h +551 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h +59 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h +65 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/kernel.h +383 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h +148 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h +84 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h +622 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h +14 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h +50 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h +414 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h +106 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h +25 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h +99 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h +19 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h +15 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h +87 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h +154 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h +37 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h +18 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h +311 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h +431 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/stmt.h +1017 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h +326 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h +14 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/types.h +163 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h +38 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h +66 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/catch_utils.hpp +15 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h +84 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h +24 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/codegen.h ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ATen.h>
5
+ #include <torch/csrc/jit/tensorexpr/ir.h>
6
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
7
+
8
+ #include <utility>
9
+
10
+ namespace torch::jit::tensorexpr {
11
+
12
+ template <typename T>
13
+ class PaddedBuffer;
14
+
15
+ class TORCH_API CodeGen {
16
+ public:
17
+ class BufferArg;
18
+ class CallArg;
19
+
20
+ template <typename... Ts>
21
+ CodeGen(StmtPtr stmt, Ts... ts)
22
+ : stmt_(std::move(stmt)), buffer_args_({BufferArg(ts)...}) {}
23
+
24
+ CodeGen(
25
+ StmtPtr stmt,
26
+ std::vector<BufferArg> buffer_args,
27
+ at::Device device = at::kCPU,
28
+ std::string kernel_func_name = "func");
29
+
30
+ virtual ~CodeGen() = default;
31
+
32
+ StmtPtr stmt() const {
33
+ return stmt_;
34
+ }
35
+
36
+ void set_stmt(StmtPtr s) {
37
+ stmt_ = std::move(s);
38
+ }
39
+
40
+ void apply_mutator(IRMutator* mutator) {
41
+ stmt_ = stmt_->accept_mutator(mutator);
42
+ }
43
+
44
+ void apply_visitor(IRVisitor* visitor) {
45
+ stmt_->accept(visitor);
46
+ }
47
+
48
+ std::vector<BufferArg>& buffer_args() {
49
+ return buffer_args_;
50
+ }
51
+
52
+ const std::vector<BufferArg>& buffer_args() const {
53
+ return buffer_args_;
54
+ }
55
+
56
+ at::Device device() {
57
+ return device_;
58
+ }
59
+
60
+ // This function returns the generated code as
61
+ // a string.
62
+ virtual std::string getCodeText(
63
+ const std::string& attr [[maybe_unused]] = "") {
64
+ return "";
65
+ }
66
+
67
+ // TODO: Figure out how to unify these call interfaces.
68
+
69
+ /// Call a function with a vector of CallArgs, which are tagged
70
+ /// unions that properly type the arguments.
71
+ virtual void call(const std::vector<CallArg>& args) = 0;
72
+
73
+ /// Call a function faster than a regular `call` by assuming that
74
+ /// the generated kernel already knows the type of the arguments, so
75
+ /// they can be type-punned with `void*`s.
76
+ virtual void call_raw(const std::vector<void*>& args) = 0;
77
+
78
+ /// Call a function even faster than a regular call, by assuming
79
+ /// that the number of thread blocks can be derived from `numel` via
80
+ /// a simple division, rather than evaluating an expression.
81
+ virtual void call_with_numel(void** args, int64_t numel);
82
+
83
+ virtual at::Tensor empty_strided(
84
+ c10::IntArrayRef size,
85
+ c10::IntArrayRef stride,
86
+ std::optional<c10::ScalarType> dtype_opt,
87
+ std::optional<c10::Layout> layout_opt,
88
+ std::optional<c10::Device> device_opt,
89
+ std::optional<bool> pin_memory_opt) {
90
+ return at::empty_strided(
91
+ size, stride, dtype_opt, layout_opt, device_opt, pin_memory_opt);
92
+ }
93
+
94
+ const std::string& kernel_func_name() const {
95
+ return kernel_func_name_;
96
+ }
97
+
98
+ void allocIntermediateBufs();
99
+
100
+ protected:
101
+ static void* argToPtr(const BufferArg& bufferArg, const CallArg& callArg);
102
+
103
+ private:
104
+ StmtPtr stmt_;
105
+ std::vector<BufferArg> buffer_args_;
106
+ at::Device device_ = at::kCPU;
107
+ std::string kernel_func_name_ = "func";
108
+ };
109
+
110
+ class TORCH_API ExtCallMemoryReuse : public IRMutator {
111
+ static std::unordered_map<std::string, std::string> makeExtCallFuncNameMap();
112
+ static const std::unordered_map<std::string, std::string> extCallFuncNameMap_;
113
+
114
+ public:
115
+ explicit ExtCallMemoryReuse(
116
+ const std::vector<CodeGen::BufferArg>& bufferArgs);
117
+ ~ExtCallMemoryReuse() override = default;
118
+ StmtPtr mutate(const ExternalCallPtr& v) override;
119
+
120
+ private:
121
+ std::unordered_set<BufPtr> bufferArgs_;
122
+ };
123
+
124
+ class CodeGen::BufferArg {
125
+ public:
126
+ BufferArg(const Tensor& tensor) : buf_(tensor.buf()) {}
127
+ BufferArg(const VarHandle& var) : var_(var.node()), isVar_(true) {}
128
+ BufferArg(const BufHandle& buf) : buf_(buf.node()) {}
129
+ BufferArg(BufPtr buf) : buf_(std::move(buf)) {}
130
+
131
+ VarPtr var() const {
132
+ return isVar_ ? var_ : buf_->base_handle();
133
+ }
134
+
135
+ BufPtr buf() const {
136
+ return buf_;
137
+ }
138
+
139
+ bool isVar() const {
140
+ return isVar_;
141
+ }
142
+
143
+ Dtype dtype() const {
144
+ return isVar_ ? var_->dtype() : buf_->dtype();
145
+ }
146
+
147
+ private:
148
+ VarPtr var_ = nullptr;
149
+ BufPtr buf_ = nullptr;
150
+ bool isVar_ = false;
151
+ };
152
+
153
+ class CodeGen::CallArg {
154
+ public:
155
+ template <typename T>
156
+ CallArg(const PaddedBuffer<T>& buffer);
157
+
158
+ template <typename T>
159
+ CallArg(const std::vector<T>& buffer)
160
+ : data_(const_cast<T*>(buffer.data())) {}
161
+
162
+ CallArg(void* ptr) : data_(ptr) {}
163
+
164
+ #define ARG_TYPE_CTOR(Type, Name) \
165
+ CallArg(Type v) { \
166
+ memcpy(buffer_, &v, sizeof(Type)); \
167
+ data_ = (void*)buffer_; \
168
+ }
169
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, ARG_TYPE_CTOR)
170
+ #undef ARG_TYPE_CTOR
171
+
172
+ void* data() const {
173
+ return data_;
174
+ }
175
+
176
+ CallArg(const CallArg& rhs) {
177
+ if (rhs.data_ == rhs.buffer_) {
178
+ memcpy(this->buffer_, rhs.buffer_, sizeof(rhs.buffer_));
179
+ this->data_ = (void*)(this->buffer_);
180
+ } else {
181
+ this->data_ = rhs.data_;
182
+ }
183
+ }
184
+
185
+ CallArg& operator=(const CallArg& rhs) {
186
+ if (this == &rhs) {
187
+ return *this;
188
+ }
189
+ if (rhs.data_ == rhs.buffer_) {
190
+ memcpy(this->buffer_, rhs.buffer_, sizeof(rhs.buffer_));
191
+ this->data_ = (void*)(this->buffer_);
192
+ } else {
193
+ this->data_ = rhs.data_;
194
+ }
195
+ return *this;
196
+ }
197
+
198
+ #define ARG_PTR_DEFINE(Type, Name) \
199
+ Type* Name##Ptr() const { \
200
+ TORCH_INTERNAL_ASSERT(data_ == (void*)buffer_); \
201
+ return (Type*)data_; \
202
+ }
203
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, ARG_PTR_DEFINE)
204
+ #undef ARG_PTR_DEFINE
205
+
206
+ private:
207
+ void* data_;
208
+ // Regarding a scalar value, CallArg uses void**=&data_ to store it. But the
209
+ // bit width of a pointer is 32bit on a 32bit platform. It cannot store the
210
+ // scalar if the bit width of the scalar is larger than 32bit, such as double
211
+ // and long. Hence, we add 8 bytes buffer dedicated to storing the scalar
212
+ // value regardless its bit width is less or greater than 32bits.
213
+ char buffer_[8] = {0}; // 64bits
214
+ };
215
+
216
+ class RegisterCodeGenList {
217
+ public:
218
+ TORCH_API static RegisterCodeGenList& GetInstance();
219
+
220
+ using StmtFactoryMethod = std::function<std::unique_ptr<CodeGen>(
221
+ StmtPtr stmt,
222
+ const std::vector<CodeGen::BufferArg>&,
223
+ at::Device device,
224
+ const std::string& kernel_func_name)>;
225
+
226
+ TORCH_API StmtFactoryMethod FindStmtFactoryMethod(const std::string& name);
227
+ RegisterCodeGenList(const RegisterCodeGenList&) = delete;
228
+ RegisterCodeGenList& operator=(const RegisterCodeGenList&) = delete;
229
+
230
+ private:
231
+ template <class CodeGenType>
232
+ friend class RegisterCodeGen;
233
+ RegisterCodeGenList() = default;
234
+ TORCH_API void AddStmtFactoryMethod(
235
+ const std::string& name,
236
+ const StmtFactoryMethod& stmt_factory_method);
237
+
238
+ std::unordered_map<std::string, StmtFactoryMethod> stmt_factory_methods_;
239
+ };
240
+
241
+ template <class CodeGenType>
242
+ class RegisterCodeGen {
243
+ public:
244
+ explicit RegisterCodeGen(const std::string& name) {
245
+ RegisterCodeGenList& codegen_list = RegisterCodeGenList::GetInstance();
246
+ codegen_list.AddStmtFactoryMethod(
247
+ name,
248
+ [](const StmtPtr& stmt,
249
+ const std::vector<CodeGen::BufferArg>& params,
250
+ at::Device device,
251
+ const std::string& kernel_func_name) {
252
+ return std::make_unique<CodeGenType>(
253
+ stmt, params, device, kernel_func_name);
254
+ });
255
+ }
256
+ };
257
+
258
+ TORCH_API std::unique_ptr<CodeGen> CreateCodeGen(
259
+ const std::string& name,
260
+ StmtPtr stmt,
261
+ const std::vector<CodeGen::BufferArg>& params,
262
+ at::Device device = at::kCPU,
263
+ const std::string& kernel_func_name = "func");
264
+
265
+ class TORCH_API GenericIntrinsicsExpander : public IRMutator {
266
+ protected:
267
+ ExprPtr mutate(const IntrinsicsPtr& v) override;
268
+ };
269
+
270
+ } // namespace torch::jit::tensorexpr
271
+
272
+ #else
273
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
274
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_codegen.h ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
5
+ #include <torch/csrc/jit/tensorexpr/ir_printer.h>
6
+
7
+ namespace torch::jit::tensorexpr {
8
+
9
+ class CppVarNameRewriter;
10
+
11
+ // Generates C++ code from the IR.
12
+ //
13
+ // Vector operations are unrolled.
14
+ // For example:
15
+ // C[Ramp(0, 1, 3)] = A[Ramp(0, 2, 3)] + B[Ramp(0, 3, 3)];
16
+ // is unrolled into:
17
+ // C[0] = A[0] + B[0];
18
+ // C[1] = A[2] + B[3];
19
+ // C[2] = A[4] + B[6];
20
+ class TORCH_API CppPrinter : public IRPrinter {
21
+ public:
22
+ explicit CppPrinter(std::ostream* os);
23
+ ~CppPrinter() override;
24
+
25
+ void printPrologue();
26
+
27
+ using IRPrinter::visit;
28
+
29
+ // Binary expressions.
30
+ void visit(const ModPtr& /*v*/) override;
31
+ void visit(const MaxPtr& /*v*/) override;
32
+ void visit(const MinPtr& /*v*/) override;
33
+
34
+ // Conditional expressions.
35
+ void visit(const CompareSelectPtr& /*v*/) override;
36
+ void visit(const IfThenElsePtr& /*v*/) override;
37
+
38
+ // Tensor operations.
39
+ void visit(const AllocatePtr& /*v*/) override;
40
+ void visit(const FreePtr& /*v*/) override;
41
+ void visit(const LoadPtr& /*v*/) override;
42
+ void visit(const StorePtr& /*v*/) override;
43
+
44
+ // Casts.
45
+ void visit(const CastPtr& /*v*/) override;
46
+ void visit(const BitCastPtr& /*v*/) override;
47
+
48
+ // Calls.
49
+ void visit(const IntrinsicsPtr& /*v*/) override;
50
+ void visit(const ExternalCallPtr& /*v*/) override;
51
+
52
+ // Vars.
53
+ void visit(const LetPtr& /*v*/) override;
54
+ void visit(const VarPtr& /*v*/) override;
55
+
56
+ // Vector data types.
57
+ void visit(const RampPtr& /*v*/) override;
58
+ void visit(const BroadcastPtr& /*v*/) override;
59
+
60
+ private:
61
+ int lane_;
62
+ std::unordered_map<VarPtr, ExprPtr> vector_vars_;
63
+ };
64
+
65
+ class TORCH_API CppCodeGen : public CodeGen {
66
+ public:
67
+ CppCodeGen(
68
+ StmtPtr stmt,
69
+ const std::vector<BufferArg>& buffer_args,
70
+ at::Device device = at::kCPU,
71
+ const std::string& kernel_func_name = "func");
72
+
73
+ ~CppCodeGen() override;
74
+
75
+ void call(const std::vector<CallArg>& args) override;
76
+ void call_raw(const std::vector<void*>& args) override;
77
+
78
+ template <typename... Ts>
79
+ void operator()(const Ts&... ts) {
80
+ call(std::vector<CallArg>({CallArg(ts)...}));
81
+ }
82
+
83
+ std::string getCodeText(const std::string& attr = "") override {
84
+ return oss_.str();
85
+ }
86
+
87
+ private:
88
+ void init();
89
+
90
+ std::ostream& os() {
91
+ return printer_->os();
92
+ }
93
+
94
+ std::ostringstream oss_;
95
+ std::unique_ptr<CppPrinter> printer_;
96
+ std::unique_ptr<CppVarNameRewriter> var_name_rewriter_;
97
+ };
98
+
99
+ } // namespace torch::jit::tensorexpr
100
+
101
+ #else
102
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
103
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cpp_intrinsics.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace torch::jit::tensorexpr {
5
+
6
+ constexpr auto cpp_intrinsics_definition = R"(
7
+ namespace std {
8
+
9
+ template <typename T,
10
+ std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
11
+ T rsqrt(T v) {
12
+ return 1.0f / std::sqrt(v);
13
+ }
14
+
15
+ template <typename T,
16
+ std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
17
+ T frac(T v) {
18
+ T intpart;
19
+ return std::modf(v, &intpart);
20
+ }
21
+
22
+ template <typename From, typename To>
23
+ To bitcast(const From& v) {
24
+ assert(sizeof(To) == sizeof(From));
25
+ To res;
26
+ std::memcpy(&res, &v, sizeof(From));
27
+ return res;
28
+ }
29
+
30
+ } // namespace std
31
+ )";
32
+
33
+ } // namespace torch::jit::tensorexpr
34
+
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_codegen.h ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <unordered_set>
5
+
6
+ #include <ATen/ATen.h>
7
+ #include <ATen/cuda/CUDAContext.h>
8
+ #include <ATen/cuda/nvrtc_stub/ATenNVRTC.h>
9
+ #include <c10/cuda/CUDACachingAllocator.h>
10
+ #include <c10/cuda/CUDAGuard.h>
11
+ #include <torch/csrc/jit/resource_guard.h>
12
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
13
+ #include <torch/csrc/jit/tensorexpr/eval.h>
14
+ #include <torch/csrc/jit/tensorexpr/ir.h>
15
+ #include <torch/csrc/jit/tensorexpr/ir_printer.h>
16
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
17
+ #include <torch/csrc/jit/tensorexpr/llvm_codegen.h>
18
+ #include <torch/csrc/jit/tensorexpr/unique_name_manager.h>
19
+
20
+ namespace torch::jit::tensorexpr {
21
+
22
+ // A class that analyzes the given program relevant for Cuda backends.
23
+ class CudaAnalysis : public IRVisitor {
24
+ public:
25
+ CudaAnalysis() {
26
+ gpu_block_extents_ = {alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
27
+ gpu_thread_extents_ = {
28
+ alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
29
+ }
30
+ bool is_buf_store_target(const BufPtr& buf) const {
31
+ return store_targets_.count(buf) > 0;
32
+ }
33
+
34
+ const std::unordered_set<VarPtr>& thread_local_bufs() const {
35
+ return thread_local_bufs_;
36
+ }
37
+
38
+ const std::unordered_set<VarPtr>& cross_block_bufs() const {
39
+ return cross_block_bufs_;
40
+ }
41
+
42
+ const std::vector<ExprPtr>& gpu_block_extents() const {
43
+ return gpu_block_extents_;
44
+ }
45
+
46
+ const std::vector<ExprPtr>& gpu_thread_extents() const {
47
+ return gpu_thread_extents_;
48
+ }
49
+
50
+ private:
51
+ void visit(const StorePtr& v) override {
52
+ store_targets_.insert(v->buf());
53
+ }
54
+
55
+ void visit(const AllocatePtr& v) override;
56
+ void visit(const FreePtr& v) override;
57
+ void visit(const PlacementAllocatePtr& v) override;
58
+ void visit(const ForPtr& v) override;
59
+
60
+ std::unordered_set<BufPtr> store_targets_;
61
+ std::unordered_set<VarPtr> thread_local_bufs_;
62
+ std::unordered_set<VarPtr> cross_block_bufs_;
63
+
64
+ std::vector<ExprPtr> gpu_block_extents_;
65
+ std::vector<ExprPtr> gpu_thread_extents_;
66
+ };
67
+
68
+ // An IRMutator that replaces binding loop options with Cuda metavars, and masks
69
+ // statements blocks which should execute with less reach than the launch
70
+ // parameter extent.
71
+ //
72
+ // We do this by segmenting each block into chunks which should have the same
73
+ // execution parameters, then if those params differ from the max mask each dim.
74
+ class GPUMetaVarRewriter : public IRMutator {
75
+ public:
76
+ explicit GPUMetaVarRewriter(const CudaAnalysis* cuda_analysis)
77
+ : cuda_analysis_(cuda_analysis) {
78
+ gpu_block_vars_ = {
79
+ alloc<Var>("blockIdx.x", kInt),
80
+ alloc<Var>("blockIdx.y", kInt),
81
+ alloc<Var>("blockIdx.z", kInt)};
82
+ gpu_thread_vars_ = {
83
+ alloc<Var>("threadIdx.x", kInt),
84
+ alloc<Var>("threadIdx.y", kInt),
85
+ alloc<Var>("threadIdx.z", kInt)};
86
+
87
+ current_block_reach_ = {
88
+ alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
89
+ current_thread_reach_ = {
90
+ alloc<IntImm>(1), alloc<IntImm>(1), alloc<IntImm>(1)};
91
+ }
92
+
93
+ StmtPtr mutate(const ForPtr& v) override;
94
+ StmtPtr mutate(const BlockPtr& v) override;
95
+
96
+ const std::vector<VarPtr>& gpu_block_vars() const {
97
+ return gpu_block_vars_;
98
+ }
99
+
100
+ const std::vector<VarPtr>& gpu_thread_vars() const {
101
+ return gpu_thread_vars_;
102
+ }
103
+
104
+ const std::vector<ExprPtr>& gpu_block_extents() const {
105
+ return cuda_analysis_->gpu_block_extents();
106
+ }
107
+
108
+ const std::vector<ExprPtr>& gpu_thread_extents() const {
109
+ return cuda_analysis_->gpu_thread_extents();
110
+ }
111
+
112
+ private:
113
+ // When processing a block, stores the contents of each sub-segment.
114
+ class Segment {
115
+ public:
116
+ void reset(bool mask) {
117
+ stmts_.clear();
118
+ mask_ = mask;
119
+ }
120
+
121
+ bool empty() const {
122
+ return stmts_.empty();
123
+ }
124
+
125
+ std::vector<StmtPtr>& stmts() {
126
+ return stmts_;
127
+ }
128
+ bool mask() {
129
+ return mask_;
130
+ }
131
+
132
+ private:
133
+ std::vector<StmtPtr> stmts_;
134
+ bool mask_{true};
135
+ };
136
+
137
+ // Returns true if the current execution scope is equivalent to the launch
138
+ // parameters.
139
+ bool isFullExtent();
140
+
141
+ std::vector<VarPtr> gpu_block_vars_;
142
+ std::vector<VarPtr> gpu_thread_vars_;
143
+
144
+ std::vector<ExprPtr> current_block_reach_;
145
+ std::vector<ExprPtr> current_thread_reach_;
146
+
147
+ const CudaAnalysis* cuda_analysis_;
148
+ };
149
+
150
+ // A class that overrides the underlying IRPrinter to produce Cuda C.
151
+ class CudaPrinter : public IRPrinter {
152
+ public:
153
+ explicit CudaPrinter(
154
+ std::ostream* os,
155
+ const CudaAnalysis* cuda_analysis,
156
+ bool has_random)
157
+ : IRPrinter(*os), cuda_analysis_(cuda_analysis) {
158
+ if (has_random) {
159
+ rand_func_ = alloc<Var>("rand", kHandle);
160
+ }
161
+ }
162
+
163
+ void visit(const CastPtr& v) override;
164
+ void visit(const IntrinsicsPtr& v) override;
165
+ void visit(const ForPtr& v) override;
166
+
167
+ void visit(const LoadPtr& v) override;
168
+ void visit(const StorePtr& v) override;
169
+ void visit(const AtomicAddPtr& v) override;
170
+ void visit(const MaxPtr& v) override;
171
+ void visit(const MinPtr& v) override;
172
+ void visit(const IfThenElsePtr& v) override;
173
+ void visit(const BlockPtr& v) override;
174
+ void visit(const AllocatePtr& v) override;
175
+ void visit(const FreePtr& v) override;
176
+ void visit(const LetPtr& v) override;
177
+
178
+ void visit(const ExternalCallPtr& v) override;
179
+
180
+ VarPtr rand_func() const {
181
+ return rand_func_;
182
+ }
183
+
184
+ std::string dtypeToCppString(const Dtype& dtype) override;
185
+
186
+ using IRPrinter::name_manager;
187
+ using IRPrinter::visit;
188
+
189
+ private:
190
+ VarPtr rand_func_;
191
+ const CudaAnalysis* cuda_analysis_;
192
+
193
+ void print_flat_alloc(const AllocatePtr& alloc);
194
+ };
195
+
196
+ // Construct Cuda C from the buffer and tensor input, and invoke the
197
+ // kernel when real arguments are provided.
198
+ class TORCH_CUDA_CU_API CudaCodeGen : public CodeGen {
199
+ public:
200
+ template <typename... Ts>
201
+ CudaCodeGen(StmtPtr stmt, Ts... ts)
202
+ : CodeGen(
203
+ stmt,
204
+ std::vector<BufferArg>({BufferArg(ts)...}),
205
+ at::Device(at::kCUDA, at::cuda::current_device())) {
206
+ Initialize();
207
+ }
208
+
209
+ CudaCodeGen(
210
+ StmtPtr stmt,
211
+ const std::vector<BufferArg>& buffer_args,
212
+ at::Device device = at::Device(at::kCUDA, at::cuda::current_device()),
213
+ const std::string& kernel_func_name = "func")
214
+ : CodeGen(std::move(stmt), buffer_args, device, kernel_func_name) {
215
+ Initialize();
216
+ }
217
+
218
+ ~CudaCodeGen() override;
219
+
220
+ void call(const std::vector<CallArg>& args) override;
221
+ void call_raw(const std::vector<void*>& args) override;
222
+ void call_with_numel(void** args, int64_t numel) override;
223
+
224
+ template <typename... Ts>
225
+ void operator()(const Ts&... ts) {
226
+ call(std::vector<CallArg>({CallArg(ts)...}));
227
+ }
228
+
229
+ at::Tensor empty_strided(
230
+ c10::IntArrayRef size,
231
+ c10::IntArrayRef stride,
232
+ std::optional<c10::ScalarType> dtype_opt,
233
+ std::optional<c10::Layout> layout_opt,
234
+ std::optional<c10::Device> device_opt,
235
+ std::optional<bool> pin_memory_opt) override;
236
+
237
+ const std::vector<ExprPtr>& gpu_block_extents() const {
238
+ return cuda_analysis_->gpu_block_extents();
239
+ }
240
+
241
+ const std::vector<ExprPtr>& gpu_thread_extents() const {
242
+ return cuda_analysis_->gpu_thread_extents();
243
+ }
244
+
245
+ std::string getCodeText(const std::string& attr = "") override {
246
+ return oss_.str();
247
+ }
248
+
249
+ private:
250
+ void Initialize();
251
+
252
+ void CompileToNVRTC(const std::string& code, const std::string& func_name);
253
+
254
+ UniqueNameManager* name_manager() {
255
+ if (!printer_) {
256
+ throw std::runtime_error("Null IRPrinter is not expected");
257
+ }
258
+ return printer_->name_manager();
259
+ }
260
+
261
+ std::ostream& os() {
262
+ return printer_->os();
263
+ }
264
+
265
+ std::ostringstream oss_;
266
+ std::unique_ptr<CudaPrinter> printer_;
267
+ std::unique_ptr<CudaAnalysis> cuda_analysis_;
268
+ std::unique_ptr<GPUMetaVarRewriter> metavar_rewriter_;
269
+ std::unordered_set<std::string> taken_func_names;
270
+ std::mutex eval_lock_;
271
+ CUfunction function_{nullptr};
272
+ bool has_random_ = false;
273
+ int thread_block_size_ = -1;
274
+
275
+ std::vector<bool> arg_pos_in_extents_;
276
+ #ifdef TORCH_ENABLE_LLVM
277
+ std::vector<ExprEval<LLVMCodeGen>> block_extents_eval_;
278
+ std::vector<ExprEval<LLVMCodeGen>> thread_extents_eval_;
279
+ #else
280
+ std::vector<ExprEval<SimpleIREvaluator>> block_extents_eval_;
281
+ std::vector<ExprEval<SimpleIREvaluator>> thread_extents_eval_;
282
+ #endif
283
+
284
+ std::string GetUniqueFuncName(const std::string& func_prefix);
285
+ };
286
+
287
+ } // namespace torch::jit::tensorexpr
288
+
289
+ #else
290
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
291
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/cuda_random.h ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace torch::jit::tensorexpr {
5
+
6
+ constexpr auto philox_random_string = R"(
7
+
8
+ class Philox {
9
+ public:
10
+ __device__ inline Philox(unsigned long long seed,
11
+ unsigned long long subsequence,
12
+ unsigned long long offset) {
13
+ key.x = (unsigned int)seed;
14
+ key.y = (unsigned int)(seed >> 32);
15
+ counter = make_uint4(0, 0, 0, 0);
16
+ counter.z = (unsigned int)(subsequence);
17
+ counter.w = (unsigned int)(subsequence >> 32);
18
+ STATE = 0;
19
+ incr_n(offset / 4);
20
+ }
21
+
22
+ __device__ inline unsigned long operator()() {
23
+ if(STATE == 0) {
24
+ uint4 counter_ = counter;
25
+ uint2 key_ = key;
26
+ for(int i = 0; i < 9; i++) {
27
+ counter_ = single_round(counter_, key_);
28
+ key_.x += (kPhilox10A); key_.y += (kPhilox10B);
29
+ }
30
+ output = single_round(counter_, key_);
31
+ incr();
32
+ }
33
+ unsigned long ret;
34
+ switch(STATE) {
35
+ case 0: ret = output.x; break;
36
+ case 1: ret = output.y; break;
37
+ case 2: ret = output.z; break;
38
+ case 3: ret = output.w; break;
39
+ }
40
+ STATE = (STATE + 1) % 4;
41
+ return ret;
42
+ }
43
+
44
+ private:
45
+ uint4 counter;
46
+ uint4 output;
47
+ uint2 key;
48
+ unsigned int STATE;
49
+ __device__ inline void incr_n(unsigned long long n) {
50
+ unsigned int nlo = (unsigned int)(n);
51
+ unsigned int nhi = (unsigned int)(n >> 32);
52
+ counter.x += nlo;
53
+ if (counter.x < nlo)
54
+ nhi++;
55
+ counter.y += nhi;
56
+ if (nhi <= counter.y)
57
+ return;
58
+ if (++counter.z)
59
+ return;
60
+ ++counter.w;
61
+ }
62
+ __device__ inline void incr() {
63
+ if (++counter.x)
64
+ return;
65
+ if (++counter.y)
66
+ return;
67
+ if (++counter.z)
68
+ return;
69
+ ++counter.w;
70
+ }
71
+ __device__ unsigned int mulhilo32(unsigned int a, unsigned int b,
72
+ unsigned int *result_high) {
73
+ *result_high = __umulhi(a, b);
74
+ return a*b;
75
+ }
76
+
77
+ __device__ inline uint4 single_round(uint4 ctr, uint2 key) {
78
+ unsigned int hi0;
79
+ unsigned int hi1;
80
+ unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0);
81
+ unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1);
82
+
83
+ uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0};
84
+ return ret;
85
+ }
86
+
87
+ static const unsigned long kPhilox10A = 0x9E3779B9;
88
+ static const unsigned long kPhilox10B = 0xBB67AE85;
89
+ static const unsigned long kPhiloxSA = 0xD2511F53;
90
+ static const unsigned long kPhiloxSB = 0xCD9E8D57;
91
+ };
92
+
93
+ // Inverse of 2^32.
94
+ #define M_RAN_INVM32 2.3283064e-10f
95
+ __device__ __inline__ float Uint32ToFloat(unsigned int x) {
96
+ return x * M_RAN_INVM32;
97
+ }
98
+
99
+ )";
100
+
101
+ } // namespace torch::jit::tensorexpr
102
+
103
+ #else
104
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
105
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/eval.h ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cmath>
5
+ #include <cstring>
6
+ #include <utility>
7
+ #include <vector>
8
+
9
+ #include <c10/macros/Macros.h>
10
+ #include <c10/util/Logging.h>
11
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
12
+ #include <torch/csrc/jit/tensorexpr/exceptions.h>
13
+ #include <torch/csrc/jit/tensorexpr/ir.h>
14
+ #include <torch/csrc/jit/tensorexpr/ir_printer.h>
15
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
16
+ #include <torch/csrc/jit/tensorexpr/types.h>
17
+ #include <torch/csrc/jit/tensorexpr/var_substitutor.h>
18
+
19
+ namespace torch::jit::tensorexpr {
20
+
21
+ class InterpValue {
22
+ public:
23
+ InterpValue() : dtype_(kInt) {
24
+ Intvalues.push_back(0);
25
+ }
26
+
27
+ template <typename T>
28
+ InterpValue(Dtype dtype, T v) : dtype_(dtype) {
29
+ #define TYPE_CASE(Type, Name) \
30
+ if (dtype == k##Name) { \
31
+ Name##values.push_back(v); \
32
+ return; \
33
+ }
34
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE)
35
+ #undef TYPE_CASE
36
+ throw unsupported_dtype();
37
+ }
38
+
39
+ #define VALUE_CTOR(Type, Name) \
40
+ InterpValue(Type v) : dtype_(k##Name) { \
41
+ Name##values.push_back(v); \
42
+ }
43
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_CTOR)
44
+ #undef VALUE_CTOR
45
+
46
+ explicit InterpValue(c10::quint8 v) : dtype_(kQUInt8) {
47
+ QUInt8values.emplace_back(v.val_);
48
+ }
49
+
50
+ explicit InterpValue(c10::qint8 v) : dtype_(kQInt8) {
51
+ QInt8values.emplace_back(v.val_);
52
+ }
53
+
54
+ #define VALUE_VEC_CTOR(Type, Name) \
55
+ InterpValue(const std::vector<Type>& v) \
56
+ : dtype_(Dtype(k##Name, v.size())), Name##values(v) {}
57
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_VEC_CTOR)
58
+ VALUE_VEC_CTOR(c10::quint8, QUInt8)
59
+ VALUE_VEC_CTOR(c10::qint8, QInt8)
60
+ #undef VALUE_VEC_CTOR
61
+
62
+ template <typename T>
63
+ T as() const;
64
+
65
+ template <typename T>
66
+ const std::vector<T>& as_vec() const;
67
+
68
+ int64_t intValue() const;
69
+
70
+ Dtype dtype() const {
71
+ return dtype_;
72
+ }
73
+
74
+ private:
75
+ Dtype dtype_;
76
+
77
+ #define VALUE_STORAGE(Type, Name) std::vector<Type> Name##values;
78
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_STORAGE)
79
+ VALUE_STORAGE(c10::qint8, QInt8)
80
+ VALUE_STORAGE(c10::quint8, QUInt8)
81
+ #undef VALUE_STORAGE
82
+ void* ptr{nullptr};
83
+ };
84
+
85
+ #define VALUE_AS_DISPATCH(Type, Name) \
86
+ template <> \
87
+ inline Type InterpValue::as<Type>() const { \
88
+ if (dtype_ != k##Name) { \
89
+ throw unsupported_dtype(); \
90
+ } \
91
+ return Name##values[0]; \
92
+ }
93
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_AS_DISPATCH)
94
+ VALUE_AS_DISPATCH(c10::quint8, QUInt8)
95
+ VALUE_AS_DISPATCH(c10::qint8, QInt8)
96
+ #undef VALUE_AS_DISPATCH
97
+
98
+ #define VALUE_AS_VEC_DISPATCH(Type, Name) \
99
+ template <> \
100
+ inline const std::vector<Type>& InterpValue::as_vec<Type>() const { \
101
+ if (dtype_.scalar_type() != ScalarType::Name) { \
102
+ throw unsupported_dtype(); \
103
+ } \
104
+ return Name##values; \
105
+ }
106
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, VALUE_AS_VEC_DISPATCH)
107
+ VALUE_AS_VEC_DISPATCH(c10::quint8, QUInt8)
108
+ VALUE_AS_VEC_DISPATCH(c10::qint8, QInt8)
109
+ #undef VALUE_AS_VEC_DISPATCH
110
+
111
+ template <typename Type>
112
+ auto underlyingValue(Type x) {
113
+ return x;
114
+ }
115
+
116
+ template <>
117
+ inline auto underlyingValue<c10::quint8>(c10::quint8 x) {
118
+ return x.val_;
119
+ }
120
+
121
+ template <>
122
+ inline auto underlyingValue<c10::qint8>(c10::qint8 x) {
123
+ return x.val_;
124
+ }
125
+
126
+ template <typename To, typename From>
127
+ To raw_bitcast(const From& src) {
128
+ TORCH_CHECK(sizeof(To) == sizeof(From), "Invalid bitcast invocation");
129
+ To storage;
130
+ std::memcpy(&storage, &src, sizeof(To));
131
+ return storage;
132
+ }
133
+
134
+ class SimpleIREvaluatorImpl;
135
+ class TORCH_API SimpleIREvaluator : public CodeGen {
136
+ public:
137
+ SimpleIREvaluator(
138
+ StmtPtr stmt,
139
+ const std::vector<BufferArg>& buffer_args,
140
+ at::Device device = at::kCPU,
141
+ const std::string& kernel_func_name = "func");
142
+
143
+ ~SimpleIREvaluator() override;
144
+
145
+ void call(const std::vector<CallArg>& args) override;
146
+ void call_raw(const std::vector<void*>& args) override;
147
+
148
+ template <typename... Ts>
149
+ void operator()(const Ts&... ts) {
150
+ std::vector<CallArg> args({CallArg(ts)...});
151
+ call(args);
152
+ }
153
+
154
+ void bindVar(const VarPtr& v, const ExprPtr& e);
155
+ InterpValue value() const;
156
+
157
+ private:
158
+ void bindArg(const BufferArg& buf, void* data);
159
+ void expand_intrinsics() {
160
+ GenericIntrinsicsExpander intrinsics_expander;
161
+ apply_mutator(&intrinsics_expander);
162
+ }
163
+
164
+ std::unique_ptr<SimpleIREvaluatorImpl> impl_;
165
+ };
166
+
167
+ template <class CodeGenType>
168
+ class ExprEval {
169
+ public:
170
+ using BufferArg = CodeGen::BufferArg;
171
+ using CallArg = CodeGen::CallArg;
172
+
173
+ template <typename... Ts>
174
+ ExprEval(const ExprHandle& expr, Ts... ts)
175
+ : ExprEval(expr, {BufferArg(ts)...}) {}
176
+
177
+ ExprEval(const ExprHandle& expr, const std::vector<BufferArg>& buffer_args)
178
+ : dtype_(expr.dtype()) {
179
+ std::vector<BufferArg> buffer_args_extended = buffer_args;
180
+ BufHandle ret_buf("ret_val", {1}, dtype_);
181
+ std::vector<ExprHandle> indices;
182
+ ExprHandle zero = IntImm::make(0);
183
+ indices.reserve(ret_buf.ndim());
184
+ for (size_t i = 0; i < ret_buf.ndim(); i++) {
185
+ indices.push_back(zero);
186
+ }
187
+ StmtPtr store_stmt = Store::make(ret_buf, indices, expr);
188
+ buffer_args_extended.emplace_back(ret_buf);
189
+ codegen_.reset(new CodeGenType(store_stmt, buffer_args_extended));
190
+ }
191
+
192
+ template <typename... Ts>
193
+ void operator()(Ts... ts) {
194
+ call(ts...);
195
+ }
196
+
197
+ void operator()(const std::vector<CallArg>& call_args) {
198
+ call(call_args);
199
+ }
200
+
201
+ void bindVar(VarPtr v, ExprPtr e) {
202
+ codegen_->bindVar(v, e);
203
+ }
204
+
205
+ void bindVar(const VarHandle& v, const ExprHandle& e) {
206
+ codegen_->bindVar(v.node(), e.node());
207
+ }
208
+
209
+ template <typename... Ts>
210
+ void call(Ts... ts) {
211
+ call({CallArg(ts)...});
212
+ }
213
+
214
+ void call(const std::vector<CallArg>& call_args) {
215
+ std::vector<CallArg> call_args_extended = call_args;
216
+ switch (dtype_.scalar_type()) {
217
+ #define TYPE_CASE(Type, Name) \
218
+ case ScalarType::Name: { \
219
+ std::vector<Type> ret_val_arg(1); \
220
+ call_args_extended.emplace_back(ret_val_arg); \
221
+ codegen_->call(call_args_extended); \
222
+ ret_value_ = InterpValue(ret_val_arg[0]); \
223
+ } break;
224
+ AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TYPE_CASE);
225
+ TYPE_CASE(c10::quint8, QUInt8);
226
+ TYPE_CASE(c10::qint8, QInt8);
227
+ #undef TYPE_CASE
228
+ case ScalarType::Bool: {
229
+ std::vector<unsigned char> ret_val_arg(1);
230
+ call_args_extended.emplace_back(ret_val_arg.data());
231
+ codegen_->call(call_args_extended);
232
+ ret_value_ = InterpValue((bool)ret_val_arg[0]);
233
+ } break;
234
+ default:
235
+ throw unsupported_dtype();
236
+ }
237
+ }
238
+
239
+ void call_raw(const std::vector<void*>& args) {
240
+ std::vector<void*> args_extended = args;
241
+ switch (dtype_.scalar_type()) {
242
+ #define TYPE_CASE(Type, Name) \
243
+ case ScalarType::Name: { \
244
+ std::vector<Type> ret_val_arg(1); \
245
+ args_extended.push_back(ret_val_arg.data()); \
246
+ codegen_->call_raw(args_extended); \
247
+ ret_value_ = InterpValue(ret_val_arg[0]); \
248
+ } break;
249
+ AT_FORALL_SCALAR_TYPES_AND2(Half, BFloat16, TYPE_CASE);
250
+ TYPE_CASE(c10::quint8, QUInt8);
251
+ TYPE_CASE(c10::qint8, QInt8);
252
+ #undef TYPE_CASE
253
+ case ScalarType::Bool: {
254
+ std::vector<unsigned char> ret_val_arg(1);
255
+ args_extended.push_back(ret_val_arg.data());
256
+ codegen_->call_raw(args_extended);
257
+ ret_value_ = InterpValue((bool)ret_val_arg[0]);
258
+ } break;
259
+ default:
260
+ throw unsupported_dtype();
261
+ }
262
+ }
263
+
264
+ template <typename T>
265
+ T value(const std::vector<void*>& args) {
266
+ call_raw(args);
267
+ return ret_value_.as<T>();
268
+ }
269
+
270
+ template <typename T, typename... Ts>
271
+ T value(Ts... ts) {
272
+ call(std::forward<Ts>(ts)...);
273
+ return ret_value_.as<T>();
274
+ }
275
+
276
+ Dtype dtype() {
277
+ return dtype_;
278
+ }
279
+
280
+ private:
281
+ Dtype dtype_;
282
+ std::unique_ptr<CodeGenType> codegen_;
283
+ InterpValue ret_value_;
284
+ };
285
+
286
+ // Evaluates the given expression and returns an int64_t value if the result of
287
+ // the given expression is int64_t.
288
+ std::optional<int64_t> evalInt(ExprPtr e);
289
+
290
+ // Substitutes the given vars with their corresponding expressions in the input
291
+ // expression.
292
+ inline ExprPtr Substitute(const ExprPtr& expr, const VarMapping& var_mapping) {
293
+ VarSubMutator var_sub(var_mapping);
294
+ return expr->accept_mutator(&var_sub);
295
+ }
296
+
297
+ // Substitutes the given vars with their corresponding expressions in the input
298
+ // statement.
299
+ inline StmtPtr Substitute(const StmtPtr& stmt, const VarMapping& var_mapping) {
300
+ VarSubMutator var_sub(var_mapping);
301
+ return stmt->accept_mutator(&var_sub);
302
+ }
303
+
304
+ // Creates a clone of the input expression and substitutes the given vars with
305
+ // their corresponding expressions in the clone.
306
+ // NOTE: This works because cloning reuses variables and does not create new
307
+ // ones, and `VarMapping` input has variables as the key.
308
+ inline ExprPtr SubstituteInClone(
309
+ const ExprPtr& expr,
310
+ const VarMapping& var_mapping) {
311
+ VarSubMutator var_sub(var_mapping);
312
+ return Expr::clone(expr)->accept_mutator(&var_sub);
313
+ }
314
+
315
+ // Creates a clone of the input statement and substitutes the given vars with
316
+ // their corresponding expressions in the clone.
317
+ // NOTE: This works because cloning reuses variables and does not create new
318
+ // ones, and `VarMapping` input has variables as the key.
319
+ inline StmtPtr SubstituteInClone(
320
+ const StmtPtr& stmt,
321
+ const VarMapping& var_mapping) {
322
+ VarSubMutator var_sub(var_mapping);
323
+ return Stmt::clone(stmt)->accept_mutator(&var_sub);
324
+ }
325
+
326
+ } // namespace torch::jit::tensorexpr
327
+
328
+ #else
329
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
330
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/exceptions.h ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
6
+
7
+ #include <stdexcept>
8
+
9
+ // Forward declarations of types
10
+
11
+ namespace torch::jit::tensorexpr {
12
+ class Expr;
13
+ class Stmt;
14
+ } // namespace torch::jit::tensorexpr
15
+
16
+ // Forward declarations of functions
17
+ namespace std {
18
+ TORCH_API std::string to_string(
19
+ const torch::jit::tensorexpr::ExprPtr& /*expr*/);
20
+ TORCH_API std::string to_string(
21
+ const torch::jit::tensorexpr::StmtPtr& /*stmt*/);
22
+ } // namespace std
23
+
24
+ namespace torch::jit::tensorexpr {
25
+
26
+ class unsupported_dtype : public std::runtime_error {
27
+ public:
28
+ explicit unsupported_dtype() : std::runtime_error("UNSUPPORTED DTYPE") {}
29
+ explicit unsupported_dtype(const std::string& err)
30
+ : std::runtime_error("UNSUPPORTED DTYPE: " + err) {}
31
+ };
32
+
33
+ class out_of_range_index : public std::runtime_error {
34
+ public:
35
+ explicit out_of_range_index() : std::runtime_error("OUT OF RANGE INDEX") {}
36
+ explicit out_of_range_index(const std::string& err)
37
+ : std::runtime_error("OUT OF RANGE INDEX: " + err) {}
38
+ };
39
+
40
+ class unimplemented_lowering : public std::runtime_error {
41
+ public:
42
+ explicit unimplemented_lowering()
43
+ : std::runtime_error("UNIMPLEMENTED LOWERING") {}
44
+ explicit unimplemented_lowering(const ExprPtr& expr)
45
+ : std::runtime_error("UNIMPLEMENTED LOWERING: " + std::to_string(expr)) {}
46
+ explicit unimplemented_lowering(const StmtPtr& stmt)
47
+ : std::runtime_error("UNIMPLEMENTED LOWERING: " + std::to_string(stmt)) {}
48
+ };
49
+
50
+ class malformed_input : public std::runtime_error {
51
+ public:
52
+ explicit malformed_input() : std::runtime_error("MALFORMED INPUT") {}
53
+ explicit malformed_input(const std::string& err)
54
+ : std::runtime_error("MALFORMED INPUT: " + err) {}
55
+ explicit malformed_input(const ExprPtr& expr)
56
+ : std::runtime_error("MALFORMED INPUT: " + std::to_string(expr)) {}
57
+ explicit malformed_input(const std::string& err, const ExprPtr& expr)
58
+ : std::runtime_error(
59
+ "MALFORMED INPUT: " + err + " - " + std::to_string(expr)) {}
60
+ explicit malformed_input(const StmtPtr& stmt)
61
+ : std::runtime_error("MALFORMED INPUT: " + std::to_string(stmt)) {}
62
+ explicit malformed_input(const std::string& err, const StmtPtr& stmt)
63
+ : std::runtime_error(
64
+ "MALFORMED INPUT: " + err + " - " + std::to_string(stmt)) {}
65
+ };
66
+
67
+ class malformed_ir : public std::runtime_error {
68
+ public:
69
+ explicit malformed_ir() : std::runtime_error("MALFORMED IR") {}
70
+ explicit malformed_ir(const std::string& err)
71
+ : std::runtime_error("MALFORMED IR: " + err) {}
72
+ explicit malformed_ir(const ExprPtr& expr)
73
+ : std::runtime_error("MALFORMED IR: " + std::to_string(expr)) {}
74
+ explicit malformed_ir(const std::string& err, const ExprPtr& expr)
75
+ : std::runtime_error(
76
+ "MALFORMED IR: " + err + " - " + std::to_string(expr)) {}
77
+ explicit malformed_ir(const StmtPtr& stmt)
78
+ : std::runtime_error("MALFORMED IR: " + std::to_string(stmt)) {}
79
+ explicit malformed_ir(const std::string& err, const StmtPtr& stmt)
80
+ : std::runtime_error(
81
+ "MALFORMED IR: " + err + " - " + std::to_string(stmt)) {}
82
+ };
83
+
84
+ TORCH_API std::string buildErrorMessage(const std::string& s = "");
85
+
86
+ } // namespace torch::jit::tensorexpr
87
+
88
+ #else
89
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
90
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/expr.h ADDED
@@ -0,0 +1,498 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ /**
3
+ * This file implements the core classes for Tensor Expressions.
4
+ *
5
+ * The structure of the expressions is inspired by Halide/TVM IR.
6
+ */
7
+ #pragma once
8
+
9
+ #include <c10/core/MemoryFormat.h>
10
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
11
+ #include <torch/csrc/jit/tensorexpr/ir_mutator.h>
12
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
13
+ #include <torch/csrc/jit/tensorexpr/types.h>
14
+ #include <optional>
15
+
16
+ #include <utility>
17
+
18
+ namespace torch::jit::tensorexpr {
19
+
20
+ enum IRNodeType {
21
+ kPrimitive,
22
+ kAdd,
23
+ kSub,
24
+ kMul,
25
+ kDiv,
26
+ kMod,
27
+ kMax,
28
+ kMin,
29
+ kAnd,
30
+ kOr,
31
+ kLshift,
32
+ kRshift,
33
+ kXor,
34
+ kCompareSelect,
35
+ kCast,
36
+ kBitCast,
37
+ kOther,
38
+ };
39
+
40
+ // The common base between all expression node.
41
+ class TORCH_API Expr : public std::enable_shared_from_this<Expr> {
42
+ public:
43
+ explicit Expr(Dtype dtype, IRNodeType expr_type = kOther)
44
+ : dtype_(dtype), expr_type_(expr_type) {}
45
+ virtual ~Expr() = default;
46
+ Dtype dtype() const {
47
+ return dtype_;
48
+ }
49
+ virtual void accept(IRVisitor* visitor) = 0;
50
+ virtual ExprPtr accept_mutator(IRMutator* mutator) = 0;
51
+
52
+ IRNodeType expr_type() const {
53
+ return expr_type_;
54
+ }
55
+ // Is this a fixed (constant) immediate value.
56
+ virtual bool isConstant() const {
57
+ return false;
58
+ }
59
+
60
+ void set_dtype(Dtype dtype) {
61
+ dtype_ = dtype;
62
+ }
63
+
64
+ /*
65
+ * Make a deep copy of the given expression.
66
+ *
67
+ * All sub-expressions inside the given expressions are also cloned. Note
68
+ * that the variables are not deep-copied since they are immutable.
69
+ */
70
+ static ExprPtr clone(const ExprPtr& s);
71
+
72
+ protected:
73
+ std::shared_ptr<Expr> getptr() {
74
+ return shared_from_this();
75
+ }
76
+
77
+ private:
78
+ Dtype dtype_;
79
+ IRNodeType expr_type_;
80
+ };
81
+
82
+ // A CRTP pattern to accept visitors for children class,
83
+ // and dispatch back to the children.
84
+ template <class Op, class Base = Expr>
85
+ class ExprNode : public Base {
86
+ public:
87
+ using ExprNodeBase = ExprNode<Op>;
88
+ void accept(IRVisitor* visitor) override {
89
+ visitor->visit(static_to<Op>(Base::getptr()));
90
+ }
91
+ ExprPtr accept_mutator(IRMutator* mutator) override;
92
+ // pass the constructor to the base class
93
+ using Base::Base;
94
+ };
95
+
96
+ // A wrapper object to the underlying ExprNode.
97
+ // Also serves the primary way to build and operate on other expressions.
98
+ class TORCH_API ExprHandle {
99
+ public:
100
+ ExprHandle() = default;
101
+ explicit ExprHandle(ExprPtr node) : base_expr_node_(std::move(node)) {}
102
+
103
+ ExprPtr node() {
104
+ return base_expr_node_;
105
+ }
106
+
107
+ ExprPtr node() const {
108
+ return base_expr_node_;
109
+ }
110
+
111
+ bool empty() const {
112
+ return base_expr_node_ == nullptr;
113
+ }
114
+
115
+ #define IMM_EXPR_DECLARE(Type, Name) ExprHandle(Type v);
116
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_EXPR_DECLARE)
117
+ #undef IMM_EXPR_DECLARE
118
+
119
+ template <class Op>
120
+ NodePtr<Op> AsNode() {
121
+ return to<Op>(this->node());
122
+ }
123
+
124
+ template <class Op>
125
+ NodePtr<Op> AsNode() const {
126
+ // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
127
+ return const_cast<ExprHandle*>(this)->AsNode<Op>();
128
+ }
129
+
130
+ Dtype dtype() const {
131
+ return node()->dtype();
132
+ }
133
+
134
+ // Handling the math operators.
135
+ ExprHandle operator+(const ExprHandle& other) const;
136
+ ExprHandle operator-(const ExprHandle& other) const;
137
+ ExprHandle operator*(const ExprHandle& other) const;
138
+ ExprHandle operator/(const ExprHandle& other) const;
139
+ ExprHandle operator%(const ExprHandle& other) const;
140
+ ExprHandle operator==(const ExprHandle& other) const;
141
+ ExprHandle operator!=(const ExprHandle& other) const;
142
+ ExprHandle operator>(const ExprHandle& other) const;
143
+ ExprHandle operator>=(const ExprHandle& other) const;
144
+ ExprHandle operator<(const ExprHandle& other) const;
145
+ ExprHandle operator<=(const ExprHandle& other) const;
146
+ ExprHandle operator&(const ExprHandle& other) const;
147
+ ExprHandle operator|(const ExprHandle& other) const;
148
+ ExprHandle operator&&(const ExprHandle& other) const;
149
+ ExprHandle operator||(const ExprHandle& other) const;
150
+ ExprHandle operator^(const ExprHandle& other) const;
151
+ ExprHandle operator<<(const ExprHandle& other) const;
152
+ ExprHandle operator>>(const ExprHandle& other) const;
153
+
154
+ private:
155
+ ExprPtr base_expr_node_ = nullptr;
156
+ };
157
+
158
+ // The underlying representation node to a Var.
159
+ // Currently, each Var object represents a unique variable, even though the
160
+ // names might be the same. We should consider add a unique_name as well.
161
+ class TORCH_API Var : public ExprNode<Var> {
162
+ public:
163
+ static ExprHandle make(const std::string& name_hint, Dtype dtype) {
164
+ return ExprHandle(alloc<Var>(name_hint, dtype));
165
+ }
166
+ static ExprHandle make(Dtype dtype) {
167
+ return ExprHandle(alloc<Var>("", dtype));
168
+ }
169
+
170
+ // TODO: unique_name
171
+ const std::string& name_hint() const {
172
+ return name_hint_;
173
+ }
174
+
175
+ void set_name_hint(const std::string& name) {
176
+ name_hint_ = name;
177
+ }
178
+
179
+ void set_name_hint(std::string&& name) {
180
+ name_hint_ = std::move(name);
181
+ }
182
+
183
+ Var(std::string name_hint, Dtype dtype)
184
+ : ExprNodeBase(dtype, kPrimitive), name_hint_(std::move(name_hint)) {}
185
+
186
+ private:
187
+ std::string name_hint_;
188
+ };
189
+
190
+ TORCH_API std::vector<ExprPtr> make_contiguous_strides(
191
+ const std::vector<ExprHandle>& dims);
192
+ TORCH_API std::vector<ExprPtr> make_channels_last_strides(
193
+ const std::vector<ExprHandle>& dims);
194
+
195
+ class TORCH_API Buf : public ExprNode<Buf> {
196
+ public:
197
+ static BufHandle make(const std::vector<ExprHandle>& dims, Dtype dtype);
198
+
199
+ static BufHandle make(
200
+ const std::string& name_hint,
201
+ const std::vector<ExprHandle>& dims,
202
+ const std::vector<ExprHandle>& strides,
203
+ Dtype dtype);
204
+
205
+ static BufHandle make(
206
+ const std::string& name_hint,
207
+ const std::vector<ExprHandle>& dims,
208
+ Dtype dtype,
209
+ std::optional<ExprHandle> initializer = std::nullopt,
210
+ const std::optional<std::vector<ExprHandle>>& strides = std::nullopt,
211
+ std::optional<ExprHandle> qscale = std::nullopt,
212
+ std::optional<ExprHandle> qzero = std::nullopt);
213
+
214
+ // TODO: unique_name
215
+ VarPtr base_handle() const {
216
+ return base_handle_;
217
+ }
218
+ void set_base_handle(VarPtr base_handle) {
219
+ base_handle_ = std::move(base_handle);
220
+ }
221
+
222
+ const std::string& name_hint() const {
223
+ return base_handle_->name_hint();
224
+ }
225
+ void set_name_hint(const std::string& name_hint) {
226
+ base_handle_->set_name_hint(name_hint);
227
+ }
228
+
229
+ Buf(const std::string& name_hint,
230
+ const std::vector<ExprPtr>& dims,
231
+ Dtype dtype,
232
+ ExprPtr initializer = nullptr,
233
+ std::optional<std::vector<ExprPtr>> strides = std::nullopt,
234
+ ExprPtr qscale = nullptr,
235
+ ExprPtr qzero = nullptr)
236
+ : Buf(alloc<Var>(name_hint, kHandle),
237
+ dims,
238
+ dtype,
239
+ std::move(initializer),
240
+ std::move(strides),
241
+ std::move(qscale),
242
+ std::move(qzero)) {}
243
+
244
+ Buf(const VarPtr& var,
245
+ std::vector<ExprPtr> dims,
246
+ Dtype dtype,
247
+ ExprPtr initializer = nullptr,
248
+ std::optional<std::vector<ExprPtr>> strides = std::nullopt,
249
+ ExprPtr qscale = nullptr,
250
+ ExprPtr qzero = nullptr);
251
+
252
+ size_t ndim() const {
253
+ return dims_.size();
254
+ }
255
+ ExprPtr dim(size_t index) const {
256
+ if (index >= ndim()) {
257
+ throw out_of_range_index();
258
+ }
259
+ return dims_[index];
260
+ }
261
+ std::vector<ExprPtr> dims() const {
262
+ return dims_;
263
+ }
264
+ void set_dims(std::vector<ExprPtr> dims) {
265
+ dims_ = std::move(dims);
266
+ }
267
+
268
+ std::vector<ExprPtr> strides() const {
269
+ return strides_;
270
+ }
271
+
272
+ void set_strides(std::vector<ExprPtr> strides) {
273
+ strides_ = std::move(strides);
274
+ }
275
+
276
+ ExprPtr initializer() const {
277
+ return initializer_;
278
+ }
279
+
280
+ ExprPtr qzero() const {
281
+ return qzero_;
282
+ }
283
+
284
+ ExprPtr qscale() const {
285
+ return qscale_;
286
+ }
287
+
288
+ void set_qzero(ExprPtr qzero) {
289
+ qzero_ = std::move(qzero);
290
+ }
291
+
292
+ void set_qscale(ExprPtr qscale) {
293
+ qscale_ = std::move(qscale);
294
+ }
295
+
296
+ bool hasConstantDims() const {
297
+ for (const auto& d : dims_) {
298
+ if (!d->isConstant()) {
299
+ return false;
300
+ }
301
+ }
302
+ return true;
303
+ }
304
+
305
+ bool is_contiguous(
306
+ at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const;
307
+
308
+ // The channels-last 1d can benefit the performance of some operators like
309
+ // conv1d. But the MemoryFormat enum has not covered this layout yet. Hence,
310
+ // we abstract a dedicated function to check channels-last 1d contiguous.
311
+ //
312
+ // Channels-last 1d:
313
+ // dims: n c l
314
+ // strides(nlc): c*l 1 c
315
+ bool is_channels_last_1d_contiguous() const {
316
+ if (dims_.size() != 3) {
317
+ return false;
318
+ }
319
+ return is_stride_one(1) && is_cont_with(2, 1) && is_cont_with(0, 2);
320
+ }
321
+
322
+ private:
323
+ bool is_cont_with(int cur_dim, int adjacent_dim) const;
324
+ bool is_stride_one(int cur_dim) const;
325
+
326
+ VarPtr base_handle_;
327
+ std::vector<ExprPtr> dims_;
328
+ std::vector<ExprPtr> strides_;
329
+ ExprPtr initializer_;
330
+ // qscale_ and qzero_ are used only for quantized dtypes Bufs: kQUInt8, kQInt8
331
+ ExprPtr qscale_;
332
+ ExprPtr qzero_;
333
+ };
334
+
335
+ class TORCH_API BufHandle : public ExprHandle {
336
+ public:
337
+ BufHandle(
338
+ const std::string& name_hint,
339
+ const std::vector<ExprHandle>& dims,
340
+ Dtype dtype)
341
+ : ExprHandle(Buf::make(name_hint, dims, dtype)) {}
342
+
343
+ BufHandle(
344
+ const std::string& name_hint,
345
+ const std::vector<ExprHandle>& dims,
346
+ const std::vector<ExprHandle>& strides,
347
+ Dtype dtype)
348
+ : ExprHandle(Buf::make(name_hint, dims, strides, dtype)) {}
349
+
350
+ BufHandle(const std::vector<ExprHandle>& dims, Dtype dtype)
351
+ : ExprHandle(Buf::make("_", dims, dtype)) {}
352
+
353
+ explicit BufHandle(Dtype dtype) : ExprHandle(Buf::make("_", {}, dtype)) {}
354
+
355
+ explicit BufHandle(BufPtr node) : ExprHandle(std::move(node)) {}
356
+ BufPtr node() const {
357
+ return static_to<Buf>(ExprHandle::node());
358
+ }
359
+ BufPtr node() {
360
+ return static_to<Buf>(ExprHandle::node());
361
+ }
362
+
363
+ template <typename... Ts>
364
+ inline ExprHandle load(const Ts&... ts) const;
365
+
366
+ template <typename T>
367
+ inline ExprHandle load(const std::vector<T>& args) const;
368
+
369
+ inline ExprHandle load(const std::vector<ExprHandle>& args) const;
370
+
371
+ StorePtr store(const std::vector<ExprHandle>& args, const ExprHandle& val)
372
+ const;
373
+
374
+ bool operator==(const BufHandle& other) const {
375
+ return this->node() == other.node();
376
+ }
377
+ bool operator!=(const BufHandle& other) const {
378
+ return !(*this == other);
379
+ }
380
+
381
+ const std::string& name_hint() const {
382
+ return this->node()->name_hint();
383
+ }
384
+
385
+ bool empty() const {
386
+ return (this->node() == nullptr);
387
+ }
388
+
389
+ size_t ndim() const {
390
+ return node()->ndim();
391
+ }
392
+
393
+ std::vector<ExprHandle> dims() const;
394
+
395
+ ExprHandle dim(size_t index) const {
396
+ return ExprHandle(node()->dim(index));
397
+ }
398
+
399
+ bool is_contiguous(
400
+ at::MemoryFormat memory_format = at::MemoryFormat::Contiguous) const {
401
+ return node()->is_contiguous(memory_format);
402
+ }
403
+
404
+ bool is_channels_last_1d_contiguous() const {
405
+ return node()->is_channels_last_1d_contiguous();
406
+ }
407
+ };
408
+
409
+ // An expression to construct the underlying variable node.
410
+ // Note: do not store any info here, since it is often possible to slice this
411
+ // object. For example: VarHandle x('x'); ExprHandle x2 = x;
412
+ class TORCH_API VarHandle : public ExprHandle {
413
+ public:
414
+ // Creates an empty VarHandle whose base Var is set to nullptr.
415
+ VarHandle() = default;
416
+
417
+ explicit VarHandle(Dtype dtype) : ExprHandle(Var::make(dtype)) {}
418
+
419
+ VarHandle(const std::string& name_hint, Dtype dtype)
420
+ : ExprHandle(Var::make(name_hint, dtype)) {}
421
+
422
+ explicit VarHandle(VarPtr node) : ExprHandle(std::move(node)) {}
423
+
424
+ VarPtr node() const {
425
+ return static_to<Var>(ExprHandle::node());
426
+ }
427
+ bool operator==(const VarHandle& other) const {
428
+ return this->node() == other.node();
429
+ }
430
+ bool operator!=(const VarHandle& other) const {
431
+ return !(*this == other);
432
+ }
433
+
434
+ const std::string& name_hint() const {
435
+ return this->node()->name_hint();
436
+ }
437
+ bool empty() const {
438
+ return (this->node() == nullptr);
439
+ }
440
+ };
441
+
442
+ template <class Op, class Base>
443
+ ExprPtr ExprNode<Op, Base>::accept_mutator(IRMutator* mutator) {
444
+ return mutator->mutate(static_to<Op>(Base::getptr()));
445
+ }
446
+
447
+ inline bool same_node(const ExprHandle& expr1, const ExprHandle& expr2) {
448
+ return expr1.AsNode<Expr>() == expr2.AsNode<Expr>();
449
+ }
450
+
451
+ TORCH_API ExprHandle sin(const ExprHandle& v);
452
+ TORCH_API ExprHandle cos(const ExprHandle& v);
453
+ TORCH_API ExprHandle tan(const ExprHandle& v);
454
+ TORCH_API ExprHandle asin(const ExprHandle& v);
455
+ TORCH_API ExprHandle acos(const ExprHandle& v);
456
+ TORCH_API ExprHandle atan(const ExprHandle& v);
457
+ TORCH_API ExprHandle sinh(const ExprHandle& v);
458
+ TORCH_API ExprHandle cosh(const ExprHandle& v);
459
+ TORCH_API ExprHandle tanh(const ExprHandle& v);
460
+ TORCH_API ExprHandle sigmoid(const ExprHandle& v);
461
+ TORCH_API ExprHandle exp(const ExprHandle& v);
462
+ TORCH_API ExprHandle expm1(const ExprHandle& v);
463
+ TORCH_API ExprHandle abs(const ExprHandle& v);
464
+ TORCH_API ExprHandle log(const ExprHandle& v);
465
+ TORCH_API ExprHandle fast_tanh(const ExprHandle& v);
466
+ TORCH_API ExprHandle fast_sigmoid(const ExprHandle& v);
467
+ TORCH_API ExprHandle fast_log(const ExprHandle& v);
468
+ TORCH_API ExprHandle log_vml(const ExprHandle& v);
469
+ TORCH_API ExprHandle log2(const ExprHandle& v);
470
+ TORCH_API ExprHandle log10(const ExprHandle& v);
471
+ TORCH_API ExprHandle log1p(const ExprHandle& v);
472
+ TORCH_API ExprHandle erf(const ExprHandle& v);
473
+ TORCH_API ExprHandle erfc(const ExprHandle& v);
474
+ TORCH_API ExprHandle sqrt(const ExprHandle& v);
475
+ TORCH_API ExprHandle rsqrt(const ExprHandle& v);
476
+ TORCH_API ExprHandle ceil(const ExprHandle& v);
477
+ TORCH_API ExprHandle floor(const ExprHandle& v);
478
+ TORCH_API ExprHandle round(const ExprHandle& v);
479
+ TORCH_API ExprHandle trunc(const ExprHandle& v);
480
+ TORCH_API ExprHandle frac(const ExprHandle& v);
481
+ TORCH_API ExprHandle lgamma(const ExprHandle& v);
482
+ TORCH_API ExprHandle atan2(const ExprHandle& v1, const ExprHandle& v2);
483
+ TORCH_API ExprHandle pow(const ExprHandle& v1, const ExprHandle& v2);
484
+ TORCH_API ExprHandle fmod(const ExprHandle& v1, const ExprHandle& v2);
485
+ TORCH_API ExprHandle remainder(const ExprHandle& v1, const ExprHandle& v2);
486
+ TORCH_API ExprHandle isnan(const ExprHandle& v1);
487
+ TORCH_API ExprHandle Relu(const ExprHandle& v1);
488
+
489
+ TORCH_API ExprHandle
490
+ ifThenElse(const ExprHandle& c, const ExprHandle& t, const ExprHandle& f);
491
+
492
+ TORCH_API ExprHandle expr_to_vec(const ExprHandle& v, int lanes);
493
+
494
+ } // namespace torch::jit::tensorexpr
495
+
496
+ #else
497
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
498
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions.h ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/Config.h>
5
+ #include <ATen/Functions.h>
6
+ #include <c10/macros/Macros.h>
7
+ #include <torch/csrc/Export.h>
8
+ #include <cstdint>
9
+ #include <vector>
10
+
11
+ #define FOR_ALL_EXTERNAL_FUNCTIONS(_) \
12
+ _(nnc_aten_adaptive_avg_pool2d) \
13
+ _(nnc_aten_addmm) \
14
+ _(nnc_aten_conv2d) \
15
+ _(nnc_aten_conv1d) \
16
+ _(nnc_aten_conv1d_out) \
17
+ _(nnc_aten_dequantize) \
18
+ _(nnc_aten_dequantize_out) \
19
+ _(nnc_aten_embedding) \
20
+ _(nnc_aten_matmul) \
21
+ _(nnc_aten_mv) \
22
+ _(nnc_aten_mm) \
23
+ _(nnc_aten_mean) \
24
+ _(nnc_aten_max_red) \
25
+ _(nnc_aten_max_red_out) \
26
+ _(nnc_aten_quantized_conv1d) \
27
+ _(nnc_aten_quantized_conv1d_out) \
28
+ _(nnc_aten_quantized_conv2d) \
29
+ _(nnc_aten_quantized_conv2d_out) \
30
+ _(nnc_aten_quantized_conv2d_relu) \
31
+ _(nnc_aten_quantized_conv2d_relu_out) \
32
+ _(nnc_aten_quantized_linear) \
33
+ _(nnc_aten_quantized_linear_out) \
34
+ _(nnc_aten_quantized_linear_relu) \
35
+ _(nnc_aten_quantized_add) \
36
+ _(nnc_aten_quantized_cat) \
37
+ _(nnc_aten_quantized_mul) \
38
+ _(nnc_aten_quantized_mul_out) \
39
+ _(nnc_aten_quantized_mul_scalar) \
40
+ _(nnc_aten_quantized_mul_scalar_out) \
41
+ _(nnc_aten_quantized_relu) \
42
+ _(nnc_aten_quantized_sigmoid) \
43
+ _(nnc_aten_quantized_sigmoid_out) \
44
+ _(nnc_aten_quantize_per_tensor) \
45
+ _(nnc_aten_quantize_per_tensor_out) \
46
+ _(nnc_aten_triangular_solve) \
47
+ _(nnc_aten_upsample_nearest2d) \
48
+ _(nnc_aten_upsample_nearest2d_out) \
49
+ _(nnc_prepacked_conv2d_clamp_run) \
50
+ _(nnc_prepacked_linear_clamp_run)
51
+
52
+ #define DECLARE_EXTERNAL_FUNCTION(NAME) \
53
+ TORCH_API void NAME( \
54
+ int64_t bufs_num, \
55
+ void** buf_data, \
56
+ int64_t* buf_ranks, \
57
+ int64_t* buf_dims, \
58
+ int64_t* buf_strides, \
59
+ int8_t* buf_dtypes, \
60
+ int64_t args_num, \
61
+ int64_t* extra_args);
62
+
63
+ namespace torch::jit::tensorexpr {
64
+ struct QIData final {
65
+ double scale;
66
+ int64_t zero;
67
+ c10::ScalarType scalarType;
68
+ };
69
+ std::vector<at::Tensor> constructTensors(
70
+ int64_t bufs_num,
71
+ void** buf_data,
72
+ int64_t* buf_ranks,
73
+ int64_t* buf_dims,
74
+ int64_t* buf_strides,
75
+ int8_t* buf_dtypes,
76
+ std::optional<std::vector<std::pair<size_t, QIData>>> qdataArg =
77
+ std::nullopt);
78
+
79
+ std::vector<at::Tensor> constructTensors2(
80
+ int64_t bufs_in_num,
81
+ void** buf_data,
82
+ int64_t* buf_ranks,
83
+ int64_t* buf_dims,
84
+ int64_t* buf_strides,
85
+ int8_t* buf_dtypes,
86
+ std::optional<std::vector<std::pair<size_t, QIData>>> qdataArg =
87
+ std::nullopt,
88
+ size_t bufs_out_num = 0);
89
+
90
+ #ifdef C10_MOBILE
91
+ extern "C" {
92
+ #endif
93
+ void DispatchParallel(
94
+ int8_t* func,
95
+ int64_t start,
96
+ int64_t stop,
97
+ int8_t* packed_data) noexcept;
98
+
99
+ FOR_ALL_EXTERNAL_FUNCTIONS(DECLARE_EXTERNAL_FUNCTION)
100
+ #if AT_MKLDNN_ENABLED()
101
+ DECLARE_EXTERNAL_FUNCTION(nnc_mkldnn_prepacked_conv_run)
102
+ #endif
103
+
104
+ TORCH_API void nnc_aten_free(size_t bufs_num, void** ptrs) noexcept;
105
+
106
+ #ifdef C10_MOBILE
107
+ } // extern "C"
108
+ #endif
109
+
110
+ } // namespace torch::jit::tensorexpr
111
+
112
+ #undef DECLARE_EXTERNAL_FUNCTION
113
+
114
+ #else
115
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
116
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_core.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ATen/ATen.h>
5
+ #include <ATen/Parallel.h>
6
+ #include <torch/csrc/Export.h>
7
+ #include <cstdint>
8
+
9
+ namespace torch::jit::tensorexpr {
10
+
11
+ #ifdef C10_MOBILE
12
+ extern "C" {
13
+ #endif
14
+ void DispatchParallel(
15
+ int8_t* func,
16
+ int64_t start,
17
+ int64_t stop,
18
+ int8_t* packed_data) noexcept;
19
+
20
+ TORCH_API void nnc_aten_free(size_t bufs_num, void** ptrs) noexcept;
21
+
22
+ #ifdef C10_MOBILE
23
+ } // extern "C"
24
+ #endif
25
+
26
+ } // namespace torch::jit::tensorexpr
27
+
28
+ #else
29
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
30
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/external_functions_registry.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <cstdint>
6
+ #include <string>
7
+ #include <unordered_map>
8
+
9
+ namespace torch::jit::tensorexpr {
10
+
11
+ // The external functions that could be called from NNC must have the same
12
+ // signature defined by `NNCExternalFunction`.
13
+ //
14
+ // Why this signature?
15
+ // It was picked for two reasons: 1) it should be generic enough to represent
16
+ // most of the ops we might want to call, 2) it should be possible to generate a
17
+ // code for this call in LLVM codegen.
18
+ // The first 5 parameters allow to pass any number of contiguous CPU tensors in
19
+ // case we need to run aten ops (TODO: support different devices). The first
20
+ // buffer in the array is assumed to be the output buffer. We couldn't use
21
+ // `at::Tensor` (or `c10::IValue`) type there directly as it would mean that
22
+ // we'd need to declare it in LLVM codegen in LLVM IR form, which would be very
23
+ // cumbersome and hard to maintain. Note that the dimensions of all tensors are
24
+ // concatenated into a single array buf_dims. We do not need to pass its length,
25
+ // since it can be deduced from total number of buffers and their ranks.
26
+ //
27
+ // The last 2 arguments allow to pass any non-tensor arguments encoded as an
28
+ // array of int64_t values. The way they are encoded is not specified and could
29
+ // be arbitrary - whatever the most convenient for the specific bridge function
30
+ // is.
31
+ //
32
+ // The bridge functions must not throw exceptions - properly propagating them
33
+ // from the generated code is too cumbersome, and thus all calls to functions
34
+ // that could throw must be wrapped with try-catch blocks.
35
+ using NNCExternalFunction = void (*)(
36
+ int64_t bufs_num,
37
+ void** buf_data,
38
+ int64_t* buf_ranks,
39
+ int64_t* buf_dims,
40
+ int64_t* buf_strides,
41
+ int8_t* buf_dtypes,
42
+ int64_t args_num,
43
+ int64_t* extra_args);
44
+
45
+ // Return a global map "function-name" -> "function-pointer" for all registered
46
+ // in NNC external functions
47
+ TORCH_API std::unordered_map<std::string, NNCExternalFunction>&
48
+ getNNCFunctionRegistry();
49
+
50
+ // To register a new external function in NNC one needs to create an instance of
51
+ // this struct
52
+ struct RegisterNNCExternalFunction {
53
+ RegisterNNCExternalFunction(const std::string& name, NNCExternalFunction fn) {
54
+ getNNCFunctionRegistry()[name] = fn;
55
+ }
56
+ };
57
+
58
+ } // namespace torch::jit::tensorexpr
59
+
60
+ #else
61
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
62
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/fwd_decls.h ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <memory>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ template <typename Node>
9
+ using NodePtr = std::shared_ptr<Node>;
10
+
11
+ template <typename To, typename From>
12
+ NodePtr<To> to(const NodePtr<From>& x) {
13
+ return std::dynamic_pointer_cast<To>(x);
14
+ }
15
+
16
+ template <typename To, typename From>
17
+ NodePtr<To> static_to(NodePtr<From> x) {
18
+ return std::static_pointer_cast<To>(x);
19
+ }
20
+
21
+ template <typename Node, typename... Args>
22
+ NodePtr<Node> alloc(Args&&... args) {
23
+ return std::make_shared<Node>(std::forward<Args>(args)...);
24
+ }
25
+
26
+ class Buf;
27
+ class Expr;
28
+ class Stmt;
29
+ class Var;
30
+
31
+ using BufPtr = NodePtr<Buf>;
32
+ using ExprPtr = NodePtr<Expr>;
33
+ using StmtPtr = NodePtr<Stmt>;
34
+ using VarPtr = NodePtr<Var>;
35
+
36
+ class ExprHandle;
37
+ class VarHandle;
38
+ class BufHandle;
39
+
40
+ class Add;
41
+ class And;
42
+ class BitCast;
43
+ class Broadcast;
44
+ class Cast;
45
+ class CompareSelect;
46
+ class Div;
47
+ class IfThenElse;
48
+ class Intrinsics;
49
+ class Let;
50
+ class Load;
51
+ class Lshift;
52
+ class Max;
53
+ class MaxTerm;
54
+ class Min;
55
+ class MinTerm;
56
+ class Mod;
57
+ class Mul;
58
+ class Or;
59
+ class Polynomial;
60
+ class Ramp;
61
+ class ReduceOp;
62
+ class RoundOff;
63
+ class Rshift;
64
+ class Store;
65
+ class Sub;
66
+ class Term;
67
+ class Xor;
68
+ using AddPtr = NodePtr<Add>;
69
+ using AndPtr = NodePtr<And>;
70
+ using BitCastPtr = NodePtr<BitCast>;
71
+ using BroadcastPtr = NodePtr<Broadcast>;
72
+ using CastPtr = NodePtr<Cast>;
73
+ using CompareSelectPtr = NodePtr<CompareSelect>;
74
+ using DivPtr = NodePtr<Div>;
75
+ using IfThenElsePtr = NodePtr<IfThenElse>;
76
+ using IntrinsicsPtr = NodePtr<Intrinsics>;
77
+ using LetPtr = NodePtr<Let>;
78
+ using LoadPtr = NodePtr<Load>;
79
+ using LshiftPtr = NodePtr<Lshift>;
80
+ using MaxPtr = NodePtr<Max>;
81
+ using MaxTermPtr = NodePtr<MaxTerm>;
82
+ using MinPtr = NodePtr<Min>;
83
+ using MinTermPtr = NodePtr<MinTerm>;
84
+ using ModPtr = NodePtr<Mod>;
85
+ using MulPtr = NodePtr<Mul>;
86
+ using OrPtr = NodePtr<Or>;
87
+ using PolynomialPtr = NodePtr<Polynomial>;
88
+ using RampPtr = NodePtr<Ramp>;
89
+ using ReduceOpPtr = NodePtr<ReduceOp>;
90
+ using RoundOffPtr = NodePtr<RoundOff>;
91
+ using RshiftPtr = NodePtr<Rshift>;
92
+ using StorePtr = NodePtr<Store>;
93
+ using SubPtr = NodePtr<Sub>;
94
+ using TermPtr = NodePtr<Term>;
95
+ using XorPtr = NodePtr<Xor>;
96
+
97
+ class Allocate;
98
+ class AtomicAdd;
99
+ class Block;
100
+ class Cond;
101
+ class ExternalCall;
102
+ class ExternalCallWithAlloc;
103
+ class For;
104
+ class Free;
105
+ class FreeExt;
106
+ class PlacementAllocate;
107
+ class SyncThreads;
108
+ using AllocatePtr = NodePtr<Allocate>;
109
+ using AtomicAddPtr = NodePtr<AtomicAdd>;
110
+ using BlockPtr = NodePtr<Block>;
111
+ using CondPtr = NodePtr<Cond>;
112
+ using ExternalCallPtr = NodePtr<ExternalCall>;
113
+ using ExternalCallWithAllocPtr = NodePtr<ExternalCallWithAlloc>;
114
+ using ForPtr = NodePtr<For>;
115
+ using FreePtr = NodePtr<Free>;
116
+ using FreeExtPtr = NodePtr<FreeExt>;
117
+ using PlacementAllocatePtr = NodePtr<PlacementAllocate>;
118
+ using SyncThreadsPtr = NodePtr<SyncThreads>;
119
+
120
+ #define IMM_DECLARE(Type, Name) \
121
+ class Name##Imm; \
122
+ using Name##ImmPtr = NodePtr<Name##Imm>;
123
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_DECLARE)
124
+ #undef IMM_DECLARE
125
+
126
+ } // namespace torch::jit::tensorexpr
127
+
128
+ #else
129
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
130
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/graph_opt.h ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/ir/ir.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ // Optimize aten::cat ops in the given subgraph.
9
+ //
10
+ // Moving users of cat to its inputs.
11
+ // Cat ops get lowered into multiple loops, one per input. When the result
12
+ // of cat is used by some other op, it results in a situation where inlining
13
+ // of cat does not happen. This in turn results in intermediate buffers
14
+ // being created for the result of cat, since it is not inlined.
15
+ //
16
+ // For example, consider the following graph:
17
+ // graph(%x : Float(10, strides=[1], device=cpu),
18
+ // %y : Float(20, strides=[1], device=cpu)):
19
+ // %dim : int = prim::Constant[value=0]()
20
+ // %xy_list : Tensor[] = prim::ListConstruct(%x, %y)
21
+ // %cat : Float(60, strides=[1], device=cpu) = aten::cat(%xy_list, %dim)
22
+ // %5 : Float(60, strides=[1], device=cpu) = aten::log(%cat)
23
+ // return (%5))IR";
24
+ //
25
+ // This will get lowered into:
26
+ // Allocate(aten_cat);
27
+ // for (...)
28
+ // aten_cat[...] = x[...]
29
+ // for (...)
30
+ // aten_cat[...] = y[...]
31
+ // for (...)
32
+ // aten_log[...] = log(aten_cat[...])
33
+ // Free(aten_cat);
34
+ // Note that aten_cat is not inlined into aten_log and it results in
35
+ // an intermediate buffer allocation as well.
36
+ //
37
+ // Optimization:
38
+ // We move the ops that use the result of `cat` into its inputs whenever
39
+ // possible.
40
+ //
41
+ // The graph above will be transformed to:
42
+ // graph(%x : Float(10, strides=[1], device=cpu),
43
+ // %y : Float(20, strides=[1], device=cpu)):
44
+ // %3 : int = prim::Constant[value=0]()
45
+ // %7 : Float(10, strides=[1], device=cpu) = aten::log(%x)
46
+ // %8 : Float(20, strides=[1], device=cpu) = aten::log(%y)
47
+ // %9 : Tensor[] = prim::ListConstruct(%7, %8)
48
+ // %10 : Float(60, strides=[1], device=cpu) = aten::cat(%9, %3)
49
+ // return (%10)
50
+ //
51
+ // This will get lowered into:
52
+ // for (...)
53
+ // aten_cat[...] = log(x[...])
54
+ // for (...)
55
+ // aten_cat[...] = log(y[...])
56
+ // aten_cat is the output buffer here.
57
+
58
+ bool OptimizeCat(const std::shared_ptr<Graph>& graph);
59
+
60
+ TORCH_API void annotateInputShapes(
61
+ const std::shared_ptr<Graph>& graph,
62
+ const std::vector<std::optional<at::Tensor>>& example_inputs);
63
+ TORCH_API std::shared_ptr<Graph> removeUnusedSelfArgument(
64
+ const std::shared_ptr<Graph>& graph);
65
+ TORCH_API std::shared_ptr<Graph> removeGraphOutput(
66
+ const std::shared_ptr<Graph>& graph,
67
+ size_t idx);
68
+ TORCH_API std::shared_ptr<Graph> replaceListOutputWithTuple(
69
+ const std::shared_ptr<Graph>& graph);
70
+
71
+ // Perform \p ITERS rounds of "trimming" for the given \p GRAPH.
72
+ //
73
+ // Trimming means that we try to remove a small portion of the graph while
74
+ // keeping it valid. This is useful for debugging when we try to find a minimal
75
+ // example reproducing the issue at hand. When ITERS is 0, the graph remains
76
+ // unchanged, when ITERS is a big number, the graph usually becomes empty.
77
+ TORCH_API std::shared_ptr<Graph> trimGraph(
78
+ const std::shared_ptr<Graph>& graph,
79
+ int64_t iters);
80
+
81
+ // Scan all values in the given graph and replace each dimension with a size Xi
82
+ // present in \p SIZES with a symbolic shape Yi. Return a vector of symbol
83
+ // values [Y0, Y1, .., Yn].
84
+ //
85
+ // For example:
86
+ // Input:
87
+ // graph(%x : Float(10, 20, 30, 40)):
88
+ // %y : Float(10, 20, 30, 40) = aten::relu(%x)
89
+ // return %y
90
+ //
91
+ // If we run makeShapesSymbolic(graph, {20, 40}), then we'll get:
92
+ //
93
+ // graph(%x : Float(10, SS(-3), 30, SS(-5))):
94
+ // %y : Float(10, SS(-3), 30, SS(-5)) = aten::relu(%x)
95
+ // return %y
96
+ //
97
+ // and get {-3, -5} as the return value.
98
+ TORCH_API std::vector<int64_t> makeShapesSymbolic(
99
+ std::shared_ptr<Graph>& graph,
100
+ const std::vector<int64_t>& sizes);
101
+
102
+ // Inspect the graph and report whether it can be converted to TE IR.
103
+ // TODO: add error reporting for graphs that can't be converted.
104
+ TORCH_API bool isGraphCompilable(const std::shared_ptr<Graph>& graph);
105
+
106
+ // Examine the graph and (hackily) fill in missing tensor type info, such as
107
+ // scalar type, device, and strides. Ideally, this should be done by a proper
108
+ // dtype/device/shape propagation passes, but until they are ready we can use
109
+ // this, not always correct, workaround pass.
110
+ TORCH_API void fixupMissingShapeInfo(const std::shared_ptr<Graph>& graph);
111
+
112
+ } // namespace torch::jit::tensorexpr
113
+
114
+ #else
115
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
116
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/half_support.h ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
5
+ #include <torch/csrc/jit/tensorexpr/ir.h>
6
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
7
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
8
+
9
+ namespace torch::jit::tensorexpr {
10
+
11
+ // Walk the Statement looking for Half size loads/stores.
12
+ class HalfChecker : public IRVisitor {
13
+ public:
14
+ HalfChecker(const std::vector<CodeGen::BufferArg>& args) {
15
+ for (const auto& BA : args) {
16
+ hasHalf_ |= BA.dtype().scalar_type() == ScalarType::Half;
17
+ }
18
+ }
19
+
20
+ bool hasHalf() const {
21
+ return hasHalf_;
22
+ }
23
+
24
+ bool hasBFloat16() const {
25
+ return hasBFloat16_;
26
+ }
27
+
28
+ void visit(const LoadPtr& v) override {
29
+ hasHalf_ |= v->dtype().scalar_type() == ScalarType::Half;
30
+ hasBFloat16_ |= v->dtype().scalar_type() == ScalarType::BFloat16;
31
+ IRVisitor::visit(v);
32
+ }
33
+
34
+ void visit(const StorePtr& v) override {
35
+ hasHalf_ |= v->buf()->dtype().scalar_type() == ScalarType::Half;
36
+ hasBFloat16_ |= v->buf()->dtype().scalar_type() == ScalarType::BFloat16;
37
+ IRVisitor::visit(v);
38
+ }
39
+
40
+ void visit(const HalfImmPtr& v) override {
41
+ hasHalf_ = true;
42
+ }
43
+
44
+ void visit(const BFloat16ImmPtr& v) override {
45
+ hasBFloat16_ = true;
46
+ }
47
+
48
+ void visit(const CastPtr& v) override {
49
+ hasHalf_ |= v->dtype().scalar_type() == ScalarType::Half;
50
+ hasBFloat16_ |= v->dtype().scalar_type() == ScalarType::BFloat16;
51
+ IRVisitor::visit(v);
52
+ }
53
+
54
+ private:
55
+ bool hasHalf_{false};
56
+ bool hasBFloat16_{false};
57
+ };
58
+
59
+ class HalfRewriter : public IRMutator {
60
+ ExprPtr mutate(const LoadPtr& v) override {
61
+ ExprPtr child = IRMutator::mutate(v);
62
+ if (!isHalf(child)) {
63
+ return child;
64
+ }
65
+
66
+ ExprPtr ret = alloc<Cast>(
67
+ child->dtype().cloneWithScalarType(ScalarType::Float), child);
68
+
69
+ inserted_half_casts_.insert(ret);
70
+ return ret;
71
+ }
72
+
73
+ StmtPtr mutate(const StorePtr& v) override {
74
+ // Since mutation changes the `value()` expression in-place, we need to
75
+ // get the dtype of the `value()` before that is mutated.
76
+ auto newType = v->value()->dtype();
77
+ ExprPtr new_val = v->value()->accept_mutator(this);
78
+ auto bufType = v->buf()->dtype();
79
+
80
+ if (isHalf(newType.scalar_type())) {
81
+ new_val = alloc<Cast>(newType, new_val);
82
+ inserted_half_casts_.insert(new_val);
83
+ }
84
+
85
+ // The scalar_type of value is not Half while the buf is Half
86
+ if (!isHalf(newType.scalar_type()) && isHalf(bufType.scalar_type())) {
87
+ new_val = alloc<Cast>(
88
+ newType.cloneWithScalarType(bufType.scalar_type()), new_val);
89
+ inserted_half_casts_.insert(new_val);
90
+ }
91
+
92
+ v->set_value(new_val);
93
+ return v;
94
+ }
95
+
96
+ ExprPtr mutate(const HalfImmPtr& v) override {
97
+ return alloc<Cast>(kFloat, v);
98
+ }
99
+
100
+ ExprPtr mutate(const BFloat16ImmPtr& v) override {
101
+ return alloc<Cast>(kFloat, v);
102
+ }
103
+
104
+ ExprPtr mutate(const CastPtr& v) override {
105
+ ExprPtr child = v->src_value()->accept_mutator(this);
106
+
107
+ // just don't allow half casts we didn't insert.
108
+ if (isHalf(v)) {
109
+ if (inserted_half_casts_.count(v) < 1) {
110
+ v->set_src_value(child);
111
+ v->set_dtype(v->dtype().cloneWithScalarType(c10::kFloat));
112
+ return v;
113
+ }
114
+ }
115
+
116
+ // Remove Half(Float()) and friends.
117
+ CastPtr cast_child = to<Cast>(child);
118
+ if (cast_child) {
119
+ auto cast_to_double = v->dtype().scalar_type() == ScalarType::Double;
120
+ auto from_half = isHalf(cast_child->src_value());
121
+ // Cannot simplify the double(float(half)) to double(half) as NNC does
122
+ // not support cast BF16 to double directly.
123
+ auto not_cast_half_to_doulbe = !(cast_to_double && from_half);
124
+ if (v->dtype().is_floating_point() &&
125
+ cast_child->dtype().is_floating_point() && not_cast_half_to_doulbe) {
126
+ return alloc<Cast>(v->dtype(), cast_child->src_value());
127
+ }
128
+ }
129
+
130
+ if (child == v->src_value()) {
131
+ return v;
132
+ }
133
+
134
+ return alloc<Cast>(v->dtype(), child);
135
+ }
136
+
137
+ StmtPtr mutate(const LetPtr& v) override {
138
+ if (isHalf(v->var()->dtype().scalar_type())) {
139
+ VarPtr load_new_var = alloc<Var>(v->var()->name_hint(), kFloat);
140
+ ExprPtr new_value = alloc<Cast>(
141
+ v->var()->dtype().cloneWithScalarType(ScalarType::Float),
142
+ v->value()->accept_mutator(this));
143
+ var_map[v->var()] = load_new_var;
144
+
145
+ return alloc<Let>(load_new_var, new_value);
146
+ }
147
+
148
+ return IRMutator::mutate(v);
149
+ }
150
+
151
+ ExprPtr mutate(const VarPtr& v) override {
152
+ auto it = var_map.find(v);
153
+ if (it != var_map.end()) {
154
+ return it->second;
155
+ }
156
+
157
+ return v;
158
+ }
159
+
160
+ template <typename T>
161
+ ExprPtr mutateArithmetic(T v) {
162
+ IRMutator::mutate(v);
163
+ if (isHalf(v)) {
164
+ v->set_dtype(v->dtype().cloneWithScalarType(c10::kFloat));
165
+ }
166
+ return v;
167
+ }
168
+
169
+ ExprPtr mutate(const AddPtr& v) override {
170
+ return mutateArithmetic(v);
171
+ }
172
+ ExprPtr mutate(const SubPtr& v) override {
173
+ return mutateArithmetic(v);
174
+ }
175
+ ExprPtr mutate(const MulPtr& v) override {
176
+ return mutateArithmetic(v);
177
+ }
178
+ ExprPtr mutate(const DivPtr& v) override {
179
+ return mutateArithmetic(v);
180
+ }
181
+ ExprPtr mutate(const MaxPtr& v) override {
182
+ return mutateArithmetic(v);
183
+ }
184
+ ExprPtr mutate(const MinPtr& v) override {
185
+ return mutateArithmetic(v);
186
+ }
187
+ ExprPtr mutate(const CompareSelectPtr& v) override {
188
+ return mutateArithmetic(v);
189
+ }
190
+ ExprPtr mutate(const BroadcastPtr& v) override {
191
+ return mutateArithmetic(v);
192
+ }
193
+ ExprPtr mutate(const IfThenElsePtr& v) override {
194
+ return mutateArithmetic(v);
195
+ }
196
+ ExprPtr mutate(const IntrinsicsPtr& v) override {
197
+ return mutateArithmetic(v);
198
+ }
199
+
200
+ private:
201
+ static bool isHalf(ScalarType st) {
202
+ return st == ScalarType::Half || st == ScalarType::BFloat16;
203
+ }
204
+
205
+ static bool isHalf(const ExprPtr& v) {
206
+ return isHalf(v->dtype().scalar_type());
207
+ }
208
+
209
+ std::unordered_set<ExprPtr> inserted_half_casts_;
210
+ std::unordered_map<VarPtr, VarPtr> var_map;
211
+ };
212
+
213
+ } // namespace torch::jit::tensorexpr
214
+
215
+ #else
216
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
217
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/hash_provider.h ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/ir.h>
5
+ #include <torch/csrc/jit/tensorexpr/ir_printer.h>
6
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
7
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
8
+
9
+ #include <utility>
10
+
11
+ namespace torch::jit::tensorexpr {
12
+
13
+ struct TORCH_API SimplifierHashType {
14
+ SimplifierHashType() = default;
15
+ explicit SimplifierHashType(size_t s) : _h(s) {}
16
+
17
+ bool operator==(const SimplifierHashType& other) const;
18
+ bool operator!=(const SimplifierHashType& other) const;
19
+ bool operator<(const SimplifierHashType& other) const;
20
+ bool operator==(const size_t other) const;
21
+ bool operator!=(const size_t other) const;
22
+
23
+ size_t _h{0};
24
+ };
25
+
26
+ } // namespace torch::jit::tensorexpr
27
+
28
+ namespace std {
29
+ template <>
30
+ struct hash<torch::jit::tensorexpr::SimplifierHashType> {
31
+ size_t operator()(const torch::jit::tensorexpr::SimplifierHashType& k) const {
32
+ return k._h;
33
+ }
34
+ };
35
+
36
+ } // namespace std
37
+
38
+ namespace torch::jit::tensorexpr {
39
+
40
+ #define CACHE_GUARD() \
41
+ if (cachedHash(v)) { \
42
+ return; \
43
+ }
44
+
45
+ class Term;
46
+ class Polynomial;
47
+
48
+ /* Expression hasher providing comparable values representing sub-exprs.
49
+ * Uses memoization to avoid excessive recursion. */
50
+ class TORCH_API HashProvider : public IRVisitor {
51
+ public:
52
+ template <class T>
53
+ SimplifierHashType hash(T e) {
54
+ e->accept(this);
55
+ return hashOf(e);
56
+ }
57
+
58
+ bool cachedHash(const ExprPtr& e) {
59
+ return exprToHash_.find(e) != exprToHash_.end();
60
+ }
61
+ bool cachedHash(const StmtPtr& s) {
62
+ return stmtToHash_.find(s) != stmtToHash_.end();
63
+ }
64
+
65
+ void clearCache() {
66
+ exprToHash_.clear();
67
+ stmtToHash_.clear();
68
+ }
69
+
70
+ void visit(const AddPtr& v) override;
71
+ void visit(const SubPtr& v) override;
72
+ void visit(const MulPtr& v) override;
73
+ void visit(const DivPtr& v) override;
74
+ void visit(const ModPtr& v) override;
75
+ void visit(const RoundOffPtr& v) override;
76
+ void visit(const MaxPtr& v) override;
77
+ void visit(const MinPtr& v) override;
78
+ void visit(const AndPtr& v) override;
79
+ void visit(const OrPtr& v) override;
80
+ void visit(const XorPtr& v) override;
81
+ void visit(const LshiftPtr& v) override;
82
+ void visit(const RshiftPtr& v) override;
83
+ void visit(const CompareSelectPtr& v) override;
84
+
85
+ #define IMM_VISIT(Type, Name) \
86
+ void visit(const Name##ImmPtr& v) override { \
87
+ CACHE_GUARD(); \
88
+ putHash(v, hash_combine(#Name, v->value())); \
89
+ }
90
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_VISIT)
91
+ #undef IMM_VISIT
92
+
93
+ void visit(const CastPtr& v) override;
94
+ void visit(const VarPtr& v) override;
95
+ void visit(const RampPtr& v) override;
96
+ void visit(const LoadPtr& v) override;
97
+ void visit(const StorePtr& v) override;
98
+ void visit(const BlockPtr& v) override;
99
+ void visit(const ForPtr& v) override;
100
+ void visit(const BroadcastPtr& v) override;
101
+ void visit(const IfThenElsePtr& v) override;
102
+ void visit(const IntrinsicsPtr& v) override;
103
+ void visit(const AllocatePtr& v) override;
104
+ void visit(const FreePtr& v) override;
105
+ void visit(const CondPtr& v) override;
106
+ void visit(const TermPtr& v) override;
107
+ void visit(const PolynomialPtr& v) override;
108
+ void visit(const MaxTermPtr& v) override;
109
+ void visit(const MinTermPtr& v) override;
110
+
111
+ template <typename... Types>
112
+ SimplifierHashType hash_combine(const Types&... args) {
113
+ SimplifierHashType seed;
114
+ _hash_combine(seed, args...);
115
+ return seed;
116
+ }
117
+
118
+ private:
119
+ SimplifierHashType hashOf(const ExprPtr& e) {
120
+ auto it = exprToHash_.find(e);
121
+ if (it != exprToHash_.end()) {
122
+ return it->second;
123
+ }
124
+
125
+ // As a failsafe fall back to IRPrinter.
126
+ std::stringstream ss;
127
+ IRPrinter printer(ss);
128
+ e->accept(&printer);
129
+ SimplifierHashType hash = SimplifierHashType(te_hash(ss.str()));
130
+ putHash(e, hash);
131
+
132
+ return hash;
133
+ }
134
+
135
+ SimplifierHashType hashOf(const StmtPtr& s) {
136
+ auto it = stmtToHash_.find(s);
137
+ if (it != stmtToHash_.end()) {
138
+ return it->second;
139
+ }
140
+
141
+ // As a failsafe fall back to IRPrinter.
142
+ std::stringstream ss;
143
+ IRPrinter printer(ss);
144
+ s->accept(&printer);
145
+ SimplifierHashType hash = SimplifierHashType(te_hash(ss.str()));
146
+ putHash(s, hash);
147
+
148
+ return hash;
149
+ }
150
+
151
+ // Hash funcs for various types, numbers are random.
152
+ template <typename T>
153
+ void _hash_combine(SimplifierHashType& seed, const T& val) {
154
+ seed._h ^= te_hash(val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4);
155
+ }
156
+
157
+ void _hash_combine(SimplifierHashType& seed, const char* val) {
158
+ seed._h ^= te_hash(val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4);
159
+ }
160
+
161
+ // at:::Half doesn't have a prime_number_hash, so cast to short.
162
+ void _hash_combine(SimplifierHashType& seed, const at::Half& val) {
163
+ seed._h ^=
164
+ te_hash((uint16_t)val) + 0x1f752c19 + (seed._h << 7) + (seed._h >> 4);
165
+ }
166
+
167
+ void _hash_combine(SimplifierHashType& seed, const Dtype& val) {
168
+ seed._h ^= te_hash(val.ToCppString()) + 0x1f752c19 + (seed._h << 7) +
169
+ (seed._h >> 4);
170
+ }
171
+
172
+ void _hash_combine(SimplifierHashType& seed, ExprPtr e) {
173
+ _hash_combine(seed, hash(std::move(e)));
174
+ }
175
+
176
+ template <typename T, typename... Types>
177
+ void _hash_combine(
178
+ SimplifierHashType& seed,
179
+ const T& val,
180
+ const Types&... args) {
181
+ _hash_combine(seed, val);
182
+ _hash_combine(seed, args...);
183
+ }
184
+
185
+ void putHash(const ExprPtr& e, SimplifierHashType h) {
186
+ auto res = exprToHash_.emplace(e, h);
187
+ if (res.second == false) {
188
+ // This is always a logic bug since we should check the cache first.
189
+ throw std::runtime_error("hash collision");
190
+ }
191
+ }
192
+ void putHash(const StmtPtr& s, SimplifierHashType h) {
193
+ auto res = stmtToHash_.emplace(s, h);
194
+ if (res.second == false) {
195
+ // This is always a logic bug since we should check the cache first.
196
+ throw std::runtime_error("hash collision");
197
+ }
198
+ }
199
+
200
+ std::unordered_map<ExprPtr, SimplifierHashType> exprToHash_;
201
+ std::unordered_map<StmtPtr, SimplifierHashType> stmtToHash_;
202
+ UniqueNameManager name_manager_;
203
+
204
+ size_t te_hash(SimplifierHashType val) {
205
+ return val._h;
206
+ }
207
+
208
+ size_t te_hash(int64_t val) {
209
+ // put the thing down.
210
+ size_t h = val ^ 0x647AA4D20C0B;
211
+ // bit flip it.
212
+ size_t h2 = ~h;
213
+ // and reverse byte order.
214
+ size_t h3 = 0;
215
+ for (unsigned int i = 0; i < 64; i += 8) {
216
+ h3 |= ((h2 >> i) & 0xFF) << (64 - i - 8);
217
+ }
218
+ return h3;
219
+ }
220
+
221
+ size_t te_hash(int32_t val) {
222
+ int64_t v2 = val;
223
+ return te_hash(v2);
224
+ }
225
+
226
+ size_t te_hash(uint32_t val) {
227
+ int64_t v2 = val;
228
+ return te_hash(v2);
229
+ }
230
+
231
+ size_t te_hash(uint64_t val) {
232
+ int64_t v2 = val;
233
+ return te_hash(v2);
234
+ }
235
+
236
+ size_t te_hash(int16_t val) {
237
+ int64_t v2 = val;
238
+ return te_hash(v2);
239
+ }
240
+
241
+ size_t te_hash(std::string val) {
242
+ size_t hash{0};
243
+ int64_t intval{0};
244
+ int64_t s = val.size() - 1;
245
+ while (s >= 0) {
246
+ for (unsigned int i = 0; i < 8; ++i) {
247
+ if (s < 0)
248
+ break;
249
+ int64_t c = val[s];
250
+ intval |= (c << (i * 8));
251
+
252
+ s--;
253
+ }
254
+ hash ^= te_hash(intval);
255
+ intval = 0;
256
+ }
257
+
258
+ return hash;
259
+ }
260
+
261
+ size_t te_hash(double d) {
262
+ int64_t* n = reinterpret_cast<int64_t*>(&d);
263
+ return te_hash(*n);
264
+ }
265
+
266
+ size_t te_hash(float d) {
267
+ int32_t* n = reinterpret_cast<int32_t*>(&d);
268
+ return te_hash(*n);
269
+ }
270
+
271
+ size_t te_hash(at::Half d) {
272
+ int16_t* n = reinterpret_cast<int16_t*>(&d);
273
+ return te_hash(*n);
274
+ }
275
+
276
+ size_t te_hash(at::BFloat16 d) {
277
+ int16_t* n = reinterpret_cast<int16_t*>(&d);
278
+ return te_hash(*n);
279
+ }
280
+ };
281
+
282
+ } // namespace torch::jit::tensorexpr
283
+
284
+ #else
285
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
286
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/intrinsic_symbols.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef TORCH_ENABLE_LLVM
5
+ #include <c10/util/ArrayRef.h>
6
+
7
+ namespace torch {
8
+ namespace jit {
9
+ namespace tensorexpr {
10
+
11
+ struct SymbolAddress {
12
+ const char* symbol;
13
+ void* address;
14
+
15
+ SymbolAddress(const char* sym, void* addr) : symbol(sym), address(addr) {}
16
+ };
17
+
18
+ c10::ArrayRef<SymbolAddress> getIntrinsicSymbols();
19
+
20
+ } // namespace tensorexpr
21
+ } // namespace jit
22
+ } // namespace torch
23
+ #endif // TORCH_ENABLE_LLVM
24
+
25
+ #else
26
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
27
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir.h ADDED
@@ -0,0 +1,921 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+ #include <utility>
6
+ #include <vector>
7
+
8
+ #include <torch/csrc/jit/tensorexpr/exceptions.h>
9
+ #include <torch/csrc/jit/tensorexpr/expr.h>
10
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
11
+ #include <torch/csrc/jit/tensorexpr/stmt.h>
12
+
13
+ #include <ATen/core/ivalue.h>
14
+
15
+ namespace torch::jit::tensorexpr {
16
+
17
+ enum CompareSelectOperation {
18
+ kEQ = 0,
19
+ kGT,
20
+ kGE,
21
+ kLT,
22
+ kLE,
23
+ kNE,
24
+ };
25
+
26
+ enum CompareSelectBias {
27
+ kUnbiased,
28
+ kLikely,
29
+ kUnlikely,
30
+ };
31
+
32
+ inline int getPrecedence(IRNodeType ty) {
33
+ // Match C++ operator precedence rules, since some pretty-print expressions to
34
+ // C++. SEE: https://en.cppreference.com/w/cpp/language/operator_precedence
35
+ switch (ty) {
36
+ case kPrimitive:
37
+ return 0;
38
+ case kCast:
39
+ case kBitCast:
40
+ return 2;
41
+ case kAdd:
42
+ case kSub:
43
+ return 6;
44
+ case kMul:
45
+ case kDiv:
46
+ case kMod:
47
+ return 5;
48
+ case kMax:
49
+ case kMin:
50
+ return 99;
51
+ case kAnd:
52
+ return 11;
53
+ case kOr:
54
+ return 13;
55
+ case kLshift:
56
+ case kRshift:
57
+ return 7;
58
+ case kXor:
59
+ return 12;
60
+ case kCompareSelect:
61
+ return 16;
62
+ default:
63
+ return 99;
64
+ }
65
+ }
66
+
67
+ class TORCH_API Cast : public ExprNode<Cast> {
68
+ public:
69
+ ExprPtr src_value() const {
70
+ return src_value_;
71
+ }
72
+
73
+ void set_src_value(ExprPtr src_value) {
74
+ src_value_ = std::move(src_value);
75
+ }
76
+
77
+ static ExprHandle make(Dtype dtype, const ExprHandle& src_value) {
78
+ return ExprHandle(alloc<Cast>(dtype, src_value.node()));
79
+ }
80
+ Cast(Dtype dtype, ExprPtr src_value)
81
+ : ExprNodeBase(dtype, kCast), src_value_(std::move(src_value)) {}
82
+
83
+ bool isConstant() const override {
84
+ return src_value_->isConstant();
85
+ }
86
+
87
+ private:
88
+ ExprPtr src_value_;
89
+ };
90
+
91
+ template <typename T>
92
+ ExprHandle cast(const ExprHandle& src_value) {
93
+ return Cast::make(Dtype(ToDtype<T>(), src_value.dtype().lanes()), src_value);
94
+ }
95
+
96
+ // This is a bitwise cast, akin to bitcast in LLVM
97
+ class TORCH_API BitCast : public ExprNode<BitCast> {
98
+ public:
99
+ ExprPtr src_value() const {
100
+ return src_value_;
101
+ }
102
+
103
+ void set_src_value(ExprPtr src_value) {
104
+ src_value_ = std::move(src_value);
105
+ }
106
+
107
+ static ExprHandle make(Dtype dtype, const ExprHandle& src_value) {
108
+ return ExprHandle(alloc<BitCast>(dtype, src_value.node()));
109
+ }
110
+ BitCast(Dtype dtype, ExprPtr src_value)
111
+ : ExprNodeBase(dtype, kBitCast), src_value_(std::move(src_value)) {
112
+ TORCH_CHECK(src_value_->dtype().byte_size() == dtype.byte_size());
113
+ }
114
+
115
+ bool isConstant() const override {
116
+ return src_value_->isConstant();
117
+ }
118
+
119
+ private:
120
+ ExprPtr src_value_;
121
+ };
122
+
123
+ template <typename T>
124
+ ExprHandle bitcast(const ExprHandle& src_value) {
125
+ return BitCast::make(
126
+ Dtype(ToDtype<T>(), src_value.dtype().lanes()), src_value);
127
+ }
128
+
129
+ // Represent the expression node for binary operators.
130
+ // A CRTP pattern to share common code among the operators.
131
+ template <typename Op>
132
+ class BinaryOpNode : public ExprNode<Op> {
133
+ public:
134
+ ExprPtr lhs() const {
135
+ return this->lhs_;
136
+ }
137
+ ExprPtr rhs() const {
138
+ return this->rhs_;
139
+ }
140
+
141
+ void set_lhs(ExprPtr lhs) {
142
+ lhs_ = std::move(lhs);
143
+ }
144
+
145
+ void set_rhs(ExprPtr rhs) {
146
+ rhs_ = std::move(rhs);
147
+ }
148
+
149
+ static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) {
150
+ return ExprHandle(alloc<Op>(lhs.node(), rhs.node()));
151
+ }
152
+
153
+ BinaryOpNode(
154
+ ExprPtr lhs_v,
155
+ ExprPtr rhs_v,
156
+ IRNodeType expr_type,
157
+ ScalarType ret_type = ScalarType::Undefined)
158
+ : ExprNode<Op>(
159
+ BinaryOpDtype(lhs_v->dtype(), rhs_v->dtype(), ret_type),
160
+ expr_type),
161
+ lhs_(CastIfNeeded(std::move(lhs_v), ExprNode<Op>::dtype())),
162
+ rhs_(CastIfNeeded(std::move(rhs_v), ExprNode<Op>::dtype())) {}
163
+
164
+ private:
165
+ static ExprPtr CastIfNeeded(ExprPtr expr, Dtype dst_dtype) {
166
+ if (expr->dtype() == dst_dtype) {
167
+ return expr;
168
+ }
169
+ return Cast::make(dst_dtype, ExprHandle(std::move(expr))).node();
170
+ }
171
+
172
+ ExprPtr lhs_;
173
+ ExprPtr rhs_;
174
+ };
175
+
176
+ namespace detail {
177
+ template <typename T>
178
+ void bin_op_deducer(BinaryOpNode<T>);
179
+ bool bin_op_deducer(...);
180
+ } // namespace detail
181
+
182
+ class TORCH_API Add : public BinaryOpNode<Add> {
183
+ public:
184
+ Add(ExprPtr lhs, ExprPtr rhs)
185
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kAdd) {}
186
+ };
187
+
188
+ class TORCH_API Sub : public BinaryOpNode<Sub> {
189
+ public:
190
+ Sub(ExprPtr lhs, ExprPtr rhs)
191
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kSub) {}
192
+ };
193
+
194
+ class TORCH_API Mul : public BinaryOpNode<Mul> {
195
+ public:
196
+ Mul(ExprPtr lhs, ExprPtr rhs)
197
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMul) {}
198
+ };
199
+
200
+ class TORCH_API Div : public BinaryOpNode<Div> {
201
+ public:
202
+ Div(ExprPtr lhs, ExprPtr rhs)
203
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kDiv) {}
204
+ };
205
+
206
+ class TORCH_API Mod : public BinaryOpNode<Mod> {
207
+ public:
208
+ Mod(ExprPtr lhs, ExprPtr rhs)
209
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMod) {}
210
+ };
211
+
212
+ template <typename Op>
213
+ class BitwiseOpNode : public BinaryOpNode<Op> {
214
+ public:
215
+ BitwiseOpNode(ExprPtr lhs, ExprPtr rhs, IRNodeType type)
216
+ : BinaryOpNode<Op>(std::move(lhs), std::move(rhs), type) {}
217
+
218
+ static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) {
219
+ if (!lhs.dtype().is_integral()) {
220
+ throw unsupported_dtype();
221
+ }
222
+ if (lhs.dtype() != rhs.dtype()) {
223
+ throw malformed_input("lhs/rhs dtype mismatch");
224
+ }
225
+ return BinaryOpNode<Op>::make(lhs, rhs);
226
+ }
227
+ };
228
+
229
+ class TORCH_API And : public BitwiseOpNode<And> {
230
+ public:
231
+ And(ExprPtr lhs, ExprPtr rhs)
232
+ : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kAnd) {}
233
+ };
234
+
235
+ class TORCH_API Or : public BitwiseOpNode<Or> {
236
+ public:
237
+ Or(ExprPtr lhs, ExprPtr rhs)
238
+ : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kOr) {}
239
+ };
240
+
241
+ class TORCH_API Xor : public BitwiseOpNode<Xor> {
242
+ public:
243
+ Xor(ExprPtr lhs, ExprPtr rhs)
244
+ : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kXor) {}
245
+ };
246
+
247
+ class TORCH_API Lshift : public BitwiseOpNode<Lshift> {
248
+ public:
249
+ Lshift(ExprPtr lhs, ExprPtr rhs)
250
+ : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kLshift) {}
251
+ };
252
+
253
+ class TORCH_API Rshift : public BitwiseOpNode<Rshift> {
254
+ public:
255
+ Rshift(ExprPtr lhs, ExprPtr rhs)
256
+ : BitwiseOpNode(std::move(lhs), std::move(rhs), IRNodeType::kRshift) {}
257
+ };
258
+
259
+ // TODO: add TORCH_API
260
+ // Currently adding it results in a compilation error on Windows
261
+ class Max : public BinaryOpNode<Max> {
262
+ private:
263
+ bool propagate_nans_;
264
+
265
+ public:
266
+ Max(ExprPtr lhs, ExprPtr rhs, bool propagate_nans)
267
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMax),
268
+ propagate_nans_(propagate_nans) {}
269
+
270
+ bool propagate_nans() const {
271
+ return propagate_nans_;
272
+ }
273
+
274
+ static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) = delete;
275
+ static ExprHandle make(
276
+ const ExprHandle& lhs,
277
+ const ExprHandle& rhs,
278
+ bool propagate_nans) {
279
+ return ExprHandle(alloc<Max>(lhs.node(), rhs.node(), propagate_nans));
280
+ }
281
+ };
282
+
283
+ // TODO: add TORCH_API
284
+ // Currently adding it results in a compilation error on Windows
285
+ class Min : public BinaryOpNode<Min> {
286
+ private:
287
+ bool propagate_nans_;
288
+
289
+ public:
290
+ Min(ExprPtr lhs, ExprPtr rhs, bool propagate_nans)
291
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kMin),
292
+ propagate_nans_(propagate_nans) {}
293
+
294
+ bool propagate_nans() const {
295
+ return propagate_nans_;
296
+ }
297
+
298
+ static ExprHandle make(const ExprHandle& lhs, const ExprHandle& rhs) = delete;
299
+ static ExprHandle make(
300
+ const ExprHandle& lhs,
301
+ const ExprHandle& rhs,
302
+ bool propagate_nans) {
303
+ return ExprHandle(alloc<Min>(lhs.node(), rhs.node(), propagate_nans));
304
+ }
305
+ };
306
+
307
+ // Encode typed immediate values e.g. IntImm, FloatImm.
308
+ #define IMM_DECLARE(Type, Name) \
309
+ class TORCH_API Name##Imm : public ExprNode<Name##Imm> { \
310
+ public: \
311
+ Name##Imm(Type value) \
312
+ : ExprNodeBase(k##Name, kPrimitive), value_(value) {} \
313
+ bool isConstant() const override { \
314
+ return true; \
315
+ } \
316
+ Type value() const { \
317
+ return value_; \
318
+ } \
319
+ static ExprHandle make(Type value) { \
320
+ return ExprHandle(alloc<Name##Imm>(value)); \
321
+ } \
322
+ \
323
+ private: \
324
+ Type value_; \
325
+ };
326
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_DECLARE)
327
+ #undef IMM_DECLARE
328
+
329
+ // Get immediate by ScalarType.
330
+ template <typename T>
331
+ ExprPtr getImmediateByType(ScalarType immType, T initialVal) {
332
+ switch (immType) {
333
+ #define TYPE_CASE(Type, Name) \
334
+ case ScalarType::Name: \
335
+ return alloc<Name##Imm>(Type(initialVal));
336
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE)
337
+ #undef TYPE_CASE
338
+ default:
339
+ throw unsupported_dtype();
340
+ }
341
+ return nullptr;
342
+ }
343
+
344
+ template <typename T>
345
+ ExprPtr getImmediateByType(Dtype dtype, T initialVal) {
346
+ return getImmediateByType<T>(dtype.scalar_type(), initialVal);
347
+ }
348
+
349
+ template <typename T>
350
+ ExprPtr immLike(const ExprPtr& e, T v) {
351
+ return getImmediateByType<T>(e->dtype(), v);
352
+ }
353
+
354
+ template <typename T>
355
+ ExprPtr immLike(const ExprHandle& e, T v) {
356
+ return immLike(e.node(), v);
357
+ }
358
+
359
+ inline std::optional<int64_t> intValue(const ExprPtr& e) {
360
+ #define TYPE_CASE(Type, Name) \
361
+ if (auto v = to<Name##Imm>(e)) { \
362
+ return v->value(); \
363
+ }
364
+ AT_FORALL_INT_TYPES(TYPE_CASE);
365
+ #undef TYPE_CASE
366
+ return std::nullopt;
367
+ }
368
+
369
+ inline std::optional<int64_t> intValue(const ExprHandle& e) {
370
+ return intValue(e.node());
371
+ }
372
+
373
+ template <typename T>
374
+ T immediateAs(const ExprPtr& e) {
375
+ #define TYPE_CASE(Type, Name) \
376
+ if (Name##ImmPtr imm = to<Name##Imm>(e)) { \
377
+ return imm->value(); \
378
+ }
379
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE)
380
+ #undef TYPE_CASE
381
+ throw unsupported_dtype();
382
+ return 0;
383
+ }
384
+
385
+ template <typename T>
386
+ T immediateAs(const ExprHandle& e) {
387
+ return immediateAs<T>(e.node());
388
+ }
389
+
390
+ template <typename T>
391
+ bool immediateEquals(const ExprPtr& e, T val) {
392
+ #define TYPE_CASE(Type, Name) \
393
+ if (Name##ImmPtr imm = to<Name##Imm>(e)) { \
394
+ return imm->value() == val; \
395
+ }
396
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE)
397
+ #undef TYPE_CASE
398
+ throw unsupported_dtype();
399
+ return false;
400
+ }
401
+
402
+ TORCH_API bool immediateIsNegative(const ExprPtr& e);
403
+
404
+ TORCH_API bool immediateIsPositive(const ExprPtr& e);
405
+
406
+ TORCH_API bool immediateIsZero(const ExprPtr& e);
407
+
408
+ // Represents a ramp vector node:
409
+ // [base, base + 1 * stride, ... , base + (lanes - 1) * stride]
410
+ class TORCH_API Ramp : public ExprNode<Ramp> {
411
+ public:
412
+ ExprPtr base() const {
413
+ return base_;
414
+ }
415
+ ExprPtr stride() const {
416
+ return stride_;
417
+ }
418
+
419
+ void set_base(ExprPtr base) {
420
+ base_ = std::move(base);
421
+ }
422
+
423
+ void set_stride(ExprPtr stride) {
424
+ stride_ = std::move(stride);
425
+ }
426
+
427
+ static ExprHandle make(
428
+ const ExprHandle& base,
429
+ const ExprHandle& stride,
430
+ int64_t lanes) {
431
+ if (stride.dtype() != base.dtype()) {
432
+ throw malformed_input("Bad stride in Ramp");
433
+ }
434
+ return ExprHandle(alloc<Ramp>(base.node(), stride.node(), lanes));
435
+ }
436
+ int64_t lanes() const {
437
+ return lanes_;
438
+ }
439
+
440
+ Ramp(ExprPtr base, ExprPtr stride, int64_t lanes)
441
+ : ExprNodeBase(Dtype(base->dtype(), lanes)),
442
+ base_(std::move(base)),
443
+ stride_(std::move(stride)),
444
+ lanes_(lanes) {}
445
+
446
+ private:
447
+ ExprPtr base_;
448
+ ExprPtr stride_;
449
+ int64_t lanes_;
450
+ };
451
+
452
+ class TORCH_API Load : public ExprNode<Load> {
453
+ public:
454
+ VarPtr base_handle() const {
455
+ return buf_->base_handle();
456
+ }
457
+ std::vector<ExprPtr> indices() const {
458
+ return indices_;
459
+ }
460
+ ExprPtr flat_index() const {
461
+ TORCH_CHECK(indices_.size() == 1, "Indices haven't been flattened.");
462
+ return indices_[0];
463
+ }
464
+ BufPtr buf() const {
465
+ return buf_;
466
+ }
467
+
468
+ void set_buf(BufPtr buf) {
469
+ buf_ = std::move(buf);
470
+ }
471
+
472
+ void set_indices(std::vector<ExprPtr> indices) {
473
+ indices_ = std::move(indices);
474
+ }
475
+
476
+ static ExprHandle make(
477
+ Dtype dtype,
478
+ const BufHandle& buf,
479
+ const std::vector<ExprHandle>& indices);
480
+ static ExprHandle make(
481
+ const BufHandle& buf,
482
+ const std::vector<ExprHandle>& indices);
483
+
484
+ Load(Dtype dtype, BufPtr base_handle, std::vector<ExprPtr> indices);
485
+ Load(const BufPtr& base_handle, const std::vector<ExprPtr>& indices);
486
+
487
+ private:
488
+ BufPtr buf_;
489
+ std::vector<ExprPtr> indices_;
490
+ };
491
+
492
+ class TORCH_API Broadcast : public ExprNode<Broadcast> {
493
+ public:
494
+ ExprPtr value() const {
495
+ return value_;
496
+ }
497
+
498
+ void set_value(ExprPtr value) {
499
+ value_ = std::move(value);
500
+ }
501
+
502
+ int64_t lanes() const {
503
+ return lanes_;
504
+ }
505
+ static ExprHandle make(const ExprHandle& value, int64_t lanes) {
506
+ return ExprHandle(alloc<Broadcast>(value.node(), lanes));
507
+ }
508
+ Broadcast(ExprPtr value, int64_t lanes)
509
+ : ExprNodeBase(Dtype(value->dtype(), lanes)),
510
+ value_(std::move(value)),
511
+ lanes_(lanes) {}
512
+
513
+ private:
514
+ ExprPtr value_;
515
+ int64_t lanes_;
516
+ };
517
+
518
+ class TORCH_API IfThenElse : public ExprNode<IfThenElse> {
519
+ public:
520
+ ExprPtr condition() const {
521
+ return condition_;
522
+ }
523
+
524
+ // Lazily evaluated only if condition is true
525
+ ExprPtr true_value() const {
526
+ return true_;
527
+ }
528
+
529
+ // Lazily evaluated only if condition is false
530
+ ExprPtr false_value() const {
531
+ return false_;
532
+ }
533
+
534
+ void set_condition(ExprPtr condition) {
535
+ condition_ = std::move(condition);
536
+ }
537
+
538
+ void set_true_value(ExprPtr true_value) {
539
+ true_ = std::move(true_value);
540
+ }
541
+
542
+ void set_false_value(ExprPtr false_value) {
543
+ false_ = std::move(false_value);
544
+ }
545
+
546
+ static ExprHandle make(
547
+ const ExprHandle& c,
548
+ const ExprHandle& t,
549
+ const ExprHandle& f) {
550
+ if (!c.dtype().is_integral()) {
551
+ throw unsupported_dtype();
552
+ }
553
+ if (c.dtype().lanes() != 1) {
554
+ throw unsupported_dtype();
555
+ }
556
+ if (t.dtype() != f.dtype()) {
557
+ throw malformed_input("Bad dtype in IfThenElse");
558
+ }
559
+ return ExprHandle(alloc<IfThenElse>(c.node(), t.node(), f.node()));
560
+ }
561
+
562
+ IfThenElse(ExprPtr c, ExprPtr t, ExprPtr f)
563
+ : ExprNodeBase(t->dtype()),
564
+ condition_(std::move(c)),
565
+ true_(std::move(t)),
566
+ false_(std::move(f)) {}
567
+
568
+ private:
569
+ ExprPtr condition_;
570
+ ExprPtr true_;
571
+ ExprPtr false_;
572
+ };
573
+
574
+ class TORCH_API CompareSelect : public ExprNode<CompareSelect> {
575
+ public:
576
+ CompareSelectOperation compare_select_op() const {
577
+ return compare_op_;
578
+ }
579
+ ExprPtr lhs() const {
580
+ return this->lhs_;
581
+ }
582
+ ExprPtr rhs() const {
583
+ return this->rhs_;
584
+ }
585
+ ExprPtr ret_val1() const {
586
+ return this->ret_val1_;
587
+ }
588
+ ExprPtr ret_val2() const {
589
+ return this->ret_val2_;
590
+ }
591
+
592
+ void set_lhs(ExprPtr lhs) {
593
+ lhs_ = std::move(lhs);
594
+ }
595
+
596
+ void set_rhs(ExprPtr rhs) {
597
+ rhs_ = std::move(rhs);
598
+ }
599
+
600
+ void set_ret_val1(ExprPtr ret_val1) {
601
+ ret_val1_ = std::move(ret_val1);
602
+ }
603
+
604
+ void set_ret_val2(ExprPtr ret_val2) {
605
+ ret_val2_ = std::move(ret_val2);
606
+ }
607
+
608
+ CompareSelectBias bias() const {
609
+ return bias_;
610
+ }
611
+
612
+ static ExprHandle make(
613
+ const ExprHandle& lhs,
614
+ const ExprHandle& rhs,
615
+ CompareSelectOperation cmp_op,
616
+ CompareSelectBias bias = kUnbiased) {
617
+ if (lhs.dtype() != rhs.dtype()) {
618
+ throw malformed_input("bad dtype in CompareSelect");
619
+ }
620
+ return ExprHandle(alloc<CompareSelect>(
621
+ lhs.node(),
622
+ rhs.node(),
623
+ IntImm::make(1).node(),
624
+ IntImm::make(0).node(),
625
+ cmp_op,
626
+ bias));
627
+ }
628
+
629
+ static ExprHandle make(
630
+ const ExprHandle& lhs,
631
+ const ExprHandle& rhs,
632
+ const ExprHandle& ret_val1,
633
+ const ExprHandle& ret_val2,
634
+ CompareSelectOperation cmp_op,
635
+ CompareSelectBias bias = kUnbiased) {
636
+ if (lhs.dtype() != rhs.dtype() || ret_val1.dtype() != ret_val2.dtype()) {
637
+ throw malformed_input("bad dtype in CompareSelect");
638
+ }
639
+ return ExprHandle(alloc<CompareSelect>(
640
+ lhs.node(),
641
+ rhs.node(),
642
+ ret_val1.node(),
643
+ ret_val2.node(),
644
+ cmp_op,
645
+ bias));
646
+ }
647
+
648
+ CompareSelect(
649
+ ExprPtr lhs,
650
+ ExprPtr rhs,
651
+ ExprPtr ret_val1,
652
+ ExprPtr ret_val2,
653
+ CompareSelectOperation cmp_op,
654
+ CompareSelectBias bias = kUnbiased)
655
+ : ExprNodeBase(ret_val1->dtype()),
656
+ lhs_(std::move(lhs)),
657
+ rhs_(std::move(rhs)),
658
+ ret_val1_(std::move(ret_val1)),
659
+ ret_val2_(std::move(ret_val2)),
660
+ compare_op_(cmp_op),
661
+ bias_(bias) {}
662
+
663
+ CompareSelect(
664
+ ExprPtr lhs,
665
+ ExprPtr rhs,
666
+ CompareSelectOperation cmp_op,
667
+ CompareSelectBias bias = kUnbiased)
668
+ : ExprNodeBase(kInt),
669
+ lhs_(std::move(lhs)),
670
+ rhs_(std::move(rhs)),
671
+ ret_val1_(alloc<IntImm>(1)),
672
+ ret_val2_(alloc<IntImm>(0)),
673
+ compare_op_(cmp_op),
674
+ bias_(bias) {}
675
+
676
+ private:
677
+ ExprPtr lhs_;
678
+ ExprPtr rhs_;
679
+ ExprPtr ret_val1_;
680
+ ExprPtr ret_val2_;
681
+ CompareSelectOperation compare_op_;
682
+ CompareSelectBias bias_;
683
+ };
684
+
685
+ enum IntrinsicsOp {
686
+ kSin,
687
+ kCos,
688
+ kTan,
689
+ kAsin,
690
+ kAcos,
691
+ kAtan,
692
+ kAtan2,
693
+ kSinh,
694
+ kCosh,
695
+ kTanh,
696
+ kSigmoid,
697
+ kExp,
698
+ kExpm1,
699
+ kAbs,
700
+ kLog,
701
+ kLog2,
702
+ kLog10,
703
+ kLog1p,
704
+ kErf,
705
+ kErfc,
706
+ kSqrt,
707
+ kRsqrt,
708
+ kPow,
709
+ kCeil,
710
+ kFloor,
711
+ kRound,
712
+ kTrunc,
713
+ kFmod,
714
+ kRemainder,
715
+ kLgamma,
716
+ kFrac,
717
+ kIsNan,
718
+ kRand, // We need more discussions on this. Should we consider stateful?
719
+ kMaxIntrinsicsOp,
720
+ };
721
+
722
+ class TORCH_API Intrinsics : public ExprNode<Intrinsics> {
723
+ public:
724
+ static ExprHandle make(IntrinsicsOp op_type, const ExprHandle& v1) {
725
+ return ExprHandle(alloc<Intrinsics>(op_type, v1.node()));
726
+ }
727
+
728
+ static ExprHandle make(
729
+ IntrinsicsOp op_type,
730
+ const ExprHandle& v1,
731
+ const ExprHandle& v2) {
732
+ return ExprHandle(alloc<Intrinsics>(op_type, v1.node(), v2.node()));
733
+ }
734
+
735
+ static ExprHandle make(
736
+ IntrinsicsOp op_type,
737
+ const std::vector<ExprHandle>& params) {
738
+ std::vector<ExprPtr> params_nodes(params.size());
739
+ for (size_t i = 0; i < params.size(); i++) {
740
+ params_nodes[i] = params[i].node();
741
+ }
742
+ return ExprHandle(alloc<Intrinsics>(op_type, params_nodes));
743
+ }
744
+
745
+ static ExprHandle make(IntrinsicsOp op_type, Dtype dtype) {
746
+ return ExprHandle(alloc<Intrinsics>(op_type, dtype));
747
+ }
748
+
749
+ IntrinsicsOp op_type() const {
750
+ return op_type_;
751
+ }
752
+
753
+ std::string func_name() const {
754
+ switch (op_type()) {
755
+ case kSin:
756
+ return "sin";
757
+ case kCos:
758
+ return "cos";
759
+ case kTan:
760
+ return "tan";
761
+ case kAsin:
762
+ return "asin";
763
+ case kAcos:
764
+ return "acos";
765
+ case kAtan:
766
+ return "atan";
767
+ case kAtan2:
768
+ return "atan2";
769
+ case kSinh:
770
+ return "sinh";
771
+ case kCosh:
772
+ return "cosh";
773
+ case kTanh:
774
+ return "tanh";
775
+ case kSigmoid:
776
+ return "sigmoid";
777
+ case kExp:
778
+ return "exp";
779
+ case kAbs:
780
+ return "abs";
781
+ case kLog:
782
+ return "log";
783
+ case kLog2:
784
+ return "log2";
785
+ case kLog10:
786
+ return "log10";
787
+ case kLog1p:
788
+ return "log1p";
789
+ case kErf:
790
+ return "erf";
791
+ case kSqrt:
792
+ return "sqrt";
793
+ case kRsqrt:
794
+ return "rsqrt";
795
+ case kPow:
796
+ return "pow";
797
+ case kCeil:
798
+ return "ceil";
799
+ case kFloor:
800
+ return "floor";
801
+ case kRound:
802
+ return "round";
803
+ case kTrunc:
804
+ return "trunc";
805
+ case kRand:
806
+ return "rand";
807
+ case kFmod:
808
+ return "fmod";
809
+ case kRemainder:
810
+ return "remainder";
811
+ case kLgamma:
812
+ return "lgamma";
813
+ case kExpm1:
814
+ return "expm1";
815
+ case kErfc:
816
+ return "erfc";
817
+ case kFrac:
818
+ return "frac";
819
+ case kIsNan:
820
+ return "isnan";
821
+ default:
822
+ throw std::runtime_error(
823
+ "invalid op_type: " + std::to_string(op_type()));
824
+ }
825
+ }
826
+
827
+ Intrinsics(IntrinsicsOp op_type, Dtype dtype)
828
+ : ExprNodeBase(IntrinsicsDtype(op_type, dtype)),
829
+ params_({}),
830
+ op_type_(op_type) {
831
+ if (OpArgCount(op_type) != 0) {
832
+ throw malformed_input("bad arg count in Intrinsics");
833
+ }
834
+ }
835
+
836
+ Intrinsics(IntrinsicsOp op_type, ExprPtr v1)
837
+ : ExprNodeBase(IntrinsicsDtype(op_type, v1->dtype())),
838
+ params_({std::move(v1)}),
839
+ op_type_(op_type) {
840
+ if (OpArgCount(op_type) != 1) {
841
+ throw malformed_input("bad arg count in Intrinsics");
842
+ }
843
+ }
844
+
845
+ Intrinsics(IntrinsicsOp op_type, ExprPtr v1, ExprPtr v2)
846
+ : ExprNodeBase(IntrinsicsDtype(op_type, v1->dtype(), v2->dtype())),
847
+ params_({std::move(v1), std::move(v2)}),
848
+ op_type_(op_type) {
849
+ if (OpArgCount(op_type) != 2) {
850
+ throw malformed_input("bad arg count in Intrinsics");
851
+ }
852
+ }
853
+
854
+ Intrinsics(IntrinsicsOp op_type, const std::vector<ExprPtr>& params)
855
+ : ExprNodeBase(IntrinsicsDtype(op_type, params)),
856
+ params_(params),
857
+ op_type_(op_type) {
858
+ if (OpArgCount(op_type) != nparams()) {
859
+ throw malformed_input("bad arg count in Intrinsics");
860
+ }
861
+ }
862
+
863
+ Intrinsics(IntrinsicsOp op_type, Dtype dtype, std::vector<ExprPtr> params)
864
+ : ExprNodeBase(IntrinsicsDtype(op_type, dtype)),
865
+ params_(std::move(params)),
866
+ op_type_(op_type) {
867
+ if (OpArgCount(op_type) != nparams()) {
868
+ throw malformed_input("bad arg count in Intrinsics");
869
+ }
870
+ }
871
+
872
+ bool isPure() const {
873
+ return op_type_ != kRand;
874
+ }
875
+
876
+ size_t nparams() const {
877
+ return params_.size();
878
+ }
879
+
880
+ ExprPtr param(size_t index) const {
881
+ return params_[index];
882
+ }
883
+ const std::vector<ExprPtr>& params() const {
884
+ return params_;
885
+ }
886
+
887
+ void set_params(std::vector<ExprPtr> params) {
888
+ params_ = std::move(params);
889
+ }
890
+
891
+ static size_t OpArgCount(IntrinsicsOp op_type);
892
+
893
+ private:
894
+ static Dtype IntrinsicsDtype(IntrinsicsOp op_type, Dtype dt1);
895
+ static Dtype IntrinsicsDtype(IntrinsicsOp op_type, Dtype dt1, Dtype dt2);
896
+ static Dtype IntrinsicsDtype(
897
+ IntrinsicsOp op_type,
898
+ const std::vector<ExprPtr>& params);
899
+
900
+ std::vector<ExprPtr> params_;
901
+ IntrinsicsOp op_type_;
902
+ };
903
+
904
+ TORCH_API std::vector<ExprPtr> ExprHandleVectorToExprVector(
905
+ const std::vector<ExprHandle>& /*v*/);
906
+ TORCH_API std::vector<ExprHandle> ExprVectorToExprHandleVector(
907
+ const std::vector<ExprPtr>& /*v*/);
908
+ TORCH_API std::vector<VarPtr> VarHandleVectorToVarVector(
909
+ const std::vector<VarHandle>& /*v*/);
910
+ TORCH_API std::vector<VarHandle> VarVectorToVarHandleVector(
911
+ const std::vector<VarPtr>& /*v*/);
912
+ TORCH_API ExprPtr flatten_index(
913
+ const std::vector<ExprPtr>& dims,
914
+ const std::vector<ExprPtr>& indices,
915
+ const std::vector<ExprPtr>& strides);
916
+
917
+ } // namespace torch::jit::tensorexpr
918
+
919
+ #else
920
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
921
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_cloner.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <torch/csrc/Export.h>
5
+ #include <vector>
6
+
7
+ #include <torch/csrc/jit/tensorexpr/ir_mutator.h>
8
+
9
+ namespace torch::jit::tensorexpr {
10
+
11
+ class TORCH_API IRCloner : public IRMutator {
12
+ public:
13
+ ~IRCloner() override = default;
14
+ ExprPtr mutate(const AddPtr& v) override;
15
+ ExprPtr mutate(const SubPtr& v) override;
16
+ ExprPtr mutate(const MulPtr& v) override;
17
+ ExprPtr mutate(const DivPtr& v) override;
18
+ ExprPtr mutate(const ModPtr& v) override;
19
+ ExprPtr mutate(const MaxPtr& v) override;
20
+ ExprPtr mutate(const MinPtr& v) override;
21
+ ExprPtr mutate(const AndPtr& v) override;
22
+ ExprPtr mutate(const OrPtr& v) override;
23
+ ExprPtr mutate(const XorPtr& v) override;
24
+ ExprPtr mutate(const LshiftPtr& v) override;
25
+ ExprPtr mutate(const RshiftPtr& v) override;
26
+ ExprPtr mutate(const CompareSelectPtr& v) override;
27
+ #define IMM_MUTATE_DECLARE(Type, Name) \
28
+ ExprPtr mutate(const Name##ImmPtr& v) override;
29
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_MUTATE_DECLARE)
30
+ #undef IMM_MUTATE_DECLARE
31
+ ExprPtr mutate(const CastPtr& v) override;
32
+ ExprPtr mutate(const BitCastPtr& v) override;
33
+ ExprPtr mutate(const VarPtr& v) override;
34
+ ExprPtr mutate(const BufPtr& v) override;
35
+ ExprPtr mutate(const RampPtr& v) override;
36
+ ExprPtr mutate(const LoadPtr& v) override;
37
+ ExprPtr mutate(const BroadcastPtr& v) override;
38
+ ExprPtr mutate(const IfThenElsePtr& v) override;
39
+ ExprPtr mutate(const IntrinsicsPtr& v) override;
40
+
41
+ ExprPtr mutate(const TermPtr& v) override;
42
+ ExprPtr mutate(const PolynomialPtr& v) override;
43
+ ExprPtr mutate(const RoundOffPtr& v) override;
44
+ ExprPtr mutate(const MaxTermPtr& v) override;
45
+ ExprPtr mutate(const MinTermPtr& v) override;
46
+
47
+ ExprPtr mutate(const ReduceOpPtr& v) override;
48
+
49
+ StmtPtr mutate(const ForPtr& v) override;
50
+ StmtPtr mutate(const BlockPtr& v) override;
51
+ StmtPtr mutate(const StorePtr& v) override;
52
+ StmtPtr mutate(const AtomicAddPtr& v) override;
53
+ StmtPtr mutate(const SyncThreadsPtr& v) override;
54
+ StmtPtr mutate(const ExternalCallPtr& v) override;
55
+ StmtPtr mutate(const ExternalCallWithAllocPtr& v) override;
56
+
57
+ StmtPtr mutate(const AllocatePtr& v) override;
58
+ StmtPtr mutate(const FreePtr& v) override;
59
+ StmtPtr mutate(const LetPtr& v) override;
60
+ StmtPtr mutate(const CondPtr& v) override;
61
+ };
62
+
63
+ } // namespace torch::jit::tensorexpr
64
+
65
+ #else
66
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
67
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_mutator.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
6
+
7
+ namespace torch::jit::tensorexpr {
8
+
9
+ class TORCH_API IRMutator {
10
+ public:
11
+ virtual ~IRMutator() = default;
12
+ virtual ExprPtr mutate(const AddPtr& v);
13
+ virtual ExprPtr mutate(const SubPtr& v);
14
+ virtual ExprPtr mutate(const MulPtr& v);
15
+ virtual ExprPtr mutate(const DivPtr& v);
16
+ virtual ExprPtr mutate(const ModPtr& v);
17
+ virtual ExprPtr mutate(const MaxPtr& v);
18
+ virtual ExprPtr mutate(const MinPtr& v);
19
+ virtual ExprPtr mutate(const AndPtr& v);
20
+ virtual ExprPtr mutate(const OrPtr& v);
21
+ virtual ExprPtr mutate(const XorPtr& v);
22
+ virtual ExprPtr mutate(const LshiftPtr& v);
23
+ virtual ExprPtr mutate(const RshiftPtr& v);
24
+ virtual ExprPtr mutate(const CompareSelectPtr& v);
25
+ #define IMM_MUTATE_DECLARE(Type, Name) \
26
+ virtual ExprPtr mutate(const Name##ImmPtr& v);
27
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_MUTATE_DECLARE)
28
+ #undef IMM_MUTATE_DECLARE
29
+ virtual ExprPtr mutate(const CastPtr& v);
30
+ virtual ExprPtr mutate(const BitCastPtr& v);
31
+ virtual ExprPtr mutate(const VarPtr& v);
32
+ virtual ExprPtr mutate(const BufPtr& v);
33
+ virtual ExprPtr mutate(const RampPtr& v);
34
+ virtual ExprPtr mutate(const LoadPtr& v);
35
+ virtual ExprPtr mutate(const BroadcastPtr& v);
36
+ virtual ExprPtr mutate(const IfThenElsePtr& v);
37
+ virtual ExprPtr mutate(const IntrinsicsPtr& v);
38
+
39
+ virtual ExprPtr mutate(const TermPtr& v);
40
+ virtual ExprPtr mutate(const PolynomialPtr& v);
41
+ virtual ExprPtr mutate(const RoundOffPtr& v);
42
+ virtual ExprPtr mutate(const MaxTermPtr& v);
43
+ virtual ExprPtr mutate(const MinTermPtr& v);
44
+
45
+ virtual ExprPtr mutate(const ReduceOpPtr& v);
46
+
47
+ virtual StmtPtr mutate(const ForPtr& v);
48
+ virtual StmtPtr mutate(const BlockPtr& v);
49
+ virtual StmtPtr mutate(const StorePtr& v);
50
+ virtual StmtPtr mutate(const AtomicAddPtr& v);
51
+ virtual StmtPtr mutate(const SyncThreadsPtr& v);
52
+ virtual StmtPtr mutate(const ExternalCallPtr& v);
53
+ virtual StmtPtr mutate(const ExternalCallWithAllocPtr& v);
54
+
55
+ virtual StmtPtr mutate(const AllocatePtr& v);
56
+ virtual StmtPtr mutate(const FreePtr& v);
57
+ virtual StmtPtr mutate(const FreeExtPtr& v);
58
+ virtual StmtPtr mutate(const PlacementAllocatePtr& v);
59
+ virtual StmtPtr mutate(const LetPtr& v);
60
+ virtual StmtPtr mutate(const CondPtr& v);
61
+ };
62
+
63
+ } // namespace torch::jit::tensorexpr
64
+
65
+ #else
66
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
67
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_printer.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <ostream>
5
+
6
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
7
+ #include <torch/csrc/jit/tensorexpr/ir.h>
8
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
9
+ #include <torch/csrc/jit/tensorexpr/unique_name_manager.h>
10
+
11
+ namespace torch::jit::tensorexpr {
12
+
13
+ class Tensor;
14
+
15
+ class TORCH_API IRPrinter : public IRVisitor {
16
+ public:
17
+ explicit IRPrinter(std::ostream& os) : printer_os_(this, os) {}
18
+
19
+ void print(ExprHandle /*expr*/);
20
+ void print(Expr& /*expr*/);
21
+ void print(Stmt& /*stmt*/);
22
+ void visit(const AddPtr& v) override;
23
+ void visit(const SubPtr& v) override;
24
+ void visit(const MulPtr& v) override;
25
+ void visit(const DivPtr& v) override;
26
+ void visit(const ModPtr& v) override;
27
+ void visit(const MaxPtr& v) override;
28
+ void visit(const MinPtr& v) override;
29
+ void visit(const AndPtr& v) override;
30
+ void visit(const OrPtr& v) override;
31
+ void visit(const XorPtr& v) override;
32
+ void visit(const LshiftPtr& v) override;
33
+ void visit(const RshiftPtr& v) override;
34
+ void visit(const CompareSelectPtr& v) override;
35
+ #define IMM_PRINT_VISIT(Type, Name) void visit(const Name##ImmPtr& v) override;
36
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_PRINT_VISIT)
37
+ #undef IMM_PRINT_VISIT
38
+ void visit(const CastPtr& v) override;
39
+ void visit(const BitCastPtr& v) override;
40
+ void visit(const VarPtr& v) override;
41
+ void visit(const BufPtr& v) override;
42
+ void visit(const RampPtr& v) override;
43
+ void visit(const LoadPtr& v) override;
44
+ void visit(const BroadcastPtr& v) override;
45
+ void visit(const IfThenElsePtr& v) override;
46
+ void visit(const IntrinsicsPtr& v) override;
47
+ void visit(const TermPtr& v) override;
48
+ void visit(const PolynomialPtr& v) override;
49
+ void visit(const RoundOffPtr& v) override;
50
+ void visit(const MaxTermPtr& v) override;
51
+ void visit(const MinTermPtr& v) override;
52
+ void visit(const ReduceOpPtr& v) override;
53
+
54
+ void visit(const AtomicAddPtr& v) override;
55
+ void visit(const SyncThreadsPtr& v) override;
56
+ void visit(const ExternalCallPtr& v) override;
57
+ void visit(const ExternalCallWithAllocPtr& v) override;
58
+ void visit(const StorePtr& v) override;
59
+ void visit(const ForPtr& v) override;
60
+ void visit(const CondPtr& v) override;
61
+ void visit(const BlockPtr& v) override;
62
+ void visit(const AllocatePtr& v) override;
63
+ void visit(const FreePtr& v) override;
64
+ void visit(const FreeExtPtr& v) override;
65
+ void visit(const PlacementAllocatePtr& v) override;
66
+ void visit(const LetPtr& v) override;
67
+
68
+ // A child class may have a difference rule for generating dtype
69
+ // string, e.g. CUDA needs int64_t to be generated as long long.
70
+ virtual std::string dtypeToCppString(const Dtype& dtype);
71
+
72
+ std::ostream& os() {
73
+ return printer_os_;
74
+ }
75
+
76
+ class PrinterStream : public std::ostream {
77
+ public:
78
+ PrinterStream(IRPrinter* printer, std::ostream& os)
79
+ : std::ostream(os.rdbuf()), printer_(printer) {
80
+ initialize_imbue();
81
+ }
82
+
83
+ void initialize_imbue();
84
+
85
+ IRPrinter* printer() {
86
+ return printer_;
87
+ }
88
+
89
+ private:
90
+ IRPrinter* printer_ = nullptr;
91
+ };
92
+
93
+ protected:
94
+ std::string to_string(CompareSelectOperation op);
95
+
96
+ UniqueNameManager* name_manager() {
97
+ return &name_manager_;
98
+ }
99
+ void emitIndent();
100
+
101
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
102
+ int indent_ = 0;
103
+
104
+ private:
105
+ PrinterStream printer_os_;
106
+ UniqueNameManager name_manager_;
107
+ };
108
+
109
+ TORCH_API std::ostream& operator<<(std::ostream& stream, const Expr& /*expr*/);
110
+ TORCH_API std::ostream& operator<<(
111
+ std::ostream& stream,
112
+ const ExprHandle& /*expr*/);
113
+ TORCH_API std::ostream& operator<<(std::ostream& stream, const Stmt& /*stmt*/);
114
+ TORCH_API std::ostream& operator<<(std::ostream& stream, const Tensor& /*t*/);
115
+
116
+ TORCH_API void print(const ExprPtr& expr);
117
+ TORCH_API void print(const StmtPtr& stmt);
118
+ TORCH_API void print(const Tensor& t);
119
+
120
+ } // namespace torch::jit::tensorexpr
121
+
122
+ namespace std {
123
+
124
+ using torch::jit::tensorexpr::Expr;
125
+ using torch::jit::tensorexpr::ExprPtr;
126
+ using torch::jit::tensorexpr::Stmt;
127
+ using torch::jit::tensorexpr::StmtPtr;
128
+ using torch::jit::tensorexpr::Tensor;
129
+
130
+ TORCH_API std::string to_string(const ExprPtr& expr);
131
+ TORCH_API std::string to_string(const StmtPtr& stmt);
132
+ TORCH_API std::string to_string(const Tensor& t);
133
+ } // namespace std
134
+
135
+ #else
136
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
137
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_simplifier.h ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/bounds_overlap.h>
5
+ #include <torch/csrc/jit/tensorexpr/eval.h>
6
+ #include <torch/csrc/jit/tensorexpr/hash_provider.h>
7
+ #include <torch/csrc/jit/tensorexpr/ir.h>
8
+ #include <torch/csrc/jit/tensorexpr/ir_mutator.h>
9
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
10
+ #include <torch/csrc/jit/tensorexpr/types.h>
11
+
12
+ #include <utility>
13
+
14
+ /* IR Simplification
15
+ *
16
+ * Simplifies expressions in two stages:
17
+ * 1. Recursively traverse the map combining similar operations into Terms
18
+ * (interacted via Multiplication) and Polynomials (interacted via Addition). We
19
+ * reorder the components of each Term or Polynomial into a consistent order to
20
+ * allow combination or cancelling of like terms.
21
+ * 2. Once the format of the tree is minimal, expand each Term into a sequence
22
+ * of Muls, and each Polynomial into a sequence of Ads.
23
+ */
24
+
25
+ namespace torch::jit::tensorexpr {
26
+
27
+ // A bunch of helpers for determine the Dtype of the output of a multi argument
28
+ // Term or Polynomial.
29
+ template <class ExprType>
30
+ Dtype promoteTypesVec(const ExprPtr& s, const std::vector<ExprType>& v) {
31
+ Dtype t = s->dtype();
32
+ bool first = true;
33
+
34
+ for (const auto& e : v) {
35
+ if (first) {
36
+ t = Dtype(t.scalar_type(), e->dtype().lanes());
37
+ first = false;
38
+ }
39
+ t = promoteTypes(t, e->dtype());
40
+ }
41
+ return t;
42
+ }
43
+
44
+ template <class ExprType>
45
+ Dtype promoteTypesVec(const std::vector<ExprType>& v) {
46
+ if (v.empty()) {
47
+ throw malformed_input("empty list of types");
48
+ }
49
+
50
+ Dtype t = v[0]->dtype();
51
+ for (const auto& e : v) {
52
+ t = promoteTypes(t, e->dtype());
53
+ }
54
+ return t;
55
+ }
56
+
57
+ template <class ExprType>
58
+ Dtype promoteTypesMap(
59
+ const ExprPtr& s,
60
+ std::unordered_map<SimplifierHashType, ExprType>& m) {
61
+ Dtype t = s->dtype();
62
+ bool first = true;
63
+ for (auto& e : m) {
64
+ if (first) {
65
+ t = Dtype(t.scalar_type(), e.second->dtype().lanes());
66
+ first = false;
67
+ }
68
+ t = promoteTypes(t, e.second->dtype());
69
+ }
70
+ return t;
71
+ }
72
+
73
+ template <class ExprType>
74
+ Dtype promoteTypesVar(ExprType e) {
75
+ return e->dtype();
76
+ }
77
+
78
+ template <class ExprType, class... Args>
79
+ Dtype promoteTypesVar(ExprType e, Args... es) {
80
+ Dtype lhs = e->dtype();
81
+ Dtype rhs = promoteTypesVar(es...);
82
+ if (e->isConstant()) {
83
+ lhs = Dtype(lhs.scalar_type(), rhs.lanes());
84
+ }
85
+
86
+ return promoteTypes(lhs, rhs);
87
+ }
88
+
89
+ // Uses the evaluator to fold an Expression with constant terms.
90
+ // E.g. evaluateOp(Add(3, 4)) => 7.
91
+ // Expr v must not have any unbound Vars.
92
+ inline ExprPtr evaluateOp(const ExprPtr& v) {
93
+ ExprHandle handle(v);
94
+ ExprEval<SimpleIREvaluator> eval(handle);
95
+
96
+ switch (v->dtype().scalar_type()) {
97
+ #define TYPE_CASE(Type, Name) \
98
+ case ScalarType::Name: { \
99
+ Type val = eval.value<Type>(); \
100
+ return getImmediateByType(v->dtype().scalar_type(), val); \
101
+ }
102
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, TYPE_CASE)
103
+ #undef TYPE_CASE
104
+ default:
105
+ LOG(FATAL) << "Unsupported datatype: " << v->dtype();
106
+ return nullptr;
107
+ }
108
+ return nullptr;
109
+ }
110
+
111
+ // A Term represents a grouping of Exprs through multiplication.
112
+ // E.g. product(scalar, *variables).
113
+ class Term : public ExprNode<Term> {
114
+ public:
115
+ template <class... Args>
116
+ Term(HashProvider& hasher, ExprPtr s, Args... ts)
117
+ : ExprNodeBase(promoteTypesVar(s, ts...)), scalar_(s), hasher_(hasher) {
118
+ CHECK(s->isConstant());
119
+ addComponent(ts...);
120
+ sort();
121
+ }
122
+
123
+ Term(HashProvider& hasher, ExprPtr s, std::vector<ExprPtr> v)
124
+ : ExprNodeBase(promoteTypesVec(s, v)),
125
+ variables_(std::move(v)),
126
+ scalar_(std::move(s)),
127
+ hasher_(hasher) {
128
+ sort();
129
+ }
130
+
131
+ // Convenience constructor from a map of hash -> var, used when merging Terms.
132
+ Term(
133
+ HashProvider& hasher,
134
+ const ExprPtr& s,
135
+ std::unordered_map<SimplifierHashType, ExprPtr> varmap)
136
+ : ExprNodeBase(promoteTypesMap(s, varmap)), scalar_(s), hasher_(hasher) {
137
+ for (auto& p : varmap) {
138
+ addComponent(p.second);
139
+ }
140
+ sort();
141
+ }
142
+
143
+ ExprPtr scalar() const {
144
+ return scalar_;
145
+ }
146
+ const std::vector<ExprPtr>& variables() const {
147
+ return variables_;
148
+ }
149
+ HashProvider& hasher() const {
150
+ return hasher_;
151
+ }
152
+
153
+ // Produce a hash of just the variable components of this term, to determine
154
+ // if it can be combined with another term.
155
+ SimplifierHashType hashVars() const;
156
+
157
+ private:
158
+ std::vector<ExprPtr> variables_;
159
+ ExprPtr scalar_;
160
+ HashProvider& hasher_;
161
+
162
+ void addComponent() {}
163
+ void addComponent(ExprPtr e) {
164
+ variables_.push_back(std::move(e));
165
+ }
166
+ template <class... Es>
167
+ void addComponent(ExprPtr e, Es&&... es) {
168
+ addComponent(std::move(e));
169
+ addComponent(std::forward<Es>(es)...);
170
+ }
171
+
172
+ // Sort by hash to normalize order of components.
173
+ void sort();
174
+ };
175
+
176
+ // Polynomial represents a grouping of Exprs by addition.
177
+ // E.g. sum(*variables, scalar).
178
+ // This would better be called Expression, but, naming conflict...
179
+ class Polynomial : public ExprNode<Polynomial> {
180
+ public:
181
+ template <class... Args>
182
+ Polynomial(HashProvider& hasher, ExprPtr s, Args... ts)
183
+ : ExprNodeBase(promoteTypesVar(s, ts...)), scalar_(s), hasher_(hasher) {
184
+ CHECK(s->isConstant());
185
+ addTerm(ts...);
186
+ sort();
187
+ }
188
+
189
+ Polynomial(HashProvider& hasher, const ExprPtr& s, std::vector<TermPtr> v)
190
+ : ExprNodeBase(promoteTypesVec(s, v)),
191
+ variables_(std::move(v)),
192
+ scalar_(s),
193
+ hasher_(hasher) {
194
+ sort();
195
+ }
196
+
197
+ // Helper constructor for list of terms with no scalar component.
198
+ Polynomial(HashProvider& hasher, std::vector<TermPtr> terms)
199
+ : ExprNodeBase(promoteTypesVec(terms)),
200
+ variables_(std::move(terms)),
201
+ scalar_(getImmediateByType(dtype(), 0)),
202
+ hasher_(hasher) {
203
+ sort();
204
+ }
205
+
206
+ // Convenience constructor for map of hash -> var, used when merging
207
+ // Polynomials.
208
+ Polynomial(
209
+ HashProvider& hasher,
210
+ const ExprPtr& s,
211
+ std::unordered_map<SimplifierHashType, TermPtr> varmap)
212
+ : ExprNodeBase(promoteTypesMap(s, varmap)), scalar_(s), hasher_(hasher) {
213
+ for (auto& p : varmap) {
214
+ addTerm(p.second);
215
+ }
216
+ sort();
217
+ }
218
+
219
+ ExprPtr scalar() const {
220
+ return scalar_;
221
+ }
222
+ const std::vector<TermPtr>& variables() const {
223
+ return variables_;
224
+ }
225
+ HashProvider& hasher() const {
226
+ return hasher_;
227
+ }
228
+
229
+ SimplifierHashType hashVars() const;
230
+
231
+ private:
232
+ std::vector<TermPtr> variables_;
233
+ ExprPtr scalar_;
234
+ HashProvider& hasher_;
235
+
236
+ void addTerm(TermPtr t) {
237
+ variables_.push_back(std::move(t));
238
+ }
239
+ template <class... Ts>
240
+ void addTerm(TermPtr t, Ts&&... ts) {
241
+ addTerm(std::move(t));
242
+ addTerm(std::forward<Ts>(ts)...);
243
+ }
244
+
245
+ // Sort by hash to normalize order of terms.
246
+ void sort();
247
+ };
248
+
249
+ class RoundOff : public BinaryOpNode<RoundOff> {
250
+ public:
251
+ RoundOff(ExprPtr lhs, ExprPtr rhs)
252
+ : BinaryOpNode(std::move(lhs), std::move(rhs), IRNodeType::kOther) {}
253
+ };
254
+
255
+ class MaxTerm : public ExprNode<MaxTerm> {
256
+ public:
257
+ template <class... Args>
258
+ MaxTerm(HashProvider& hasher, ExprPtr s, bool p, Args... ts)
259
+ : ExprNodeBase(s ? promoteTypesVar(s, ts...) : promoteTypesVar(ts...)),
260
+ scalar_(s),
261
+ hasher_(hasher),
262
+ propagate_nans_(p) {
263
+ addComponent(ts...);
264
+ uniquefy();
265
+ }
266
+
267
+ MaxTerm(
268
+ HashProvider& hasher,
269
+ const ExprPtr& s,
270
+ bool p,
271
+ std::vector<ExprPtr> v)
272
+ : ExprNodeBase(s ? promoteTypesVec(s, v) : promoteTypesVec(v)),
273
+ variables_(std::move(v)),
274
+ scalar_(s),
275
+ hasher_(hasher),
276
+ propagate_nans_(p) {
277
+ uniquefy();
278
+ }
279
+
280
+ bool propagate_nans() const {
281
+ return propagate_nans_;
282
+ }
283
+
284
+ ExprPtr scalar() const {
285
+ return scalar_;
286
+ }
287
+ const std::vector<ExprPtr>& variables() const {
288
+ return variables_;
289
+ }
290
+ HashProvider& hasher() const {
291
+ return hasher_;
292
+ }
293
+
294
+ private:
295
+ std::vector<ExprPtr> variables_;
296
+ ExprPtr scalar_;
297
+ HashProvider& hasher_;
298
+ bool propagate_nans_;
299
+
300
+ void addComponent() {}
301
+ void addComponent(ExprPtr e) {
302
+ variables_.push_back(std::move(e));
303
+ }
304
+ template <class... Es>
305
+ void addComponent(ExprPtr e, Es&&... es) {
306
+ addComponent(std::move(e));
307
+ addComponent(std::forward<Es>(es)...);
308
+ }
309
+
310
+ // Uniquefy the terms using their hash.
311
+ void uniquefy();
312
+ };
313
+
314
+ class MinTerm : public ExprNode<MinTerm> {
315
+ public:
316
+ template <class... Args>
317
+ MinTerm(HashProvider& hasher, ExprPtr s, bool p, Args... ts)
318
+ : ExprNodeBase(s ? promoteTypesVar(s, ts...) : promoteTypesVar(ts...)),
319
+ scalar_(s),
320
+ hasher_(hasher),
321
+ propagate_nans_(p) {
322
+ addComponent(ts...);
323
+ uniquefy();
324
+ }
325
+
326
+ MinTerm(
327
+ HashProvider& hasher,
328
+ const ExprPtr& s,
329
+ bool p,
330
+ std::vector<ExprPtr> v)
331
+ : ExprNodeBase(s ? promoteTypesVec(s, v) : promoteTypesVec(v)),
332
+ variables_(std::move(v)),
333
+ scalar_(s),
334
+ hasher_(hasher),
335
+ propagate_nans_(p) {
336
+ uniquefy();
337
+ }
338
+
339
+ bool propagate_nans() const {
340
+ return propagate_nans_;
341
+ }
342
+
343
+ ExprPtr scalar() const {
344
+ return scalar_;
345
+ }
346
+ const std::vector<ExprPtr>& variables() const {
347
+ return variables_;
348
+ }
349
+ HashProvider& hasher() const {
350
+ return hasher_;
351
+ }
352
+
353
+ private:
354
+ std::vector<ExprPtr> variables_;
355
+ ExprPtr scalar_;
356
+ HashProvider& hasher_;
357
+ bool propagate_nans_;
358
+
359
+ void addComponent() {}
360
+ void addComponent(ExprPtr e) {
361
+ variables_.push_back(std::move(e));
362
+ }
363
+ template <class... Es>
364
+ void addComponent(ExprPtr e, Es&&... es) {
365
+ addComponent(std::move(e));
366
+ addComponent(std::forward<Es>(es)...);
367
+ }
368
+
369
+ // Uniquefy the terms using their hash.
370
+ void uniquefy();
371
+ };
372
+
373
+ // Context-sensitive IR simplification
374
+ using VarBoundInfo = std::unordered_map<VarPtr, analysis::Bound>;
375
+
376
+ class TORCH_API SimplifierUnderContext : public IRMutator {
377
+ public:
378
+ ~SimplifierUnderContext() override = default;
379
+ // Add boundary info for index variables in for-loops
380
+ StmtPtr mutate(const ForPtr& v) override;
381
+
382
+ ExprPtr mutate(const DivPtr& v) override;
383
+ ExprPtr mutate(const ModPtr& v) override;
384
+ ExprPtr mutate(const CompareSelectPtr& v) override;
385
+ ExprPtr mutate(const IfThenElsePtr& v) override;
386
+
387
+ protected:
388
+ bool getLoopBoundInfo(const ExprPtr& expr, analysis::Bound* loop_bound_info);
389
+
390
+ protected:
391
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
392
+ HashProvider hasher_;
393
+ VarBoundInfo var_bound_info_;
394
+ };
395
+
396
+ // Stmt simplification should occur in both modes.
397
+ class TORCH_API PolynomialBase : public IRMutator {
398
+ public:
399
+ ~PolynomialBase() override = default;
400
+
401
+ StmtPtr mutate(const BlockPtr& v) override;
402
+
403
+ StmtPtr mutate(const CondPtr& v) override;
404
+
405
+ StmtPtr mutate(const ForPtr& v) override;
406
+
407
+ // Trivially factorize terms by GCD of scalar components.
408
+ TermPtr factorizePolynomial(const PolynomialPtr& poly);
409
+
410
+ HashProvider& hasher() {
411
+ return hasher_;
412
+ }
413
+
414
+ protected:
415
+ // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
416
+ HashProvider hasher_;
417
+ };
418
+
419
+ // Simplify the IR by combining arithmetic expressions over common terms.
420
+ class TORCH_API PolynomialTransformer : public PolynomialBase {
421
+ public:
422
+ using PolynomialBase::mutate;
423
+ // Inserts term into the provided map, in the case of a hash collision
424
+ // combines the term with the existing and updates the map.
425
+ void addOrUpdateTerm(
426
+ std::unordered_map<SimplifierHashType, TermPtr>& varmap,
427
+ const TermPtr& term);
428
+
429
+ // Add Polynomial expressions, combining Terms representing the same
430
+ // variables.
431
+ ExprPtr addPolynomials(const PolynomialPtr& lhs, const PolynomialPtr& rhs);
432
+
433
+ // Insert a new Term into the provided polynomial. If the new term has
434
+ // common variables to an existing term it is combined.
435
+ ExprPtr insertTerm(const PolynomialPtr& poly, const TermPtr& term);
436
+
437
+ // Merge and simplify addition.
438
+ ExprPtr mutate(const AddPtr& v) override;
439
+
440
+ // Subtract one term from another, cancelling if necessary.
441
+ ExprPtr subTerms(const TermPtr& lhs, TermPtr rhs, bool negated);
442
+
443
+ // Subtract the RHS Polynomial from the LHS Polynomial, cancelling out where
444
+ // possible.
445
+ ExprPtr subPolynomials(const PolynomialPtr& lhs, const PolynomialPtr& rhs);
446
+
447
+ // Merge and simplify subtraction.
448
+ ExprPtr mutate(const SubPtr& v) override;
449
+
450
+ // Multiply two terms together, usually creating a new term with the variable
451
+ // lists concatenated.
452
+ TermPtr mulTerms(const TermPtr& lhs, const TermPtr& rhs);
453
+
454
+ // Multiply a Polynomial by a Term.
455
+ ExprPtr polyByTerm(const PolynomialPtr& poly, const TermPtr& term);
456
+
457
+ // Match a rounding pattern and create a RoundOff if found.
458
+ ExprPtr isRoundOff(const ExprPtr& lhs, const ExprPtr& rhs);
459
+
460
+ // Inserts a new component into a term, simplifying if possible.
461
+ ExprPtr insertIntoTerm(const TermPtr& term, const ExprPtr& expr);
462
+
463
+ // Merge and simplify multiplication.
464
+ ExprPtr mutate(const MulPtr& v) override;
465
+
466
+ ExprPtr mutate(const DivPtr& v) override;
467
+
468
+ ExprPtr mutate(const ModPtr& v) override;
469
+
470
+ ExprPtr mutate(const AndPtr& v) override;
471
+
472
+ ExprPtr mutate(const XorPtr& v) override;
473
+
474
+ ExprPtr mutate(const LshiftPtr& v) override;
475
+
476
+ ExprPtr mutate(const RshiftPtr& v) override;
477
+
478
+ ExprPtr mutate(const MaxPtr& v) override;
479
+
480
+ ExprPtr mutate(const MinPtr& v) override;
481
+
482
+ ExprPtr mutate(const CompareSelectPtr& v) override;
483
+
484
+ ExprPtr mutate(const IntrinsicsPtr& v) override;
485
+
486
+ ExprPtr mutate(const CastPtr& v) override;
487
+
488
+ ExprPtr mutate(const IfThenElsePtr& v) override;
489
+
490
+ static ExprPtr simplify(ExprPtr e);
491
+ static ExprHandle simplify(const ExprHandle& e);
492
+ static StmtPtr simplify(StmtPtr e);
493
+ };
494
+
495
+ // Expands Terms and Polynomial expressions into primitive operations.
496
+ // Does some simple factorization and reordering.
497
+ class TORCH_API TermExpander : public PolynomialBase {
498
+ PolynomialTransformer* simplifier_;
499
+ std::set<VarPtr> eliminated_allocations_;
500
+
501
+ public:
502
+ using PolynomialBase::mutate;
503
+ TermExpander(PolynomialTransformer* simplifier) : simplifier_(simplifier) {}
504
+ bool check_safe() {
505
+ return eliminated_allocations_.empty();
506
+ }
507
+
508
+ // Expand Terms out to a series of Muls.
509
+ ExprPtr mutate(const TermPtr& v) override;
510
+
511
+ // Expand Polynomials out to a series of Adds.
512
+ ExprPtr mutate(const PolynomialPtr& v) override;
513
+
514
+ // Expand MaxTerms to a series of Max ops.
515
+ ExprPtr mutate(const MaxTermPtr& v) override;
516
+
517
+ // Expand MinTerms to a series of Min ops.
518
+ ExprPtr mutate(const MinTermPtr& v) override;
519
+
520
+ // Expand RoundOff to it's component: Mul(Div(lhs, rhs), rhs).
521
+ ExprPtr mutate(const RoundOffPtr& v) override;
522
+
523
+ // Eliminate zero length allocations.
524
+ StmtPtr mutate(const AllocatePtr& v) override;
525
+ StmtPtr mutate(const FreePtr& v) override;
526
+
527
+ // Override to enable condition fusing.
528
+ BlockPtr fuseConditions(BlockPtr v);
529
+ StmtPtr fuseSyncThreads(BlockPtr block);
530
+ StmtPtr mutate(const BlockPtr& v) override;
531
+ };
532
+
533
+ class TORCH_API IRSimplifier {
534
+ public:
535
+ static StmtPtr simplify(StmtPtr s);
536
+ static ExprPtr simplify(ExprPtr e);
537
+ static ExprHandle simplify(const ExprHandle& e) {
538
+ return ExprHandle(simplify(e.node()));
539
+ }
540
+ };
541
+
542
+ // Flattens the buf and performs the simplifier on the flattened dims.
543
+ ExprPtr buf_flat_size(const BufPtr& v);
544
+ // Returns true if expressions A and B can be simplified to an equal expression.
545
+ TORCH_API bool exprEquals(const ExprPtr& A, const ExprPtr& B);
546
+
547
+ } // namespace torch::jit::tensorexpr
548
+
549
+ #else
550
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
551
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_verifier.h ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
5
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
6
+
7
+ namespace torch::jit::tensorexpr {
8
+
9
+ class Expr;
10
+ class ExprHandle;
11
+ class Mod;
12
+ class And;
13
+ class Or;
14
+ class Xor;
15
+ class Lshift;
16
+ class Rshift;
17
+ class CompareSelect;
18
+ class Ramp;
19
+ class Load;
20
+ class IfThenElse;
21
+ class Intrinsics;
22
+
23
+ class Stmt;
24
+ class ExternalCall;
25
+ class Store;
26
+ class For;
27
+ class Block;
28
+
29
+ class TORCH_API IRVerifier : public IRVisitor {
30
+ public:
31
+ IRVerifier() = default;
32
+
33
+ void visit(const ModPtr& v) override;
34
+ void visit(const AndPtr& v) override;
35
+ void visit(const OrPtr& v) override;
36
+ void visit(const XorPtr& v) override;
37
+ void visit(const LshiftPtr& v) override;
38
+ void visit(const RshiftPtr& v) override;
39
+ void visit(const CompareSelectPtr& v) override;
40
+ void visit(const RampPtr& v) override;
41
+ void visit(const LoadPtr& v) override;
42
+ void visit(const IfThenElsePtr& v) override;
43
+ void visit(const IntrinsicsPtr& v) override;
44
+
45
+ void visit(const ExternalCallPtr& v) override;
46
+ void visit(const StorePtr& v) override;
47
+ void visit(const ForPtr& v) override;
48
+ void visit(const BlockPtr& v) override;
49
+ };
50
+
51
+ TORCH_API void verify(const StmtPtr& /*s*/);
52
+ TORCH_API void verify(const ExprPtr& /*e*/);
53
+ TORCH_API void verify(const ExprHandle& /*e*/);
54
+
55
+ } // namespace torch::jit::tensorexpr
56
+
57
+ #else
58
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
59
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/ir_visitor.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <torch/csrc/Export.h>
5
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
6
+
7
+ namespace torch::jit::tensorexpr {
8
+
9
+ class TORCH_API IRVisitor {
10
+ public:
11
+ virtual ~IRVisitor() = default;
12
+ virtual void visit(const AddPtr& v);
13
+ virtual void visit(const SubPtr& v);
14
+ virtual void visit(const MulPtr& v);
15
+ virtual void visit(const DivPtr& v);
16
+ virtual void visit(const ModPtr& v);
17
+ virtual void visit(const MaxPtr& v);
18
+ virtual void visit(const MinPtr& v);
19
+ virtual void visit(const AndPtr& v);
20
+ virtual void visit(const OrPtr& v);
21
+ virtual void visit(const XorPtr& v);
22
+ virtual void visit(const LshiftPtr& v);
23
+ virtual void visit(const RshiftPtr& v);
24
+ virtual void visit(const CompareSelectPtr& v);
25
+
26
+ #define IMM_PRINT_VISIT(Type, Name) virtual void visit(const Name##ImmPtr& v);
27
+
28
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, IMM_PRINT_VISIT)
29
+ #undef IMM_PRINT_VISIT
30
+
31
+ virtual void visit(const CastPtr& v);
32
+ virtual void visit(const BitCastPtr& v);
33
+ virtual void visit(const VarPtr& v);
34
+ virtual void visit(const BufPtr& v);
35
+ virtual void visit(const RampPtr& v);
36
+ virtual void visit(const LoadPtr& v);
37
+ virtual void visit(const ForPtr& v);
38
+ virtual void visit(const BlockPtr& v);
39
+ virtual void visit(const StorePtr& v);
40
+ virtual void visit(const BroadcastPtr& v);
41
+ virtual void visit(const IfThenElsePtr& v);
42
+ virtual void visit(const IntrinsicsPtr& v);
43
+ virtual void visit(const AllocatePtr& v);
44
+ virtual void visit(const FreePtr& v);
45
+ virtual void visit(const FreeExtPtr& v);
46
+ virtual void visit(const PlacementAllocatePtr& v);
47
+ virtual void visit(const LetPtr& v);
48
+ virtual void visit(const CondPtr& v);
49
+ virtual void visit(const TermPtr& v);
50
+ virtual void visit(const PolynomialPtr& v);
51
+ virtual void visit(const RoundOffPtr& v);
52
+ virtual void visit(const MaxTermPtr& v);
53
+ virtual void visit(const MinTermPtr& v);
54
+ virtual void visit(const ReduceOpPtr& v);
55
+ virtual void visit(const AtomicAddPtr& v);
56
+ virtual void visit(const SyncThreadsPtr& v);
57
+ virtual void visit(const ExternalCallPtr& v);
58
+ virtual void visit(const ExternalCallWithAllocPtr& v);
59
+ };
60
+
61
+ } // namespace torch::jit::tensorexpr
62
+
63
+ #else
64
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
65
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/kernel.h ADDED
@@ -0,0 +1,383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/ir/ir.h>
5
+ #include <torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h>
6
+ #include <torch/csrc/jit/passes/utils/subgraph_utils.h>
7
+ #include <torch/csrc/jit/runtime/interpreter.h>
8
+ #include <torch/csrc/jit/tensorexpr/analysis.h>
9
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
10
+ #include <torch/csrc/jit/tensorexpr/lowerings.h>
11
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
12
+
13
+ namespace torch::jit::tensorexpr {
14
+
15
+ struct SmallSizeTPairHash {
16
+ public:
17
+ std::size_t operator()(const std::pair<size_t, size_t>& x) const {
18
+ // hashing input index and then dim index
19
+ return x.first * 128 + x.second;
20
+ }
21
+ };
22
+
23
+ // Returns true if the TE fuser supports this conv2d.
24
+ bool conv2dIsSupportedJit(const Node* node);
25
+ // Returns true if the TE fuser supports this conv2d with mkldnn prepacked conv.
26
+ bool mkldnnPrepackedConvIsSupportedJit(const Node* node);
27
+ // Returns true if the TE _convolution node is Conv2d.
28
+ bool isConv2d(const Node* node);
29
+ // Returns true if the TE fuser supports this matmul.
30
+ bool matmulIsSupported(const Node* node);
31
+ template <typename T>
32
+ inline std::vector<int64_t> bufferSizes(const T& t) {
33
+ std::vector<int64_t> sizes;
34
+ for (size_t i = 0; i < t->ndim(); i++) {
35
+ sizes.push_back(*intValue(t->dim(i)));
36
+ }
37
+ return sizes;
38
+ }
39
+
40
+ // Get the dimensions of a value.
41
+ std::vector<ExprHandle> valueShape(const ArgValue& v);
42
+
43
+ // If v is a tensor, broadcast it to match the shape of axes, or return
44
+ // directly if v is a constant.
45
+ ExprHandle tensorOrConstant(
46
+ const ArgValue& v,
47
+ const std::vector<ExprHandle>& axes);
48
+
49
+ int64_t normalizeAndCheckIndex(int64_t idx, int64_t list_size);
50
+
51
+ ExprHandle broadcast(const BufHandle& b, const std::vector<ExprHandle>& axes);
52
+
53
+ ExprHandle constant(const ArgValue& v);
54
+
55
+ std::vector<ExprHandle> computeIndicesToBroadcast(
56
+ const std::vector<ExprHandle>& outputAxes,
57
+ const std::vector<ExprHandle>& inputSizes);
58
+
59
+ inline std::string getArgValueName(const ArgValue& a) {
60
+ if (std::holds_alternative<tensorexpr::BufHandle>(a)) {
61
+ return "BufHandle";
62
+ } else if (std::holds_alternative<tensorexpr::VarHandle>(a)) {
63
+ return "VarHandle";
64
+ } else if (std::holds_alternative<double>(a)) {
65
+ return "double";
66
+ } else if (std::holds_alternative<int64_t>(a)) {
67
+ return "int64_t";
68
+ } else if (std::holds_alternative<bool>(a)) {
69
+ return "bool";
70
+ } else if (std::holds_alternative<BufList>(a)) {
71
+ return "BufList";
72
+ } else if (std::holds_alternative<DoubleList>(a)) {
73
+ return "DoubleList";
74
+ } else if (std::holds_alternative<IntList>(a)) {
75
+ return "IntList";
76
+ } else if (std::holds_alternative<ArgNone>(a)) {
77
+ return "None";
78
+ } else {
79
+ throw std::runtime_error("ArgValue type not handled in string conversion");
80
+ }
81
+ }
82
+
83
+ template <class T>
84
+ std::vector<T> convertVecArgValue(const std::vector<ArgValue>& v) {
85
+ std::vector<T> res;
86
+ for (auto& x : v) {
87
+ auto val = std::get_if<T>(&x);
88
+ if (val) {
89
+ res.push_back(*val);
90
+ } else {
91
+ throw std::runtime_error(
92
+ "vector type not homogeneous - found " + getArgValueName(x) +
93
+ ", expected " + getArgValueName(v[0]));
94
+ }
95
+ }
96
+ return res;
97
+ }
98
+
99
+ class TORCH_API TensorExprKernel {
100
+ struct ConstantDescr {
101
+ BufPtr buf;
102
+ // Only one of ptr and node is used at a time
103
+ // 1) ptr for the constant tensors
104
+ // 2) node for the constant custom class objects
105
+ void* ptr = nullptr;
106
+ Node* node = nullptr;
107
+ };
108
+
109
+ public:
110
+ // Constructor Params:
111
+ // * subgraph
112
+ // - the graph that needs to be compiled.
113
+ // * kernel_func_name
114
+ // - the name that should be used for the generated kernel.
115
+ // * custom_lowerings
116
+ // - map that represents custom lowering definitions for a set of ops.
117
+ // * symbolic_shape_inputs
118
+ // - a list of symbolic graph inputs that represent the symbolic dims of
119
+ // the input tensors.
120
+ // * pre_alloc
121
+ // - a flag to control pre-allocation of buffers.
122
+ explicit TensorExprKernel(
123
+ const std::shared_ptr<Graph>& subgraph,
124
+ std::string kernel_func_name,
125
+ std::unordered_map<c10::Symbol, NNCLoweringFunction> custom_lowerings =
126
+ {},
127
+ std::vector<int64_t> symbolic_shape_inputs = {},
128
+ bool pre_alloc = false,
129
+ std::unordered_map<
130
+ const torch::jit::Value*,
131
+ std::vector<torch::jit::StrideInput>> symbolic_strides = {});
132
+
133
+ explicit TensorExprKernel(
134
+ const std::shared_ptr<Graph>& subgraph,
135
+ std::unordered_map<c10::Symbol, NNCLoweringFunction> custom_lowerings =
136
+ {},
137
+ std::vector<int64_t> symbolic_shape_inputs = {},
138
+ bool pre_alloc = false,
139
+ std::unordered_map<
140
+ const torch::jit::Value*,
141
+ std::vector<torch::jit::StrideInput>> symbolic_strides = {})
142
+ : TensorExprKernel(
143
+ subgraph,
144
+ SubgraphUtils::generateNameForGraph(subgraph),
145
+ std::move(custom_lowerings),
146
+ std::move(symbolic_shape_inputs),
147
+ pre_alloc,
148
+ std::move(symbolic_strides)) {}
149
+
150
+ void run(Stack& stack) const;
151
+ void runFast(
152
+ const std::vector<void*>& inputs,
153
+ const std::vector<void*>& outputs) const;
154
+ // Expected format of stack:
155
+ // ... <outputs> <inputs>
156
+ // i.e., output IValues must be below the input IValues in the stack.
157
+ void runWithAllocatedOutputs(Stack& stack) const;
158
+
159
+ void fallback(Stack& stack) const {
160
+ InterpreterState(code_).run(stack);
161
+ }
162
+ void recompile();
163
+
164
+ StmtPtr getCodeGenStmt();
165
+
166
+ std::string getCodeText(const std::string& attr = "") {
167
+ return codegen_->getCodeText(attr);
168
+ }
169
+
170
+ const std::shared_ptr<Graph> graph() {
171
+ return graph_;
172
+ }
173
+
174
+ const std::vector<ConstantDescr>& getConstantDescriptors() const {
175
+ return constants_;
176
+ }
177
+
178
+ const std::vector<CodeGen::BufferArg>& getBufferArgs() const {
179
+ return bufferArgs_;
180
+ }
181
+
182
+ const std::string& getKernelName() const {
183
+ return (codegen_ ? codegen_->kernel_func_name() : kernel_func_name_);
184
+ }
185
+
186
+ const std::vector<int64_t>& getSymbolicShapeInputs() const {
187
+ return symbolic_shape_inputs_;
188
+ }
189
+
190
+ private:
191
+ enum BackendType {
192
+ kUninitialized,
193
+ kSimpleIREval,
194
+ kLLVMCodeGen,
195
+ kCudaCodeGen,
196
+ kBlockCodeGen,
197
+ };
198
+
199
+ enum MemoryLayoutPolicy {
200
+ kContiguous,
201
+ kChannelsLastNdContiguous,
202
+ };
203
+
204
+ void compile();
205
+ void genInputDebugNames();
206
+ void runKernel(Stack& stack) const;
207
+
208
+ std::vector<ExprHandle> sizesForValue(const torch::jit::Value* v);
209
+
210
+ // These functions broadcast shape and also store a `hasBroadcast_` variable.
211
+ std::vector<ExprHandle> broadcastShapesMut(
212
+ const std::vector<ExprHandle>& a,
213
+ const std::vector<ExprHandle>& b);
214
+ std::vector<ExprHandle> broadcastShapesMut(
215
+ std::vector<std::vector<ExprHandle>> shapes);
216
+
217
+ ArgValue toArg(const torch::jit::Value* v) const;
218
+ ExprHandle constant(const torch::jit::Value* v);
219
+
220
+ Tensor computeValue(const torch::jit::Value* v);
221
+
222
+ void bindConstant(const torch::jit::Value* v);
223
+
224
+ StmtPtr transformLoops(BackendType backendType, StmtPtr st);
225
+
226
+ std::string getCodeGenName(BackendType backendType);
227
+
228
+ void getStaticOutputSizesAndStrides(
229
+ const at::ArrayRef<IValue>& inputs,
230
+ std::vector<std::vector<int64_t>>* static_sizes,
231
+ std::vector<std::vector<int64_t>>* static_strides) const;
232
+
233
+ std::vector<CodeGen::CallArg> prepareRunArgs(
234
+ const at::ArrayRef<IValue>& inputs,
235
+ std::vector<at::Tensor>& outputs) const;
236
+ BackendType inferBackendTypeFromDevice(at::Device device);
237
+
238
+ Tensor bindInput(const torch::jit::Value* input);
239
+ BlockPtr bindAllInputs();
240
+
241
+ // Deduce the memory layout policy to be propagated within
242
+ // NNC fusion group. The memory layout policy could be `kContiguous`
243
+ // or `kChannelsLastNdContiguous`.
244
+ // `kContiguous`: Always convert the non-contiguous input tensors and
245
+ // internal buffers to contiguous.
246
+ // `kChannelsLastNdContiguous`: Always convert the input tensors and
247
+ // internal buffers to channels-last contiguous.
248
+ // Currently, the rule is simple.
249
+ // If all the input and out tensors of NNC fusion group are channels-last
250
+ // contiguous, the policy is `kChannelsLastNdContiguous`. Otherwise, it
251
+ // is always `kContiguous`.
252
+ void deduceMemoryLayoutPolicy();
253
+
254
+ Tensor convertSymbolicOutputToCorrectStrides(torch::jit::Value* v);
255
+ Tensor convertStaticShapeOutputToCorrectStrides(torch::jit::Value* v);
256
+ Tensor convertSymbolicOutputToCorrectStrides(
257
+ const std::vector<ExprHandle>& sizes,
258
+ const std::vector<size_t>& sorted_stride_indices_descending,
259
+ const std::vector<ExprPtr>& strides,
260
+ BufPtr& buf);
261
+
262
+ NNCLoweringFunction getCustomLoweringFor(c10::Symbol op) const;
263
+ std::unordered_map<c10::Symbol, NNCLoweringFunction> getCustomLowerings()
264
+ const {
265
+ return custom_lowerings_;
266
+ }
267
+
268
+ // Allocate memory for intermediate buffers at compile time.
269
+ // Specifically, we pre-allocate memory for intermediate buffers with static
270
+ // size and manage these buffers in the way we manage JIT constant tensors:
271
+ // push the buf args into the stack so NNC IR can access them at runtime.
272
+ std::vector<BufPtr> preAllocIntermediateBufs(
273
+ const std::vector<BufPtr>& interm_bufs);
274
+
275
+ struct UnpackedTensorOptions {
276
+ std::optional<c10::ScalarType> dtype;
277
+ std::optional<c10::Layout> layout;
278
+ std::optional<c10::Device> device;
279
+ std::optional<bool> pinned_memory;
280
+
281
+ UnpackedTensorOptions(const c10::TensorOptions& opts)
282
+ : dtype(c10::optTypeMetaToScalarType(opts.dtype_opt())),
283
+ layout(opts.layout_opt()),
284
+ device(opts.device_opt()),
285
+ pinned_memory(opts.pinned_memory_opt()) {}
286
+ };
287
+
288
+ ExprHandle getVarForShape(const c10::ShapeSymbol& ss);
289
+ std::vector<ExprHandle> computeInputTensorDims(
290
+ const torch::jit::Value* input);
291
+ ExprHandle getStrideArg(size_t tensor_input, size_t stride_index);
292
+ std::vector<ExprHandle> sizesFromSymbolicShape(
293
+ const c10::SymbolicShape& shape);
294
+ std::vector<ExprHandle> getInputStrides(
295
+ const torch::jit::Value* input,
296
+ const std::vector<ExprHandle>& inputTensorDims);
297
+ std::vector<torch::jit::StrideInput>& getSymbolicStrideDesc(
298
+ const torch::jit::Value* value);
299
+
300
+ // Apply the optimizations to the graph owned by the current fusion group,
301
+ // like concatenation optimization, post-op fusion, and some other graph-level
302
+ // optimizations.
303
+ void optimizeOwningGraph();
304
+
305
+ int64_t nInputs_ = 0;
306
+ int64_t nOutputs_ = 0;
307
+ std::vector<CodeGen::BufferArg> bufferArgs_;
308
+ std::vector<std::vector<int64_t>> tensorOutputSizes_;
309
+ std::vector<std::vector<int64_t>> tensorOutputStrides_;
310
+ std::vector<torch::jit::StrideInput> tensorOutputStrideDesc_;
311
+ std::vector<bool> isOutputScalar_;
312
+ std::vector<UnpackedTensorOptions> tensorOutputTensorOptions_;
313
+ std::unordered_set<BufPtr> bufOutputs_;
314
+ std::unordered_set<BufPtr> bufsToBeParallelized_;
315
+ std::unordered_map<const torch::jit::Value*, BufPtr> bufs_;
316
+ std::unordered_map<const torch::jit::Value*, VarHandle> scalars_;
317
+ std::unordered_map<const torch::jit::Value*, std::string> input_name_map_;
318
+ std::unique_ptr<CodeGen> codegen_;
319
+ at::Device device_ = at::kCPU;
320
+ std::shared_ptr<Graph> graph_;
321
+ Code code_;
322
+ bool allow_fallback_{false};
323
+ bool use_fallback_{false};
324
+ bool hasRandom_{false};
325
+ bool hasBroadcast_{false};
326
+ std::unordered_map<const torch::jit::Value*, std::vector<ExprHandle>>
327
+ known_sizes_;
328
+
329
+ std::vector<std::vector<ExprHandle>> tensorOutputSymbolicSizes_;
330
+ // A map from ShapeSymbol.value() to the corresponding Var.
331
+ std::unordered_map<int64_t, VarHandle> shapeSymbolToVar_;
332
+ std::unordered_map<ExprPtr, size_t> shapeSymbolInputPos_;
333
+ // List of values corresponding to the ShapeSymbols that are inputs to
334
+ // kernel being compiled. The order of these values correspond to the order
335
+ // of the symbolic inputs at the end of the list of inputs to the kernel.
336
+ std::vector<int64_t> symbolic_shape_inputs_;
337
+ bool has_symbolic_shapes_{false};
338
+
339
+ std::vector<at::Tensor> unpacked_constant_tensors_;
340
+ std::vector<ConstantDescr> constants_;
341
+
342
+ std::unordered_map<c10::Symbol, NNCLoweringFunction> custom_lowerings_;
343
+ StmtPtr stmt_ = nullptr;
344
+ bool pre_alloc_{false};
345
+ std::string kernel_func_name_;
346
+
347
+ // index of stack, stride index of tensor that will be appended as a codegen
348
+ // arg
349
+ std::vector<std::pair<size_t, size_t>> input_stride_args_;
350
+ // map from <input index, tensor dimension> to stride as arg VarHandle
351
+ std::unordered_map<std::pair<size_t, size_t>, VarHandle, SmallSizeTPairHash>
352
+ strideArgToVar_;
353
+ std::unordered_map<
354
+ const torch::jit::Value*,
355
+ std::vector<torch::jit::StrideInput>>
356
+ symbolic_strides_;
357
+
358
+ // Memory layout to be propagated with fusion group
359
+ MemoryLayoutPolicy memory_layout_policy_ = MemoryLayoutPolicy::kContiguous;
360
+ };
361
+
362
+ TORCH_API int& getTECudaPointwiseLoopLevels();
363
+ TORCH_API int& getTECudaPointwiseBlockCount();
364
+ TORCH_API int& getTECudaPointwiseBlockSize();
365
+ TORCH_API bool& getTEGenerateBlockCode();
366
+ TORCH_API bool& getTEMustUseLLVMOnCPU();
367
+ TORCH_API bool fallbackAllowed();
368
+ TORCH_API bool setFallbackAllowed(bool value);
369
+ TORCH_API bool& getCatWoConditionals();
370
+ TORCH_API bool& getOptConditionals();
371
+
372
+ TORCH_API std::optional<at::Device> pickDeviceType(
373
+ const at::ArrayRef<torch::jit::Value*>& inputs);
374
+
375
+ bool isContiguous(
376
+ const torch::jit::Value* v,
377
+ at::MemoryFormat memory_format = at::MemoryFormat::Contiguous);
378
+
379
+ } // namespace torch::jit::tensorexpr
380
+
381
+ #else
382
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
383
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_codegen.h ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef TORCH_ENABLE_LLVM
5
+ #include <torch/csrc/Export.h>
6
+
7
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
8
+ #include <torch/csrc/jit/tensorexpr/ir.h>
9
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
10
+
11
+ #include <optional>
12
+
13
+ #include <unordered_map>
14
+ #include <vector>
15
+
16
+ namespace torch {
17
+ namespace jit {
18
+ namespace tensorexpr {
19
+
20
+ class LLVMCodeGenImpl;
21
+ class LLVMCodeGenCallee;
22
+
23
+ class TORCH_API LLVMCodeGen : public CodeGen {
24
+ public:
25
+ explicit LLVMCodeGen(
26
+ StmtPtr stmt,
27
+ const std::vector<BufferArg>& args,
28
+ at::Device device = at::kCPU,
29
+ const std::string& kernel_func_name = "func",
30
+ Dtype dtype = kInt,
31
+ std::optional<std::string> triple = std::nullopt,
32
+ std::optional<std::string> cpu = std::nullopt,
33
+ std::optional<std::string> attrs = std::nullopt);
34
+ explicit LLVMCodeGen(StmtPtr stmt);
35
+
36
+ LLVMCodeGen() = delete;
37
+ ~LLVMCodeGen() override;
38
+
39
+ // Cleans up all the memory used during LLVM code generation pass except
40
+ // the generated kernel. After calling this method, users should not call
41
+ // methods like `getCodeText` that require the LLVMCodeGenImpl data. However,
42
+ // users can continue to call this kernel using `call` and `call_raw`.
43
+ void cleanup_memory();
44
+
45
+ TORCH_API void call(const std::vector<CallArg>& args) override;
46
+ TORCH_API void call_raw(const std::vector<void*>& args) override;
47
+ TORCH_API void call_with_numel(void** args, int64_t numel) override;
48
+
49
+ at::Tensor empty_strided(
50
+ c10::IntArrayRef size,
51
+ c10::IntArrayRef stride,
52
+ std::optional<c10::ScalarType> dtype_opt,
53
+ std::optional<c10::Layout> layout_opt,
54
+ std::optional<c10::Device> device_opt,
55
+ std::optional<bool> pin_memory_opt) override;
56
+
57
+ template <typename T>
58
+ T value() {
59
+ return value<T>(nullptr);
60
+ }
61
+
62
+ template <typename T>
63
+ T value(std::vector<void*>& args) {
64
+ return value<T>(args.data());
65
+ }
66
+
67
+ template <typename T>
68
+ T value(void** args) {
69
+ T (*fp)(void**) = (T(*)(void**))getKernelAddress(callee_.get());
70
+ T rv = fp(args);
71
+ return rv;
72
+ }
73
+
74
+ std::string getCodeText(const std::string& attr = "") override;
75
+
76
+ private:
77
+ void* getKernelAddress(LLVMCodeGenCallee* callee);
78
+
79
+ std::unique_ptr<LLVMCodeGenCallee> callee_;
80
+ std::unique_ptr<LLVMCodeGenImpl> impl_;
81
+ };
82
+
83
+ struct TORCH_API LLVMCodeGenBuilder {
84
+ using BufferArg = CodeGen::BufferArg;
85
+
86
+ LLVMCodeGenBuilder(StmtPtr stmt, std::vector<BufferArg> args)
87
+ : stmt_(stmt), args_(std::move(args)) {}
88
+
89
+ LLVMCodeGenBuilder& device(at::Device device) {
90
+ device_ = device;
91
+ return *this;
92
+ }
93
+
94
+ LLVMCodeGenBuilder& kernelFuncName(std::string name) {
95
+ kernelFuncName_ = std::move(name);
96
+ return *this;
97
+ }
98
+
99
+ LLVMCodeGenBuilder& dtype(Dtype d) {
100
+ dtype_ = d;
101
+ return *this;
102
+ }
103
+
104
+ LLVMCodeGenBuilder& triple(std::string triple) {
105
+ triple_ = std::move(triple);
106
+ return *this;
107
+ }
108
+
109
+ LLVMCodeGenBuilder& cpu(std::string cpu) {
110
+ cpu_ = std::move(cpu);
111
+ return *this;
112
+ }
113
+
114
+ LLVMCodeGenBuilder& attrs(std::string attrs) {
115
+ attrs_ = std::move(attrs);
116
+ return *this;
117
+ }
118
+
119
+ std::unique_ptr<LLVMCodeGen> build() {
120
+ return std::make_unique<LLVMCodeGen>(
121
+ stmt_, args_, device_, kernelFuncName_, dtype_, triple_, cpu_, attrs_);
122
+ }
123
+
124
+ private:
125
+ StmtPtr stmt_;
126
+ std::vector<BufferArg> args_;
127
+ at::Device device_ = at::kCPU;
128
+ std::string kernelFuncName_ = "func";
129
+ Dtype dtype_ = kInt;
130
+ std::optional<std::string> triple_ = std::nullopt;
131
+ std::optional<std::string> cpu_ = std::nullopt;
132
+ std::optional<std::string> attrs_ = std::nullopt;
133
+ };
134
+
135
+ TORCH_API std::optional<std::string>& LLVMTargetTriple();
136
+ TORCH_API std::optional<std::string>& LLVMTargetCPU();
137
+ TORCH_API std::optional<std::string>& LLVMTargetAttrs();
138
+ TORCH_API bool& LLVMAOTWorkflow();
139
+
140
+ } // namespace tensorexpr
141
+ } // namespace jit
142
+ } // namespace torch
143
+
144
+ #endif // TORCH_ENABLE_LLVM
145
+
146
+ #else
147
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
148
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/llvm_jit.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #ifdef TORCH_ENABLE_LLVM
5
+ #include <c10/macros/Macros.h>
6
+ #include <c10/util/Exception.h>
7
+ #include <torch/csrc/Export.h>
8
+ #include <optional>
9
+
10
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wsuggest-override")
11
+ #include <llvm/ExecutionEngine/JITSymbol.h>
12
+ C10_DIAGNOSTIC_POP()
13
+ C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wextra-semi")
14
+ #include <llvm/ExecutionEngine/Orc/Core.h>
15
+ #include <llvm/ExecutionEngine/Orc/ThreadSafeModule.h>
16
+ #include <llvm/Target/TargetMachine.h>
17
+ C10_DIAGNOSTIC_POP()
18
+
19
+ #include <memory>
20
+ #include <string>
21
+
22
+ namespace torch {
23
+ namespace jit {
24
+ namespace tensorexpr {
25
+
26
+ inline std::string formatError(llvm::Error&& err, const char* msg) {
27
+ static constexpr const char* defaultErrorMsg =
28
+ "Unexpected failure in LLVM JIT";
29
+ std::string errorMsg(msg ? msg : defaultErrorMsg);
30
+ llvm::raw_string_ostream ss(errorMsg);
31
+ ss << ": " << err;
32
+ return ss.str();
33
+ }
34
+
35
+ template <typename T>
36
+ T assertSuccess(llvm::Expected<T> valOrErr, const char* msg = nullptr) {
37
+ TORCH_INTERNAL_ASSERT(valOrErr, formatError(valOrErr.takeError(), msg));
38
+ return std::move(*valOrErr);
39
+ }
40
+
41
+ inline void assertSuccess(llvm::Error err, const char* msg = nullptr) {
42
+ TORCH_INTERNAL_ASSERT(!err, formatError(std::move(err), msg));
43
+ }
44
+
45
+ } // namespace tensorexpr
46
+ } // namespace jit
47
+ } // namespace torch
48
+
49
+ namespace llvm {
50
+ namespace orc {
51
+
52
+ class PytorchLLVMJITImpl;
53
+
54
+ class TORCH_API PytorchLLVMJIT {
55
+ public:
56
+ PytorchLLVMJIT(
57
+ std::optional<std::string> triple,
58
+ std::optional<std::string> cpu,
59
+ std::optional<std::string> attrs);
60
+ ~PytorchLLVMJIT();
61
+
62
+ void addModule(std::unique_ptr<Module> M, std::unique_ptr<LLVMContext> C);
63
+
64
+ JITSymbol findSymbol(const std::string Name);
65
+
66
+ bool hasSymbol(const std::string& Name);
67
+
68
+ TargetMachine& getTargetMachine();
69
+
70
+ const DataLayout& getDataLayout();
71
+
72
+ private:
73
+ // Use the PImpl idiom here to hide the no-rtti parts of the JIT structure.
74
+ std::unique_ptr<PytorchLLVMJITImpl> impl_;
75
+ };
76
+
77
+ } // end namespace orc
78
+ } // end namespace llvm
79
+
80
+ #endif // ENABLE LLVM
81
+
82
+ #else
83
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
84
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest.h ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+ #include <unordered_map>
6
+ #include <unordered_set>
7
+ #include <vector>
8
+
9
+ #include <torch/csrc/Export.h>
10
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
11
+
12
+ namespace torch::jit::tensorexpr {
13
+
14
+ class Expr;
15
+ class Var;
16
+ class Buf;
17
+ class Tensor;
18
+ class Function;
19
+ class Stmt;
20
+ class For;
21
+ class Block;
22
+ class Store;
23
+ class Dtype;
24
+
25
+ class TORCH_API LoopNest {
26
+ public:
27
+ // A constructor for building a LoopNest from a list of Tensors
28
+ LoopNest(
29
+ const std::vector<Tensor>& output_tensors,
30
+ const std::vector<Tensor>& tensors_to_compute);
31
+
32
+ // A convenience constructor for the case when all tensors are output tensors
33
+ LoopNest(const std::vector<Tensor>& output_tensors);
34
+
35
+ // A constructor for building a LoopNest from an Stmt and a list of output
36
+ // buffers.
37
+ LoopNest(StmtPtr stmt, std::unordered_set<BufPtr> output_bufs);
38
+
39
+ // A constructor for building a LoopNest from another loopnest. It clones the
40
+ // other loopnest's stmt.
41
+ LoopNest(const LoopNest& other);
42
+
43
+ StmtPtr root_stmt() const {
44
+ return root_stmt_;
45
+ }
46
+
47
+ std::vector<ForPtr> getLoopStmtsFor(const Tensor& /*t*/) const;
48
+ std::vector<ForPtr> getLoopStmtsFor(const BufPtr& /*buf*/) const;
49
+ std::vector<ForPtr> getLoopStmtsFor(StmtPtr /*s*/) const;
50
+ StmtPtr getLoopBodyFor(const Tensor& /*t*/) const;
51
+ StmtPtr getLoopBodyFor(BufPtr /*buf*/) const;
52
+
53
+ // Returns the For stmt indexed by 'indices' in the 'root' For stmt.
54
+ //'indices' indicates the path to the returned loop from 'root' in AST, e.g.,
55
+ //
56
+ // root: for(int i...){
57
+ // j_loop: for (int j...){
58
+ // k1_loop: for (int k1...){
59
+ // A[i, j, k1] = ....
60
+ // }
61
+ // B[i, j] = ...
62
+ // k2_loop: for (int k2...){
63
+ // A[i, j, k2] = ...
64
+ // }
65
+ // }
66
+ // }
67
+ //
68
+ // the path from 'root' to 'j_loop' is [0]
69
+ // the path from 'root' to 'k1_loop' is [0, 0]
70
+ // the path from 'root' to 'k2_loop' is [0, 2]
71
+ ForPtr getLoopAt(ForPtr root, const std::vector<int>& indices) const;
72
+
73
+ // Returns the For stmt that is immediately enclosing the given stmt.
74
+ static ForPtr getParentLoop(const StmtPtr& st);
75
+
76
+ // Returns the list of For stmts corresponding to the loopnest that is
77
+ // enclosing the given stmt.
78
+ static std::vector<ForPtr> getEnclosingLoopNest(const StmtPtr& st);
79
+
80
+ // Returns a list of all Stmts that write to the given buf.
81
+ std::vector<StmtPtr> getAllWritesToBuf(BufPtr /*buf*/) const;
82
+
83
+ // The following methods return the For loops that contain writes to
84
+ // the given buf.
85
+ //
86
+ // For example, consider the following code:
87
+ // for i1
88
+ // for j1
89
+ // a[i1,j1] =
90
+ // for i2
91
+ // for j2
92
+ // for k2
93
+ // a[i2,j2] =
94
+ // for j3
95
+ // a[i2,j3] =
96
+
97
+ // Returns a list of For loops which directly contain a Stmt that writes
98
+ // to buf.
99
+ // For the above example:
100
+ // getAllInnermostLoopsWritingToBuf(a) => {j1, k2, j3}
101
+ std::vector<ForPtr> getAllInnermostLoopsWritingToBuf(BufPtr /*buf*/) const;
102
+
103
+ // Returns a list of For loopnests which contain a Stmt that writes to
104
+ // the given buf. Each loopnest here is a vector For loops.
105
+ // For the above example:
106
+ // getAllLoopNestsWritingToBuf(a) => {{i1,j1}, {i2,j2,k2}, {i2,j3}}
107
+ std::vector<std::vector<ForPtr>> getAllLoopNestsWritingToBuf(
108
+ BufPtr /*buf*/) const;
109
+
110
+ StmtPtr simplify();
111
+
112
+ // Sanitize variables and buffer names.
113
+ // The pass assigns predefined names for loop index variables
114
+ // (i,j,k,l,m,n,o,p,i1,j1,k1,...) and ensures these names are not conflicting
115
+ // anywhere. It also removes duplicates from other Buf nad Var names as well
116
+ // as replaces illegal characters in them with underscores.
117
+ //
118
+ // Note: since it's currently technically possible to use the same variable
119
+ // as index in two different loops, this transformation finds such cases and
120
+ // introduces new variables to avoid duplication.
121
+ static StmtPtr sanitizeNames(StmtPtr s);
122
+
123
+ bool computeInline(const StmtPtr& s);
124
+ bool computeInline(const BufPtr& b);
125
+ void inlineIntermediateBufs(bool allow_duplicated_work);
126
+
127
+ // Optimizes conditionals.
128
+ //
129
+ // Currently, only the following pattern of conditionals is optimized.
130
+ // This corresponds to the conditional format that is generated to handle
131
+ // `aten::cat` op.
132
+ //
133
+ // for (int i = 0; i < 20; i++) {
134
+ // A[i] = IfThenElse(i<5 ? 1 : 0, B[i], C[i-5])
135
+ // }
136
+ //
137
+ // Constraints that must be satisfied for this optimization:
138
+ // * All conditions should be of the form "var < expr".
139
+ // * All conditions should have the same variable, say v.
140
+ // * The condition variable found should be the same as the inner-most
141
+ // loop variable. TODO: Remove this constraint.
142
+ // * If there are multiple stores that contain conditionals using the same
143
+ // loop variable, only the first conditional will be optimized.
144
+ // TODO: Remove this constraint.
145
+ bool optimizeConditionals();
146
+
147
+ // Splits the given loop into 2 nested loops with the given factor as the
148
+ // inner loop bound. If the factor does not evenly divide the loop bound,
149
+ // then the remaining iterations are extracted into a tail loop that is
150
+ // added after the given loop.
151
+ //
152
+ // For example, consider the following code:
153
+ // for (int i = 0; i < 100; ++i) {
154
+ // A[i] =
155
+ // }
156
+ //
157
+ // splitWithTail(i, 8, ...) will result in:
158
+ // for (int i_outer = 0; i_outer < 12; ++i_outer) {
159
+ // for (int i_inner = 0; i_inner < 8; ++i_inner) {
160
+ // A[i_outer * 8 + i_inner] =
161
+ // }
162
+ // }
163
+ // for (int i_tail = 0; i_tail < 4; ++i_tail) {
164
+ // A[i_tail + 96] =
165
+ // }
166
+ //
167
+ // The given loop will be transformed to the outer loop after splitting.
168
+ // So, the pointer to the input loop should be valid after splitting and
169
+ // will point to the outer loop. The `inner` and `tail` parameters will be
170
+ // set to point to the inner and tail loops that are generated.
171
+ static void splitWithTail(
172
+ const ForPtr& f,
173
+ int factor,
174
+ ForPtr* inner,
175
+ ForPtr* tail);
176
+ // A convenience wrapper when the caller does not need to access the
177
+ // split loops.
178
+ static void splitWithTail(const ForPtr& f, int factor);
179
+
180
+ // Splits the given loop into 2 nested loops with the given factor as the
181
+ // inner loop bound. If the factor does not evenly divide the loop bound,
182
+ // then a conditional is inserted into the body to handle the remaining
183
+ // iterations appropriately.
184
+ //
185
+ // For example, consider the following code:
186
+ // for (int i = 0; i < 100; ++i) {
187
+ // A[i] =
188
+ // }
189
+ //
190
+ // splitWithMask(i, 8, ...) will result in:
191
+ // for (int i_outer = 0; i_outer < 13; ++i_outer) {
192
+ // for (int i_inner = 0; i_inner < 8; ++i_inner) {
193
+ // if (i_outer * 8 + i_inner < 100) {
194
+ // A[i_outer * 8 + i_inner] =
195
+ // }
196
+ // }
197
+ // }
198
+ //
199
+ // The given loop will be transformed to the outer loop after splitting.
200
+ // So, the pointer to the input loop should be valid after splitting and
201
+ // will point to the outer loop. The `inner` parameter will be set to point
202
+ // to the inner loop that is generated.
203
+ static void splitWithMask(const ForPtr& f, int factor, ForPtr* inner);
204
+ // A convenience wrapper when the caller does not need to access the
205
+ // split loops.
206
+ static void splitWithMask(const ForPtr& f, int factor);
207
+
208
+ // The following methods support loop distribution.
209
+ // For example, consider the following code. This will be used to
210
+ // demonstrate the methods below.
211
+ //
212
+ // S0: for m
213
+ // S1: for i
214
+ // S2: A[i] = 0
215
+ // S3: for j
216
+ // S4: A[i] = A[i] +
217
+ // S5: B[i] = A[i]
218
+ // S6: for k
219
+ // S7: B[i] = B[i] +
220
+
221
+ // This method distributes the given loop over its body by splitting
222
+ // after every given pivot stmt.
223
+ //
224
+ // NOTE: Pivot stmts that are not in the given loop's body will be ignored.
225
+ //
226
+ // For the above example:
227
+ // distributeLoop(S1, {S3, S5})
228
+ // will result in:
229
+ // S0: for m
230
+ // S1: for i
231
+ // S2: A[i] = 0
232
+ // S3: for j
233
+ // S4: A[i] = A[i] +
234
+ // : for i
235
+ // S5: B[i] = A[i]
236
+ // : for i
237
+ // S6: for k
238
+ // S7: B[i] = B[i] +
239
+ static std::vector<ForPtr> distributeLoop(
240
+ const ForPtr& loop,
241
+ const std::unordered_set<StmtPtr>& pivots);
242
+
243
+ // This method distributes the given loop over every stmt in its body.
244
+ //
245
+ // For the above example:
246
+ // distributeLoop(S1)
247
+ // will result in:
248
+ // S0: for m
249
+ // S1: for i
250
+ // S2: A[i] = 0
251
+ // : for i
252
+ // S3: for j
253
+ // S4: A[i] = A[i] +
254
+ // : for i
255
+ // S5: B[i] = A[i]
256
+ // : for i
257
+ // S6: for k
258
+ // S7: B[i] = B[i] +
259
+ static std::vector<ForPtr> distributeLoop(const ForPtr& loop);
260
+ // Same as above, but also distribute parent loops.
261
+ // Returns the result of distributing the outermost loop.
262
+ //
263
+ // For the above example:
264
+ // distributeLoopAndParents(S1) will result in:
265
+ // S0: for m
266
+ // S1: for i
267
+ // S2: A[i] = 0
268
+ // : for m
269
+ // : for i
270
+ // S3: for j
271
+ // S4: A[i] = A[i] +
272
+ // : for m
273
+ // : for i
274
+ // S5: B[i] = A[i]
275
+ // : for m
276
+ // : for i
277
+ // S6: for k
278
+ // S7: B[i] = B[i] +
279
+ static std::vector<ForPtr> distributeLoopAndParents(const ForPtr& loop);
280
+
281
+ // This method distributes the given loop over its body by splitting
282
+ // after every For stmt in its body.
283
+ //
284
+ // For the above example:
285
+ // distributeLoopOverInnerLoops(S1)
286
+ // will result in:
287
+ // S0: for m
288
+ // S1: for i
289
+ // S2: A[i] = 0
290
+ // S3: for j
291
+ // S4: A[i] = A[i] +
292
+ // : for i
293
+ // S5: B[i] = A[i]
294
+ // S6: for k
295
+ // S7: B[i] = B[i] +
296
+ static std::vector<ForPtr> distributeLoopOverInnerLoops(const ForPtr& loop);
297
+ // Same as above, but also distribute parent loops.
298
+ // Returns the result of distributing the outermost loop.
299
+ //
300
+ // For the above example:
301
+ // distributeLoopAndParentsOverInnerLoops(S1)
302
+ // will result in:
303
+ // S0: for m
304
+ // S1: for i
305
+ // S2: A[i] = 0
306
+ // S3: for j
307
+ // S4: A[i] = A[i] +
308
+ // : for m
309
+ // : for i
310
+ // S5: B[i] = A[i]
311
+ // S6: for k
312
+ // S7: B[i] = B[i] +
313
+ static std::vector<ForPtr> distributeLoopAndParentsOverInnerLoops(
314
+ const ForPtr& loop);
315
+
316
+ // This method performs loop fusion.
317
+ // For example, consider the following code.
318
+ //
319
+ // S1: for m
320
+ // S2: A[m] = 0
321
+ // S3: for j
322
+ // S4: A[m] = A[m] +
323
+ // S5: for n
324
+ // S5: B[n] = A[n]
325
+ // S6: for k
326
+ // S7: B[n] = B[n] +
327
+ //
328
+ // fuseLoops({S1, S5}), will return the following loop:
329
+ // S1: for m
330
+ // S2: A[m] = 0
331
+ // S3: for j
332
+ // S4: A[m] = A[m] +
333
+ // S5: B[m] = A[m]
334
+ // S6: for k
335
+ // S7: B[m] = B[m] +
336
+ //
337
+ // This transformation is unsafe as it simply add all loops into the body of
338
+ // the first loop for fusion without correctness checks.
339
+ //
340
+ // Below are the two requirements to apply unsafeFuseLoops:
341
+ // * All the loops have the same parent.
342
+ // * There are no statements between these loops in their parent body.
343
+ static bool unsafeFuseLoops(const std::vector<ForPtr>& loops, ForPtr* fused);
344
+
345
+ // Loop fusion is done only when all the conditions below are satisfied.
346
+ // * All the loops have the same parent.
347
+ // * There are no statements between these loops in their parent body.
348
+ // * The start bounds are the same for all loops.
349
+ // * The stop bounds are the same for all loops.
350
+ // * Fusing the loops does not violate or add any dependencies.
351
+ static bool fuseLoops(const std::vector<ForPtr>& loops, ForPtr* fused);
352
+
353
+ static void reorderAxis(const ForPtr& a, const ForPtr& b);
354
+
355
+ // Reorder the given list of loops according to the permutation specified.
356
+ // Here `permutation[i]` represents the position of the loop in the input
357
+ // which will end up at position `i` after the reorder.
358
+ //
359
+ // For example, consider the following code:
360
+ // for p
361
+ // for q
362
+ // for r
363
+ // for s
364
+ // A[p,q,r,s] =
365
+ //
366
+ // reorder({p, q, r, s}, {2, 3, 0, 1}) will return the list of loops in the
367
+ // following form:
368
+ // for r
369
+ // for s
370
+ // for p
371
+ // for q
372
+ // A[p,q,r,s] =
373
+ static std::vector<ForPtr> reorder(
374
+ const std::vector<ForPtr>& loops,
375
+ const std::vector<size_t>& permutation);
376
+
377
+ // Tile takes a 2d domain (x, y) and splits it into small rectangular blocks
378
+ // each with shape (x_factor, y_factor). The traversal over the domain turns
379
+ // into an outer iteration over the blocks and an inner traversal over all
380
+ // points in the block.
381
+ // Note that if x dim % x_factor or y dim % y_factor does not equal to 0, the
382
+ // loop body will generate corresponding tailing loops.
383
+ // The transformation is in-place and returns 'xtail'.
384
+ //
385
+ // For example, consider the following code:
386
+ // for i: [0, 64)
387
+ // for j: [0, 64)
388
+ // for k: [0, 32)
389
+ // A[i, j] = B[i, k] + C[j, k]
390
+ //
391
+ // tile(i, j, 4, 8) will transform "i" for-stmt into the following nested
392
+ // loop:
393
+ // for i_outer: [0, 16)
394
+ // for j_outer: [0, 8)
395
+ // for i_inner: [0, 4)
396
+ // for j_inner: [0, 8)
397
+ // for k: [0, 32)
398
+ // A[i_outer * 4 + i_inner, j_outer * 8 + j_inner] =
399
+ // B[i_outer * 4 + i_inner, k] + C[j_outer * 8 + j_inner, k]
400
+ //
401
+ // tile(i, j, 4, 9) will transform "i" for-stmt into the following nested
402
+ // loop:
403
+ // for i_outer: [0, 16)
404
+ // for j_outer: [0, 7)
405
+ // for i_inner: [0, 4)
406
+ // for j_inner: [0, 9)
407
+ // for k: (0, 32)
408
+ // A[i_outer * 4 + i_inner, j_outer * 9 + j_inner] =
409
+ // B[i_outer * 4 + i_inner, k] + C[j_outer * 9 + j_inner, k]
410
+ // for j_tail: [0, 1)
411
+ // for i_inner: [0, 4)
412
+ // for k: (0, 32)
413
+ // A[i_outer * 4 + i_inner, 7 * 9 + j_tail] =
414
+ // B[i_outer * 4 + i_inner, k] + C[7 * 9 + j_tail, k]
415
+ ForPtr tile(const ForPtr& x, const ForPtr& y, int x_factor, int y_factor);
416
+
417
+ // Returns true if the given loops are perfectly nested, i.e., every loop
418
+ // (except the innermost) should have exactly one statement in its body
419
+ // and that statement must be the next inner loop.
420
+ static bool areLoopsPerfectlyNested(const std::vector<ForPtr>& loops);
421
+
422
+ // Returns true if the given loop has a loop-carried dependence.
423
+ static bool hasLoopCarriedDependence(const ForPtr& loop);
424
+
425
+ // Unrolls all the iterations of the given loop.
426
+ // Requires that the loop bounds are constant.
427
+ static void fullUnroll(const ForPtr& f, StmtPtr* unrolled);
428
+ static void fullUnroll(const ForPtr& f);
429
+
430
+ // Unrolls the given loop for the specified factor.
431
+ // This does not require constant bounds for the loop being unrolled.
432
+ static void unroll(const ForPtr& f, int factor, ForPtr* tail);
433
+ static void unroll(const ForPtr& f, int factor);
434
+
435
+ static bool normalize(const ForPtr& f);
436
+ static bool isNormalized(const ForPtr& f);
437
+
438
+ static bool flatten(const std::vector<ForPtr>& f, ForPtr* flattened);
439
+ static bool flatten(const std::vector<ForPtr>& f);
440
+
441
+ // Compresses the given buffer based on its use in the given Stmts.
442
+ //
443
+ // NOTE: This API assumes that there are no accesses to the given buffer
444
+ // outside the given statement. So, this should be called with the entire
445
+ // kernel statement to avoid incorrect buffer compressions.
446
+ //
447
+ // For example, given the input:
448
+ //
449
+ // for (int i = 0; i < 100; ++i) {
450
+ // for (int j = 0; j < 200; ++j) {
451
+ // A[i,j] = sin(i*j)
452
+ // }
453
+ // for (int j = 0; j < 199; ++j) {
454
+ // B[i,j] = A[i,j] + A[i, j+1]
455
+ // }
456
+ // }
457
+ //
458
+ // compressBuffer(A, ...) will compress buffer A from
459
+ // [100, 200] to [1, 200] and modify the code as follows:
460
+ //
461
+ // for (int i = 0; i < 100; ++i) {
462
+ // for (int j = 0; j < 200; ++j) {
463
+ // A[0,j] = sin(i*j)
464
+ // }
465
+ // for (int j = 0; j < 199; ++j) {
466
+ // B[i,j] = A[0,j] + A[0, j+1]
467
+ // }
468
+ // }
469
+ static void compressBuffer(const BufPtr& buf, const StmtPtr& stmt);
470
+
471
+ // Compresses all buffers in the given statement.
472
+ //
473
+ // NOTE: This API assumes that there are no accesses to buffers outside
474
+ // the given statement. So, this should be called with the entire
475
+ // kernel statement to avoid incorrect buffer compressions.
476
+ //
477
+ // TODO: Add an IR verifier check to detect invalidly compressed buffers.
478
+ static void compressAllBuffers(const StmtPtr& stmt);
479
+
480
+ // Get 'num' loops from the loopnest starting at 'f'.
481
+ static std::vector<ForPtr> getLoopStmtsInLoopNest(
482
+ const ForPtr& f,
483
+ size_t num);
484
+
485
+ // LoopOptions are propagated to tail.
486
+ static void sliceHead(
487
+ const ForPtr& f,
488
+ int factor,
489
+ ForPtr* head,
490
+ ForPtr* tail);
491
+ static void sliceHead(const ForPtr& f, int factor);
492
+ // LoopOptions are propagated to head.
493
+ static void sliceTail(
494
+ const ForPtr& f,
495
+ int factor,
496
+ ForPtr* head,
497
+ ForPtr* tail);
498
+ static void sliceTail(const ForPtr& f, int factor);
499
+
500
+ using AccessResult = std::pair<BufPtr, StmtPtr>;
501
+ // Insert a cache for the consumer's usages of the buffer produced in
502
+ // consumer, and redirect reads and writes in the consumer to that cache.
503
+ // Returns a pair of the new cache buffer, and the new rewritten consumer.
504
+ static AccessResult cacheAccesses(
505
+ const BufPtr& producer,
506
+ const std::string& name,
507
+ const StmtPtr& consumer);
508
+
509
+ // Insert a temporary computation of statement S in the scope of loop AT.
510
+ // S is assumed to be a Store or a Block containing a Store. Along with the
511
+ // computation itself, this transformation inserts Alloc/Free statements for
512
+ // the temporary buffer used in the computation.
513
+ static void computeAt(const StmtPtr& s, const ForPtr& at);
514
+
515
+ // Rfactor a reduction axis into a normal axis.
516
+ //
517
+ // Requirements:
518
+ // * S is the reduction store
519
+ // * S is the only statement in the innermost loop
520
+ // * There is at least two reduction arguments in S
521
+ // * OUTER_REDUCTION_FOR loop corresponds to the outermost reduction variable
522
+ // used in the store and all other reduction variables are index variables of
523
+ // children loops of OUTER_REDUCTION_FOR
524
+ // * OUTER_REDUCTION_FOR is a perfect loop nest, i.e. it has only loops
525
+ // corresponding to the other reduction variables and the store, nested into
526
+ // each other
527
+ //
528
+ // What it does:
529
+ // * Introduce a new buffer with an extra dimension of a size equal to the
530
+ // span of the loop OUTER_REDUCTION_FOR (the new buffer is returned via
531
+ // RFAC_BUF_PTR)
532
+ // * Insert an initialization store for the new buffer in
533
+ // OUTER_REDUCTION_FOR before its nested loop
534
+ // * Replace the reduction store to the original buffer with the reduction
535
+ // store to the temp buffer, removing the index var of OUTER_REDUCTION_FOR
536
+ // from reduction arguments
537
+ // * Insert a final reduction store over the extra dimension of the new
538
+ // buffer to the original buffer
539
+ // * Returns TRUE if the transformation succeeded and FALSE otherwise
540
+ //
541
+ // Example:
542
+ // Original IR:
543
+ // S1: for i # normal axis
544
+ // S2: X[i] = 0
545
+ // S3: for j # reduction axis
546
+ // S4: for k # reduction axis
547
+ // S5: X[i] = ReduceOp(X[i] + Y[i,j,k], reduce_axis={j,k})
548
+ //
549
+ // After RFACTOR(S5, S3)
550
+ // S1: for i # normal axis
551
+ // S2: X[i] = 0
552
+ // S3: for j # reduction axis for X, normal axis for X_rfac
553
+ // X_rfac[i,j] = 0
554
+ // S4: for k # reduction axis
555
+ // X_rfac[i,j] = ReduceOp(X_rfac[i,j] + Y[i,j,k], reduce_axis={k})
556
+ // X[i] = ReduceOp(X[i] + X_rfac[i,j], reduce_axis={j})
557
+ static bool rfactor(const StmtPtr& s, const ForPtr& outer_reduction_for);
558
+ static bool rfactor(
559
+ const StmtPtr& s,
560
+ const ForPtr& outer_reduction_for,
561
+ BufPtr* rfac_buf_ptr);
562
+
563
+ // Vectorize the given loop. This method requires that the given loop
564
+ // does not perform a reduction.
565
+ // It returns true if vectorization is successful and false otherwise.
566
+ static bool vectorize(const ForPtr& /*f*/);
567
+
568
+ // Find the inner-most loops and vectorize them. Currently, this only works
569
+ // for the LLVM backend, when no reductions are involved.
570
+ void vectorizeInnerLoops();
571
+
572
+ void eliminateDeadStores();
573
+
574
+ void prepareForCodegen();
575
+
576
+ const std::unordered_set<BufPtr> getInputBufs() const;
577
+ const std::unordered_set<BufPtr> getOutputBufs() const {
578
+ return output_bufs_;
579
+ }
580
+ std::vector<BufPtr> getIntermediateBufs() const;
581
+
582
+ // Finds which is the outer For between a and b for loops. If neither of the 2
583
+ // Fors is an ancestor of the other, it returns nullptr.
584
+ static ForPtr findOuterFor(ForPtr a, ForPtr b);
585
+
586
+ private:
587
+ void initialize(
588
+ const std::vector<Tensor>& output_tensors,
589
+ const std::vector<Tensor>& tensors_to_compute);
590
+
591
+ StmtPtr root_stmt_;
592
+
593
+ std::unordered_set<BufPtr> output_bufs_;
594
+ };
595
+
596
+ TORCH_API StmtPtr FlattenIndexes(const StmtPtr& s);
597
+
598
+ // TODO: Revisit this once we decide on how dependencies analysis should look
599
+ // like. Maybe we would choose to use a different API and BufUse would be
600
+ // removed, or if we decide to keep it we need to properly document its API.
601
+ struct BufLoadOrStoreUse {
602
+ StmtPtr s;
603
+ bool isStore;
604
+ };
605
+
606
+ /*
607
+ * Returns a map ( Buf -> uses of this Buf), uses are represented as vectors of
608
+ * BufUse elements, which are StmtPtr and a bool isStore flag. The order of uses
609
+ * in the vectors reflects the order in which the uses appear in the given
610
+ * statement.
611
+ */
612
+ std::unordered_map<BufPtr, std::vector<BufLoadOrStoreUse>> findLoadOrStoreUses(
613
+ const StmtPtr& s);
614
+
615
+ // replaces all invalid characters with underscore
616
+ TORCH_API std::string sanitizeName(const std::string& input_name);
617
+
618
+ } // namespace torch::jit::tensorexpr
619
+
620
+ #else
621
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
622
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/loopnest_randomization.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ namespace torch::jit::tensorexpr {
5
+
6
+ // Applies a series of loop optimizations chosen randomly. This is only for
7
+ // testing purposes. This allows automatic stress testing of NNC loop
8
+ // transformations.
9
+ void loopnestRandomization(int64_t seed, LoopNest& l);
10
+ } // namespace torch::jit::tensorexpr
11
+
12
+ #else
13
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
14
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/lowerings.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ // This file defines classes for registering standard lowerings from JIT to TE
3
+ // IR.
4
+ #pragma once
5
+
6
+ #include <torch/csrc/jit/ir/ir.h>
7
+ #include <torch/csrc/jit/runtime/interpreter.h>
8
+ #include <torch/csrc/jit/tensorexpr/analysis.h>
9
+ #include <torch/csrc/jit/tensorexpr/codegen.h>
10
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
11
+
12
+ namespace torch::jit::tensorexpr {
13
+
14
+ using ArgNone = std::monostate;
15
+ using BufList = std::vector<tensorexpr::BufHandle>;
16
+ using DoubleList = std::vector<double>;
17
+ using IntList = std::vector<int64_t>;
18
+ using ArgValue = std::variant<
19
+ tensorexpr::BufHandle,
20
+ tensorexpr::VarHandle,
21
+ double,
22
+ int64_t,
23
+ bool,
24
+ BufList,
25
+ DoubleList,
26
+ IntList,
27
+ std::string,
28
+ ArgNone>;
29
+
30
+ using NNCLoweringFunction = std::function<Tensor(
31
+ const std::vector<ArgValue>&,
32
+ const std::vector<ExprHandle>&,
33
+ const std::vector<ExprHandle>&,
34
+ const std::optional<ScalarType>&,
35
+ at::Device)>;
36
+
37
+ TORCH_API FunctionSchemaMap<NNCLoweringFunction>& getNNCLoweringRegistry();
38
+ TORCH_API NNCLoweringFunction getStandardLoweringFor(const std::string& op);
39
+
40
+ struct RegisterNNCLoweringsFunction {
41
+ RegisterNNCLoweringsFunction(
42
+ const std::vector<std::string>& schemas,
43
+ const NNCLoweringFunction& fn);
44
+ };
45
+
46
+ } // namespace torch::jit::tensorexpr
47
+
48
+ #else
49
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
50
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/mem_dependency_checker.h ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <torch/csrc/Export.h>
5
+ #include <utility>
6
+ #include <vector>
7
+
8
+ #include <torch/csrc/jit/tensorexpr/bounds_overlap.h>
9
+ #include <torch/csrc/jit/tensorexpr/ir_mutator.h>
10
+ #include <torch/csrc/jit/tensorexpr/ir_simplifier.h>
11
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
12
+ #include <torch/csrc/jit/tensorexpr/stmt.h>
13
+
14
+ namespace torch::jit::tensorexpr::analysis {
15
+
16
+ enum class AccessType {
17
+ Input,
18
+ Output,
19
+ Load,
20
+ Store,
21
+ Call,
22
+ AtomicAdd,
23
+ Alloc,
24
+ Free
25
+ };
26
+ const char* AccessToString(AccessType a);
27
+
28
+ class AccessInfo;
29
+ using DependencySet = std::unordered_set<std::shared_ptr<AccessInfo>>;
30
+
31
+ /* AccessInfo
32
+ *
33
+ * Represents a single bounded memory access to a buffer, for instance a Load or
34
+ * a Store. Holds information relating to the specific access and links to
35
+ * connected accesses in the dependency graph.
36
+ */
37
+ class TORCH_API AccessInfo {
38
+ public:
39
+ AccessInfo(
40
+ size_t id,
41
+ AccessType type,
42
+ StmtPtr stmt,
43
+ VarPtr var,
44
+ IndexBounds bounds)
45
+ : id_(id),
46
+ type_(type),
47
+ stmt_(std::move(stmt)),
48
+ expr_(nullptr),
49
+ var_(std::move(var)),
50
+ bounds_(std::move(bounds)) {}
51
+
52
+ AccessInfo(
53
+ size_t id,
54
+ AccessType type,
55
+ ExprPtr expr,
56
+ StmtPtr stmt,
57
+ VarPtr var,
58
+ IndexBounds bounds)
59
+ : id_(id),
60
+ type_(type),
61
+ stmt_(std::move(stmt)),
62
+ expr_(std::move(expr)),
63
+ var_(std::move(var)),
64
+ bounds_(std::move(bounds)) {}
65
+
66
+ // Id is a unique int representing the order this access occurred in the
67
+ // graph.
68
+ size_t id() const {
69
+ return id_;
70
+ }
71
+
72
+ // The type of the access (Load, Store, etc).
73
+ AccessType type() const {
74
+ return type_;
75
+ }
76
+
77
+ // The enclosing Stmt this access represents. E.g. if this is a Store then
78
+ // Stmt is the Store itself, while if the access is caused by an Expr, this is
79
+ // the most immediate parent Stmt.
80
+ StmtPtr stmt() const {
81
+ return stmt_;
82
+ }
83
+
84
+ // If the access is represented by an Expr (such as Load or Call) then this is
85
+ // it, otherwise it's nullptr.
86
+ ExprPtr expr() const {
87
+ return expr_;
88
+ }
89
+
90
+ // The Var representing the underlying Buffer.
91
+ VarPtr var() const {
92
+ return var_;
93
+ }
94
+
95
+ // A vector of Bounds representing the start and end expression for each
96
+ // dimension.
97
+ IndexBounds& bounds() {
98
+ return bounds_;
99
+ }
100
+
101
+ // Each access that this depends upon,
102
+ // eg. if this is a Load, then it contains every Store that immediately
103
+ // contributes to a load of the bounds.
104
+ // or: if this is a Store, it contains all reads on the RHS of the Store.
105
+ const std::map<size_t, std::shared_ptr<AccessInfo>>& dependencies() const {
106
+ return dependencies_;
107
+ }
108
+
109
+ // Each access that depends on this one.
110
+ // ie. this access is present in the dependencies map of all accesses that are
111
+ // dependent.
112
+ std::map<size_t, std::shared_ptr<AccessInfo>> dependents() const {
113
+ std::map<size_t, std::shared_ptr<AccessInfo>> res;
114
+ for (const auto& kv : dependents_) {
115
+ res.emplace(kv.first, kv.second.lock());
116
+ }
117
+ return res;
118
+ }
119
+
120
+ // Returns the symbolic expression of the indices of this access.
121
+ std::vector<ExprPtr> getIndices() const;
122
+
123
+ // Establishes a dependency or dependent relationship with another access.
124
+ void addDependency(const std::shared_ptr<AccessInfo>& write);
125
+ void addDependent(const std::shared_ptr<AccessInfo>& read);
126
+
127
+ // helper for checking dependencies.
128
+ bool hasDependency(const std::shared_ptr<AccessInfo>& info) const;
129
+
130
+ // Returns the set of all nodes that are direct (immediate) dependencies of
131
+ // this access.
132
+ DependencySet getDirectDependencies();
133
+ // likewise, returns all nodes that directly depend on this one.
134
+ DependencySet getDirectDependents();
135
+
136
+ // Returns the full list of all nodes in the graph that this access depends
137
+ // on, and all nodes they depend on, and so forth, back to the inputs.
138
+ DependencySet getIndirectDependencies();
139
+ // likewise, returns the full list of all nodes that depend on this node, and
140
+ // all nodes that depend on those nodes and so on down to the outputs.
141
+ DependencySet getIndirectDependents();
142
+
143
+ // Does this access represent a read of memory (Load, ReduceOp, Call, etc).
144
+ bool isRead() const;
145
+ // Does this access represent a write of memory (Store, etc).
146
+ bool isWrite() const;
147
+
148
+ // Helpers for dumping accesses in various formats.
149
+ void print() const;
150
+ void dumpDOT(std::ostream& os) const;
151
+ const char* AccessTypeColour() const;
152
+
153
+ private:
154
+ size_t id_;
155
+ AccessType type_;
156
+ StmtPtr stmt_;
157
+ ExprPtr expr_;
158
+ VarPtr var_;
159
+ IndexBounds bounds_;
160
+
161
+ // Yes these should be sorted.
162
+ std::map<size_t, std::shared_ptr<AccessInfo>> dependencies_;
163
+ std::map<size_t, std::weak_ptr<AccessInfo>> dependents_;
164
+ };
165
+
166
+ using VarBoundMap = std::unordered_map<VarPtr, Bound>;
167
+
168
+ /* MemDependencyChecker analyses a IR fragment and builds a dependency graph of
169
+ * accesses contained within.
170
+ *
171
+ * It's possible to retrieve the entire graph in node-object form, or can be
172
+ * used as an oracle for answering dependency questions. e.g:
173
+ *
174
+ * analyzer.hasIndirectDependency(BufA, BufB); or,
175
+ * analyzer.hasDirectDependency(LoadA, StoreB);
176
+ */
177
+ class TORCH_API MemDependencyChecker : public IRVisitor {
178
+ struct Scope;
179
+
180
+ public:
181
+ MemDependencyChecker();
182
+ MemDependencyChecker(
183
+ const std::unordered_set<BufPtr>& inputs,
184
+ const std::unordered_set<BufPtr>& outputs);
185
+ MemDependencyChecker(
186
+ const std::vector<BufHandle>& inputs,
187
+ const std::vector<BufHandle>& outputs);
188
+
189
+ ~MemDependencyChecker() override = default;
190
+
191
+ // Whether or not to allow loop execution order to influence dependency
192
+ // calculation. If the loop may later be parallelized you don't want this.
193
+ bool allowLoopExecutionOrderAnalysis(bool allow = true);
194
+
195
+ // Dependency Checking API.
196
+ // The goal is to have enough overloads here so you don't really have to think
197
+ // about it.
198
+
199
+ // Returns true if any read in A has a direct dependence on a write in B.
200
+ bool dependsDirectly(const StmtPtr& A, const StmtPtr& B);
201
+ bool dependsDirectly(const ExprPtr& A, const StmtPtr& B);
202
+
203
+ // Returns true of the output depends directly on a write contained in B.
204
+ bool dependsDirectly(const BufPtr& output, const StmtPtr& B);
205
+
206
+ // Returns true if a read in A depends directly on the provided input.
207
+ bool dependsDirectly(const StmtPtr& A, const BufPtr& input);
208
+ bool dependsDirectly(const ExprPtr& A, const BufPtr& input);
209
+
210
+ // Outputs/inputs cannot depend directly.
211
+
212
+ // Returns true if the access A has B as an immediate dependency.
213
+ bool dependsDirectly(
214
+ const std::shared_ptr<AccessInfo>& A,
215
+ const std::shared_ptr<AccessInfo>& B);
216
+
217
+ // Returns true if any read in A has an ancestor write contained in B.
218
+ bool dependsIndirectly(const StmtPtr& A, const StmtPtr& B);
219
+ bool dependsIndirectly(const ExprPtr& A, const StmtPtr& B);
220
+
221
+ // Returns true of the output depends indirectly on a write contained in B.
222
+ bool dependsIndirectly(const BufPtr& output, const StmtPtr& B);
223
+
224
+ // Returns true if a read in A depends indirectly on the provided input.
225
+ bool dependsIndirectly(const StmtPtr& A, const BufPtr& input);
226
+ bool dependsIndirectly(const ExprPtr& A, const BufPtr& input);
227
+
228
+ // returns true if the output uses any load of the input.
229
+ bool dependsIndirectly(const BufPtr& output, const BufPtr& input);
230
+
231
+ // Returns true if the access A has a dependency chain to access B.
232
+ bool dependsIndirectly(
233
+ const std::shared_ptr<AccessInfo>& A,
234
+ const std::shared_ptr<AccessInfo>& B);
235
+
236
+ // Returns the AccessInfo
237
+ std::shared_ptr<AccessInfo> accessFor(const StmtPtr& A) const;
238
+ std::shared_ptr<AccessInfo> accessFor(const ExprPtr& A) const;
239
+
240
+ // Returns all AccessInfos.
241
+ std::unordered_set<std::shared_ptr<AccessInfo>> accessesWithin(
242
+ const StmtPtr& A) const;
243
+ // TODO: this will return only the AccessInfo for A. It's included for
244
+ // completeness but be aware it won't return accesses used in the computation
245
+ // of A.
246
+ std::unordered_set<std::shared_ptr<AccessInfo>> accessesWithin(
247
+ const ExprPtr& A) const;
248
+
249
+ // Accesses relating to input and output buffers.
250
+ std::shared_ptr<AccessInfo> input(const BufPtr& B) const;
251
+ std::shared_ptr<AccessInfo> output(const BufPtr& B) const;
252
+
253
+ // Returns the full history of reads and writes.
254
+ const std::vector<std::shared_ptr<AccessInfo>>& getHistory() const;
255
+
256
+ // Dumps the dependency graph in DOT format.
257
+ void dumpDAG(const std::string& filename) const;
258
+
259
+ private:
260
+ // Node visitors.
261
+ void visit(const StorePtr& v) override;
262
+ void visit(const LoadPtr& v) override;
263
+ void visit(const ForPtr& v) override;
264
+ void visit(const CondPtr& v) override;
265
+ void visit(const IfThenElsePtr& v) override;
266
+ void visit(const CompareSelectPtr& v) override;
267
+ void visit(const BlockPtr& v) override;
268
+ void visit(const LetPtr& v) override;
269
+ void visit(const AtomicAddPtr& v) override;
270
+ void visit(const AllocatePtr& v) override;
271
+ void visit(const FreePtr& v) override;
272
+
273
+ using BoundRelationship = std::pair<IndexBounds, std::shared_ptr<AccessInfo>>;
274
+
275
+ // An internal struct holding the accesses found within a scope Block.
276
+ struct Scope {
277
+ Scope(BlockPtr b, std::shared_ptr<Scope> p)
278
+ : block(std::move(b)), parent(std::move(p)) {}
279
+
280
+ BlockPtr block;
281
+ std::shared_ptr<Scope> parent;
282
+
283
+ std::unordered_map<VarPtr, Bound> shadowedVarBounds;
284
+ std::unordered_set<VarPtr> localVars;
285
+
286
+ std::vector<std::shared_ptr<AccessInfo>> accesses_;
287
+
288
+ std::unordered_map<VarPtr, std::list<BoundRelationship>> openWrites_;
289
+ };
290
+ std::shared_ptr<Scope> currentScope_;
291
+
292
+ bool allowExecutionOrderAnalysis_{false};
293
+
294
+ std::unordered_multimap<StmtPtr, std::shared_ptr<AccessInfo>> stmtToAccess_;
295
+ std::unordered_multimap<ExprPtr, std::shared_ptr<AccessInfo>> exprToAccess_;
296
+ std::unordered_map<StmtPtr, std::vector<std::shared_ptr<AccessInfo>>>
297
+ scopeToAccesses_;
298
+
299
+ VarBoundMap knownVarBounds_;
300
+
301
+ // Finds all accesses that are reads within the scope of v.
302
+ template <typename StmtOrExprPtr>
303
+ DependencySet getAllReadsWithin(const StmtOrExprPtr& v) {
304
+ DependencySet reads;
305
+ auto insertAllReads = [&](const auto& nodes) {
306
+ for (const auto& l : nodes) {
307
+ auto bound = exprToAccess_.equal_range(l);
308
+ for (auto it = bound.first; it != bound.second; ++it) {
309
+ if (it->second->isRead()) {
310
+ reads.insert(it->second);
311
+ }
312
+ }
313
+ }
314
+ };
315
+
316
+ // Look for and insert accesses belonging to all nodes that act like
317
+ // reads.
318
+ insertAllReads(NodeFinder<Load>::find(v));
319
+ insertAllReads(NodeFinder<ReduceOp>::find(v));
320
+
321
+ return reads;
322
+ }
323
+
324
+ // Finds all accesses that are writes within the scope of v.
325
+ // Writes cannot occur in Exprs, so this is a little simpler.
326
+ DependencySet getAllWritesWithin(const StmtPtr& v) {
327
+ DependencySet writes;
328
+
329
+ // writes just Store currently.
330
+ auto stores = NodeFinder<Store>::find(v);
331
+ for (const auto& s : stores) {
332
+ auto bound = stmtToAccess_.equal_range(s);
333
+ for (auto it = bound.first; it != bound.second; ++it) {
334
+ if (it->second->isWrite()) {
335
+ writes.insert(it->second);
336
+ }
337
+ }
338
+ }
339
+ return writes;
340
+ }
341
+
342
+ // Templated helpers to work on either Exprs or Stmts.
343
+ template <typename StmtOrExprPtr>
344
+ bool dependsDirectlyHelper(const StmtOrExprPtr& A, const StmtPtr& B) {
345
+ auto aReads = getAllReadsWithin(A);
346
+ auto bWrites = getAllWritesWithin(B);
347
+
348
+ for (auto& read : aReads) {
349
+ for (auto& depPair : read->dependencies()) {
350
+ if (bWrites.count(depPair.second) != 0) {
351
+ return true;
352
+ }
353
+ }
354
+ }
355
+
356
+ return false;
357
+ }
358
+
359
+ template <typename StmtOrExprPtr>
360
+ bool dependsIndirectlyHelper(StmtOrExprPtr A, const StmtPtr& B) {
361
+ auto aReads = getAllReadsWithin(A);
362
+ auto bWrites = getAllWritesWithin(B);
363
+
364
+ auto aDeps = getAllWriteDependencies(aReads);
365
+
366
+ for (auto& dependency : aDeps) {
367
+ if (bWrites.count(dependency) != 0) {
368
+ return true;
369
+ }
370
+ }
371
+
372
+ return false;
373
+ }
374
+
375
+ DependencySet getAllWriteDependencies(const DependencySet& products);
376
+
377
+ // Maps for inputs and outputs, since they aren't present directly in the IR.
378
+ std::unordered_map<BufPtr, std::shared_ptr<AccessInfo>> inputs_;
379
+ std::unordered_map<BufPtr, std::shared_ptr<AccessInfo>> outputs_;
380
+ std::unordered_map<VarPtr, std::shared_ptr<AccessInfo>> intermediates_;
381
+
382
+ // Inserts accesses for Buf's: specifically for inputs and outputs.
383
+ void insertBuffers(
384
+ std::unordered_map<BufPtr, std::shared_ptr<AccessInfo>>& bufs,
385
+ AccessType type);
386
+
387
+ // Update the write history with a new write, adding dependencies and closing
388
+ // any overlapped writes (if possible).
389
+ void updateWriteHistory(
390
+ std::list<BoundRelationship>& writeHistory,
391
+ const std::shared_ptr<AccessInfo>& info,
392
+ size_t latestAccessToClose,
393
+ bool closeOverlapped = true,
394
+ bool insert = true);
395
+
396
+ // Merge a child scope into a parent scope, adding dependencies for open
397
+ // writes in the parent to accesses in the child.
398
+ void mergeScope(
399
+ const std::shared_ptr<Scope>& child,
400
+ const std::shared_ptr<Scope>& parent,
401
+ bool closeOverlapped = true);
402
+
403
+ // Binds symbolic vars in indices with the low and high bound for those vars.
404
+ std::vector<Bound> getIndicesBounds(const std::vector<ExprPtr>& indices);
405
+
406
+ size_t nextAccess_{0};
407
+ StmtPtr lastStmt_{nullptr};
408
+ };
409
+
410
+ } // namespace torch::jit::tensorexpr::analysis
411
+
412
+ #else
413
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
414
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/conv2d.h ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/operators/misc.h>
5
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
6
+
7
+ namespace torch::jit::tensorexpr {
8
+
9
+ // An API to compute 2D depthwise convolutions with bias.
10
+ TORCH_API Tensor conv2d_depthwise(
11
+ BufHandle input,
12
+ BufHandle weight,
13
+ BufHandle bias,
14
+ int stride,
15
+ int pad,
16
+ int groups);
17
+
18
+ // An API to compute 2D depthwise convolutions without bias.
19
+ TORCH_API Tensor conv2d_depthwise(
20
+ BufHandle input,
21
+ BufHandle weight,
22
+ int stride,
23
+ int pad,
24
+ int groups);
25
+
26
+ TORCH_API Tensor conv2d_depthwise(
27
+ BufHandle input,
28
+ BufHandle weight,
29
+ BufHandle bias,
30
+ ExprHandle N,
31
+ ExprHandle C,
32
+ ExprHandle H,
33
+ ExprHandle W,
34
+ ExprHandle K,
35
+ ExprHandle CperG,
36
+ ExprHandle R,
37
+ ExprHandle S,
38
+ ExprHandle stride,
39
+ ExprHandle pad,
40
+ ExprHandle groups);
41
+
42
+ TORCH_API Tensor conv2d_depthwise(
43
+ BufHandle input,
44
+ BufHandle weight,
45
+ ExprHandle N,
46
+ ExprHandle C,
47
+ ExprHandle H,
48
+ ExprHandle W,
49
+ ExprHandle K,
50
+ ExprHandle CperG,
51
+ ExprHandle R,
52
+ ExprHandle S,
53
+ ExprHandle stride,
54
+ ExprHandle pad,
55
+ ExprHandle groups);
56
+
57
+ bool conv2dIsSupported(
58
+ const TensorInfo& input,
59
+ const TensorInfo& weight,
60
+ const TensorInfo& bias,
61
+ const std::vector<int64_t>& stride,
62
+ const std::vector<int64_t>& pad,
63
+ const std::vector<int64_t>& dilation,
64
+ int64_t groups);
65
+ bool mkldnnPrepackedConvIsSupported(
66
+ const TensorInfo& input,
67
+ const TensorInfo& weight,
68
+ const std::vector<int64_t>& stride,
69
+ const std::vector<int64_t>& pad,
70
+ const std::vector<int64_t>& dilation,
71
+ int64_t groups);
72
+ Tensor computeConv2d(
73
+ const std::vector<ArgValue>& inputs,
74
+ const std::vector<ExprHandle>& outputShape,
75
+ const std::vector<ExprHandle>& outputStrides,
76
+ const std::optional<ScalarType>& outputType,
77
+ at::Device device);
78
+ Tensor computeConv1d(
79
+ const std::vector<ArgValue>& inputs,
80
+ const std::vector<ExprHandle>& outputShape,
81
+ const std::vector<ExprHandle>& outputStrides,
82
+ const std::optional<ScalarType>& outputType,
83
+ at::Device device);
84
+ Tensor computePrepackedConv2dClampRun(
85
+ const std::vector<ArgValue>& inputs,
86
+ const std::vector<ExprHandle>& outputShape,
87
+ const std::vector<ExprHandle>& outputStrides,
88
+ const std::optional<ScalarType>& outputType,
89
+ at::Device device);
90
+ Tensor computePrepackedLinearClampRun(
91
+ const std::vector<ArgValue>& inputs,
92
+ const std::vector<ExprHandle>& outputShape,
93
+ const std::vector<ExprHandle>& outputStrides,
94
+ const std::optional<ScalarType>& outputType,
95
+ at::Device device);
96
+ Tensor computeMkldnnPrepackedConvRun(
97
+ const std::vector<ArgValue>& inputs,
98
+ const std::vector<ExprHandle>& outputShape,
99
+ const std::vector<ExprHandle>& outputStrides,
100
+ const std::optional<ScalarType>& outputType,
101
+ at::Device device);
102
+ } // namespace torch::jit::tensorexpr
103
+
104
+ #else
105
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
106
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/matmul.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/kernel.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ Tensor computeMatmul(
9
+ const std::vector<ArgValue>& inputs,
10
+ const std::vector<ExprHandle>& outputShape,
11
+ const std::vector<ExprHandle>& outputStrides,
12
+ const std::optional<ScalarType>& outputType,
13
+ at::Device device);
14
+ Tensor computeAddMM(
15
+ const std::vector<ArgValue>& inputs,
16
+ const std::vector<ExprHandle>& outputShape,
17
+ const std::vector<ExprHandle>& outputStrides,
18
+ const std::optional<ScalarType>& outputType,
19
+ at::Device device);
20
+
21
+ } // namespace torch::jit::tensorexpr
22
+
23
+ #else
24
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
25
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/misc.h ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
5
+ #include <torch/csrc/jit/tensorexpr/lowerings.h>
6
+ #include <torch/csrc/jit/tensorexpr/tensor.h>
7
+
8
+ namespace torch::jit::tensorexpr {
9
+
10
+ struct TensorInfo {
11
+ std::vector<int64_t> dims;
12
+ c10::ScalarType dtype;
13
+ };
14
+ std::optional<TensorInfo> getTensorInfo(const BufHandle& b);
15
+
16
+ int64_t normalizeAndCheckIndex(int64_t idx, int64_t list_size);
17
+
18
+ // Convert boolean to integer, if needed.
19
+ ExprHandle boolToInteger(const ExprHandle& x);
20
+ ExprHandle promoteToDtype(ExprHandle e, ScalarType dt);
21
+ void promoteInputs(
22
+ std::vector<ExprHandle>& inputs,
23
+ const int typeConstraints = kAllTypes);
24
+ ExprHandle promoteIntegerToDefaultType(const ExprHandle& e);
25
+ ExprHandle promoteHalfToFloat(const ExprHandle& e);
26
+ ExprHandle demoteOutput(
27
+ const ExprHandle& e,
28
+ const std::optional<ScalarType> type);
29
+
30
+ std::vector<ExprHandle> broadcastShapes(
31
+ std::vector<std::vector<ExprHandle>> shapes);
32
+ std::vector<ExprHandle> broadcastShapes(
33
+ const std::vector<ExprHandle>& a,
34
+ const std::vector<ExprHandle>& b);
35
+
36
+ std::vector<ExprHandle> valueShape(const ArgValue& v);
37
+ ExprHandle tensorOrConstant(
38
+ const ArgValue& v,
39
+ const std::vector<ExprHandle>& axes);
40
+ ExprHandle scalarOrConstant(const ArgValue& v);
41
+ ExprHandle broadcast(const BufHandle& b, const std::vector<ExprHandle>& axes);
42
+ ExprHandle constant(const ArgValue& v);
43
+
44
+ ExprHandle clamp(
45
+ const ExprHandle& cmin,
46
+ const ExprHandle& cmax,
47
+ const ExprHandle& input);
48
+
49
+ Tensor computeChunk(
50
+ const std::vector<ArgValue>& inputs,
51
+ const std::vector<ExprHandle>& outputShape,
52
+ const std::vector<ExprHandle>& outputStrides,
53
+ const std::optional<ScalarType>& outputType,
54
+ at::Device device);
55
+ Tensor computeTranspose(
56
+ const std::vector<ArgValue>& inputs,
57
+ const std::vector<ExprHandle>& outputShape,
58
+ const std::vector<ExprHandle>& outputStrides,
59
+ const std::optional<ScalarType>& outputType,
60
+ at::Device device);
61
+ Tensor computeExpand(
62
+ const std::vector<ArgValue>& inputs,
63
+ const std::vector<ExprHandle>& outputShape,
64
+ const std::vector<ExprHandle>& outputStrides,
65
+ const std::optional<ScalarType>& outputType,
66
+ at::Device device);
67
+ Tensor computeReshape(
68
+ const std::vector<ArgValue>& inputs,
69
+ const std::vector<ExprHandle>& outputShape,
70
+ const std::vector<ExprHandle>& outputStrides,
71
+ const std::optional<ScalarType>& outputType,
72
+ at::Device device);
73
+ Tensor computeFlatten(
74
+ const std::vector<ArgValue>& inputs,
75
+ const std::vector<ExprHandle>& outputShape,
76
+ const std::vector<ExprHandle>& outputStrides,
77
+ const std::optional<ScalarType>& outputType,
78
+ at::Device device);
79
+ Tensor computeCatWoConditionals(
80
+ const std::vector<ArgValue>& inputs,
81
+ const std::vector<ExprHandle>& outputShape);
82
+ Tensor computeCat(
83
+ const std::vector<ArgValue>& inputs,
84
+ const std::vector<ExprHandle>& outputShape,
85
+ const std::vector<ExprHandle>& outputStrides,
86
+ const std::optional<ScalarType>& outputType,
87
+ at::Device device);
88
+ Tensor computeEmbedding(
89
+ const std::vector<ArgValue>& inputs,
90
+ const std::vector<ExprHandle>& outputShape,
91
+ const std::vector<ExprHandle>& outputStrides,
92
+ const std::optional<ScalarType>& outputType,
93
+ at::Device device);
94
+
95
+ } // namespace torch::jit::tensorexpr
96
+
97
+ #else
98
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
99
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/norm.h ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/kernel.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ Tensor computeBatchNorm(
9
+ const std::vector<ArgValue>& inputs,
10
+ const std::vector<ExprHandle>& outputShape,
11
+ const std::vector<ExprHandle>& outputStrides,
12
+ const std::optional<ScalarType>& outputType,
13
+ at::Device device);
14
+
15
+ } // namespace torch::jit::tensorexpr
16
+
17
+ #else
18
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
19
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/operators.h ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/operators/conv2d.h>
5
+ #include <torch/csrc/jit/tensorexpr/operators/matmul.h>
6
+ #include <torch/csrc/jit/tensorexpr/operators/misc.h>
7
+ #include <torch/csrc/jit/tensorexpr/operators/norm.h>
8
+ #include <torch/csrc/jit/tensorexpr/operators/pointwise.h>
9
+ #include <torch/csrc/jit/tensorexpr/operators/quantization.h>
10
+ #include <torch/csrc/jit/tensorexpr/operators/reduction.h>
11
+ #include <torch/csrc/jit/tensorexpr/operators/softmax.h>
12
+
13
+ #else
14
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
15
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/pointwise.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/kernel.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ TORCH_API Tensor computeSign(
9
+ const std::vector<ArgValue>& inputs,
10
+ const std::vector<ExprHandle>& outputShape,
11
+ const std::optional<std::vector<ExprHandle>>& outputStrides = std::nullopt);
12
+
13
+ Tensor computeOneOperand(
14
+ const std::string& name,
15
+ const std::vector<ArgValue>& inputValues,
16
+ const std::vector<ExprHandle>& outputShape,
17
+ const std::vector<ExprHandle>& outputStrides,
18
+ const std::optional<ScalarType>& outputType,
19
+ const std::function<ExprHandle(const ExprHandle&)>& innerExpr,
20
+ const int checkParamTypes = kAllTypes);
21
+ Tensor computeTwoOperand(
22
+ const std::string& name,
23
+ const std::vector<ArgValue>& inputValues,
24
+ const std::vector<ExprHandle>& outputShape,
25
+ const std::vector<ExprHandle>& outputStrides,
26
+ const std::optional<ScalarType>& outputType,
27
+ const std::function<ExprHandle(const ExprHandle&, const ExprHandle&)>&
28
+ innerExpr);
29
+ Tensor computeTwoOperandWithAlpha(
30
+ const std::string& name,
31
+ const std::vector<ArgValue>& inputValues,
32
+ const std::vector<ExprHandle>& outputShape,
33
+ const std::vector<ExprHandle>& outputStrides,
34
+ const std::optional<ScalarType>& outputType,
35
+ const std::function<ExprHandle(const ExprHandle&, const ExprHandle&)>&
36
+ innerExpr);
37
+ Tensor computeConditionWithTwoOperand(
38
+ const std::string& name,
39
+ const std::vector<ArgValue>& inputValues,
40
+ const std::vector<ExprHandle>& outputShape,
41
+ const std::vector<ExprHandle>& outputStrides,
42
+ const std::optional<ScalarType>& outputType,
43
+ const std::function<
44
+ ExprHandle(const ExprHandle&, const ExprHandle&, const ExprHandle&)>&
45
+ innerExpr);
46
+ Tensor computeThreeOperand(
47
+ const std::string& name,
48
+ const std::vector<ArgValue>& inputValues,
49
+ const std::vector<ExprHandle>& outputShape,
50
+ const std::vector<ExprHandle>& outputStrides,
51
+ const std::optional<ScalarType>& outputType,
52
+ const std::function<
53
+ ExprHandle(const ExprHandle&, const ExprHandle&, const ExprHandle&)>&
54
+ innerExpr,
55
+ bool promote_inputs = true);
56
+ Tensor computeFourOperand(
57
+ const std::string& name,
58
+ const std::vector<ArgValue>& inputValues,
59
+ const std::vector<ExprHandle>& outputShape,
60
+ const std::vector<ExprHandle>& outputStrides,
61
+ const std::optional<ScalarType>& outputType,
62
+ const std::function<ExprHandle(
63
+ const ExprHandle&,
64
+ const ExprHandle&,
65
+ const ExprHandle&,
66
+ const ExprHandle&)>& innerExpr);
67
+ Tensor computeNoop(
68
+ const std::vector<ArgValue>& inputs,
69
+ const std::vector<ExprHandle>& outputShape,
70
+ const std::vector<ExprHandle>& outputStrides,
71
+ const std::optional<ScalarType>& outputType,
72
+ at::Device device);
73
+
74
+ Tensor computeScalar(
75
+ const std::string& name,
76
+ const std::vector<ArgValue>& inputValues,
77
+ const std::vector<ExprHandle>& outputShape,
78
+ const std::vector<ExprHandle>& outputStrides,
79
+ const std::optional<ScalarType>& outputType,
80
+ const std::function<ExprHandle(const ExprHandle&, const ExprHandle&)>&
81
+ innerExpr);
82
+
83
+ } // namespace torch::jit::tensorexpr
84
+
85
+ #else
86
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
87
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/quantization.h ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/kernel.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ TORCH_API ExprHandle quantizePerTensorQParamFromArg(ArgValue arg);
9
+
10
+ TORCH_API double immQScale(const BufHandle& qx);
11
+
12
+ TORCH_API int64_t immQZero(const BufHandle& qx);
13
+
14
+ TORCH_API ScalarType immQDType(const BufHandle& qx);
15
+
16
+ TORCH_API bool isQuantized(const BufHandle& qx);
17
+
18
+ TORCH_API Tensor computeQuantizePerTensor(
19
+ const std::vector<ArgValue>& inputs,
20
+ const std::vector<ExprHandle>& outputShape,
21
+ const std::vector<ExprHandle>& outputStrides,
22
+ const std::optional<ScalarType>& outputType,
23
+ at::Device device);
24
+
25
+ TORCH_API Tensor computeQuantizePerTensorExternalCall(
26
+ const std::vector<ArgValue>& inputs,
27
+ const std::vector<ExprHandle>& outputShape,
28
+ const std::vector<ExprHandle>& outputStrides,
29
+ const std::optional<ScalarType>& outputType,
30
+ at::Device device);
31
+
32
+ TORCH_API Tensor computeQuantizedConv1d(
33
+ const std::vector<ArgValue>& inputs,
34
+ const std::vector<ExprHandle>& outputShape,
35
+ const std::vector<ExprHandle>& outputStrides,
36
+ const std::optional<ScalarType>& outputType,
37
+ at::Device device);
38
+
39
+ TORCH_API Tensor computeQuantizedConv2dPrepack(
40
+ const std::vector<ArgValue>& inputs,
41
+ const std::vector<ExprHandle>& outputShape,
42
+ const std::vector<ExprHandle>& outputStrides,
43
+ const std::optional<ScalarType>& outputType,
44
+ at::Device device);
45
+
46
+ TORCH_API Tensor computeQuantizedConv2d(
47
+ const std::vector<ArgValue>& inputs,
48
+ const std::vector<ExprHandle>& outputShape,
49
+ const std::vector<ExprHandle>& outputStrides,
50
+ const std::optional<ScalarType>& outputType,
51
+ at::Device device);
52
+
53
+ TORCH_API Tensor computeQuantizedConv2dRelu(
54
+ const std::vector<ArgValue>& inputs,
55
+ const std::vector<ExprHandle>& outputShape,
56
+ const std::vector<ExprHandle>& outputStrides,
57
+ const std::optional<ScalarType>& outputType,
58
+ at::Device device);
59
+
60
+ TORCH_API Tensor computeQuantizedLinear(
61
+ const std::vector<ArgValue>& inputs,
62
+ const std::vector<ExprHandle>& outputShape,
63
+ const std::vector<ExprHandle>& outputStrides,
64
+ const std::optional<ScalarType>& outputType,
65
+ at::Device device);
66
+
67
+ TORCH_API Tensor computeQuantizedLinearRelu(
68
+ const std::vector<ArgValue>& inputs,
69
+ const std::vector<ExprHandle>& outputShape,
70
+ const std::vector<ExprHandle>& outputStrides,
71
+ const std::optional<ScalarType>& outputType,
72
+ at::Device device);
73
+
74
+ TORCH_API Tensor computeQuantizedAdd(
75
+ const std::vector<ArgValue>& inputs,
76
+ const std::vector<ExprHandle>& outputShape,
77
+ const std::vector<ExprHandle>& outputStrides,
78
+ const std::optional<ScalarType>& outputType,
79
+ at::Device device);
80
+
81
+ Tensor computeQuantizedAddExternalCall(
82
+ const std::vector<ArgValue>& inputs,
83
+ const std::vector<ExprHandle>& outputShape,
84
+ const std::vector<ExprHandle>& outputStrides,
85
+ const std::optional<ScalarType>& outputType,
86
+ at::Device device);
87
+
88
+ TORCH_API Tensor computeQuantizedMul(
89
+ const std::vector<ArgValue>& inputs,
90
+ const std::vector<ExprHandle>& outputShape,
91
+ const std::vector<ExprHandle>& outputStrides,
92
+ const std::optional<ScalarType>& outputType,
93
+ at::Device device);
94
+
95
+ TORCH_API Tensor computeQuantizedMulScalar(
96
+ const std::vector<ArgValue>& inputs,
97
+ const std::vector<ExprHandle>& outputShape,
98
+ const std::vector<ExprHandle>& outputStrides,
99
+ const std::optional<ScalarType>& outputType,
100
+ at::Device device);
101
+
102
+ TORCH_API Tensor computeQuantizedCat(
103
+ const std::vector<ArgValue>& inputs,
104
+ const std::vector<ExprHandle>& outputShape,
105
+ const std::vector<ExprHandle>& outputStrides,
106
+ const std::optional<ScalarType>& outputType,
107
+ at::Device device);
108
+
109
+ TORCH_API Tensor computeQuantizedRelu(
110
+ const std::vector<ArgValue>& inputs,
111
+ const std::vector<ExprHandle>& outputShape,
112
+ const std::vector<ExprHandle>& outputStrides,
113
+ const std::optional<ScalarType>& outputType,
114
+ at::Device device);
115
+
116
+ TORCH_API Tensor computeDequantize(
117
+ const std::vector<ArgValue>& inputs,
118
+ const std::vector<ExprHandle>& outputShape,
119
+ const std::vector<ExprHandle>& outputStrides,
120
+ const std::optional<ScalarType>& outputType,
121
+ at::Device device);
122
+
123
+ TORCH_API Tensor computeDequantizeExternalCall(
124
+ const std::vector<ArgValue>& inputs,
125
+ const std::vector<ExprHandle>& outputShape,
126
+ const std::vector<ExprHandle>& outputStrides,
127
+ const std::optional<ScalarType>& outputType,
128
+ at::Device device);
129
+
130
+ TORCH_API Tensor computeUpsampleNearest2d(
131
+ const std::vector<ArgValue>& inputs,
132
+ const std::vector<ExprHandle>& outputShape,
133
+ const std::vector<ExprHandle>& outputStrides,
134
+ const std::optional<ScalarType>& outputType,
135
+ at::Device device);
136
+
137
+ TORCH_API Tensor computeUpsampleNearest2dExternalCall(
138
+ const std::vector<ArgValue>& inputs,
139
+ const std::vector<ExprHandle>& outputShape,
140
+ const std::vector<ExprHandle>& outputStrides,
141
+ const std::optional<ScalarType>& outputType,
142
+ at::Device device);
143
+
144
+ TORCH_API Tensor computeQuantizedSigmoidExternalCall(
145
+ const std::vector<ArgValue>& inputs,
146
+ const std::vector<ExprHandle>& outputShape,
147
+ const std::vector<ExprHandle>& outputStrides,
148
+ const std::optional<ScalarType>& outputType,
149
+ at::Device /*unused*/);
150
+ } // namespace torch::jit::tensorexpr
151
+
152
+ #else
153
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
154
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/reduction.h ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/kernel.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ TORCH_API Tensor computeSum(
9
+ const std::vector<ArgValue>& inputs,
10
+ const std::vector<ExprHandle>& outputShape,
11
+ const std::vector<ExprHandle>& outputStrides,
12
+ const std::optional<ScalarType>& outputType,
13
+ at::Device device);
14
+ TORCH_API Tensor computeMean(
15
+ const std::vector<ArgValue>& inputs,
16
+ const std::vector<ExprHandle>& outputShape,
17
+ const std::vector<ExprHandle>& outputStrides,
18
+ const std::optional<ScalarType>& outputType,
19
+ at::Device device);
20
+ TORCH_API Tensor computeAdaptiveAvgPool2d(
21
+ const std::vector<ArgValue>& inputs,
22
+ const std::vector<ExprHandle>& outputShape,
23
+ const std::vector<ExprHandle>& outputStrides,
24
+ const std::optional<ScalarType>& outputType,
25
+ at::Device device);
26
+ Tensor computeMax(
27
+ const std::vector<ArgValue>& inputs,
28
+ const std::vector<ExprHandle>& outputShape,
29
+ const std::vector<ExprHandle>& outputStrides,
30
+ const std::optional<ScalarType>& outputType,
31
+ at::Device device);
32
+
33
+ } // namespace torch::jit::tensorexpr
34
+
35
+ #else
36
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
37
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/operators/softmax.h ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/kernel.h>
5
+
6
+ namespace torch::jit::tensorexpr {
7
+
8
+ Tensor computeSoftmax(
9
+ const std::vector<ArgValue>& inputs,
10
+ const std::vector<ExprHandle>& outputShape,
11
+ const std::vector<ExprHandle>& outputStrides,
12
+ bool log_softmax);
13
+
14
+ } // namespace torch::jit::tensorexpr
15
+
16
+ #else
17
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
18
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/reduction.h ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/tensorexpr/expr.h>
5
+ #include <torch/csrc/jit/tensorexpr/ir.h>
6
+ #include <torch/csrc/jit/tensorexpr/ir_printer.h>
7
+ #include <torch/csrc/jit/tensorexpr/stmt.h>
8
+ #include <torch/csrc/jit/tensorexpr/types.h>
9
+
10
+ #include <functional>
11
+ #include <utility>
12
+ #include <vector>
13
+
14
+ namespace torch::jit::tensorexpr {
15
+
16
+ using ParameterList = const std::vector<VarHandle>;
17
+ using ReduceInteraction = std::function<ExprHandle(ExprHandle, ExprHandle)>;
18
+
19
+ // A Reducer is a user interface describing a particular reduction
20
+ // operation. It has three components: An initialization value, a way of
21
+ // interacting each value with the accumulation, and a method for obtaining the
22
+ // current value to be reduced. It is materialized into a ReduceOp when loop
23
+ // variables are known.
24
+ class TORCH_API Reducer {
25
+ public:
26
+ Reducer(ExprHandle init, ReduceInteraction& interaction)
27
+ : init_(init.node()), interaction_(interaction) {}
28
+
29
+ template <typename RI>
30
+ Reducer(ExprHandle init, RI interaction)
31
+ : init_(init.node()), interaction_(std::move(interaction)) {}
32
+
33
+ ExprPtr initializer() const {
34
+ return init_;
35
+ }
36
+
37
+ ExprHandle operator()(
38
+ const BufHandle& result_buf,
39
+ ExprHandle body,
40
+ const std::vector<ExprHandle>& output,
41
+ const std::vector<VarHandle>& inner) const;
42
+
43
+ ReduceOpPtr operator()(
44
+ const BufPtr& result_buf,
45
+ ExprPtr body,
46
+ const std::vector<ExprPtr>& output,
47
+ const std::vector<VarPtr>& inner) const;
48
+
49
+ ExprHandle operator()(
50
+ const BufHandle& result_buf,
51
+ BufHandle acc_buf,
52
+ const ExprHandle& body,
53
+ const std::vector<ExprHandle>& output,
54
+ const std::vector<VarHandle>& inner) const;
55
+
56
+ // Polymorphic handling of Body functions with a variety of parameters.
57
+ static ExprHandle getReduceBody(
58
+ const std::function<ExprHandle(ParameterList&)>& func,
59
+ const std::vector<VarHandle>& vars) {
60
+ return func(vars);
61
+ }
62
+
63
+ static ExprHandle getReduceBody(
64
+ const std::function<ExprHandle(const VarHandle&)>& func,
65
+ const std::vector<VarHandle>& vars) {
66
+ if (vars.size() != 1) {
67
+ throw malformed_input("mismatch between reduce body and arg size (1)");
68
+ }
69
+
70
+ return func(vars[0]);
71
+ }
72
+
73
+ static ExprHandle getReduceBody(
74
+ const std::function<ExprHandle(const VarHandle&, const VarHandle&)>& func,
75
+ const std::vector<VarHandle>& vars) {
76
+ if (vars.size() != 2) {
77
+ throw malformed_input("mismatch between reduce body and arg size (2)");
78
+ }
79
+ return func(vars[0], vars[1]);
80
+ }
81
+
82
+ static ExprHandle getReduceBody(
83
+ const std::function<
84
+ ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>&
85
+ func,
86
+ const std::vector<VarHandle>& vars) {
87
+ if (vars.size() != 3) {
88
+ throw malformed_input("mismatch between reduce body and arg size (3)");
89
+ }
90
+ return func(vars[0], vars[1], vars[2]);
91
+ }
92
+
93
+ static ExprHandle getReduceBody(
94
+ const std::function<ExprHandle(
95
+ const VarHandle&,
96
+ const VarHandle&,
97
+ const VarHandle&,
98
+ const VarHandle&)>& func,
99
+ const std::vector<VarHandle>& vars) {
100
+ if (vars.size() != 4) {
101
+ throw malformed_input("mismatch between reduce body and arg size (4)");
102
+ }
103
+ return func(vars[0], vars[1], vars[2], vars[3]);
104
+ }
105
+
106
+ // Completes the reduction operator by applying the interaction function to
107
+ // the accumulation and the body expression.
108
+ static ExprPtr complete(
109
+ const BufPtr& accumulator,
110
+ const ReduceInteraction& interaction,
111
+ ExprHandle body,
112
+ const std::vector<ExprPtr>& output_args,
113
+ const std::vector<VarPtr>& reduce_args) {
114
+ ExprHandle accum =
115
+ ExprHandle(alloc<Load>(body.dtype(), accumulator, output_args));
116
+ auto e = interaction(std::move(accum), std::move(body));
117
+ return e.node();
118
+ }
119
+ static ExprHandle complete(
120
+ const BufHandle& accumulator,
121
+ const ReduceInteraction& interaction,
122
+ ExprHandle body,
123
+ const std::vector<ExprHandle>& output_args,
124
+ const std::vector<VarHandle>& reduce_args) {
125
+ ExprHandle accum = Load::make(body.dtype(), accumulator, output_args);
126
+ auto e = interaction(std::move(accum), std::move(body));
127
+ return e;
128
+ }
129
+
130
+ private:
131
+ ExprPtr init_;
132
+ ReduceInteraction interaction_;
133
+ };
134
+
135
+ // An expression representing a Reduction operation (e.g. Sum, Max) broken into
136
+ // it's component parts: initialization, accumulation var, acquisition of value
137
+ // to be reduced and interaction.
138
+ //
139
+ // This is intended to be expanded in the loopnest and not make it to codegen.
140
+ class TORCH_API ReduceOp : public ExprNode<ReduceOp> {
141
+ public:
142
+ ReduceOp(
143
+ const ExprPtr& body,
144
+ std::vector<VarPtr> reduce_args,
145
+ Reducer reducer)
146
+ : ExprNodeBase(body->dtype()),
147
+ body_(body),
148
+ reduce_args_(std::move(reduce_args)),
149
+ reducer_(std::move(reducer)) {
150
+ result_buf_ = nullptr;
151
+ acc_buf_ = nullptr;
152
+ ri_operand_ = nullptr;
153
+ }
154
+
155
+ ReduceOp(
156
+ const ExprPtr& body,
157
+ std::vector<VarPtr> reduce_args,
158
+ BufPtr result_buf,
159
+ BufPtr acc_buf,
160
+ ExprPtr ri_operand,
161
+ Reducer reducer)
162
+ : ExprNodeBase(body->dtype()),
163
+ body_(body),
164
+ reduce_args_(std::move(reduce_args)),
165
+ result_buf_(std::move(result_buf)),
166
+ acc_buf_(std::move(acc_buf)),
167
+ ri_operand_(std::move(ri_operand)),
168
+ reducer_(std::move(reducer)) {}
169
+
170
+ static ExprHandle make(
171
+ ExprHandle body,
172
+ const std::vector<VarHandle>& reduce_args,
173
+ const Reducer& reducer);
174
+
175
+ static ExprHandle make(
176
+ ExprHandle body,
177
+ const std::vector<VarHandle>& reduce_args,
178
+ BufHandle result_buf,
179
+ BufHandle acc_buf,
180
+ ExprHandle ri_operand,
181
+ const Reducer& reducer);
182
+
183
+ // return the body expression which obtains the value to be reduced.
184
+ ExprPtr body() const {
185
+ return body_;
186
+ }
187
+
188
+ // Returns the original Reducer factory that can create ReduceOps.
189
+ const Reducer& reducer() const {
190
+ return reducer_;
191
+ }
192
+
193
+ // returns variables associated with the axes of reduction.
194
+ const std::vector<VarPtr>& reduce_args() const {
195
+ return reduce_args_;
196
+ }
197
+
198
+ void setAccBuf(BufHandle acc_buf) {
199
+ acc_buf_ = acc_buf.node();
200
+ }
201
+ BufPtr getAccBuf() {
202
+ return acc_buf_;
203
+ }
204
+
205
+ void setResultBuf(BufHandle buf) {
206
+ result_buf_ = buf.node();
207
+ }
208
+ BufPtr getResultBuf() {
209
+ return result_buf_;
210
+ }
211
+
212
+ void setRiOperand(ExprHandle ri_operand) {
213
+ ri_operand_ = ri_operand.node();
214
+ }
215
+ ExprPtr getRiOperand() {
216
+ return ri_operand_;
217
+ }
218
+
219
+ private:
220
+ // body_ = reducer_->interaction_(result_buf_, ri_operand_)
221
+ ExprPtr body_;
222
+ std::vector<VarPtr> reduce_args_;
223
+
224
+ BufPtr result_buf_;
225
+ BufPtr acc_buf_;
226
+ ExprPtr ri_operand_;
227
+
228
+ const Reducer reducer_;
229
+ };
230
+
231
+ class Sum : public Reducer {
232
+ public:
233
+ Sum()
234
+ : Reducer(ExprHandle(0), [](const ExprHandle& a, const ExprHandle& b) {
235
+ return a + b;
236
+ }) {}
237
+ };
238
+
239
+ inline ExprHandle maximumVal(ScalarType type) {
240
+ switch (type) {
241
+ #define MAX_BY_TYPE_CASE(Type, Name) \
242
+ case ScalarType::Name: \
243
+ return ExprHandle(std::numeric_limits<Type>::max());
244
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE)
245
+ #undef MAX_BY_TYPE_CASE
246
+ default:
247
+ throw unsupported_dtype();
248
+ }
249
+ return ExprHandle();
250
+ }
251
+
252
+ inline ExprHandle minimumVal(ScalarType type) {
253
+ switch (type) {
254
+ #define MAX_BY_TYPE_CASE(Type, Name) \
255
+ case ScalarType::Name: \
256
+ return ExprHandle(std::numeric_limits<Type>::min());
257
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, MAX_BY_TYPE_CASE)
258
+ #undef MAX_BY_TYPE_CASE
259
+ default:
260
+ throw unsupported_dtype();
261
+ }
262
+ }
263
+
264
+ class Maximum : public Reducer {
265
+ public:
266
+ // TODO possible to remove this arg by deferring the init value until we
267
+ // know the dtype of the body.
268
+ Maximum(Dtype dtype)
269
+ : Reducer(
270
+ minimumVal(dtype.scalar_type()),
271
+ [](const ExprHandle& a, const ExprHandle& b) {
272
+ return Max::make(a, b, true);
273
+ }) {}
274
+ Maximum(ExprHandle initializer)
275
+ : Reducer(
276
+ std::move(initializer),
277
+ [](const ExprHandle& a, const ExprHandle& b) {
278
+ return Max::make(a, b, true);
279
+ }) {}
280
+ };
281
+
282
+ class Minimum : public Reducer {
283
+ public:
284
+ Minimum(Dtype dtype)
285
+ : Reducer(
286
+ maximumVal(dtype.scalar_type()),
287
+ [](const ExprHandle& a, const ExprHandle& b) {
288
+ return Min::make(a, b, true);
289
+ }) {}
290
+ Minimum(const ExprHandle& initializer)
291
+ : Reducer(initializer, [](const ExprHandle& a, const ExprHandle& b) {
292
+ return Min::make(a, b, true);
293
+ }) {}
294
+ };
295
+
296
+ class ReductionExpander : public IRMutator {
297
+ public:
298
+ StmtPtr expand(const StmtPtr& s) {
299
+ return s->accept_mutator(this);
300
+ }
301
+
302
+ ExprPtr mutate(const ReduceOpPtr& v) override {
303
+ return v->body();
304
+ }
305
+ };
306
+
307
+ } // namespace torch::jit::tensorexpr
308
+
309
+ #else
310
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
311
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/registerizer.h ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <c10/core/ScalarType.h>
4
+ #include <c10/util/irange.h>
5
+ #include <torch/csrc/Export.h>
6
+
7
+ #include <torch/csrc/jit/tensorexpr/hash_provider.h>
8
+ #include <torch/csrc/jit/tensorexpr/ir_mutator.h>
9
+ #include <torch/csrc/jit/tensorexpr/ir_simplifier.h>
10
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
11
+
12
+ #include <utility>
13
+ #include <vector>
14
+
15
+ namespace torch::jit::tensorexpr {
16
+ namespace registerizer {
17
+
18
+ /* The Registerizer performs scalar replacement by looking for common Stores and
19
+ Loads to a single item in a buffer and replacing them with a local temporary
20
+ scalar which is cheaper to write.
21
+
22
+ For example it can replace:
23
+
24
+ {
25
+ A[0] = 0;
26
+ for(const auto x : c10::irange(10)) {
27
+ A[0] = (A[0]) + x;
28
+ }
29
+ }
30
+
31
+ with:
32
+
33
+ {
34
+ int A_ = 0;
35
+ for(const auto x : c10::irange(10)) {
36
+ A_ = x + A_;
37
+ }
38
+ A[0] = A_;
39
+ }
40
+
41
+ This is particularly useful on GPUs when parallelizing, since after replacing
42
+ loops with metavars we have a lot of accesses like this. */
43
+
44
+ class Scope;
45
+
46
+ /* Holds analysis information about accesses to a specific range of a
47
+ buffer, including the number of loads and stores and the lowest common parent
48
+ Block.
49
+ */
50
+ class AccessInfo {
51
+ public:
52
+ AccessInfo() = default;
53
+ AccessInfo(
54
+ SimplifierHashType h,
55
+ BufPtr b,
56
+ std::vector<ExprPtr> i,
57
+ size_t accessOrder)
58
+ : hash_(h),
59
+ buf_(std::move(b)),
60
+ indices_(std::move(i)),
61
+ store_cost_(alloc<IntImm>(0)),
62
+ load_cost_(alloc<IntImm>(0)),
63
+ accessOrder_(accessOrder) {}
64
+
65
+ // Adds a Store to this access, which is in the provided scope.
66
+ void addStore(const StorePtr& store, const std::shared_ptr<Scope>& scope);
67
+
68
+ // Adds a Load to this access, which occurs in the usage Stmt in the provided
69
+ // scope.
70
+ void addLoad(
71
+ const LoadPtr& load,
72
+ const std::shared_ptr<Scope>& scope,
73
+ const StmtPtr& usage);
74
+
75
+ // Merge another AccessInfo into this one.
76
+ void merge(const std::shared_ptr<AccessInfo>& other);
77
+
78
+ // Returns true if the other AccessInfo's bounds may overlap this one.
79
+ bool overlaps(const std::shared_ptr<AccessInfo>& other);
80
+
81
+ // Returns true if the indices of this access depend on the provided Var.
82
+ bool dependsOnVar(const VarPtr& v);
83
+
84
+ // Clone this AccessInfo, and set this as the new accesses' hiddenAccess.
85
+ static std::shared_ptr<AccessInfo> cloneWithHiddenInfo(
86
+ const std::shared_ptr<AccessInfo>& orig);
87
+
88
+ // print for debugging.
89
+ void print() const;
90
+
91
+ SimplifierHashType hash() const {
92
+ return hash_;
93
+ }
94
+
95
+ BufPtr buf() const {
96
+ return buf_;
97
+ }
98
+
99
+ const std::vector<ExprPtr>& indices() const {
100
+ return indices_;
101
+ }
102
+
103
+ BlockPtr block() const {
104
+ return block_;
105
+ }
106
+
107
+ void setEnclosingBlock(BlockPtr b) {
108
+ block_ = std::move(b);
109
+ }
110
+
111
+ StmtPtr first_usage() const {
112
+ return first_usage_;
113
+ }
114
+ StmtPtr last_usage() const {
115
+ return last_usage_;
116
+ }
117
+
118
+ void setUsageMarks(StmtPtr first, StmtPtr last) {
119
+ first_usage_ = std::move(first);
120
+ last_usage_ = std::move(last);
121
+ }
122
+
123
+ bool firstUsageOverlapped() const {
124
+ return firstUsageOverlapped_;
125
+ }
126
+
127
+ ExprPtr store_cost() const {
128
+ return store_cost_;
129
+ }
130
+
131
+ ExprPtr load_cost() const {
132
+ return load_cost_;
133
+ }
134
+
135
+ const std::vector<StorePtr>& stores() const {
136
+ return stores_;
137
+ }
138
+
139
+ const std::vector<LoadPtr>& loads() const {
140
+ return loads_;
141
+ }
142
+
143
+ void hoistCosts(const ExprPtr& extent) {
144
+ store_cost_ = IRSimplifier::simplify(alloc<Mul>(store_cost_, extent));
145
+ load_cost_ = IRSimplifier::simplify(alloc<Mul>(load_cost_, extent));
146
+ }
147
+
148
+ size_t conditionId() const {
149
+ return conditionId_;
150
+ }
151
+
152
+ void setConditionId(size_t c) {
153
+ conditionId_ = c;
154
+ }
155
+
156
+ size_t accessOrder() const {
157
+ return accessOrder_;
158
+ }
159
+
160
+ std::shared_ptr<AccessInfo> hiddenAccess() const {
161
+ return hiddenAccess_;
162
+ }
163
+
164
+ // Holds state relating to the scalar variable we will insert to replace some
165
+ // number of loads and stores.
166
+ struct ScalarReplacement {
167
+ VarPtr var{nullptr};
168
+ BufPtr var_wrapper{nullptr};
169
+ LetPtr initializer{nullptr};
170
+ };
171
+
172
+ ScalarReplacement& replacement() {
173
+ return replacement_;
174
+ }
175
+
176
+ private:
177
+ SimplifierHashType hash_;
178
+ BufPtr buf_;
179
+ std::vector<ExprPtr> indices_;
180
+ BlockPtr block_{nullptr};
181
+
182
+ StmtPtr first_usage_{nullptr};
183
+ StmtPtr last_usage_{nullptr};
184
+
185
+ // Whether or not this access is overlapped in the first Stmt it appears. This
186
+ // means we cannot use it's first Store as the initializer.
187
+ bool firstUsageOverlapped_{false};
188
+
189
+ // The cost in real ops that this access represents, to enable
190
+ // filtering accesses that won't save any loads or stores.
191
+ ExprPtr store_cost_;
192
+ ExprPtr load_cost_;
193
+
194
+ // The actual Stores and Loads which represent this access.
195
+ // Be careful with these, any mutator will invalidate these pointers.
196
+ std::vector<StorePtr> stores_;
197
+ std::vector<LoadPtr> loads_;
198
+
199
+ // An identifier representing the conditional block, if any, this access
200
+ // depends on.
201
+ size_t conditionId_{0};
202
+
203
+ // An identifier representing the order this access was first encountered, for
204
+ // sorting returned results.
205
+ size_t accessOrder_{0};
206
+
207
+ // Sometimes when traversing the tree we need to record what would happen if
208
+ // we hoisted an access, but sometimes it doesn't work out. This lets us
209
+ // "undo" some mutation and return to the internal hidden AccessInfo.
210
+ // It will be removed after any further additions to this AccessInfo.
211
+ std::shared_ptr<AccessInfo> hiddenAccess_;
212
+
213
+ ScalarReplacement replacement_;
214
+ };
215
+
216
+ using AccessHashMap =
217
+ std::unordered_map<SimplifierHashType, std::shared_ptr<AccessInfo>>;
218
+
219
+ // Represents a scope block and holds all accesses contained within it.
220
+ class Scope {
221
+ public:
222
+ Scope(BlockPtr b, std::shared_ptr<Scope> parent, size_t conditionId = 0)
223
+ : block_(std::move(b)),
224
+ parent_(std::move(parent)),
225
+ conditionId_(conditionId) {}
226
+
227
+ AccessHashMap& getAccessMapByBuf(const BufPtr& b);
228
+
229
+ std::unordered_map<BufPtr, AccessHashMap>& openAccesses() {
230
+ return openAccesses_;
231
+ }
232
+
233
+ std::vector<std::shared_ptr<AccessInfo>>& closedAccesses() {
234
+ return closedAccesses_;
235
+ }
236
+
237
+ BlockPtr block() const {
238
+ return block_;
239
+ }
240
+
241
+ std::shared_ptr<Scope> parent() const {
242
+ return parent_;
243
+ }
244
+
245
+ size_t conditionId() const {
246
+ return conditionId_;
247
+ }
248
+
249
+ const std::unordered_set<VarPtr>& localVars() const {
250
+ return localVars_;
251
+ }
252
+ void addLocalVar(VarPtr v) {
253
+ localVars_.insert(std::move(v));
254
+ }
255
+
256
+ void closeAccess(const std::shared_ptr<AccessInfo>& info);
257
+
258
+ void filterClosed();
259
+
260
+ private:
261
+ // Map of map to access, narrowing by Buf then by hash(Buf+Indices).
262
+ // This allows us to find a candidate access easily, and also check for
263
+ // overlap with other accesses to the same buf. Buf ->
264
+ // Hash ->
265
+ // Access
266
+ std::unordered_map<BufPtr, AccessHashMap> openAccesses_;
267
+ std::vector<std::shared_ptr<AccessInfo>> closedAccesses_;
268
+
269
+ // The Block object this scope represents.
270
+ BlockPtr block_;
271
+
272
+ // The enclosing scope object.
273
+ std::shared_ptr<Scope> parent_;
274
+
275
+ // An identifier representing the condition block this scope depends on.
276
+ size_t conditionId_;
277
+
278
+ // A set of variables local to this scope (e.g. loop vars).
279
+ std::unordered_set<VarPtr> localVars_;
280
+ };
281
+
282
+ /* Analyzes the graph and collects accesses to the same symbolic tensor element
283
+ * which can be replaced by a single local scalar.
284
+ *
285
+ * This works by recursively walking the tree in postfix order, building sets of
286
+ * accesses to the same symbolic element by scope and then merging lower scopes
287
+ * into their enclosing scope.
288
+ *
289
+ * It is safe to move two accesses of the same Tensor element to a local scalar
290
+ * Var if between all usages of the element there are no other Loads or Stores
291
+ * that may refer to it. In the comments I refer to this as overlapping the
292
+ * access, or "cutting" the existing AccessInfo. In the case where a candidate
293
+ * for registerization is cut, it may be possible to finalize the access early
294
+ * by writing it back to the Tensor and then create a new scalar variable after
295
+ * the overlapping access is complete. We will attempt to do this when it saves
296
+ * memory accesses.
297
+ *
298
+ * There are a few cases that make this more challenging:
299
+ *
300
+ * - For: Loops change the number of real usages of a buffer by the loop
301
+ * extent, but only if we can pull the definition and finalization of the scalar
302
+ * variable out of the loop block.
303
+ *
304
+ * - Cond: Conditions complicate lifting scalars out of internal scopes.
305
+ * Generally we cannot lift an access outside of a conditional scope unless
306
+ * there is already a reference to that same access at the higher scope, since
307
+ * we don't know if the condition was guarding an array access not safe at the
308
+ * higher scope. In the comments I refer to this as the condition "hiding" the
309
+ * access, and the outer access "unhiding" it.
310
+ *
311
+ * - IfThenElse: Same situation as Cond, except since IfThenElse is an Expr
312
+ * rather than a Stmt we cannot insert the scalar definition or finalizer
313
+ * within the conditional scope. Accesses inside an IfThenElse can be safely
314
+ * combined with external accesses but cannot exist completely within.
315
+ *
316
+ * - Let: Accesses dependent on local variables via Let Stmts, or loop vars,
317
+ * cannot be raised outside of the scope of the dependent var.
318
+ */
319
+ class TORCH_API RegisterizerAnalysis : public IRVisitor {
320
+ public:
321
+ RegisterizerAnalysis()
322
+ : currentScope_(std::make_shared<Scope>(nullptr, nullptr, 0)) {}
323
+ ~RegisterizerAnalysis() override = default;
324
+
325
+ void visit(const ForPtr& v) override;
326
+
327
+ void visit(const CondPtr& v) override;
328
+
329
+ void visit(const BlockPtr& v) override;
330
+
331
+ void visit(const StorePtr& v) override;
332
+
333
+ void visit(const LoadPtr& v) override;
334
+
335
+ void visit(const IfThenElsePtr& v) override;
336
+
337
+ void visit(const LetPtr& v) override;
338
+
339
+ #define STMT_ON_STACK(Op) \
340
+ void visit(const Op##Ptr& v) override { \
341
+ stmtStack_.push_front(v); \
342
+ IRVisitor::visit(v); \
343
+ stmtStack_.pop_front(); \
344
+ }
345
+
346
+ STMT_ON_STACK(AtomicAdd)
347
+ STMT_ON_STACK(Allocate)
348
+ STMT_ON_STACK(Free)
349
+
350
+ #undef STMT_ON_STACK
351
+
352
+ std::vector<std::shared_ptr<AccessInfo>> getCandidates();
353
+
354
+ private:
355
+ void mergeCurrentScopeIntoParent();
356
+ void mergeHiddenScope(bool allowClosed);
357
+ void closeAccessIntoScope(
358
+ const std::shared_ptr<AccessInfo>& info,
359
+ const std::shared_ptr<Scope>& scope);
360
+
361
+ std::unordered_set<size_t> exprConditionals_;
362
+
363
+ // A stack of enclosing Stmts for tracking the usage Stmt of Loads.
364
+ std::deque<StmtPtr> stmtStack_;
365
+
366
+ // The current scope being analyzed.
367
+ std::shared_ptr<Scope> currentScope_;
368
+
369
+ HashProvider hasher_;
370
+
371
+ size_t conditionId_{0};
372
+ size_t accessOrder_{0};
373
+ };
374
+
375
+ /* Replaces each registerizable access with a Scalar variable, including
376
+ * definition, initializer and finalizer.
377
+ */
378
+ class TORCH_API RegisterizerReplacer : public IRMutator {
379
+ public:
380
+ RegisterizerReplacer(std::vector<std::shared_ptr<AccessInfo>>& vec)
381
+ : infoSet_(vec) {
382
+ buildReplacements();
383
+ }
384
+
385
+ ExprPtr mutate(const LoadPtr& v) override;
386
+
387
+ StmtPtr mutate(const StorePtr& v) override;
388
+
389
+ StmtPtr mutate(const BlockPtr& v) override;
390
+
391
+ private:
392
+ struct ReplacerScope {
393
+ std::unordered_map<StmtPtr, std::deque<std::shared_ptr<AccessInfo>>>
394
+ initializerPoints_;
395
+ std::unordered_map<StmtPtr, std::deque<std::shared_ptr<AccessInfo>>>
396
+ finalizePoints_;
397
+ };
398
+
399
+ // Creates the various ReplacerScope objects and builds internal maps.
400
+ void buildReplacements();
401
+
402
+ // State relating to the accesses yet to be replaced.
403
+ // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
404
+ std::vector<std::shared_ptr<AccessInfo>>& infoSet_;
405
+ std::unordered_map<StorePtr, std::shared_ptr<AccessInfo>> storeToAccess_;
406
+ std::unordered_map<LoadPtr, std::shared_ptr<AccessInfo>> loadToAccess_;
407
+ std::unordered_map<BlockPtr, ReplacerScope> parentToAccesses_;
408
+
409
+ // Holds the set of Stores that should be pulled into an initializer, so they
410
+ // can be eliminated.
411
+ std::set<StorePtr> eliminatedIntializers_;
412
+
413
+ // Tracks the number of times we've seen each buffer, so we can name the
414
+ // scalar Vars appropriately.
415
+ std::unordered_map<BufPtr, unsigned int> bufferAccessCounts_;
416
+ unsigned int getBufferAccessCount(const BufPtr& b) {
417
+ return ++bufferAccessCounts_[b];
418
+ }
419
+ };
420
+ } // namespace registerizer
421
+
422
+ // Apply scalar replacement to all accesses in s.
423
+ // To produce safe code, this must occur after handling parallelized axes and
424
+ // atomics.
425
+ TORCH_API StmtPtr registerize(StmtPtr s);
426
+
427
+ } // namespace torch::jit::tensorexpr
428
+
429
+ #else
430
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
431
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/stmt.h ADDED
@@ -0,0 +1,1017 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <algorithm>
5
+ #include <list>
6
+ #include <string>
7
+ #include <unordered_set>
8
+ #include <utility>
9
+ #include <vector>
10
+
11
+ #include <torch/csrc/jit/tensorexpr/expr.h>
12
+
13
+ namespace torch::jit::tensorexpr {
14
+
15
+ // The common base between all statement node.
16
+ class TORCH_API Stmt : public std::enable_shared_from_this<Stmt> {
17
+ public:
18
+ Stmt() = default;
19
+ virtual ~Stmt() = default;
20
+ virtual void accept(IRVisitor* visitor) = 0;
21
+ virtual StmtPtr accept_mutator(IRMutator* mutator) = 0;
22
+
23
+ StmtPtr get_parent() const {
24
+ return parent_ ? parent_->getptr() : nullptr;
25
+ }
26
+
27
+ /*
28
+ * Make a deep copy of the given statement.
29
+ *
30
+ * All statements and expressions used in children of the statement are
31
+ * cloned. Note that the variables are not deep-copied since they are
32
+ * immutable.
33
+ */
34
+ static StmtPtr clone(const StmtPtr& s);
35
+
36
+ protected:
37
+ static void set_parent(const StmtPtr& s, Stmt* new_parent) {
38
+ s->parent_ = new_parent;
39
+ }
40
+ std::shared_ptr<Stmt> getptr() {
41
+ return shared_from_this();
42
+ }
43
+
44
+ private:
45
+ Stmt* parent_ = nullptr;
46
+ };
47
+
48
+ template <class Op>
49
+ class StmtNode : public Stmt {
50
+ public:
51
+ using StmtNodeBase = StmtNode<Op>;
52
+ void accept(IRVisitor* visitor) override {
53
+ visitor->visit(static_to<Op>(getptr()));
54
+ }
55
+ StmtPtr accept_mutator(IRMutator* mutator) override;
56
+ friend Op;
57
+
58
+ private:
59
+ StmtNode() = default;
60
+ };
61
+
62
+ template <class Op>
63
+ StmtPtr StmtNode<Op>::accept_mutator(IRMutator* mutator) {
64
+ return mutator->mutate(static_to<Op>(getptr()));
65
+ }
66
+
67
+ // Concrete Stmt classes
68
+ class TORCH_API Block : public StmtNode<Block> {
69
+ public:
70
+ static BlockPtr make(const std::vector<StmtPtr>& stmts) {
71
+ std::vector<StmtPtr> valid_stmts;
72
+ for (auto& stmt : stmts) {
73
+ if (!stmt) {
74
+ continue;
75
+ }
76
+ valid_stmts.push_back(stmt);
77
+ }
78
+ if (valid_stmts.empty()) {
79
+ return nullptr;
80
+ }
81
+ return alloc<Block>(valid_stmts);
82
+ }
83
+
84
+ size_t nstmts() const {
85
+ return stmts_.size();
86
+ }
87
+ bool empty() const {
88
+ return stmts_.empty();
89
+ }
90
+
91
+ void prepend_stmt(const StmtPtr& s) {
92
+ if (s->get_parent()) {
93
+ throw malformed_input("Block prepend Stmt with existing parent", s);
94
+ }
95
+
96
+ stmts_.push_front(s);
97
+ set_parent(s, this);
98
+ }
99
+ void append_stmt(const StmtPtr& s) {
100
+ if (s->get_parent()) {
101
+ throw malformed_input("Block append Stmt with existing parent", s);
102
+ }
103
+
104
+ stmts_.push_back(s);
105
+ set_parent(s, this);
106
+ }
107
+
108
+ void insert_stmt_before(const StmtPtr& s, const StmtPtr& before) {
109
+ if (s->get_parent()) {
110
+ throw malformed_input("Block append Stmt with existing parent", s);
111
+ }
112
+
113
+ auto pos = std::find(stmts_.begin(), stmts_.end(), before);
114
+ if (pos == stmts_.end()) {
115
+ throw malformed_input(
116
+ "Inserting after statement that is not in block", s);
117
+ }
118
+
119
+ stmts_.insert(pos, s);
120
+ set_parent(s, this);
121
+ }
122
+
123
+ void insert_stmt_after(const StmtPtr& s, const StmtPtr& after) {
124
+ if (s->get_parent()) {
125
+ throw malformed_input("Block append Stmt with existing parent", s);
126
+ }
127
+
128
+ auto pos = std::find(stmts_.begin(), stmts_.end(), after);
129
+ if (pos == stmts_.end()) {
130
+ throw malformed_input(
131
+ "Inserting after statement that is not in block", s);
132
+ }
133
+
134
+ ++pos;
135
+
136
+ stmts_.insert(pos, s);
137
+ set_parent(s, this);
138
+ }
139
+
140
+ bool replace_stmt(const StmtPtr& old_stmt, const StmtPtr& new_stmt) {
141
+ if (new_stmt->get_parent()) {
142
+ throw malformed_input(
143
+ "Block replace Stmt with existing parent", new_stmt);
144
+ }
145
+
146
+ auto pos = std::find(stmts_.begin(), stmts_.end(), old_stmt);
147
+ if (pos == stmts_.end()) {
148
+ return false;
149
+ }
150
+ stmts_.insert(pos, new_stmt);
151
+ stmts_.erase(pos);
152
+ set_parent(old_stmt, nullptr);
153
+ set_parent(new_stmt, this);
154
+ return true;
155
+ }
156
+
157
+ // Creates a new block by cloning `this` block and replacing the given
158
+ // statement with a new statement. Note that `old_stmt` refers to a statement
159
+ // in `this` block. If the `old_stmt` is not found, it will return `nullptr`.
160
+ BlockPtr clone_and_replace(const StmtPtr& old_stmt, const StmtPtr& new_stmt) {
161
+ if (new_stmt->get_parent()) {
162
+ throw malformed_input(
163
+ "Block replace Stmt with existing parent", new_stmt);
164
+ }
165
+
166
+ std::vector<StmtPtr> stmts(stmts_.begin(), stmts_.end());
167
+ std::vector<StmtPtr> cloned_stmts(stmts.size());
168
+ bool found = false;
169
+ for (int i = 0; i < static_cast<int>(stmts.size()); ++i) {
170
+ if (stmts[i] == old_stmt) {
171
+ found = true;
172
+ cloned_stmts[i] = new_stmt;
173
+ } else {
174
+ cloned_stmts[i] = Stmt::clone(stmts[i]);
175
+ }
176
+ }
177
+ if (!found) {
178
+ return nullptr;
179
+ }
180
+ return alloc<Block>(cloned_stmts);
181
+ }
182
+
183
+ bool remove_stmt(const StmtPtr& stmt) {
184
+ auto pos = std::find(stmts_.begin(), stmts_.end(), stmt);
185
+ if (pos == stmts_.end()) {
186
+ return false;
187
+ }
188
+
189
+ set_parent(stmt, nullptr);
190
+ stmts_.erase(pos);
191
+ return true;
192
+ }
193
+
194
+ std::list<StmtPtr> stmts() const {
195
+ return stmts_;
196
+ }
197
+
198
+ void clear() {
199
+ for (const auto& s : stmts_) {
200
+ set_parent(s, nullptr);
201
+ }
202
+ stmts_.clear();
203
+ }
204
+
205
+ void set_stmts(const std::vector<StmtPtr>& stmts) {
206
+ clear();
207
+ init(stmts);
208
+ }
209
+
210
+ explicit Block(const std::vector<StmtPtr>& stmts) {
211
+ init(stmts);
212
+ }
213
+
214
+ typedef std::list<StmtPtr>::iterator iterator;
215
+ typedef std::list<StmtPtr>::const_iterator const_iterator;
216
+
217
+ iterator begin() {
218
+ return stmts_.begin();
219
+ }
220
+
221
+ const_iterator begin() const {
222
+ return stmts_.begin();
223
+ }
224
+
225
+ iterator end() {
226
+ return stmts_.end();
227
+ }
228
+
229
+ const_iterator end() const {
230
+ return stmts_.end();
231
+ }
232
+
233
+ StmtPtr front() {
234
+ return stmts_.front();
235
+ }
236
+
237
+ StmtPtr front() const {
238
+ return stmts_.front();
239
+ }
240
+
241
+ StmtPtr back() {
242
+ return stmts_.back();
243
+ }
244
+
245
+ StmtPtr back() const {
246
+ return stmts_.back();
247
+ }
248
+
249
+ void splice(Block::iterator it, const BlockPtr& other) {
250
+ for (const StmtPtr& s : *other) {
251
+ set_parent(s, this);
252
+ }
253
+
254
+ stmts_.splice(it, other->stmts_);
255
+ }
256
+
257
+ static BlockPtr getSharedParent(StmtPtr p1, StmtPtr p2) {
258
+ std::unordered_set<BlockPtr> enclosing;
259
+
260
+ StmtPtr p1_p = std::move(p1);
261
+ while (p1_p) {
262
+ if (BlockPtr b = to<Block>(p1_p)) {
263
+ enclosing.insert(b);
264
+ }
265
+ p1_p = p1_p->get_parent();
266
+ }
267
+
268
+ StmtPtr p2_p = std::move(p2);
269
+ while (p2_p) {
270
+ if (BlockPtr b = to<Block>(p2_p)) {
271
+ if (enclosing.count(b) != 0) {
272
+ return b;
273
+ }
274
+ }
275
+ p2_p = p2_p->get_parent();
276
+ }
277
+
278
+ return nullptr;
279
+ }
280
+
281
+ // returns the immediate child containing statement s.
282
+ StmtPtr getEnclosedRoot(StmtPtr s) const {
283
+ while (s && s->get_parent().get() != this) {
284
+ s = s->get_parent();
285
+ }
286
+ return s;
287
+ }
288
+
289
+ private:
290
+ std::list<StmtPtr> stmts_;
291
+
292
+ void init(const std::vector<StmtPtr>& stmts) {
293
+ for (const StmtPtr& s : stmts) {
294
+ if (!s) {
295
+ continue;
296
+ }
297
+ if (!s->get_parent()) {
298
+ // If we get here, it's a bug, but we cannot throw an error from a
299
+ // constructor. But IR verifier would catch this.
300
+ set_parent(s, this);
301
+ }
302
+
303
+ stmts_.push_back(s);
304
+ }
305
+ }
306
+ };
307
+
308
+ class TORCH_API Store : public StmtNode<Store> {
309
+ public:
310
+ VarPtr base_handle() const {
311
+ return buf_->base_handle();
312
+ }
313
+ std::vector<ExprPtr> indices() const {
314
+ return indices_;
315
+ }
316
+ ExprPtr flat_index() const {
317
+ TORCH_CHECK(indices_.size() == 1, "Indices haven't been flattened.");
318
+ return indices_[0];
319
+ }
320
+ ExprPtr value() const {
321
+ return value_;
322
+ }
323
+ BufPtr buf() const {
324
+ return buf_;
325
+ }
326
+
327
+ void set_buf(BufPtr buf) {
328
+ buf_ = std::move(buf);
329
+ }
330
+
331
+ void set_indices(std::vector<ExprPtr> indices) {
332
+ indices_ = std::move(indices);
333
+ }
334
+
335
+ void set_value(ExprPtr value) {
336
+ value_ = std::move(value);
337
+ }
338
+
339
+ static StorePtr make(
340
+ const BufHandle& buf,
341
+ const std::vector<ExprHandle>& indices,
342
+ const ExprHandle& value);
343
+
344
+ Store(BufPtr buf, std::vector<ExprPtr> indices, ExprPtr value);
345
+
346
+ private:
347
+ BufPtr buf_;
348
+ std::vector<ExprPtr> indices_;
349
+ ExprPtr value_;
350
+ };
351
+
352
+ // Allocate a buffer of given shapes and dtypes and bind it with the given
353
+ // buffer var. The life span is at most through the current program, until it is
354
+ // explicitly freed. An unfreed memory is likely considered an error.
355
+ class TORCH_API Allocate : public StmtNode<Allocate> {
356
+ public:
357
+ static AllocatePtr make(const BufHandle& buf_handle) {
358
+ return alloc<Allocate>(buf_handle.node());
359
+ }
360
+
361
+ VarPtr buffer_var() const {
362
+ return buf_->base_handle();
363
+ }
364
+
365
+ Dtype dtype() const {
366
+ return buf_->dtype();
367
+ }
368
+
369
+ const std::vector<ExprPtr> dims() const {
370
+ return buf_->dims();
371
+ }
372
+
373
+ BufPtr buf() const {
374
+ return buf_;
375
+ }
376
+
377
+ void set_buf(BufPtr buf) {
378
+ buf_ = std::move(buf);
379
+ }
380
+
381
+ explicit Allocate(BufPtr buf) : buf_(std::move(buf)) {}
382
+
383
+ private:
384
+ BufPtr buf_;
385
+ // TODO: add memory types.
386
+ };
387
+
388
+ // PlacementAllocate is a variation of the Allocate operator in NNC IR. It does
389
+ // not allocate memory but reuse the memory of another buffer for the given
390
+ // buffer.
391
+ class TORCH_API PlacementAllocate : public StmtNode<PlacementAllocate> {
392
+ public:
393
+ static PlacementAllocatePtr make(
394
+ const BufHandle& buf_handle,
395
+ const BufHandle& buf_handle_to_reuse) {
396
+ return alloc<PlacementAllocate>(
397
+ buf_handle.node(), buf_handle_to_reuse.node());
398
+ }
399
+
400
+ BufPtr buf() const {
401
+ return buf_;
402
+ }
403
+
404
+ BufPtr buf_to_reuse() const {
405
+ return buf_to_reuse_;
406
+ }
407
+
408
+ void set_buf(BufPtr buf) {
409
+ buf_ = std::move(buf);
410
+ }
411
+
412
+ void set_buf_to_reuse(BufPtr buf) {
413
+ buf_to_reuse_ = std::move(buf);
414
+ }
415
+
416
+ explicit PlacementAllocate(BufPtr buf, BufPtr buf_to_reuse)
417
+ : buf_(std::move(buf)), buf_to_reuse_(std::move(buf_to_reuse)) {}
418
+
419
+ private:
420
+ BufPtr buf_;
421
+ BufPtr buf_to_reuse_;
422
+ };
423
+
424
+ // Free the specific buffer. It is an error.
425
+ class TORCH_API Free : public StmtNode<Free> {
426
+ public:
427
+ static FreePtr make(const BufHandle& buf_handle) {
428
+ return alloc<Free>(buf_handle.node());
429
+ }
430
+
431
+ VarPtr buffer_var() const {
432
+ return buf_->base_handle();
433
+ }
434
+
435
+ BufPtr buf() const {
436
+ return buf_;
437
+ }
438
+
439
+ void set_buf(BufPtr buf) {
440
+ buf_ = std::move(buf);
441
+ }
442
+
443
+ explicit Free(BufPtr buf) : buf_(std::move(buf)) {}
444
+
445
+ private:
446
+ BufPtr buf_;
447
+ };
448
+
449
+ class TORCH_API FreeExt : public StmtNode<FreeExt> {
450
+ public:
451
+ static FreeExtPtr make(const std::vector<BufHandle>& bufs);
452
+
453
+ std::vector<BufPtr> bufs() const {
454
+ return bufs_;
455
+ }
456
+
457
+ void set_bufs(std::vector<BufPtr> bufs) {
458
+ bufs_ = std::move(bufs);
459
+ }
460
+
461
+ explicit FreeExt(std::vector<BufPtr> bufs) : bufs_(std::move(bufs)) {}
462
+
463
+ private:
464
+ std::vector<BufPtr> bufs_;
465
+ };
466
+
467
+ class TORCH_API Let : public StmtNode<Let> {
468
+ public:
469
+ static LetPtr make(const VarHandle& var, const ExprHandle& val) {
470
+ return alloc<Let>(var.node(), val.node());
471
+ }
472
+
473
+ Let(VarPtr var, ExprPtr val) : var_(std::move(var)), val_(std::move(val)) {}
474
+
475
+ VarPtr var() const {
476
+ return var_;
477
+ }
478
+
479
+ ExprPtr value() const {
480
+ return val_;
481
+ }
482
+
483
+ void set_var(VarPtr var) {
484
+ var_ = std::move(var);
485
+ }
486
+
487
+ void set_val(ExprPtr val) {
488
+ val_ = std::move(val);
489
+ }
490
+
491
+ private:
492
+ VarPtr var_;
493
+ ExprPtr val_;
494
+ };
495
+
496
+ class TORCH_API Cond : public StmtNode<Cond> {
497
+ public:
498
+ static CondPtr make(
499
+ const ExprHandle& condition,
500
+ const StmtPtr& true_stmt,
501
+ const StmtPtr& false_stmt) {
502
+ return alloc<Cond>(condition.node(), true_stmt, false_stmt);
503
+ }
504
+
505
+ ExprPtr condition() const {
506
+ return condition_;
507
+ }
508
+
509
+ BlockPtr true_stmt() const {
510
+ return true_stmt_;
511
+ }
512
+
513
+ BlockPtr false_stmt() const {
514
+ return false_stmt_;
515
+ }
516
+
517
+ void set_condition(ExprPtr condition) {
518
+ condition_ = std::move(condition);
519
+ }
520
+
521
+ void set_true_stmt(StmtPtr true_stmt) {
522
+ if (true_stmt) {
523
+ BlockPtr b = to<Block>(true_stmt);
524
+ if (!b) {
525
+ b = alloc<Block>(std::vector<StmtPtr>({std::move(true_stmt)}));
526
+ }
527
+ true_stmt_ = b;
528
+ set_parent(true_stmt_, this);
529
+ }
530
+ }
531
+
532
+ void set_false_stmt(StmtPtr false_stmt) {
533
+ if (false_stmt) {
534
+ BlockPtr b = to<Block>(false_stmt);
535
+ if (!b) {
536
+ b = alloc<Block>(std::vector<StmtPtr>({std::move(false_stmt)}));
537
+ }
538
+ false_stmt_ = b;
539
+ set_parent(false_stmt_, this);
540
+ }
541
+ }
542
+
543
+ Cond(ExprPtr condition, StmtPtr true_stmt, StmtPtr false_stmt)
544
+ : condition_(std::move(condition)) {
545
+ set_true_stmt(std::move(true_stmt));
546
+ set_false_stmt(std::move(false_stmt));
547
+ }
548
+
549
+ CondPtr cloneWithNewBodies(
550
+ const StmtPtr& true_stmt,
551
+ const StmtPtr& false_stmt) {
552
+ return alloc<Cond>(condition_, true_stmt, false_stmt);
553
+ }
554
+
555
+ CondPtr cloneWithNewBody(const StmtPtr& true_stmt) {
556
+ return alloc<Cond>(condition_, true_stmt, nullptr);
557
+ }
558
+
559
+ private:
560
+ ExprPtr condition_;
561
+ BlockPtr true_stmt_ = nullptr;
562
+ BlockPtr false_stmt_ = nullptr;
563
+ };
564
+
565
+ class TORCH_API LoopOptions {
566
+ public:
567
+ enum {
568
+ IDX_UNSET = -1,
569
+ IDX_X = 0,
570
+ IDX_Y = 1,
571
+ IDX_Z = 2,
572
+ IDX_W = 3,
573
+ IDX_MAX = IDX_W,
574
+ };
575
+ // GPU Block Index
576
+ bool is_gpu_block_index() const {
577
+ return gpu_block_index_ != IDX_UNSET;
578
+ }
579
+
580
+ int gpu_block_index() const {
581
+ return gpu_block_index_;
582
+ }
583
+
584
+ std::string gpu_block_index_str() const {
585
+ if (!is_gpu_block_index()) {
586
+ throw malformed_input("Has no GPU block index");
587
+ }
588
+
589
+ // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
590
+ static constexpr const char* kBlockIndexNames[] = {
591
+ "blockIdx.x",
592
+ "blockIdx.y",
593
+ "blockIdx.z",
594
+ "blockIdx.w",
595
+ };
596
+
597
+ if (gpu_block_index_ < IDX_X || gpu_block_index_ > IDX_MAX) {
598
+ throw malformed_input("invalid GPU block index");
599
+ }
600
+
601
+ return kBlockIndexNames[gpu_block_index_];
602
+ }
603
+
604
+ void set_gpu_block_index(int index) {
605
+ if (index == IDX_UNSET) {
606
+ gpu_block_index_ = IDX_UNSET;
607
+ }
608
+
609
+ if (is_gpu_thread_index()) {
610
+ throw std::runtime_error("Cannot set both gpu block and thread index");
611
+ }
612
+ if (is_gpu_block_index() && gpu_block_index() != index) {
613
+ throw std::runtime_error("Cannot set a previously set block index");
614
+ }
615
+ gpu_block_index_ = index;
616
+ }
617
+
618
+ // GPU Thread Index
619
+ bool is_gpu_thread_index() const {
620
+ return gpu_thread_index() != IDX_UNSET;
621
+ }
622
+
623
+ int gpu_thread_index() const {
624
+ return gpu_thread_index_;
625
+ }
626
+
627
+ std::string gpu_thread_index_str() const {
628
+ if (!is_gpu_thread_index()) {
629
+ throw malformed_input("has no GPU thread index");
630
+ }
631
+
632
+ // NOLINTNEXTLINE(modernize-avoid-c-arrays,cppcoreguidelines-avoid-c-arrays)
633
+ static constexpr const char* kThreadIndexNames[] = {
634
+ "threadIdx.x", "threadIdx.y", "threadIdx.z", "threadIdx.w"};
635
+
636
+ if (gpu_thread_index_ < IDX_X || gpu_thread_index_ > IDX_MAX) {
637
+ throw malformed_input("invalid GPU thread index");
638
+ }
639
+
640
+ return kThreadIndexNames[gpu_thread_index_];
641
+ }
642
+
643
+ void set_gpu_thread_index(int index) {
644
+ if (index == IDX_UNSET) {
645
+ gpu_thread_index_ = IDX_UNSET;
646
+ }
647
+
648
+ if (is_gpu_block_index()) {
649
+ throw std::runtime_error("Cannot set both gpu thread and block index");
650
+ }
651
+ if (is_gpu_thread_index() && gpu_thread_index() != index) {
652
+ throw std::runtime_error("Cannot set a previously set thread index");
653
+ }
654
+ gpu_thread_index_ = index;
655
+ }
656
+
657
+ void set_parallel() {
658
+ is_parallel_ = true;
659
+ }
660
+
661
+ bool is_parallel() const {
662
+ return is_parallel_;
663
+ }
664
+
665
+ std::string ToString() const {
666
+ if (is_gpu_block_index()) {
667
+ return gpu_block_index_str();
668
+ } else if (is_gpu_thread_index()) {
669
+ return gpu_thread_index_str();
670
+ } else if (is_parallel()) {
671
+ return "parallel";
672
+ }
673
+ return "";
674
+ }
675
+
676
+ bool isDefault() const {
677
+ return gpu_block_index_ == IDX_UNSET && gpu_thread_index_ == IDX_UNSET &&
678
+ !is_parallel_;
679
+ }
680
+
681
+ void set_buffer_mapping(const std::unordered_map<std::string, BufPtr>& map) {
682
+ map_input_to_tensor_bufs_ = map;
683
+ }
684
+
685
+ std::unordered_map<std::string, BufPtr> get_buffer_mapping() const {
686
+ return map_input_to_tensor_bufs_;
687
+ }
688
+
689
+ private:
690
+ int gpu_block_index_{IDX_UNSET};
691
+ int gpu_thread_index_{IDX_UNSET};
692
+ bool is_parallel_{false};
693
+ std::unordered_map<std::string, BufPtr> map_input_to_tensor_bufs_;
694
+ };
695
+
696
+ class TORCH_API For : public StmtNode<For> {
697
+ public:
698
+ VarPtr var() const {
699
+ return var_;
700
+ }
701
+ ExprPtr start() const {
702
+ return start_;
703
+ }
704
+ ExprPtr stop() const {
705
+ return stop_;
706
+ }
707
+ BlockPtr body() const {
708
+ return body_;
709
+ }
710
+ static ForPtr make(
711
+ const VarHandle& var,
712
+ const ExprHandle& start,
713
+ const ExprHandle& stop,
714
+ const StmtPtr& body) {
715
+ if (!body) {
716
+ return nullptr;
717
+ }
718
+ return alloc<For>(var.node(), start.node(), stop.node(), body);
719
+ }
720
+ static ForPtr make(
721
+ const VarHandle& var,
722
+ const ExprHandle& start,
723
+ const ExprHandle& stop,
724
+ const StmtPtr& body,
725
+ const LoopOptions& loop_options) {
726
+ if (!body) {
727
+ return nullptr;
728
+ }
729
+ return alloc<For>(
730
+ var.node(), start.node(), stop.node(), body, loop_options);
731
+ }
732
+ const LoopOptions loop_options() const {
733
+ return loop_options_;
734
+ }
735
+
736
+ For(VarPtr var, ExprPtr start, ExprPtr stop, StmtPtr body)
737
+ : var_(std::move(var)), start_(std::move(start)), stop_(std::move(stop)) {
738
+ BlockPtr b = to<Block>(body);
739
+ if (!b) {
740
+ b = alloc<Block>(std::vector<StmtPtr>({std::move(body)}));
741
+ }
742
+ body_ = b;
743
+ set_parent(body_, this);
744
+ }
745
+
746
+ For(VarPtr var,
747
+ ExprPtr start,
748
+ ExprPtr stop,
749
+ StmtPtr body,
750
+ LoopOptions loop_options)
751
+ : var_(std::move(var)),
752
+ start_(std::move(start)),
753
+ stop_(std::move(stop)),
754
+ loop_options_(std::move(loop_options)) {
755
+ if (!var_) {
756
+ throw malformed_input("invalid Var in For loop");
757
+ } else if (!start_) {
758
+ throw malformed_input("invalid Start in For loop");
759
+ } else if (!stop_) {
760
+ throw malformed_input("invalid Stop in For loop");
761
+ } else if (!body || body->get_parent()) {
762
+ throw malformed_input("invalid Body in For loop");
763
+ }
764
+
765
+ BlockPtr b = to<Block>(body);
766
+ if (!b) {
767
+ b = alloc<Block>(std::vector<StmtPtr>({std::move(body)}));
768
+ }
769
+ body_ = b;
770
+ set_parent(body_, this);
771
+ }
772
+
773
+ void set_gpu_block_index(int block_index) {
774
+ loop_options_.set_gpu_block_index(block_index);
775
+ }
776
+
777
+ void set_gpu_thread_index(int thread_index) {
778
+ loop_options_.set_gpu_thread_index(thread_index);
779
+ }
780
+
781
+ void set_parallel() {
782
+ loop_options_.set_parallel();
783
+ }
784
+
785
+ bool is_parallel() const {
786
+ return loop_options_.is_parallel();
787
+ }
788
+
789
+ void set_buffer_map(const std::unordered_map<std::string, BufPtr>& map) {
790
+ loop_options_.set_buffer_mapping(map);
791
+ }
792
+
793
+ ForPtr cloneWithNewBody(const StmtPtr& body) const {
794
+ return alloc<For>(var_, start_, stop_, body, loop_options_);
795
+ }
796
+
797
+ BlockPtr removeBody() {
798
+ auto res = body_;
799
+ set_parent(res, nullptr);
800
+ body_ = nullptr;
801
+ return res;
802
+ }
803
+
804
+ void set_body(StmtPtr body) {
805
+ BlockPtr b = to<Block>(body);
806
+ if (!b) {
807
+ b = alloc<Block>(std::vector<StmtPtr>({std::move(body)}));
808
+ }
809
+ body_ = b;
810
+ set_parent(body_, this);
811
+ }
812
+
813
+ void set_start(ExprPtr start) {
814
+ start_ = std::move(start);
815
+ }
816
+
817
+ void set_stop(ExprPtr stop) {
818
+ stop_ = std::move(stop);
819
+ }
820
+
821
+ void set_var(VarPtr var) {
822
+ var_ = std::move(var);
823
+ }
824
+
825
+ private:
826
+ VarPtr var_;
827
+ ExprPtr start_;
828
+ ExprPtr stop_;
829
+ BlockPtr body_;
830
+ LoopOptions loop_options_;
831
+ };
832
+
833
+ // A backend specific IR Node that implements atomic-add.
834
+ // This node could only shows up as an internal with GPU backends.
835
+ // TODO: move to this an internal IR.
836
+ // TODO: make IR nodes extensible.
837
+ class TORCH_API AtomicAdd : public StmtNode<AtomicAdd> {
838
+ public:
839
+ AtomicAdd(BufPtr buf, std::vector<ExprPtr> indices, ExprPtr value)
840
+ : buf_(std::move(buf)),
841
+ indices_(std::move(indices)),
842
+ value_(std::move(value)) {}
843
+
844
+ VarPtr base_handle() const {
845
+ return buf_->base_handle();
846
+ }
847
+
848
+ BufPtr buf() const {
849
+ return buf_;
850
+ }
851
+
852
+ ExprPtr flat_index() const {
853
+ TORCH_CHECK(indices_.size() == 1, "Indices haven't been flattened.");
854
+ return indices_[0];
855
+ }
856
+
857
+ ExprPtr value() const {
858
+ return value_;
859
+ }
860
+
861
+ const std::vector<ExprPtr>& indices() const {
862
+ return indices_;
863
+ }
864
+
865
+ void set_buf(BufPtr buf) {
866
+ buf_ = std::move(buf);
867
+ }
868
+
869
+ void set_indices(std::vector<ExprPtr> indices) {
870
+ indices_ = std::move(indices);
871
+ }
872
+
873
+ void set_value(ExprPtr value) {
874
+ value_ = std::move(value);
875
+ }
876
+
877
+ private:
878
+ BufPtr buf_;
879
+ std::vector<ExprPtr> indices_;
880
+ ExprPtr value_;
881
+ };
882
+
883
+ class TORCH_API SyncThreads : public StmtNode<SyncThreads> {
884
+ public:
885
+ SyncThreads() = default;
886
+ };
887
+
888
+ /*
889
+ * ExternalCall statement represents a call to an external function that would
890
+ * compute the contents of the output buffer. An ExternalCall statement consists
891
+ * of:
892
+ * 1) output buffer - the buffer that'll be initialized by the call
893
+ * 2) external function name - a key from the NNC function registry to lookup
894
+ * the actual function to call
895
+ * 3) buffer arguments - the input buffers used by the function
896
+ * 4) non-buffer arguments - scalar arguments to pass to the function
897
+ *
898
+ * An example:
899
+ * A = nnc_conv2d(buf_args={Input, Weight, Bias}, args={1})
900
+ * Here 'A' is the output buffer, "nnc_conv2d" is the function name, the buffer
901
+ * arguments are 'Input', 'Weight', and 'Bias', and there is a single non-buffer
902
+ * argument - 1.
903
+ *
904
+ * The semantics of the scalar arguments is defined solely by the implementation
905
+ * of the external function.
906
+ */
907
+ class TORCH_API ExternalCall : public StmtNode<ExternalCall> {
908
+ public:
909
+ static ExternalCallPtr make(
910
+ BufHandle buf,
911
+ const std::string& func_name,
912
+ const std::vector<BufHandle>& buf_args,
913
+ const std::vector<ExprHandle>& args);
914
+
915
+ BufPtr buf() const {
916
+ return buf_;
917
+ }
918
+
919
+ std::string func_name() const {
920
+ return func_name_;
921
+ }
922
+
923
+ std::vector<BufPtr> buf_args() const {
924
+ return buf_args_;
925
+ }
926
+
927
+ std::vector<ExprPtr> args() const {
928
+ return args_;
929
+ }
930
+
931
+ void set_buf(BufPtr buf) {
932
+ buf_ = std::move(buf);
933
+ }
934
+
935
+ void set_buf_args(std::vector<BufPtr> buf_args) {
936
+ buf_args_ = std::move(buf_args);
937
+ }
938
+
939
+ void set_args(std::vector<ExprPtr> args) {
940
+ args_ = std::move(args);
941
+ }
942
+
943
+ ExternalCall(
944
+ BufPtr buf,
945
+ std::string func_name,
946
+ std::vector<BufPtr> buf_args,
947
+ std::vector<ExprPtr> args)
948
+ : buf_(std::move(buf)),
949
+ func_name_(std::move(func_name)),
950
+ buf_args_(std::move(buf_args)),
951
+ args_(std::move(args)) {}
952
+
953
+ private:
954
+ BufPtr buf_;
955
+ std::string func_name_;
956
+ std::vector<BufPtr> buf_args_;
957
+ std::vector<ExprPtr> args_;
958
+ };
959
+
960
+ class TORCH_API ExternalCallWithAlloc : public StmtNode<ExternalCallWithAlloc> {
961
+ public:
962
+ static ExternalCallWithAllocPtr make(
963
+ const std::string& func_name,
964
+ const std::vector<BufHandle>& buf_out_args,
965
+ const std::vector<BufHandle>& buf_args,
966
+ const std::vector<ExprHandle>& args);
967
+
968
+ std::vector<BufPtr> buf_out_args() const {
969
+ return buf_out_args_;
970
+ }
971
+
972
+ std::string func_name() const {
973
+ return func_name_;
974
+ }
975
+
976
+ std::vector<BufPtr> buf_args() const {
977
+ return buf_args_;
978
+ }
979
+
980
+ std::vector<ExprPtr> args() const {
981
+ return args_;
982
+ }
983
+
984
+ void set_buf_out_args(std::vector<BufPtr> buf_out_args) {
985
+ buf_out_args_ = std::move(buf_out_args);
986
+ }
987
+
988
+ void set_buf_args(std::vector<BufPtr> buf_args) {
989
+ buf_args_ = std::move(buf_args);
990
+ }
991
+
992
+ void set_args(std::vector<ExprPtr> args) {
993
+ args_ = std::move(args);
994
+ }
995
+
996
+ ExternalCallWithAlloc(
997
+ std::string func_name,
998
+ std::vector<BufPtr> buf_out_args,
999
+ std::vector<BufPtr> buf_args,
1000
+ std::vector<ExprPtr> args)
1001
+ : func_name_(std::move(func_name)),
1002
+ buf_out_args_(std::move(buf_out_args)),
1003
+ buf_args_(std::move(buf_args)),
1004
+ args_(std::move(args)) {}
1005
+
1006
+ private:
1007
+ std::string func_name_;
1008
+ std::vector<BufPtr> buf_out_args_;
1009
+ std::vector<BufPtr> buf_args_;
1010
+ std::vector<ExprPtr> args_;
1011
+ };
1012
+
1013
+ } // namespace torch::jit::tensorexpr
1014
+
1015
+ #else
1016
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
1017
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensor.h ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <functional>
6
+ #include <utility>
7
+ #include <vector>
8
+
9
+ #include <torch/csrc/jit/tensorexpr/expr.h>
10
+ #include <torch/csrc/jit/tensorexpr/reduction.h>
11
+
12
+ namespace torch::jit::tensorexpr {
13
+
14
+ class TORCH_API Tensor {
15
+ public:
16
+ Tensor(BufPtr buf, const std::vector<VarPtr>& args, const ExprPtr& body)
17
+ : buf_(std::move(buf)) {
18
+ stmt_ = constructStmt(args, body, {}, {});
19
+ }
20
+ Tensor(BufHandle buf, const std::vector<VarHandle>& args, ExprHandle body)
21
+ : Tensor(buf.node(), VarHandleVectorToVarVector(args), body.node()) {}
22
+
23
+ Tensor(
24
+ BufPtr buf,
25
+ const std::vector<VarPtr>& args,
26
+ const std::vector<ExprPtr>& reduce_dims,
27
+ const std::vector<VarPtr>& reduce_args,
28
+ const ExprPtr& body)
29
+ : buf_(std::move(buf)) {
30
+ stmt_ = constructStmt(args, body, reduce_dims, reduce_args);
31
+ }
32
+ Tensor(
33
+ BufHandle buf,
34
+ const std::vector<VarHandle>& args,
35
+ const std::vector<ExprHandle>& reduce_dims,
36
+ const std::vector<VarHandle>& reduce_args,
37
+ ExprHandle body)
38
+ : Tensor(
39
+ buf.node(),
40
+ VarHandleVectorToVarVector(args),
41
+ ExprHandleVectorToExprVector(reduce_dims),
42
+ VarHandleVectorToVarVector(reduce_args),
43
+ body.node()) {}
44
+
45
+ Tensor(BufPtr buf, StmtPtr stmt)
46
+ : buf_(std::move(buf)), stmt_(std::move(stmt)) {}
47
+
48
+ BufPtr buf() const {
49
+ return buf_;
50
+ }
51
+
52
+ StmtPtr stmt() const {
53
+ return stmt_;
54
+ }
55
+
56
+ template <typename T>
57
+ inline ExprHandle load(const std::vector<T>& args) const;
58
+ template <typename... Ts>
59
+ inline ExprHandle load(const Ts&... ts) const;
60
+
61
+ private:
62
+ StmtPtr constructStmt(
63
+ const std::vector<VarPtr>& args,
64
+ const ExprPtr& body,
65
+ const std::vector<ExprPtr>& reduce_dims,
66
+ const std::vector<VarPtr>& reduce_args) const;
67
+
68
+ BufPtr buf_;
69
+ StmtPtr stmt_;
70
+ };
71
+
72
+ TORCH_API Tensor Compute(
73
+ const std::string& func_name,
74
+ const std::vector<ExprHandle>& dims,
75
+ const std::optional<std::vector<ExprHandle>>& strides,
76
+ const std::function<ExprHandle(const VarHandle&)>& body_func);
77
+ TORCH_API Tensor Compute(
78
+ const std::string& func_name,
79
+ const std::vector<ExprHandle>& dims,
80
+ const std::function<ExprHandle(const VarHandle&)>& body_func);
81
+ TORCH_API Tensor Compute(
82
+ const std::string& func_name,
83
+ const std::vector<ExprHandle>& dims,
84
+ const std::optional<std::vector<ExprHandle>>& strides,
85
+ const std::function<ExprHandle(const VarHandle&, const VarHandle&)>&
86
+ body_func);
87
+ TORCH_API Tensor Compute(
88
+ const std::string& func_name,
89
+ const std::vector<ExprHandle>& dims,
90
+ const std::function<ExprHandle(const VarHandle&, const VarHandle&)>&
91
+ body_func);
92
+ TORCH_API Tensor Compute(
93
+ const std::string& func_name,
94
+ const std::vector<ExprHandle>& dims,
95
+ const std::optional<std::vector<ExprHandle>>& strides,
96
+ const std::function<
97
+ ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>&
98
+ body_func);
99
+ TORCH_API Tensor Compute(
100
+ const std::string& func_name,
101
+ const std::vector<ExprHandle>& dims,
102
+ const std::function<
103
+ ExprHandle(const VarHandle&, const VarHandle&, const VarHandle&)>&
104
+ body_func);
105
+ TORCH_API Tensor Compute(
106
+ const std::string& func_name,
107
+ const std::vector<ExprHandle>& dims,
108
+ const std::optional<std::vector<ExprHandle>>& strides,
109
+ const std::function<ExprHandle(
110
+ const VarHandle&,
111
+ const VarHandle&,
112
+ const VarHandle&,
113
+ const VarHandle&)>& body_func);
114
+ TORCH_API Tensor Compute(
115
+ const std::string& func_name,
116
+ const std::vector<ExprHandle>& dims,
117
+ const std::function<ExprHandle(
118
+ const VarHandle&,
119
+ const VarHandle&,
120
+ const VarHandle&,
121
+ const VarHandle&)>& body_func);
122
+ TORCH_API Tensor Compute(
123
+ const std::string& func_name,
124
+ const std::vector<ExprHandle>& dims,
125
+ const std::optional<std::vector<ExprHandle>>& strides,
126
+ const std::function<ExprHandle(const std::vector<VarHandle>&)>& body_func);
127
+ TORCH_API Tensor Compute(
128
+ const std::string& func_name,
129
+ const std::vector<ExprHandle>& dims,
130
+ const std::function<ExprHandle(const std::vector<VarHandle>&)>& body_func);
131
+
132
+ inline std::vector<VarHandle> create_index_vars(
133
+ const std::vector<ExprHandle>& dims) {
134
+ std::vector<VarHandle> vars;
135
+ vars.reserve(dims.size());
136
+ for (const ExprHandle& dim : dims) {
137
+ vars.emplace_back(alloc<Var>(
138
+ "i", dim.dtype().scalar_type() == ScalarType::Long ? kLong : kInt));
139
+ }
140
+ return vars;
141
+ }
142
+
143
+ // Handle reductions over a Reducer and a body_func which produces values.
144
+ template <typename InitFunc, typename BodyFunc>
145
+ Tensor Reduce(
146
+ const std::string& func_name,
147
+ const std::vector<ExprHandle>& dims,
148
+ const std::optional<std::vector<ExprHandle>>& strides,
149
+ const Reducer& reducer,
150
+ const InitFunc& init_func,
151
+ const BodyFunc& body_func,
152
+ const std::vector<ExprHandle>& reduce_dims) {
153
+ std::vector<VarHandle> vars = create_index_vars(dims);
154
+ std::vector<VarHandle> reduce_vars = create_index_vars(reduce_dims);
155
+
156
+ // If reduce_vars is empty, then it's not a reduction, but rather a simple
157
+ // copy
158
+ if (reduce_vars.empty()) {
159
+ ExprHandle body = Reducer::getReduceBody(body_func, vars);
160
+ BufHandle func_result =
161
+ Buf::make(func_name, dims, body.dtype(), std::nullopt, strides);
162
+ return Tensor(std::move(func_result), vars, std::move(body));
163
+ }
164
+
165
+ std::vector<VarHandle> all_vars;
166
+ all_vars.insert(all_vars.end(), vars.begin(), vars.end());
167
+ all_vars.insert(all_vars.end(), reduce_vars.begin(), reduce_vars.end());
168
+
169
+ ExprHandle body = Reducer::getReduceBody(body_func, all_vars);
170
+ std::vector<ExprHandle> output_args(vars.begin(), vars.end());
171
+ ExprHandle init_expr = Cast::make(body.dtype(), init_func(vars));
172
+ BufHandle func_result = Buf::make(func_name, dims, body.dtype(), init_expr);
173
+
174
+ ExprHandle reduce_op = reducer(func_result, body, output_args, reduce_vars);
175
+ if (body.dtype() == kBFloat16) {
176
+ ExprHandle init_expr_acc = Cast::make(kFloat, init_func(vars));
177
+ BufHandle func_result_acc =
178
+ Buf::make(func_name + "_acc", dims, kFloat, init_expr_acc);
179
+ reduce_op = reducer(
180
+ func_result,
181
+ std::move(func_result_acc),
182
+ body,
183
+ output_args,
184
+ reduce_vars);
185
+ }
186
+
187
+ Tensor t = Tensor(
188
+ std::move(func_result),
189
+ vars,
190
+ reduce_dims,
191
+ reduce_vars,
192
+ std::move(reduce_op));
193
+ return t;
194
+ }
195
+ template <typename InitFunc, typename BodyFunc>
196
+ Tensor Reduce(
197
+ const std::string& func_name,
198
+ const std::vector<ExprHandle>& dims,
199
+ const Reducer& reducer,
200
+ const InitFunc& init_func,
201
+ const BodyFunc& body_func,
202
+ const std::vector<ExprHandle>& reduce_dims) {
203
+ return Reduce<InitFunc, BodyFunc>(
204
+ func_name,
205
+ dims,
206
+ std::nullopt,
207
+ reducer,
208
+ init_func,
209
+ body_func,
210
+ reduce_dims);
211
+ }
212
+
213
+ template <typename BodyFunc>
214
+ Tensor Reduce(
215
+ const std::string& func_name,
216
+ const std::vector<ExprHandle>& dims,
217
+ const std::optional<std::vector<ExprHandle>>& strides,
218
+ const Reducer& reducer,
219
+ const BodyFunc& body_func,
220
+ const std::vector<ExprHandle>& reduce_dims) {
221
+ return Reduce(
222
+ func_name,
223
+ dims,
224
+ strides,
225
+ reducer,
226
+ [&](ParameterList& p [[maybe_unused]]) {
227
+ return ExprHandle(reducer.initializer());
228
+ },
229
+ body_func,
230
+ reduce_dims);
231
+ }
232
+ template <typename BodyFunc>
233
+ Tensor Reduce(
234
+ const std::string& func_name,
235
+ const std::vector<ExprHandle>& dims,
236
+ const Reducer& reducer,
237
+ const BodyFunc& body_func,
238
+ const std::vector<ExprHandle>& reduce_dims) {
239
+ return Reduce<BodyFunc>(
240
+ func_name, dims, std::nullopt, reducer, body_func, reduce_dims);
241
+ }
242
+
243
+ // Overload which allows inline lambda functions for the body_func.
244
+ template <typename BodyFunc>
245
+ Tensor Reduce(
246
+ const std::string& func_name,
247
+ const std::vector<ExprHandle>& dims,
248
+ const std::optional<std::vector<ExprHandle>>& strides,
249
+ const Reducer& reducer,
250
+ const BodyFunc&& body_func,
251
+ const std::vector<ExprHandle>& reduce_dims) {
252
+ return Reduce(func_name, dims, strides, reducer, body_func, reduce_dims);
253
+ }
254
+ template <typename BodyFunc>
255
+ Tensor Reduce(
256
+ const std::string& func_name,
257
+ const std::vector<ExprHandle>& dims,
258
+ const Reducer& reducer,
259
+ const BodyFunc&& body_func,
260
+ const std::vector<ExprHandle>& reduce_dims) {
261
+ return Reduce(func_name, dims, std::nullopt, reducer, body_func, reduce_dims);
262
+ }
263
+
264
+ TORCH_API Tensor Reduce(
265
+ const std::string& name,
266
+ const std::vector<ExprHandle>& dims,
267
+ const std::optional<std::vector<ExprHandle>>& strides,
268
+ const Reducer& reducer,
269
+ const BufHandle& buffer,
270
+ const std::vector<ExprHandle>& reduce_dims);
271
+ TORCH_API Tensor Reduce(
272
+ const std::string& name,
273
+ const std::vector<ExprHandle>& dims,
274
+ const Reducer& reducer,
275
+ const BufHandle& buffer,
276
+ const std::vector<ExprHandle>& reduce_dims);
277
+
278
+ // Overload for the common case of all dimensions of a previously Computed
279
+ // Tensor.
280
+ TORCH_API Tensor Reduce(
281
+ const std::string& func_name,
282
+ const std::vector<ExprHandle>& dims,
283
+ const std::optional<std::vector<ExprHandle>>& strides,
284
+ const Reducer& reducer,
285
+ const Tensor& tensor,
286
+ const std::vector<ExprHandle>& reduce_dims);
287
+ TORCH_API Tensor Reduce(
288
+ const std::string& func_name,
289
+ const std::vector<ExprHandle>& dims,
290
+ const Reducer& reducer,
291
+ const Tensor& tensor,
292
+ const std::vector<ExprHandle>& reduce_dims);
293
+
294
+ template <typename... Ts>
295
+ inline ExprHandle Tensor::load(const Ts&... ts) const {
296
+ std::vector<ExprHandle> params({ExprHandle(ts)...});
297
+ return Load::make(BufHandle(this->buf()), params);
298
+ }
299
+
300
+ template <typename T>
301
+ inline ExprHandle Tensor::load(const std::vector<T>& args) const {
302
+ std::vector<ExprHandle> params(args.begin(), args.end());
303
+ return Load::make(BufHandle(this->buf()), params);
304
+ }
305
+
306
+ template <typename... Ts>
307
+ inline ExprHandle BufHandle::load(const Ts&... ts) const {
308
+ std::vector<ExprHandle> params({ExprHandle(ts)...});
309
+ return ExprHandle(alloc<Load>(node(), ExprHandleVectorToExprVector(params)));
310
+ }
311
+
312
+ template <typename T>
313
+ inline ExprHandle BufHandle::load(const std::vector<T>& args) const {
314
+ std::vector<ExprHandle> params(args.begin(), args.end());
315
+ return ExprHandle(alloc<Load>(node(), ExprHandleVectorToExprVector(params)));
316
+ }
317
+
318
+ inline ExprHandle BufHandle::load(const std::vector<ExprHandle>& args) const {
319
+ return this->template load<ExprHandle>(args);
320
+ }
321
+
322
+ } // namespace torch::jit::tensorexpr
323
+
324
+ #else
325
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
326
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/tensorexpr_init.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/jit/python/pybind.h>
5
+ #include <torch/csrc/utils/pybind.h>
6
+
7
+ namespace torch::jit {
8
+ // Initialize Python bindings for Tensor Expressions
9
+ void initTensorExprBindings(PyObject* module);
10
+ } // namespace torch::jit
11
+
12
+ #else
13
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
14
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/types.h ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <cstdint>
5
+ #include <iosfwd>
6
+
7
+ #include <c10/core/ScalarType.h>
8
+ #include <c10/util/Logging.h>
9
+ #include <torch/csrc/Export.h>
10
+
11
+ #include <torch/csrc/jit/tensorexpr/exceptions.h>
12
+
13
+ namespace torch::jit::tensorexpr {
14
+
15
+ using int32 = std::int32_t;
16
+
17
+ class Dtype;
18
+ TORCH_API std::ostream& operator<<(std::ostream& stream, const Dtype& dtype);
19
+
20
+ using ScalarType = c10::ScalarType;
21
+
22
+ enum ElementType {
23
+ kAllTypes = 0,
24
+ kIntegralTypes = 1 << 0,
25
+ kFloatingPointTypes = 1 << 1,
26
+ kBoolType = 1 << 2,
27
+ kComplexTypes = 1 << 3,
28
+ kQintTypes = 1 << 4,
29
+ kNonComplexOrQintTypes = kIntegralTypes | kBoolType | kFloatingPointTypes,
30
+ };
31
+
32
+ // Data types for scalar and vector elements.
33
+ class TORCH_API Dtype {
34
+ public:
35
+ explicit Dtype(int8_t type)
36
+ : scalar_type_(static_cast<ScalarType>(type)), lanes_(1) {}
37
+ explicit Dtype(ScalarType type) : scalar_type_(type), lanes_(1) {}
38
+ Dtype(int8_t type, int64_t lanes)
39
+ : scalar_type_(static_cast<ScalarType>(type)), lanes_(lanes) {}
40
+ Dtype(ScalarType type, int64_t lanes) : scalar_type_(type), lanes_(lanes) {}
41
+ Dtype(Dtype type, int64_t lanes)
42
+ : scalar_type_(type.scalar_type_), lanes_(lanes) {
43
+ if (type.lanes() != 1) {
44
+ throw malformed_input("dtype lanes dont match");
45
+ }
46
+ }
47
+ int64_t lanes() const {
48
+ return lanes_;
49
+ }
50
+ ScalarType scalar_type() const {
51
+ return scalar_type_;
52
+ }
53
+ Dtype scalar_dtype() const;
54
+ bool operator==(const Dtype& other) const {
55
+ return scalar_type_ == other.scalar_type_ && lanes_ == other.lanes_;
56
+ }
57
+ bool operator!=(const Dtype& other) const {
58
+ return !(*this == other);
59
+ }
60
+ int byte_size() const;
61
+ std::string ToCppString() const;
62
+
63
+ bool is_integral() const {
64
+ return c10::isIntegralType(scalar_type_, true);
65
+ }
66
+ bool is_floating_point() const {
67
+ return c10::isFloatingType(scalar_type_);
68
+ }
69
+ bool is_signed() const {
70
+ return c10::isSignedType(scalar_type_);
71
+ }
72
+
73
+ Dtype cloneWithScalarType(ScalarType nt) const {
74
+ return Dtype(nt, lanes_);
75
+ }
76
+
77
+ private:
78
+ friend TORCH_API std::ostream& operator<<(
79
+ std::ostream& stream,
80
+ const Dtype& dtype);
81
+ ScalarType scalar_type_;
82
+ int64_t lanes_; // the width of the element for a vector time
83
+ };
84
+
85
+ extern TORCH_API Dtype kHandle;
86
+
87
+ #define NNC_DTYPE_DECLARATION(ctype, name) extern TORCH_API Dtype k##name;
88
+
89
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, NNC_DTYPE_DECLARATION)
90
+ NNC_DTYPE_DECLARATION(c10::quint8, QUInt8)
91
+ NNC_DTYPE_DECLARATION(c10::qint8, QInt8)
92
+ #undef NNC_DTYPE_DECLARATION
93
+
94
+ template <typename T>
95
+ TORCH_API Dtype ToDtype();
96
+
97
+ #define NNC_TODTYPE_DECLARATION(ctype, name) \
98
+ template <> \
99
+ inline Dtype ToDtype<ctype>() { \
100
+ return k##name; \
101
+ }
102
+ AT_FORALL_SCALAR_TYPES_AND3(Bool, Half, BFloat16, NNC_TODTYPE_DECLARATION)
103
+ NNC_TODTYPE_DECLARATION(c10::quint8, QUInt8)
104
+ NNC_TODTYPE_DECLARATION(c10::qint8, QInt8)
105
+ #undef NNC_TODTYPE_DECLARATION
106
+
107
+ TORCH_API Dtype ToDtype(ScalarType type);
108
+
109
+ inline Dtype promoteTypes(Dtype a, Dtype b) {
110
+ if (a.lanes() != b.lanes()) {
111
+ throw malformed_input("promoting types with different lanes");
112
+ }
113
+ return Dtype(
114
+ static_cast<ScalarType>(c10::promoteTypes(
115
+ static_cast<c10::ScalarType>(a.scalar_type()),
116
+ static_cast<c10::ScalarType>(b.scalar_type()))),
117
+ a.lanes());
118
+ }
119
+
120
+ inline Dtype BinaryOpDtype(
121
+ Dtype op1_dtype,
122
+ Dtype op2_dtype,
123
+ ScalarType ret_type = ScalarType::Undefined) {
124
+ if (op1_dtype == op2_dtype) {
125
+ if (ret_type == ScalarType::Undefined) {
126
+ return op1_dtype;
127
+ }
128
+
129
+ return ToDtype(ret_type);
130
+ }
131
+
132
+ if (op1_dtype.lanes() != op2_dtype.lanes()) {
133
+ throw malformed_input("lanes dont match");
134
+ }
135
+ int64_t lanes = op1_dtype.lanes();
136
+
137
+ Dtype resultType = promoteTypes(op1_dtype, op2_dtype);
138
+ if (resultType.scalar_type() == ScalarType::Undefined) {
139
+ throw malformed_input("scalar type doesn't match");
140
+ }
141
+
142
+ if (lanes == 1) {
143
+ // Use the fixed scalar Dtypes.
144
+ return ToDtype(resultType.scalar_type());
145
+ }
146
+
147
+ return resultType;
148
+ }
149
+
150
+ } // namespace torch::jit::tensorexpr
151
+
152
+ namespace std {
153
+
154
+ using torch::jit::tensorexpr::Dtype;
155
+ std::string to_string(const Dtype& dtype);
156
+ using torch::jit::tensorexpr::ScalarType;
157
+ std::string to_string(const ScalarType& dtype);
158
+
159
+ } // namespace std
160
+
161
+ #else
162
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
163
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/unique_name_manager.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <string>
5
+ #include <unordered_map>
6
+ #include <unordered_set>
7
+
8
+ #include <torch/csrc/Export.h>
9
+ #include <torch/csrc/jit/tensorexpr/fwd_decls.h>
10
+
11
+ namespace torch::jit::tensorexpr {
12
+
13
+ class VarHandle;
14
+ class Var;
15
+
16
+ using VarNameMap = std::unordered_map<VarPtr, std::string>;
17
+
18
+ // A manager to get unique names from vars.
19
+ // It starts with the name hints of the var and append "_" + $counter until it
20
+ // hits a unique name.
21
+ class TORCH_API UniqueNameManager {
22
+ public:
23
+ const std::string& get_unique_name(const VarHandle& v);
24
+
25
+ const std::string& get_unique_name(const VarPtr& v);
26
+
27
+ private:
28
+ friend class ScopedVarName;
29
+ VarNameMap unique_name_mapping_;
30
+ std::unordered_map<std::string, int> unique_name_count_;
31
+ std::unordered_set<std::string> all_unique_names_;
32
+ };
33
+
34
+ } // namespace torch::jit::tensorexpr
35
+
36
+ #else
37
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
38
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/tensorexpr/var_substitutor.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <unordered_map>
5
+ #include <utility>
6
+ #include <vector>
7
+
8
+ #include <torch/csrc/jit/tensorexpr/analysis.h>
9
+ #include <torch/csrc/jit/tensorexpr/ir.h>
10
+ #include <torch/csrc/jit/tensorexpr/ir_mutator.h>
11
+ #include <torch/csrc/jit/tensorexpr/ir_visitor.h>
12
+ #include <torch/csrc/jit/tensorexpr/reduction.h>
13
+
14
+ namespace torch::jit::tensorexpr {
15
+
16
+ using VarMapping = std::vector<std::pair<VarPtr, ExprPtr>>;
17
+
18
+ class VarSubMutator : public IRMutator {
19
+ public:
20
+ VarSubMutator(const VarMapping& var_mapping) {
21
+ for (auto& entry : var_mapping) {
22
+ VarPtr key_var = entry.first;
23
+ ExprPtr value = entry.second;
24
+ if (!key_var) {
25
+ throw malformed_input("missing key in VarSubMutator");
26
+ }
27
+ var_mapping_[std::move(key_var)] = std::move(value);
28
+ }
29
+ }
30
+
31
+ ExprPtr mutate(const VarPtr& var) override {
32
+ auto iter = var_mapping_.find(var);
33
+ if (iter == var_mapping_.end()) {
34
+ return var;
35
+ }
36
+ return iter->second;
37
+ }
38
+
39
+ ExprPtr mutate(const ReduceOpPtr& var) override {
40
+ auto body = var->body()->accept_mutator(this);
41
+ std::vector<VarPtr> new_inner;
42
+
43
+ for (const auto& v : var->reduce_args()) {
44
+ ExprPtr e = v->accept_mutator(this);
45
+ if (VarPtr new_var = to<Var>(e)) {
46
+ new_inner.push_back(std::move(new_var));
47
+ } else {
48
+ VarFinder varFinder;
49
+ e->accept(&varFinder);
50
+ auto varlist = varFinder.vars();
51
+ new_inner.insert(new_inner.end(), varlist.begin(), varlist.end());
52
+ }
53
+ }
54
+
55
+ return alloc<ReduceOp>(body, new_inner, var->reducer());
56
+ }
57
+
58
+ private:
59
+ std::unordered_map<VarPtr, ExprPtr> var_mapping_;
60
+ };
61
+
62
+ } // namespace torch::jit::tensorexpr
63
+
64
+ #else
65
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
66
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/catch_utils.hpp ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #define CATCH_CONFIG_PREFIX_ALL
5
+ #include <catch.hpp>
6
+
7
+ // CATCH_REQUIRE_THROWS is not defined identically to REQUIRE_THROWS and causes
8
+ // warning; define our own version that doesn't warn.
9
+ #define _CATCH_REQUIRE_THROWS(...) \
10
+ INTERNAL_CATCH_THROWS( \
11
+ "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
12
+
13
+ #else
14
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
15
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/file_check.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+
4
+ #include <torch/csrc/Export.h>
5
+ #include <memory>
6
+ #include <string>
7
+
8
+ namespace torch::jit {
9
+
10
+ struct Graph;
11
+
12
+ namespace testing {
13
+
14
+ struct FileCheckImpl;
15
+
16
+ struct FileCheck {
17
+ public:
18
+ TORCH_API explicit FileCheck();
19
+ TORCH_API ~FileCheck();
20
+
21
+ // Run FileCheck against test string
22
+ TORCH_API void run(const std::string& test_string);
23
+
24
+ // Run FileCheck against dump of graph IR
25
+ TORCH_API void run(const Graph& graph);
26
+
27
+ // Parsing input checks string and run against test string / dump of graph IR
28
+ TORCH_API void run(
29
+ const std::string& input_checks_string,
30
+ const std::string& test_string);
31
+ TORCH_API void run(
32
+ const std::string& input_checks_string,
33
+ const Graph& graph);
34
+
35
+ // Checks that the string occurs, starting at the end of the most recent match
36
+ TORCH_API FileCheck* check(const std::string& str);
37
+
38
+ // Checks that the string does not occur between the previous match and next
39
+ // match. Consecutive check_nots test against the same previous match and next
40
+ // match
41
+ TORCH_API FileCheck* check_not(const std::string& str);
42
+
43
+ // Checks that the string occurs on the same line as the previous match
44
+ TORCH_API FileCheck* check_same(const std::string& str);
45
+
46
+ // Checks that the string occurs on the line immediately following the
47
+ // previous match
48
+ TORCH_API FileCheck* check_next(const std::string& str);
49
+
50
+ // Checks that the string occurs count number of times, starting at the end
51
+ // of the previous match. If exactly is true, checks that there are exactly
52
+ // count many matches
53
+ TORCH_API FileCheck* check_count(
54
+ const std::string& str,
55
+ size_t count,
56
+ bool exactly = false);
57
+
58
+ // A series of consecutive check_dags get turned into a group of checks
59
+ // which can appear in any order relative to each other. The checks begin
60
+ // at the end of the previous match, and the match for the check_dag group
61
+ // is the minimum match of all individual checks to the maximum match of all
62
+ // individual checks.
63
+ TORCH_API FileCheck* check_dag(const std::string& str);
64
+
65
+ // Checks that source token is highlighted in str (usually an error message).
66
+ TORCH_API FileCheck* check_source_highlighted(const std::string& str);
67
+
68
+ // Checks that the regex matched string occurs, starting at the end of the
69
+ // most recent match
70
+ TORCH_API FileCheck* check_regex(const std::string& str);
71
+
72
+ // reset checks
73
+ TORCH_API void reset();
74
+
75
+ private:
76
+ bool has_run = false;
77
+ std::unique_ptr<FileCheckImpl> fcImpl;
78
+ };
79
+ } // namespace testing
80
+ } // namespace torch::jit
81
+
82
+ #else
83
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
84
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
miniconda3/envs/active_proaction/lib/python3.10/site-packages/torch/include/torch/csrc/jit/testing/hooks_for_testing.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
2
+ #pragma once
3
+ #include <torch/csrc/Export.h>
4
+ #include <torch/csrc/jit/api/compilation_unit.h>
5
+ #include <functional>
6
+ #include <memory>
7
+
8
+ namespace torch::jit {
9
+ struct Module;
10
+
11
+ using ModuleHook = std::function<void(Module module)>;
12
+ using FunctionHook = std::function<void(StrongFunctionPtr function)>;
13
+
14
+ TORCH_API void didFinishEmitModule(Module module);
15
+ TORCH_API void didFinishEmitFunction(StrongFunctionPtr defined);
16
+ TORCH_API void setEmitHooks(ModuleHook for_module, FunctionHook for_fn);
17
+
18
+ TORCH_API std::pair<ModuleHook, FunctionHook> getEmitHooks();
19
+
20
+ } // namespace torch::jit
21
+
22
+ #else
23
+ #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
24
+ #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)