-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathTHSJIT.cpp
More file actions
682 lines (594 loc) · 19.1 KB
/
THSJIT.cpp
File metadata and controls
682 lines (594 loc) · 19.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
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
//// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.
#include "THSJIT.h"
JITModule THSJIT_load(const char* filename, int64_t device, int64_t index)
{
c10::DeviceType dev = c10::kCPU;
if (device == 1)
dev = c10::kCUDA;
if (device == 13)
dev = c10::kMPS;
CATCH(
auto res = torch::jit::load(filename, torch::Device(dev, index));
auto copy = new torch::jit::Module(res);
return new std::shared_ptr<torch::jit::Module>(copy);
);
return nullptr;
}
JITModule THSJIT_load_byte_array(char* bytes, int64_t size, int64_t device, int64_t index)
{
c10::DeviceType dev = c10::kCPU;
if (device == 1)
dev = c10::kCUDA;
if (device == 13)
dev = c10::kMPS;
CATCH(
std::istringstream stream(std::string(bytes, size));
auto res = torch::jit::load(stream, torch::Device(dev, index));
auto copy = new torch::jit::Module(res);
return new std::shared_ptr<torch::jit::Module>(copy);
);
return nullptr;
}
JITCompilationUnit THSJIT_compile(const char* script)
{
CATCH(
auto res = torch::jit::compile(script);
return new std::shared_ptr<torch::jit::CompilationUnit>(res);
);
return nullptr;
}
void THSJIT_save(JITModule module, const char* filename)
{
CATCH(
(*module)->save(filename);
);
}
void THSJIT_save_byte_array(JITModule module, char* bytes, int64_t size)
{
CATCH(
std::ostringstream stream(std::string(bytes, size));
(*module)->save(stream);
);
}
int THSJIT_Module_is_training(JITModule module)
{
return (*module)->is_training();
}
void THSJIT_Module_zero_grad(const JITModule module, bool set_to_none)
{
// According to https://github.com/pytorch/pytorch/issues/27144,
// torch::jit::Module has no zero_grad().
// As a workaround, manually loop over the parameters and zero them out like optimizer does;
// https://github.com/pytorch/pytorch/blob/v2.5.1/torch/csrc/api/src/optim/optimizer.cpp#L123
for (const auto& p : (*module)->parameters()) {
if (p.mutable_grad().defined()) {
p.mutable_grad().detach_();
if (set_to_none)
p.mutable_grad().reset();
else
p.mutable_grad().zero_();
}
}
}
void THSJIT_Module_train(JITModule module, bool on)
{
(*module)->train(on);
}
void THSJIT_Module_eval(JITModule module)
{
(*module)->eval();
}
void THSJIT_Module_to_device_dtype(JITModule module, int8_t dtype, int64_t device, int64_t index)
{
c10::DeviceType dev = c10::kCPU;
if (device == 1)
dev = c10::kCUDA;
if (device == 13)
dev = c10::kMPS;
(*module)->to(torch::Device(dev, index));
}
void THSJIT_Module_to_device(JITModule module, int64_t device, int64_t index)
{
c10::Device dev = (device == 1) ? torch::Device(c10::kCUDA, index) : torch::Device(c10::kCPU);
(*module)->to(dev);
}
void THSJIT_Module_to_dtype(JITModule module, int8_t dtype)
{
(*module)->to((at::ScalarType)dtype);
}
void THSJIT_Module_modules(const JITModule module, JITModule* (*allocator)(size_t length))
{
auto modules = (*module)->modules();
JITModule* result = allocator(modules.size());
int i = 0;
for (const auto& child : modules) {
auto copy = new torch::jit::Module(child);
result[i++] = new std::shared_ptr<torch::jit::Module>(copy);
}
}
void THSJIT_Module_named_modules(const JITModule module,
JITModule* (*allocator1)(size_t length),
const char** (*allocator2)(size_t length))
{
auto modules = (*module)->named_modules();
JITModule* result = allocator1(modules.size());
const char** names = allocator2(modules.size());
int i = 0;
for (const auto& child : modules) {
auto copy = new torch::jit::Module(child.value);
result[i] = new std::shared_ptr<torch::jit::Module>(copy);
names[i] = make_sharable_string(child.name);
i++;
}
}
void THSJIT_Module_named_children(const JITModule module,
JITModule* (*allocator1)(size_t length),
const char** (*allocator2)(size_t length))
{
auto modules = (*module)->named_children();
JITModule* result = allocator1(modules.size());
const char** names = allocator2(modules.size());
int i = 0;
for (const auto& child : modules) {
auto copy = new torch::jit::Module(child.value);
result[i] = new std::shared_ptr<torch::jit::Module>(copy);
names[i] = make_sharable_string(child.name);
i++;
}
}
void THSJIT_Module_parameters(const JITModule module, Tensor* (*allocator)(size_t length))
{
auto parameters = (*module)->parameters();
Tensor* result = allocator(parameters.size());
int i = 0;
for (const auto& child : parameters) {
result[i++] = new torch::Tensor(child);
}
}
void THSJIT_Module_named_parameters(const JITModule module,
Tensor* (*allocator1)(size_t length),
const char** (*allocator2)(size_t length))
{
auto parameters = (*module)->named_parameters();
Tensor* result = allocator1(parameters.size());
const char** names = allocator2(parameters.size());
int i = 0;
for (const auto& child : parameters) {
result[i] = new torch::Tensor(child.value);
names[i] = make_sharable_string(child.name);
i++;
}
}
void THSJIT_Module_named_buffers(const JITModule module,
Tensor* (*allocator1)(size_t length),
const char** (*allocator2)(size_t length))
{
auto parameters = (*module)->named_buffers();
Tensor* result = allocator1(parameters.size());
const char** names = allocator2(parameters.size());
int i = 0;
for (const auto& child : parameters) {
result[i] = new torch::Tensor(child.value);
names[i] = make_sharable_string(child.name);
i++;
}
}
void THSJIT_Module_named_attributes(const JITModule module, bool recurse,
Tensor* (*allocator1)(size_t length),
const char** (*allocator2)(size_t length))
{
auto attributes = (*module)->named_attributes(recurse);
Tensor* result = allocator1(attributes.size());
const char** names = allocator2(attributes.size());
int i = 0;
for (const auto& child : attributes) {
if (!child.name.empty() && child.value.isTensor())
{
auto& t = child.value.toTensor();
result[i] = new torch::Tensor(child.value.toTensor());
names[i] = make_sharable_string(child.name);
i++;
}
}
}
void THSJIT_Module_set_attribute(const JITModule module, const char *name, Tensor tensor)
{
CATCH((*module)->setattr(name, *tensor););
}
JITMethod THSJIT_Module_get_method(const JITModule module, const char* name)
{
auto method = (*module)->get_method(name);
auto copy = new torch::jit::Method(method);
return new std::shared_ptr<torch::jit::Method>(copy);
}
TensorOrScalar* validate(TensorOrScalar* ptr)
{
if (ptr == nullptr)
torch_last_err = strdup("null returned from TorchSharp return value allocator.");
return ptr;
}
TensorOrScalar* ReturnHelper(c10::IValue result, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t* idx)
{
// TypeCode:
//
// 0 -- Not supported
// 1 -- Single tensor
// 2 -- Tuple of tensors
// 3 -- List of tensors
// 4 -- Single scalar
// 5 -- Scalar tuple
// 6 -- List of scalars
// 7 -- List of scalars and tensors
// 8 -- None / null
// 9 -- List of anything
// 10 -- Tuple of anything
if (result.isNone())
{
TensorOrScalar* output = validate(allocator(idx[0]++, 1));
if (output == nullptr) return output;
output[0] = { 8, -1, (ptrdiff_t)0 };
*typeCode = 8;
return output;
}
if (result.isScalar())
{
TensorOrScalar* output = validate(allocator(idx[0]++, 1));
if (output == nullptr) return output;
output[0] = { 0, -1, (ptrdiff_t)new torch::Scalar(result.toScalar()) };
*typeCode = 4;
return output;
}
if (result.isTensor()) {
TensorOrScalar* output = validate(allocator(idx[0]++, 1));
if (output == nullptr) return output;
output[0] = { 0, -1, (ptrdiff_t)ResultTensor(result.toTensor()) };
*typeCode = 1;
return output;
}
if (result.isTensorList()) {
auto list = result.toTensorList();
*typeCode = 3;
TensorOrScalar* output = validate(allocator(idx[0]++, list.size()));
if (output == nullptr) return output;
for (size_t i = 0; i < list.size(); i++)
output[i] = { 0, -1, (ptrdiff_t)ResultTensor(list[i]) };
return output;
}
if (result.isList())
{
int foundTensor = 0;
int foundScalar = 0;
int foundNull = 0;
int foundListOrTuple = 0;
auto list = result.toList();
TensorOrScalar* output = validate(allocator(idx[0]++, list.size()));
if (output == nullptr) return output;
for (int i = 0; i < list.size(); ++i)
{
output[i].Handle = -1;
c10::IValue value = list[i];
if (value.isTensor())
{
output[i] = { 0, -1, (ptrdiff_t)ResultTensor(value.toTensor()) };
foundTensor += 1;
continue;
}
if (value.isScalar())
{
output[i] = { 4, -1, (ptrdiff_t)new torch::Scalar(value.toScalar()) };
foundScalar += 1;
continue;
}
if (value.isNone())
{
output[i] = { 8, -1, (ptrdiff_t)0 };
foundNull += 1;
continue;
}
else {
int8_t nestedTC = 0;
int64_t arrIdx = idx[0];
auto nested = ReturnHelper(value, allocator, &nestedTC, idx);
if (nested == nullptr) return nested;
foundListOrTuple += 1;
output[i] = { nestedTC, arrIdx, (ptrdiff_t)nested };
}
}
if (foundListOrTuple > 0) {
*typeCode = 9;
}
else {
*typeCode = 7;
if (foundScalar == 0 && foundNull == 0)
*typeCode = 3;
if (foundTensor == 0 && foundNull == 0)
*typeCode = 6;
}
return output;
}
if (result.isTuple()) {
int foundTensor = 0;
int foundScalar = 0;
int foundNull = 0;
int foundListOrTuple = 0;
auto& list = result.toTuple()->elements();
TensorOrScalar* output = validate(allocator(idx[0]++, list.size()));
if (output == nullptr) return output;
for (int i = 0; i < list.size(); ++i)
{
output[i].Handle = -1;
c10::IValue value = list[i];
if (value.isTensor())
{
output[i] = { 0, -1, (ptrdiff_t)ResultTensor(value.toTensor()) };
foundTensor += 1;
continue;
}
if (value.isScalar())
{
output[i] = { 4, -1, (ptrdiff_t)new torch::Scalar(value.toScalar()) };
foundScalar += 1;
continue;
}
if (value.isNone())
{
output[i] = { 8, -1, (ptrdiff_t)0 };
foundNull += 1;
continue;
}
else {
int8_t nestedTC = 0;
int64_t arrIdx = idx[0];
auto nested = ReturnHelper(value, allocator, &nestedTC, idx);
if (nested == nullptr) return nested;
foundListOrTuple += 1;
output[i] = { nestedTC, arrIdx, (ptrdiff_t)nested };
}
}
*typeCode = 10;
if (foundListOrTuple == 0) {
if (foundScalar == 0 && foundNull == 0)
*typeCode = 2;
if (foundTensor == 0 && foundNull == 0)
*typeCode = 5;
}
return output;
}
*typeCode = 0;
return nullptr;
}
c10::impl::GenericList toScalarValueList(const TensorOrScalar* tensorPtrs, const int length)
{
auto list = c10::impl::GenericList(c10::ScalarTypeType::get());
if (tensorPtrs != nullptr) {
for (int i = 0; i < length; i++)
{
switch (tensorPtrs[i].TypeCode) {
case 1:
list.push_back(*(torch::Scalar*)(tensorPtrs[i].Handle));
break;
}
}
}
return list;
}
c10::impl::GenericList toTensorValueList(const TensorOrScalar* tensorPtrs, const int length)
{
auto list = c10::impl::GenericList(c10::TensorType::get());
if (tensorPtrs != nullptr) {
for (int i = 0; i < length; i++)
{
switch (tensorPtrs[i].TypeCode) {
case 0:
list.push_back(*(torch::Tensor*)(tensorPtrs[i].Handle));
break;
}
}
}
return list;
}
std::vector<c10::IValue> toIValue(const TensorOrScalar* tensorPtrs, const int length)
{
// TypeCode:
//
// 0 -- Single tensor
// 1 -- Single scalar
// 2 -- Boolean
// 3 -- Int32
// 5 -- List of tensors
// 6 -- List of scalars
// 8 -- None / null
std::vector<c10::IValue> tensors;
if (tensorPtrs != nullptr) {
for (int i = 0; i < length; i++)
{
switch (tensorPtrs[i].TypeCode) {
case 0:
tensors.push_back(*(torch::Tensor*)(tensorPtrs[i].Handle));
break;
case 1:
tensors.push_back(*(torch::Scalar*)(tensorPtrs[i].Handle));
break;
case 2:
tensors.push_back(tensorPtrs[i].Handle != 0);
break;
case 3:
tensors.push_back((int)tensorPtrs[i].Handle);
break;
case 5:
{
auto ts = toTensorValueList(reinterpret_cast<const TensorOrScalar*>(tensorPtrs[i].Handle), (int)tensorPtrs[i].ArrayIndex);
tensors.push_back(ts);
break;
}
case 6:
{
auto ts = toScalarValueList(reinterpret_cast<const TensorOrScalar*>(tensorPtrs[i].Handle), (int)tensorPtrs[i].ArrayIndex);
tensors.push_back(ts);
break;
}
//case 4:
// tensors.push_back(c10::IValue(tensorPtrs[i].Handle)); // Clang on MacOS doesn't like. Pass as Scalar from .NET.
// break;
case 8:
tensors.push_back(c10::nullopt);
break;
}
}
}
return tensors;
}
void THSJIT_Module_forward(const JITModule module, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx)
{
*typeCode = 0;
CATCH(
auto result = (*module)->forward(toIValue(tensorPtrs, length));
ReturnHelper(result, allocator, typeCode, &idx);
)
}
void THSJIT_Module_invoke(const JITModule module, const char* name, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx)
{
*typeCode = 0;
CATCH(
auto method = (*module)->get_method(name);
auto result = method(toIValue(tensorPtrs, length));
ReturnHelper(result, allocator, typeCode, &idx);
)
}
void THSJIT_CompilationUnit_Invoke(const JITCompilationUnit module, const char* method, const TensorOrScalar* tensorPtrs, const int length, TensorOrScalar* (*allocator)(int32_t idx, size_t length), int8_t* typeCode, int32_t idx)
{
*typeCode = 0;
CATCH(
auto args = toIValue(tensorPtrs, length);
auto func = (*module)->find_function(method);
auto result = (*func)(args);
ReturnHelper(result, allocator, typeCode, &idx);
)
}
void THSJIT_Module_dispose(const JITModule module)
{
delete module;
}
const char* THSJIT_Method_name(const JITMethod method)
{
return make_sharable_string((*method)->name());
}
int THSJIT_Method_num_inputs(const JITMethod method)
{
return (int)(*method)->num_inputs();
}
int THSJIT_Module_num_inputs(const JITModule module)
{
return (int)(*module)->get_method("forward").num_inputs() - 1; // Don't count the 'self' argument.
}
int THSJIT_Module_num_outputs(const JITModule module)
{
return (int)(*module)->get_method("forward").function().getSchema().returns().size();
}
JITFunction THSJIT_Method_function(const JITMethod method)
{
return new std::shared_ptr<torch::jit::Function>(&(*method)->function());
}
void THSJIT_Method_dispose(const JITMethod method)
{
delete method;
}
//-------------------------------------------------------------------------------------
// JITFunction
int THSJIT_Function_num_inputs(const JITFunction function)
{
return (int)(*function)->num_inputs();
}
// TODO other function operations
void THSJIT_Function_dispose(const JITFunction function)
{
delete function;
}
void THSJIT_Type_dispose(const JITType type)
{
delete type;
}
void THSJIT_TensorType_dispose(const JITTensorType type)
{
delete type;
}
void THSJIT_CompilationUnit_dispose(const JITCompilationUnit module)
{
delete module;
}
void* THSJIT_Type_cast(const JITType type)
{
switch ((*type)->kind())
{
case c10::TypeKind::TensorType:
return new std::shared_ptr<torch::jit::TensorType>((*type)->cast<c10::TensorType>());
default:
return nullptr;
}
}
int8_t THSJIT_TensorType_dtype(const JITTensorType type)
{
auto scT = (*type)->scalarType();
if (scT.has_value()) {
return (int8_t)scT.value();
}
else {
return -1;
}
}
void THSJIT_TensorType_sizes(const JITTensorType type, int64_t* (*allocator)(size_t length))
{
//CATCH(
auto& t = *type;
auto dim = t->dim();
auto res = (*type)->sizes().concrete_sizes();
if (res.has_value()) {
const size_t sz = res.value().size();
auto& vec = res.value();
int64_t* result = allocator(sz);
for (size_t i = 0; i < sz; i++)
result[i] = vec[i];
}
//);
}
int8_t THSJIT_Type_kind(const JITType type)
{
switch ((*type)->kind())
{
case c10::TypeKind::TensorType:
return (int8_t)TypeKind::TensorType;
default:
return -1;
}
}
JITType THSJIT_Module_getInputType(JITModule module, int8_t index)
{
auto typ = (*module)->type();
c10::TypeKind kind = typ->kind();
auto& schema = typ->getMethod("forward").getSchema();
return new std::shared_ptr<c10::Type>(schema.arguments()[1 + index].type()->cast<c10::TensorType>());
}
void THSJIT_typeDispose(const JITType type)
{
delete type;
}
TensorOrScalar* THSJIT_AllocateTensorOrScalarArray(int32_t size)
{
auto result = new TensorOrScalar[size];
memset(result, 0, size * sizeof(TensorOrScalar));
return result;
}
void THSJIT_FreeTensorOrScalarArray(TensorOrScalar* ptr)
{
delete ptr;
}
void THSJIT_SetTensorOrScalar(TensorOrScalar* array, int32_t index, int64_t type_code, int64_t array_index, ptrdiff_t handle)
{
array[index].TypeCode = type_code;
array[index].ArrayIndex = array_index;
array[index].Handle = handle;
}
TensorOrScalar* THSJIT_GetTensorOrScalar(TensorOrScalar* array, int32_t index)
{
return array + index;
}