-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_loop_nnc.cpp
More file actions
372 lines (309 loc) · 12.1 KB
/
simple_loop_nnc.cpp
File metadata and controls
372 lines (309 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
//
// Created by jimyma on 2/3/23.
//
#include <string>
#include "ATen/Context.h"
#include "torch/csrc/jit/tensorexpr/analysis.h"
#include "torch/csrc/jit/tensorexpr/codegen.h"
#include "torch/csrc/jit/tensorexpr/expr.h"
#include "torch/csrc/jit/tensorexpr/ir_simplifier.h"
#include "torch/csrc/jit/tensorexpr/loopnest.h"
#include "tensorexpr/functor_parallization.h"
#include <torch/csrc/jit/tensorexpr/ir.h>
#include <torch/csrc/jit/tensorexpr/types.h>
/*
* Torch Simple Loop Code
// input shape: [torch.Size([1, 255, 10, 10]), torch.Size([1, 255, 20, 20]), torch.Size([1, 255, 40, 40])]
//def forward(self, pred_maps: List[torch.Tensor]):
// featmap_strides = [32, 16, 8]
// num_imgs = pred_maps[0].shape[0]
//
// flatten_preds = []
// flatten_strides = []
// for pred, stride in zip(pred_maps, featmap_strides):
// pred = pred.permute(0, 2, 3, 1).reshape(num_imgs, -1, 85)
// pred[..., :2].sigmoid_()
// flatten_preds.append(pred)
// flatten_strides.append(torch.tensor(stride).expand(pred.size(1)))
// flatten_preds = torch.cat(flatten_preds, dim=1)
// flatten_strides = torch.cat(flatten_strides)
//
// return flatten_preds, flatten_strides
*/
using namespace torch::jit::tensorexpr;
bool verbose = true;
int main() {
// Step 0: Init CUDA Enviroment
at::globalContext().lazyInitCUDA();
// Step 1: Define Compute Functor
// Step 1.0: Define Shape Args
auto N = LongImm::make(1);
auto C = LongImm::make(255);
auto H = VarHandle("dyn_shape_h", kLong);
auto W = VarHandle("dyn_shape_w", kLong);
// Step 1.1: Define Input Tensor Args
BufHandle pred("pred", {N, C, H, W}, kDouble);
VarHandle stride("stride", kLong);
// Step 1.2: Define Compute Op
// permute
Tensor permute_0 = Compute(
"permute_0",
{N, H, W, C},
[&](const std::vector<VarHandle>& axes) {
return pred.load(axes[0], axes[2], axes[3], axes[1]);
});
// reshape
auto reshape_dim_0 = LongImm::make(85);
auto reshape_dim_1 = H * W * C / reshape_dim_0;
Tensor reshape_0 = Compute(
"reshape_0",
{N, reshape_dim_1, reshape_dim_0},
[&](const std::vector<VarHandle>& axes) {
auto flatten = axes[0] * reshape_dim_1 * reshape_dim_0 + axes[1] * reshape_dim_0 + axes[2];
auto dim_c = flatten % C;
auto res_0 = flatten / C;
auto dim_w = res_0 % W;
auto res_1 = res_0 / W;
auto dim_h = res_1 % H;
auto dim_n = res_1 / H;
return permute_0.load(dim_n, dim_h, dim_w, dim_c);
});
// sigmoid
Tensor sigmoid_0 = Compute(
"sigmoid_0",
{N, reshape_dim_1, reshape_dim_0},
[&](const std::vector<VarHandle>& axes) {
return CompareSelect::make(
axes[2],
LongImm::make(2),
sigmoid(reshape_0.load(axes[0], axes[1], axes[2])),
reshape_0.load(axes[0], axes[1], axes[2]),
CompareSelectOperation::kLT);
});
// tensor
Tensor tensor_0 = Compute(
"tensor_0",
{reshape_dim_0, },
[&](const std::vector<VarHandle>& axes) {
return stride;
});
// Step 1.4: Register Output Args
std::unordered_set<BufPtr> bufOutputs;
bufOutputs.insert(sigmoid_0.buf());
bufOutputs.insert(tensor_0.buf());
// Step 1.5: Construct Statement
auto block = alloc<Block>(std::vector<StmtPtr>({}));
block->append_stmt(permute_0.stmt());
block->append_stmt(reshape_0.stmt());
block->append_stmt(sigmoid_0.stmt());
block->append_stmt(tensor_0.stmt());
// Step 2.0: Loop Schedule
LoopNest l(block, bufOutputs);
LoopNest::sanitizeNames(l.root_stmt());
if (verbose) {
std::cout << "Original Functor: " << std::endl;
std::cout << to_string(l.root_stmt()) << std::endl;
}
l.simplify();
if (verbose) {
std::cout << "after simplify: " << std::endl;
std::cout << to_string(l.root_stmt()) << std::endl;
}
// Step 2.1: Compute Inline
l.inlineIntermediateBufs(true);
// l.optimizeConditionals();
auto stmt_ = l.root_stmt();
if (verbose) {
std::cout << "after compute inline: " << std::endl;
std::cout << to_string(stmt_) << std::endl;
}
// Step 2.2: Loop Binding
for (auto buf : bufOutputs) {
std::vector<ForPtr> loops = l.getLoopStmtsFor(buf);
if (loops.empty()) {
// This happens when Buf is 0-dim
continue;
}
ForPtr flattened = nullptr;
LoopNest::flatten(loops, &flattened);
assert(flattened);
int loopLevels = -1;
const int kDefaultLoopLevels = 2;
loopLevels = (loopLevels > 0) ? loopLevels : kDefaultLoopLevels;
int blockCount = -1;
int blockSize = -1;
ForPtr inner;
const int kDefaultBlockSize = 512;
blockSize = (blockSize > 0) ? blockSize : kDefaultBlockSize;
LoopNest::splitWithMask(flattened, blockSize, &inner);
flattened->set_gpu_block_index(0);
inner->set_gpu_thread_index(0);
}
// Step 3: Functor Parallelization
// Step 3.1: Add a New Loop
auto new_loop_axis = VarHandle("new_axis_i", kLong);
stmt_ = alloc<For>(new_loop_axis.node(),
LongImm::make(0).node(),
LongImm::make(3).node(),
stmt_);
static_to<For>(stmt_)->set_gpu_block_index(1);
if (verbose) {
std::cout << "after loop binding: " << std::endl;
std::cout << to_string(stmt_) << std::endl;
}
// Step 3.2: Arguments Replacement
int64_t list_size = 3;
// shapes
std::vector<VarHandle> H_parall_args;
std::vector<VarHandle> W_parall_args;
// inputs
std::vector<BufHandle> pred_parall_args;
std::vector<VarHandle> stride_parall_args;
// outputs
std::vector<BufHandle> sigmoid_parall_args;
std::vector<BufHandle> tensor_parall_args;
sigmoid_parall_args.reserve(list_size);
tensor_parall_args.reserve(list_size);
H_parall_args.reserve(list_size);
H_parall_args.reserve(list_size);
pred_parall_args.reserve(list_size);
stride_parall_args.reserve(list_size);
for (int i = 0; i < list_size; i++) {
auto H_parall_arg = VarHandle("H_" + std::to_string(i), kLong);
auto W_parall_arg = VarHandle("w_" + std::to_string(i), kLong);
H_parall_args.push_back(H_parall_arg);
W_parall_args.push_back(W_parall_arg);
pred_parall_args.push_back({"pred_"+ std::to_string(i), {N, C, H_parall_arg, W_parall_arg}, kDouble});
stride_parall_args.push_back({"stride_" + std::to_string(i), kLong});
auto sigmoid_shape_parall_dim_1 = H_parall_arg * W_parall_arg * C / LongImm::make(85) / 2;
auto sigmoid_shape_parall_dim_0 = LongImm::make(85);
sigmoid_parall_args.push_back({"sigmoid_" + std::to_string(i),
{N, sigmoid_shape_parall_dim_1, sigmoid_shape_parall_dim_0},
kDouble});
tensor_parall_args.push_back({"tensor_" + std::to_string(i),
{LongImm::make(85)},
kLong});
}
stmt_ = FunctorParallization::parallel_functor_load(stmt_, list_size, new_loop_axis.node(),
{
{pred.node(), pred_parall_args}
}, {
{stride.node(), stride_parall_args}
});
stmt_ = FunctorParallization::parallel_functor_store(stmt_, list_size, new_loop_axis.node(),
{
{sigmoid_0.buf(), sigmoid_parall_args},
{tensor_0.buf(), tensor_parall_args}
});
stmt_ = FunctorParallization::parallel_functor_shape(stmt_, list_size, new_loop_axis.node(),
{
{H.node(), H_parall_args},
{W.node(), W_parall_args}
});
l.prepareForCodegen();
l.simplify();
auto stmt = l.root_stmt();
IRSimplifier::simplify(stmt);
if (verbose) {
std::cout << "after loop parallization: " << std::endl;
std::cout << to_string(stmt_) << std::endl;
}
std::vector<CodeGen::BufferArg> bufferArgs_;
bufferArgs_.insert(bufferArgs_.end(),pred_parall_args.begin(), pred_parall_args.end());
bufferArgs_.insert(bufferArgs_.end(),stride_parall_args.begin(), stride_parall_args.end());
bufferArgs_.insert(bufferArgs_.end(),H_parall_args.begin(), H_parall_args.end());
bufferArgs_.insert(bufferArgs_.end(),W_parall_args.begin(), W_parall_args.end());
bufferArgs_.insert(bufferArgs_.end(),sigmoid_parall_args.begin(), sigmoid_parall_args.end());
bufferArgs_.insert(bufferArgs_.end(),tensor_parall_args.begin(), tensor_parall_args.end());
auto codegen_ = CreateCodeGen(
"cuda_codegen",
stmt_,
bufferArgs_,
at::kCUDA);
if (verbose){
std::cout << "codegen text" << std::endl;
std::cout << codegen_->getCodeText() << std::endl;
}
// Runtime
auto N_runtime = 1;
auto C_runtime = 255;
auto H_0_runtime = 10l;
auto H_1_runtime = 20l;
auto H_2_runtime = 40l;
auto W_0_runtime = 10l;
auto W_1_runtime = 20l;
auto W_2_runtime = 40l;
auto pred_0 = at::ones({N_runtime, C_runtime, H_0_runtime, W_0_runtime}).to(at::kDouble).cuda();
auto pred_1 = at::ones({N_runtime, C_runtime, H_1_runtime, W_1_runtime}).to(at::kDouble).cuda();
auto pred_2 = at::ones({N_runtime, C_runtime, H_2_runtime, W_2_runtime}).to(at::kDouble).cuda();
auto stride_0 = 32l;
auto stride_1 = 16l;
auto stride_2 = 8l;
auto sigmoid_dim_0 = 1;
auto sigmoid_dim_1_0 = 300;
auto sigmoid_dim_1_1 = 1200;
auto sigmoid_dim_1_2 = 4800;
auto sigmoid_dim_2 = 85;
auto sigmoid_0_runtime = codegen_->empty_strided(
{sigmoid_dim_0, sigmoid_dim_1_0, sigmoid_dim_2},
{sigmoid_dim_2 * sigmoid_dim_1_0, sigmoid_dim_2, 1},
c10::kDouble,
c10::kStrided,
c10::kCUDA,
false);
auto sigmoid_1_runtime = codegen_->empty_strided(
{sigmoid_dim_0, sigmoid_dim_1_1, sigmoid_dim_2},
{sigmoid_dim_2 * sigmoid_dim_1_1, sigmoid_dim_2, 1},
c10::kDouble,
c10::kStrided,
c10::kCUDA,
false);
auto sigmoid_2_runtime = codegen_->empty_strided(
{sigmoid_dim_0, sigmoid_dim_1_2, sigmoid_dim_2},
{sigmoid_dim_2 * sigmoid_dim_1_2, sigmoid_dim_2, 1},
c10::kDouble,
c10::kStrided,
c10::kCUDA,
false);
auto tensor_0_runtime = codegen_->empty_strided(
{sigmoid_dim_2, },
{1, },
c10::kLong,
c10::kStrided,
c10::kCUDA,
false);
auto tensor_1_runtime = codegen_->empty_strided(
{sigmoid_dim_2, },
{1, },
c10::kLong,
c10::kStrided,
c10::kCUDA,
false);
auto tensor_2_runtime = codegen_->empty_strided(
{sigmoid_dim_2, },
{1, },
c10::kLong,
c10::kStrided,
c10::kCUDA,
false);
std::vector<CodeGen::CallArg> runArgs = {pred_0.data_ptr(), pred_1.data_ptr(), pred_2.data_ptr(),
stride_0, stride_1, stride_2,
H_0_runtime, H_1_runtime, H_2_runtime,
W_0_runtime, W_1_runtime, W_2_runtime,
sigmoid_0_runtime.data_ptr(),
sigmoid_1_runtime.data_ptr(),
sigmoid_2_runtime.data_ptr(),
tensor_0_runtime.data_ptr(),
tensor_1_runtime.data_ptr(),
tensor_2_runtime.data_ptr()};
codegen_->call(runArgs);
// std::cout << sigmoid_0_runtime << std::endl;
// std::cout << sigmoid_1_runtime << std::endl;
// std::cout << sigmoid_2_runtime << std::endl;
//
// std::cout << tensor_0_runtime << std::endl;
// std::cout << tensor_1_runtime << std::endl;
// std::cout << tensor_2_runtime << std::endl;
//
return 0;
}