forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vararg_functions.cpp
428 lines (398 loc) · 12.2 KB
/
vararg_functions.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
#include <torch/csrc/jit/runtime/vararg_functions.h>
#include <ATen/Functions.h>
#include <ATen/Tensor.h>
#include <ATen/core/class_type.h>
#include <c10/util/irange.h>
namespace torch {
namespace jit {
namespace {
static constexpr int defaultPrecision = 6;
// IValue tags are intentionally private, so we need additional logic to cast
// the IValue type to the specified format.
void addFormattedArg(
char key,
const IValue& ival,
std::stringstream& ss,
int precision = defaultPrecision) {
// TODO: Implement precision-based formatting
std::stringstream tmp;
switch (key) {
case 'd':
case 'i':
TORCH_CHECK(
ival.isScalar(),
"%",
key,
" requires a number for formatting, but got ",
ival.tagKind());
if (ival.isInt()) {
ss << ival.toInt();
} else {
ss << static_cast<int>(ival.toDouble());
}
break;
case 'e':
case 'E':
TORCH_CHECK(
ival.isScalar(),
"%",
key,
" requires a number for formatting, but got ",
ival.tagKind());
tmp << std::setprecision(precision) << std::scientific;
if (key == 'E') {
tmp << std::uppercase;
}
if (ival.isInt()) {
tmp << static_cast<float>(ival.toInt());
} else {
tmp << static_cast<float>(ival.toDouble());
}
ss << tmp.str();
break;
case 'f':
case 'F':
TORCH_CHECK(
ival.isScalar(),
"%",
key,
" requires a number for formatting, but got ",
ival.tagKind());
tmp << std::setprecision(precision) << std::fixed;
if (ival.isInt()) {
tmp << static_cast<float>(ival.toInt());
} else {
tmp << static_cast<float>(ival.toDouble());
}
ss << tmp.str();
break;
case 'c':
TORCH_CHECK(
ival.isInt() || (ival.isString() && ival.toStringRef().length() == 1),
"%",
key,
" requires an int or char for formatting, but got ",
ival.tagKind());
if (ival.isInt()) {
ss << static_cast<char>(ival.toInt());
} else {
ss << ival.toStringRef();
}
break;
case 's':
if (ival.isString()) {
ss << ival.toStringRef();
} else {
ss << ival;
}
break;
default:
TORCH_CHECK(
false,
"The specifier %",
key,
" is not supported in TorchScript format strings");
}
}
} // namespace
void tupleUnpack(Stack& stack) {
auto tuple = pop(stack).toTuple();
stack.insert(stack.end(), tuple->elements().begin(), tuple->elements().end());
}
void format(Stack& stack, size_t num_inputs) {
// static const std::regex unsupported_options("\\{(.*?)\\}");
auto format = peek(stack, 0, num_inputs).toStringRef();
// // Temporally comment out the warning message because of
// // "StdRegexIsAwful" internal Lint error, to prevent sev
// // of std::regex from PT mobile.
// if (std::regex_search(format, unsupported_options)) {
// TORCH_WARN("Format options are not supported.");
// }
auto args = last(stack, num_inputs - 1);
std::stringstream ss;
for (size_t begin = 0, used_args = 0; true; ++used_args) {
size_t loc = format.find("{}", begin);
if (loc == std::string::npos) {
ss << format.substr(begin);
break;
}
ss << format.substr(begin, loc - begin);
if (used_args >= args.size()) {
AT_ERROR("Too few arguments for format string: ", format);
}
ss << args[used_args];
begin = loc + 2;
}
drop(stack, num_inputs);
push(stack, ss.str());
}
void einsum(Stack& stack, size_t num_inputs) {
TORCH_CHECK(
num_inputs >= 2,
"einsum(): must specify the equation string and at least one operand, ",
"or at least one operand and its subscripts list");
const auto args = last(stack, num_inputs);
// Convert the subscript list format which is an interleaving of operand and
// its subscripts list with an optional output subscripts list at the end
// (see documentation for more details on this) to the equation string
// format by creating the equation string from the subscripts list and
// grouping the input operands into a tensorlist (List[Tensor]).
std::stringstream ss;
auto parse_sublist = [&ss](const c10::List<int64_t>& l, size_t arg_num) {
for (const auto i : c10::irange(l.size())) {
TORCH_CHECK(
l[i] >= 0 && l[i] < 52,
"einsum(): expected subscript ",
i,
" in argument ",
arg_num,
" to be within the range [0, 52), but got ",
l[i]);
if (l[i] < 26) {
ss << static_cast<char>(l[i] + 'A');
} else {
ss << static_cast<char>(l[i] - 26 + 'a');
}
}
};
// Parse subscripts for input operands
for (auto i = decltype(num_inputs){1}; i < num_inputs; i += 2) {
TORCH_CHECK(
args[i].isIntList(),
"einsum(): expected List[int] in argument ",
i,
", but got ",
args[i].type()->repr_str());
parse_sublist(args[i].toIntList(), i);
if (i + 2 < num_inputs) {
ss << ',';
}
}
// Parse optional output subscripts (provided if #args is odd)
if (num_inputs % 2 == 1) {
TORCH_CHECK(
args.back().isIntList(),
"einsum(): expected List[int] in argument ",
num_inputs - 1,
", but got ",
args.back().type()->repr_str());
ss << "->";
parse_sublist(args.back().toIntList(), num_inputs - 1);
}
const auto equation = ss.str();
std::vector<at::Tensor> operands;
// Parse input operands
const auto end = num_inputs % 2 == 1 ? num_inputs - 1 : num_inputs;
for (auto i = decltype(num_inputs){0}; i < end; i += 2) {
TORCH_CHECK(
args[i].isTensor(),
"einsum(): expected Tensor in argument ",
i,
", but got ",
args[i].type()->repr_str());
operands.emplace_back(args[i].toTensor());
}
drop(stack, num_inputs);
push(stack, at::einsum(equation, operands));
}
void percentFormat(Stack& stack, size_t num_inputs) {
auto format_str = peek(stack, 0, num_inputs).toStringRef();
auto args = last(stack, num_inputs - 1)[0];
size_t args_size = 1; // assumed size
if (args.isTuple()) {
args_size = args.toTupleRef().elements().size();
}
std::stringstream ss;
size_t used_args = 0;
size_t begin = 0;
while (true) {
size_t percent_idx = format_str.find('%', begin);
if (percent_idx == std::string::npos) {
ss << format_str.substr(begin);
break;
}
size_t format_idx = percent_idx + 1;
TORCH_CHECK(
percent_idx < format_str.length() - 1, "Incomplete format specifier");
ss << format_str.substr(begin, percent_idx - begin);
if (format_str.at(format_idx) == '%') {
ss << '%';
begin = percent_idx + 2; // skip the `%` and the format specifier
continue;
}
TORCH_CHECK(used_args < args_size, "Too few arguments for format string");
char key = format_str.at(format_idx);
IValue arg;
if (args.isTuple()) {
arg = args.toTupleRef().elements()[used_args];
} else {
arg = args;
}
addFormattedArg(key, arg, ss);
begin = percent_idx + 2;
++used_args;
}
TORCH_CHECK(used_args == args_size, "Too many arguments for format string");
drop(stack, num_inputs);
push(stack, ss.str());
}
void listUnpack(Stack& stack, size_t num_outputs) {
auto list = pop(stack).toList();
TORCH_CHECK(
list.size() == num_outputs,
"Expected ",
num_outputs,
" elements in a list but found ",
list.size());
stack.insert(stack.end(), list.begin(), list.end());
}
void tupleConstruct(Stack& stack, size_t num_inputs) {
switch (num_inputs) {
case 0:
stack.emplace_back(c10::ivalue::Tuple::create());
break;
case 1:
stack.back() = c10::ivalue::Tuple::create(std::move(stack.back()));
break;
case 2: {
auto tuple = c10::ivalue::Tuple::create(
std::move(stack[stack.size() - 2]),
std::move(stack[stack.size() - 1]));
stack.pop_back();
stack.back() = std::move(tuple);
break;
}
case 3: {
auto tuple = c10::ivalue::Tuple::create(
std::move(stack[stack.size() - 3]),
std::move(stack[stack.size() - 2]),
std::move(stack[stack.size() - 1]));
stack.pop_back();
stack.pop_back();
stack.back() = std::move(tuple);
break;
}
default: {
std::vector<IValue> elems{
std::make_move_iterator(stack.end() - num_inputs),
std::make_move_iterator(stack.end())};
drop(stack, num_inputs - 1);
stack.back() = c10::ivalue::Tuple::create(std::move(elems));
break;
}
}
}
void namedTupleConstruct(
Stack& stack,
c10::TypePtr tuple_type,
size_t num_inputs) {
std::vector<IValue> elems{
std::make_move_iterator(stack.end() - num_inputs),
std::make_move_iterator(stack.end())};
drop(stack, num_inputs);
push(
stack,
c10::ivalue::Tuple::createNamed(std::move(elems), std::move(tuple_type)));
}
void listConstruct(
Stack& stack,
const c10::Type& list_type,
size_t num_inputs) {
// Structuring the implementation this way allows NRVO to avoid
// move-constructing vals on its way onto the stack. Moving a List
// isn't free.
auto makeList =
[](Stack& stack, const c10::Type& list_type, size_t num_inputs) {
c10::List<IValue> vals(list_type.containedType(0));
vals.reserve(num_inputs);
for (size_t i = stack.size() - num_inputs; i < stack.size(); ++i) {
vals.push_back(std::move(stack[i]));
}
drop(stack, num_inputs);
return vals;
};
stack.emplace_back(makeList(stack, list_type, num_inputs));
}
void dictConstruct(
Stack& stack,
const c10::Type& dict_type,
size_t num_inputs) {
auto vals = c10::impl::GenericDict(
dict_type.containedType(0), dict_type.containedType(1));
vals.reserve(num_inputs / 2);
// loop from the bottom of the stack to ensure the dictConstruct preserve
// the inputs order.
auto inputs = last(stack, num_inputs);
for (size_t i = 0; i < num_inputs; i += 2) {
auto key = inputs[i];
auto val = inputs[i + 1];
vals.insert_or_assign(std::move(key), std::move(val));
}
drop(stack, num_inputs);
push(stack, std::move(vals));
}
void createObject(
Stack& stack,
const at::ClassTypePtr& type,
bool as_weak_ref) {
if (as_weak_ref) {
c10::WeakTypePtr weak(type->compilation_unit(), type);
auto userObj = c10::ivalue::Object::create(
c10::WeakOrStrongTypePtr(weak), type->numAttributes());
push(stack, std::move(userObj));
} else {
auto userObj = c10::ivalue::Object::create(
c10::StrongTypePtr(type->compilation_unit(), type),
type->numAttributes());
push(stack, std::move(userObj));
}
}
void isinstance(Stack& stack, at::ArrayRef<at::TypePtr> types) {
at::TypePtr ty = pop(stack).type();
for (const at::TypePtr& candidate : types) {
if (ty->isSubtypeOf(*candidate)) {
push(stack, true);
return;
}
}
push(stack, false);
}
void tupleSlice(Stack& stack, size_t begin, size_t end) {
auto tuple = pop(stack).toTuple();
push(
stack,
c10::ivalue::Tuple::create(
tuple->elements().asArrayRef().slice(begin, end - begin)));
}
void dequantize(Stack& stack) {
auto iv = pop(stack);
if (iv.isTuple()) {
auto tuple = iv.toTuple();
const auto& elems = tuple->elements();
std::vector<IValue> output_elems;
output_elems.reserve(elems.size());
for (const auto& elem : elems) {
if (elem.isTensor()) {
output_elems.emplace_back(at::dequantize(elem.toTensor()));
} else {
output_elems.emplace_back(elem);
}
}
push(stack, c10::ivalue::Tuple::create(std::move(output_elems)));
} else if (iv.isTensorList()) {
auto elems = iv.toTensorList();
auto output_list = c10::impl::GenericList(elems.elementType());
for (auto&& elem : elems) {
output_list.emplace_back(at::dequantize(elem));
}
push(stack, std::move(output_list));
} else {
TORCH_CHECK(
false,
"Unsupported type in dequantize, only List[Tensor] and \
Tuple[Tensor or other types] are supported, got type:",
toString(iv.type()));
}
}
} // namespace jit
} // namespace torch