forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_train_impl.cpp
522 lines (493 loc) · 15.9 KB
/
test_train_impl.cpp
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#include "test/cpp/tensorexpr/test_train.h"
#include "test/cpp/tensorexpr/test_utils.h"
#include "torch/csrc/jit/tensorexpr/eval.h"
#include "torch/csrc/jit/tensorexpr/ir.h"
#include "torch/csrc/jit/tensorexpr/ir_printer.h"
#include "torch/csrc/jit/tensorexpr/loopnest.h"
#include "torch/csrc/jit/tensorexpr/tensor.h"
#include <queue>
#include <set>
std::unordered_map<std::string, VMethod>& getMethodMap() {
static std::unordered_map<std::string, VMethod> methods_;
return methods_;
}
RegMethod::RegMethod(
std::string name,
VMethod::LowerFn lower,
VMethod::GradFn grad,
VMethod::ShapeFn shape,
size_t num_out) {
auto& method = getMethodMap()[name];
method.name = name;
method.num_outputs = num_out;
method.lower = lower;
method.grad = grad;
method.shape = shape;
}
const VMethod& VMethod::get(const std::string& name) {
auto method_iter = getMethodMap().find(name);
TORCH_CHECK(
method_iter != getMethodMap().end(),
std::string("Couldn't find method for ") + name);
auto& method = method_iter->second;
return method;
}
std::vector<VTensor*> call(
const std::string& name,
const std::vector<VTensor*>& vs) {
TORCH_CHECK(vs.size());
auto* graph = vs[0]->graph;
for (const auto& v : vs) {
TORCH_CHECK(
v,
std::string(
"Invalid input, perhaps an invalid index into the inputs of a grad function that calls ") +
name);
TORCH_CHECK(graph == v->graph);
}
const auto& method = VMethod::get(name);
auto op = graph->create_op(name, vs, method.num_outputs);
size_t index = 0;
if (!method.shape) {
std::stringstream ss;
ss << "method \"" << method.name << "\" has no shape function";
TORCH_CHECK(method.shape, ss.str());
}
const auto& shapes = method.shape(vs);
for (auto& output : op->outputs) {
output->shape = shapes[index];
index++;
}
for (auto& v : vs) {
v->consumers.emplace_back(op);
}
return op->outputs;
}
VTensor* grad(VTensor* y, VTensor* x, VTensor* j) {
std::unordered_set<VTensor*> need_grad;
need_grad.insert(y);
std::unordered_set<VTensor*> no_grad;
using Route = std::unordered_set<VTensor*>;
std::queue<std::pair<VTensor*, Route>> q;
// Iterate from X, as most nets work this way
Route init_route;
init_route.insert(x);
q.push(std::make_pair(x, init_route));
// q contains variables that haven't been
// traversed.
while (q.size()) {
// Take a variable and try to find y,
// "staying left" (first dep every time).
//
// |
// v
// dep1 dep2
// \ /
// var
//
// Every time we "stay left," add the other consumers to q
// If we find y -- add the whole route to need_grad
// If we can't find y -- add the whole route to no_grad
VTensor* var;
std::unordered_set<VTensor*> route;
std::tie(var, route) = q.front();
q.pop();
route.insert(var);
while (var) {
if (var == y) {
need_grad.insert(route.begin(), route.end());
break;
}
// add to q
std::vector<VTensor*> next;
for (auto dep : var->consumers) {
auto i = 0;
for (auto inp : dep->inputs) {
if (inp == var) {
for (const auto& out : dep->outputs) {
next.emplace_back(out);
}
}
i++;
}
}
if (!next.size()) {
no_grad.insert(route.begin(), route.end());
break;
}
auto iter = next.begin();
var = *iter;
route.insert(var);
iter++;
while (iter != next.end()) {
q.push(std::make_pair(*iter, route));
iter++;
}
}
}
// Now calculate the gradients
std::unordered_map<VTensor*, VTensor*> grad_map;
// This is the input
grad_map[y] = j;
std::vector<VOp*> frontier{y->op};
std::vector<VOp*> next_frontier;
// This could be way more efficient
std::set<VOp*> seen_ops{y->op};
while (frontier.size()) {
next_frontier.clear();
for (const auto& op : frontier) {
TORCH_CHECK(op, "Invalid operation found!");
std::vector<VTensor*> grad_inputs;
for (const auto& op_out : op->outputs) {
TORCH_CHECK(op_out, "Invalid output");
TORCH_CHECK(need_grad.find(op_out) != need_grad.end());
auto grad_inp_iter = grad_map.find(op_out);
TORCH_CHECK(grad_inp_iter != grad_map.end());
grad_inputs.emplace_back(grad_inp_iter->second);
}
bool run_grad = false;
for (const auto& input : op->inputs) {
if (need_grad.find(input) != need_grad.end()) {
run_grad = true;
break;
}
}
if (run_grad) {
const auto& g = op->method->grad;
if (!g) {
std::stringstream ss;
ss << "no known grad for method \"" << op->method->name << "\"";
TORCH_CHECK(g, ss.str());
}
auto g_outs = g(op->inputs, grad_inputs);
for (auto i = 0U; i < g_outs.size(); ++i) {
auto input = op->inputs[i];
if (need_grad.find(input) != need_grad.end()) {
if (grad_map.find(input) != grad_map.end()) {
grad_map[input] = call("add", {grad_map[input], g_outs[i]})[0];
} else {
grad_map[input] = g_outs[i];
}
if (input->op && seen_ops.find(input->op) == seen_ops.end()) {
next_frontier.emplace_back(input->op);
seen_ops.insert(input->op);
}
}
}
}
}
frontier = next_frontier;
}
TORCH_CHECK(grad_map.find(x) != grad_map.end());
return grad_map[x];
}
VOp::VOp(
const std::string& name,
const std::vector<VTensor*>& inputs_,
size_t num_outputs,
VGraph* graph_)
: inputs(inputs_), graph(graph_) {
method = &VMethod::get(name);
for (auto i = 0U; i < num_outputs; ++i) {
outputs.emplace_back(graph->create_tensor({}));
outputs.back()->op = this;
}
}
using namespace torch::jit::tensorexpr;
std::vector<DimArg> get_vars(
std::vector<std::string> dims,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>& vbindings) {
std::vector<DimArg> vars;
for (auto k : dims) {
vars.emplace_back(vbindings.at(k));
}
if (vars.size() == 0) {
vars.emplace_back(IntImm::make(1));
}
return vars;
}
REGISTER_METHOD(
add,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 2);
TORCH_CHECK(vinputs.at(0)->shape.size() == vinputs.at(1)->shape.size());
auto vars = get_vars(vinputs.at(0)->shape, vbindings);
Tensor* o = Compute("o", vars, [&](const VarHandle& i) {
return inputs.at(0)->call(i) + inputs.at(1)->call(i);
});
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
return {ginputs[0], ginputs[0]};
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> {
return {inputs[0]->shape};
});
REGISTER_METHOD(
sub,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 2);
TORCH_CHECK(vinputs.at(0)->shape.size() == vinputs.at(1)->shape.size());
auto vars = get_vars(vinputs.at(0)->shape, vbindings);
Tensor* o = Compute("o", vars, [&](const VarHandle& i) {
return inputs.at(0)->call(i) - inputs.at(1)->call(i);
});
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
return {ginputs[0], call("neg", {ginputs[0]})[0]};
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> {
return {inputs[0]->shape};
});
REGISTER_METHOD(
neg,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 1);
auto vars = get_vars(vinputs.at(0)->shape, vbindings);
Tensor* o = Compute("o", vars, [&](const VarHandle& i) {
return FloatImm::make(-1.0f) * inputs.at(0)->call(i);
});
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
return call("neg", {ginputs[0]});
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> {
return {inputs[0]->shape};
});
REGISTER_METHOD(
mul,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 2);
TORCH_CHECK(vinputs.at(0)->shape.size() == vinputs.at(1)->shape.size());
auto vars = get_vars(vinputs.at(0)->shape, vbindings);
Tensor* o = Compute("o", vars, [&](const VarHandle& i) {
return inputs.at(0)->call(i) * inputs.at(1)->call(i);
});
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
return {call("mul", {ginputs[0], inputs[1]})[0],
call("mul", {ginputs[0], inputs[0]})[0]};
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> {
return {inputs[0]->shape};
});
REGISTER_METHOD(
div,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 2);
TORCH_CHECK(vinputs.at(0)->shape.size() == vinputs.at(1)->shape.size());
auto vars = get_vars(vinputs.at(0)->shape, vbindings);
Tensor* o = Compute("o", vars, [&](const VarHandle& i) {
return inputs.at(0)->call(i) / inputs.at(1)->call(i);
});
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
auto b_2 = call("mul", {inputs[1], inputs[1]})[0];
auto a_div_b_2 = call("div", {inputs[0], b_2})[0];
return {call("div", {ginputs[0], inputs[1]})[0],
call("mul", {ginputs[0], call("neg", {a_div_b_2})[0]})[0]};
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> {
return {inputs[0]->shape};
});
REGISTER_METHOD(
sum,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 1);
auto vars = get_vars(vinputs.at(0)->shape, vbindings);
Tensor* o = Reduce(
"sum",
{},
Sum(),
[=](const VarHandle& i) -> ExprHandle {
return inputs.at(0)->call(i);
},
vars);
// Tensor* o = Reduce("sum", {}, Sum(), inputs.at(0), vars);
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
return call("broadcast", {ginputs[0], inputs[0]});
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> { return {{}}; });
REGISTER_METHOD(
broadcast,
[](const std::vector<Tensor*>& inputs,
const std::vector<VTensor*>& vinputs,
const std::map<std::string, torch::jit::tensorexpr::VarHandle>&
vbindings) -> std::vector<Tensor*> {
TORCH_CHECK(inputs.size() == 2);
auto vars = get_vars(vinputs.at(1)->shape, vbindings);
Tensor* o = Compute(
"o", vars, [&](const VarHandle& i) { return inputs.at(0)->call(0); });
return {o};
},
[](const std::vector<VTensor*>& inputs,
const std::vector<VTensor*>& ginputs) -> std::vector<VTensor*> {
return call("sum", {ginputs[0]});
},
[](const std::vector<VTensor*>& inputs)
-> std::vector<std::vector<std::string>> {
return {inputs[1]->shape};
});
std::string dot(const VGraph& g) {
std::stringstream ss;
ss << "digraph {\n";
for (const auto& op : g.vops) {
auto name = op.method->name;
auto id = reinterpret_cast<size_t>(&op);
for (const auto& o : op.outputs) {
ss << id << " -> " << reinterpret_cast<size_t>(o) << ";\n";
}
for (const auto& i : op.inputs) {
ss << reinterpret_cast<size_t>(i) << " -> " << id << ";\n";
}
ss << id << "[shape=box;label=" << name << "];\n";
}
ss << "}\n";
return ss.str();
}
std::tuple<
Stmt*,
std::map<const VTensor*, Placeholder>,
std::map<const VTensor*, Tensor*>,
std::map<std::string, VarHandle>>
to_tensorexpr(const VGraph& graph, std::vector<VTensor*> outputs) {
std::map<size_t, std::string> unique_name_map;
auto get_name = [&](size_t id) {
if (!unique_name_map.count(id)) {
std::stringstream ss;
auto k = unique_name_map.size() + 1;
while (k) {
auto n = k % 26;
ss << "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[n - 1];
k /= 26;
}
auto name = ss.str();
unique_name_map[id] = name;
}
return unique_name_map.at(id);
};
auto topo = [](const VGraph& g) {
std::set<const VOp*> nodes;
for (auto& vop : g.vops) {
nodes.insert(&vop);
}
std::set<const VOp*> temp;
std::vector<const VOp*> order;
std::function<void(const VOp*)> visit = [&](const VOp* n) -> void {
if (!nodes.count(n)) {
return;
}
if (temp.count(n)) {
throw std::runtime_error("Cycle in constructed graph");
}
temp.insert(n);
for (auto o : n->outputs) {
for (auto c : o->consumers) {
visit(c);
}
}
temp.erase(n);
nodes.erase(n);
order.emplace(order.begin(), n);
};
while (nodes.size()) {
visit(*nodes.begin());
}
return order;
};
std::map<const VTensor*, Placeholder> inputs;
std::map<const VTensor*, Tensor*> bindings;
std::map<std::string, torch::jit::tensorexpr::VarHandle> vbindings;
for (const auto& t : graph.vtensors) {
auto id = reinterpret_cast<size_t>(&t);
for (auto d : t.shape) {
if (!vbindings.count(d)) {
VarHandle D(d, kInt);
vbindings[d] = D;
}
}
// input
if (!t.op) {
std::vector<DimArg> vars;
std::vector<ExprHandle> exprs;
for (auto k : t.shape) {
vars.emplace_back(vbindings.at(k));
exprs.emplace_back(vbindings.at(k));
}
if (vars.size() == 0) {
vars.emplace_back(IntImm::make(1));
}
Placeholder inpB(BufHandle(get_name(id), exprs, kFloat));
auto inpT =
Compute("input" + get_name(id), vars, [&](const VarHandle& i) {
return Load::make(BufHandle(inpB.data()), {i}, 1);
});
inputs.emplace(&t, inpB);
bindings.emplace(&t, inpT);
}
}
auto order = topo(graph);
for (auto vop : order) {
std::vector<Tensor*> inps;
for (auto i : vop->inputs) {
inps.emplace_back(bindings.at(i));
}
auto outs = vop->method->lower(inps, vop->inputs, vbindings);
TORCH_CHECK(outs.size() == vop->outputs.size());
for (auto i = 0U; i < outs.size(); ++i) {
bindings[vop->outputs[i]] = outs[i];
}
}
std::vector<Tensor*> toutputs;
if (outputs.size() == 0) {
for (auto& vtensor : graph.vtensors) {
if (vtensor.consumers.size() == 0) {
toutputs.emplace_back(bindings.at(&vtensor));
}
}
} else {
for (auto vtensor : outputs) {
toutputs.emplace_back(bindings.at(vtensor));
}
}
LoopNest l(toutputs);
l.prepareForCodegen();
Stmt* s = l.root_stmt();
return std::make_tuple(s, inputs, bindings, vbindings);
}