-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathTHSNN.cpp
More file actions
1073 lines (910 loc) · 37.1 KB
/
THSNN.cpp
File metadata and controls
1073 lines (910 loc) · 37.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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information.
#include "THSNN.h"
#include <torch/nn/init.h>
Tensor THSNN_functional_linear(const Tensor input, const Tensor weights, const Tensor bias)
{
CATCH_TENSOR(bias == nullptr ?
torch::nn::functional::linear(*input, *weights) :
torch::nn::functional::linear(*input, *weights, *bias));
}
Tensor THSNN_functional_bilinear(const Tensor input1, const Tensor input2, const Tensor weights, const Tensor bias)
{
CATCH_TENSOR(bias == nullptr ?
torch::nn::functional::bilinear(*input1, *input2, *weights) :
torch::nn::functional::bilinear(*input1, *input2, *weights, *bias));
}
Tensor THSNN_dropout(const Tensor input, const double p, bool training, bool inplace)
{
auto opts = torch::nn::functional::DropoutFuncOptions()
.inplace(inplace)
.training(training)
.p(p);
CATCH_TENSOR(torch::nn::functional::dropout(*input, opts));
}
Tensor THSNN_dropout2d(const Tensor input, const double p, bool training, bool inplace)
{
auto opts = torch::nn::functional::Dropout2dFuncOptions()
.inplace(inplace)
.training(training)
.p(p);
CATCH_TENSOR(torch::nn::functional::dropout2d(*input, opts));
}
Tensor THSNN_dropout3d(const Tensor input, const double p, bool training, bool inplace)
{
auto opts = torch::nn::functional::Dropout3dFuncOptions()
.inplace(inplace)
.training(training)
.p(p);
CATCH_TENSOR(torch::nn::functional::dropout3d(*input, opts));
}
Tensor THSNN_alpha_dropout(const Tensor input, const double p, bool training, bool inplace)
{
auto opts = torch::nn::functional::AlphaDropoutFuncOptions()
.inplace(inplace)
.training(training)
.p(p);
CATCH_TENSOR(torch::nn::functional::alpha_dropout(*input, opts));
}
Tensor THSNN_feature_alpha_dropout(const Tensor input, const double p, bool training, bool inplace)
{
auto opts = torch::nn::functional::FeatureAlphaDropoutFuncOptions()
.inplace(inplace)
.training(training)
.p(p);
CATCH_TENSOR(torch::nn::functional::feature_alpha_dropout(*input, opts));
}
Tensor THSNN_pixel_shuffle(const Tensor tensor, const int64_t upscale_factor)
{
auto opts = torch::nn::functional::PixelShuffleFuncOptions(upscale_factor);
CATCH_TENSOR(torch::nn::functional::pixel_shuffle(*tensor, opts));
}
Tensor THSNN_pixel_unshuffle(const Tensor tensor, const int64_t downscale_factor)
{
auto opts = torch::nn::functional::PixelUnshuffleFuncOptions(downscale_factor);
CATCH_TENSOR(torch::nn::functional::pixel_unshuffle(*tensor, opts));
}
template<typename T>
void ApplyUpsampleMode(T& opts, const int8_t mode)
{
if (mode == 0)
opts = opts.mode(torch::kNearest);
if (mode == 1)
opts = opts.mode(torch::kLinear);
if (mode == 2)
opts = opts.mode(torch::kBilinear);
if (mode == 3)
opts = opts.mode(torch::kBicubic);
if (mode == 4)
opts = opts.mode(torch::kTrilinear);
}
template<typename T>
void ApplyInterpolateMode(T& opts, const int8_t mode)
{
if (mode == 0)
opts = opts.mode(torch::kNearest);
if (mode == 1)
opts = opts.mode(torch::kLinear);
if (mode == 2)
opts = opts.mode(torch::kBilinear);
if (mode == 3)
opts = opts.mode(torch::kBicubic);
if (mode == 4)
opts = opts.mode(torch::kTrilinear);
if (mode == 5)
opts = opts.mode(torch::kArea);
if (mode == 6)
opts = opts.mode(torch::kNearestExact);
}
template<typename T>
void ApplyPadMode(T& opts, const int64_t padding)
{
if (padding == 1)
opts = opts.mode(torch::kReflect);
if (padding == 2)
opts = opts.mode(torch::kReplicate);
if (padding == 3)
opts = opts.mode(torch::kCircular);
if (padding == 4)
opts = opts.mode(torch::kConstant);
}
template<typename T>
void ApplyGridMode(T& opts, const int8_t mode)
{
if (mode == 0)
opts = opts.mode(torch::kNearest);
if (mode == 2)
opts = opts.mode(torch::kBilinear);
// The PyTorch docs say that bicubic should be supported, but the C++
// mode type does not allow for it. I'm leaving this in for future use.
//if (mode == 3)
// opts = opts.mode(torch::kBicubic);
}
template<typename T>
void ApplyGridPadMode(T& opts, const int64_t padding)
{
if (padding == 0)
opts = opts.padding_mode(torch::kZeros);
if (padding == 1)
opts = opts.padding_mode(torch::kReflection);
if (padding == 2)
opts = opts.padding_mode(torch::kBorder);
}
Tensor THSNN_pad(const Tensor input, const int64_t* pad, const int pad_length, const int8_t mode, const double value)
{
std::vector<int64_t> padding;
for (int i = 0; i < pad_length; ++i) {
padding.push_back(pad[i]);
}
auto opts = torch::nn::functional::PadFuncOptions(padding).value(value);
ApplyPadMode(opts, mode);
CATCH_TENSOR(torch::nn::functional::pad(*input, opts));
}
Tensor THSNN_grid_sample(const Tensor input, const Tensor grid, const int8_t mode, const int8_t padding_mode, const int8_t align_corners)
{
auto opts = torch::nn::functional::GridSampleFuncOptions();
if (align_corners != 0)
opts.align_corners(align_corners == 1);
ApplyGridMode(opts, mode);
ApplyGridPadMode(opts, padding_mode);
CATCH_TENSOR(torch::nn::functional::grid_sample(*input, *grid, opts));
}
Tensor THSNN_affine_grid(const Tensor theta, const int64_t* size, const int size_len, const bool align_corners)
{
CATCH_TENSOR(torch::nn::functional::affine_grid(*theta, at::ArrayRef<int64_t>(size, size_len), align_corners));
}
EXPORT_API(Tensor) THSNN_interpolate(const Tensor input, const int64_t* size, const int size_len, const double* scale_factor, const int scale_factor_len, const int8_t mode, const int8_t align_corners, const bool recompute_scale_factor, const bool antialias)
{
auto opts = torch::nn::functional::InterpolateFuncOptions().recompute_scale_factor(recompute_scale_factor);
// align_corners -- 0=None, 1=true, 2=false
if (align_corners != 0)
opts.align_corners(align_corners == 1);
ApplyInterpolateMode(opts, mode);
opts.antialias(antialias);
if (size_len > 0) {
std::vector<int64_t> sizes;
for (int i = 0; i < size_len; ++i) {
sizes.push_back(size[i]);
}
opts.size(sizes);
}
if (scale_factor_len > 0) {
std::vector<double> scales;
for (int i = 0; i < scale_factor_len; ++i) {
scales.push_back(scale_factor[i]);
}
opts.scale_factor(scales);
}
CATCH_TENSOR(torch::nn::functional::interpolate(*input, opts));
}
NNModule THSNN_Embedding_ctor(const int64_t num_embeddings, const int64_t embedding_dims,
const int64_t padding_idx, bool has_pi, const double max_norm, const bool has_mn, const double norm_type,
const bool scale_grad_by_freq, const bool sparse,
NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::EmbeddingOptions(num_embeddings, embedding_dims)
.norm_type(norm_type)
.scale_grad_by_freq(scale_grad_by_freq)
.sparse(sparse);
if (has_pi)
opts.padding_idx(padding_idx);
if (has_mn)
opts.max_norm(max_norm);
res = create_module<torch::nn::EmbeddingImpl>(opts, outAsAnyModule);
);
}
NNModule THSNN_Embedding_from_pretrained(const Tensor embeddings, const bool freeze,
const int64_t padding_idx, bool has_pi, const double max_norm, const bool has_mn, const double norm_type,
const bool scale_grad_by_freq, const bool sparse,
NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto rows = embeddings->size(0);
auto cols = embeddings->size(1);
auto opts = torch::nn::EmbeddingOptions(rows, cols)
.norm_type(norm_type)
.scale_grad_by_freq(scale_grad_by_freq)
.sparse(sparse);
if (has_pi)
opts.padding_idx(padding_idx);
if (has_mn)
opts.max_norm(max_norm);
// Can't use the template function here -- custom logic.
auto mod = std::make_shared<torch::nn::EmbeddingImpl>(opts);
mod->weight = *embeddings;
mod->weight.set_requires_grad(!freeze);
// Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means
// a Module can only be boxed to AnyModule at the point its static type is known).
if (outAsAnyModule != nullptr)
{
auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<torch::nn::EmbeddingImpl>(*mod));
*outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);
}
res = new std::shared_ptr<torch::nn::Module>(mod);
);
}
Tensor THSNN_Embedding_forward(const NNModule module, const Tensor tensor)
{
CATCH_TENSOR((*module)->as<torch::nn::Embedding>()->forward(*tensor));
}
Tensor THSNN_Embedding_weight(const NNModule module)
{
return get_weight<torch::nn::Embedding>(module);
}
void THSNN_Embedding_set_weight(const NNModule module, const Tensor weights)
{
set_weight<torch::nn::Embedding>(module, weights);
}
template<typename T>
void ApplyEmbeddingBagMode(T& opts, const int64_t mode)
{
if (mode == 0)
opts = opts.mode(torch::kSum);
if (mode == 1)
opts = opts.mode(torch::kMean);
if (mode == 2)
opts = opts.mode(torch::kMax);
}
NNModule THSNN_EmbeddingBag_ctor(const int64_t num_embeddings, const int64_t embedding_dims,
const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq,
const int64_t mode, const bool sparse, const bool include_last_offset, const int64_t padding_idx,
NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::EmbeddingBagOptions(num_embeddings, embedding_dims)
.norm_type(norm_type)
.scale_grad_by_freq(scale_grad_by_freq)
.include_last_offset(include_last_offset)
.sparse(sparse);
ApplyEmbeddingBagMode(opts, mode);
if (has_mn)
opts = opts.max_norm(max_norm);
if (padding_idx >= 0)
opts = opts.padding_idx(padding_idx);
res = create_module<torch::nn::EmbeddingBagImpl>(opts, outAsAnyModule);
);
}
NNModule THSNN_EmbeddingBag_from_pretrained(const Tensor embeddings, const bool freeze,
const double max_norm, const bool has_mn, const double norm_type, const bool scale_grad_by_freq,
const int64_t mode, const bool sparse, const bool include_last_offset, const int64_t padding_idx,
NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto rows = embeddings->size(0);
auto cols = embeddings->size(1);
auto opts = torch::nn::EmbeddingBagOptions(rows, cols)
.norm_type(norm_type)
.scale_grad_by_freq(scale_grad_by_freq)
.include_last_offset(include_last_offset)
.sparse(sparse);
ApplyEmbeddingBagMode(opts, mode);
if (has_mn)
opts.max_norm(max_norm);
if (padding_idx >= 0)
opts = opts.padding_idx(padding_idx);
// Can't use the template function here -- custom logic.
auto mod = std::make_shared<torch::nn::EmbeddingBagImpl>(opts);
mod->weight = *embeddings;
mod->weight.set_requires_grad(!freeze);
// Keep a boxed version of the module in case we add it to a Sequential later (the C++ templating means
// a Module can only be boxed to AnyModule at the point its static type is known).
if (outAsAnyModule != nullptr)
{
auto wrapped = std::make_shared<torch::nn::AnyModule>(torch::nn::ModuleHolder<torch::nn::EmbeddingBagImpl>(*mod));
*outAsAnyModule = new std::shared_ptr<torch::nn::AnyModule>(wrapped);
}
res = new std::shared_ptr<torch::nn::Module>(mod);
);
}
Tensor THSNN_EmbeddingBag_forward(const NNModule module, const Tensor input, const Tensor offsets, const Tensor per_sample_weights)
{
if (offsets != nullptr && per_sample_weights != nullptr)
{
CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input, *offsets, *per_sample_weights));
}
else if (offsets == nullptr && per_sample_weights != nullptr)
{
CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input, {}, *per_sample_weights));
}
else if (offsets != nullptr && per_sample_weights == nullptr)
{
CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input, *offsets));
}
else
{
CATCH_TENSOR((*module)->as<torch::nn::EmbeddingBag>()->forward(*input));
}
}
Tensor THSNN_EmbeddingBag_weight(const NNModule module)
{
return get_weight<torch::nn::EmbeddingBag>(module);
}
void THSNN_EmbeddingBag_set_weight(const NNModule module, const Tensor weights)
{
set_weight<torch::nn::EmbeddingBag>(module, weights);
}
template<typename T>
void ApplyTransformerActivation(T& opts, const int64_t activation)
{
if (activation == 0)
opts = opts.activation(torch::kReLU);
if (activation == 1)
opts = opts.activation(torch::kGELU);
}
template<typename T>
void ApplyRnnActivation(T& opts, const int64_t activation)
{
if (activation == 0)
opts = opts.nonlinearity(torch::kReLU);
if (activation == 1)
opts = opts.nonlinearity(torch::kTanh);
}
NNModule THSNN_Transformer_ctor(const int64_t d_model, const int64_t nhead, const int64_t num_encoder_layers, const int64_t num_decoder_layers, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::TransformerOptions(d_model, nhead)
.num_encoder_layers(num_encoder_layers)
.num_decoder_layers(num_decoder_layers)
.dim_feedforward(dim_feedforward)
.dropout(dropout);
ApplyTransformerActivation(opts, activation);
res = create_module<torch::nn::TransformerImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_Transformer_forward(const NNModule module, const Tensor src, const Tensor tgt, const Tensor src_mask, const Tensor tgt_mask, const Tensor memory_mask, const Tensor src_key_padding_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask)
{
CATCH_TENSOR((*module)->as<torch::nn::Transformer>()->forward(
*src,
*tgt,
(src_mask ? *src_mask : at::Tensor()),
(tgt_mask ? *tgt_mask : at::Tensor()),
(memory_mask ? *memory_mask : at::Tensor()),
(src_key_padding_mask ? *src_key_padding_mask : at::Tensor()),
(tgt_key_padding_mask ? *tgt_key_padding_mask : at::Tensor()),
(memory_key_padding_mask ? *memory_key_padding_mask : at::Tensor()))
);
}
NNModule THSNN_TransformerEncoderLayer_ctor(const int64_t d_model, const int64_t nhead, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::TransformerEncoderLayerOptions(d_model, nhead)
.dim_feedforward(dim_feedforward)
.dropout(dropout);
ApplyTransformerActivation(opts, activation);
res = create_module<torch::nn::TransformerEncoderLayerImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_TransformerEncoderLayer_forward(const NNModule module, const Tensor src, const Tensor src_mask, const Tensor src_key_padding_mask)
{
CATCH_TENSOR((*module)->as<torch::nn::TransformerEncoderLayer>()->forward(
*src,
(src_mask ? *src_mask : at::Tensor()),
(src_key_padding_mask ? *src_key_padding_mask : at::Tensor()))
);
}
NNModule THSNN_TransformerDecoderLayer_ctor(const int64_t d_model, const int64_t nhead, const int64_t dim_feedforward, const double dropout, const int64_t activation, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::TransformerDecoderLayerOptions(d_model, nhead)
.dim_feedforward(dim_feedforward)
.dropout(dropout);
ApplyTransformerActivation(opts, activation);
res = create_module<torch::nn::TransformerDecoderLayerImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_TransformerDecoderLayer_forward(const NNModule module, const Tensor tgt, const Tensor memory, const Tensor tgt_mask, const Tensor memory_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask)
{
CATCH_TENSOR((*module)->as<torch::nn::TransformerDecoderLayer>()->forward(
*tgt,
*memory,
(tgt_mask ? *tgt_mask : at::Tensor()),
(memory_mask ? *memory_mask : at::Tensor()),
(tgt_key_padding_mask ? *tgt_key_padding_mask : at::Tensor()),
(memory_key_padding_mask ? *memory_key_padding_mask : at::Tensor()))
);
}
NNModule THSNN_MultiheadAttention_ctor(const int64_t embeded_dim, const int64_t num_heads, const double dropout, const bool bias, const bool add_bias_kv, const bool add_zero_attn, const int64_t kdim, const int64_t vdim, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::MultiheadAttentionOptions(embeded_dim, num_heads)
.dropout(dropout)
.bias(bias)
.add_bias_kv(add_bias_kv)
.add_zero_attn(add_zero_attn)
.kdim(kdim)
.vdim(vdim);
res = create_module<torch::nn::MultiheadAttentionImpl>(opts, outAsAnyModule);
);
}
void THSNN_MultiheadAttention_forward(const NNModule module, const Tensor query, const Tensor key, const Tensor value, const Tensor key_padding_mask, const bool need_weights, const Tensor attn_mask, Tensor& res1, Tensor& res2)
{
CATCH_TENSORS_2((*module)->as<torch::nn::MultiheadAttention>()->forward(
*query,
*key,
*value,
(key_padding_mask ? *key_padding_mask : at::Tensor()),
need_weights,
(attn_mask ? *attn_mask : at::Tensor()))
);
}
NNModule THSNN_TransformerEncoder_ctor(const NNModule encoder_layer, const int64_t num_layers, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto enc = (*encoder_layer)->as<torch::nn::TransformerEncoderLayer>();
auto opts = torch::nn::TransformerEncoderOptions(torch::nn::TransformerEncoderLayer(*enc), num_layers);
res = create_module<torch::nn::TransformerEncoderImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_TransformerEncoder_forward(const NNModule module, const Tensor src, const Tensor src_mask, const Tensor src_key_padding_mask)
{
CATCH_TENSOR((*module)->as<torch::nn::TransformerEncoder>()->forward(
*src,
(src_mask ? *src_mask : at::Tensor()),
(src_key_padding_mask ? *src_key_padding_mask : at::Tensor()))
);
}
NNModule THSNN_TransformerDecoder_ctor(const NNModule decoder_layer, const int64_t num_layers, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto dec = (*decoder_layer)->as<torch::nn::TransformerDecoderLayer>();
auto opts = torch::nn::TransformerDecoderOptions(torch::nn::TransformerDecoderLayer(*dec), num_layers);
res = create_module<torch::nn::TransformerDecoderImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_TransformerDecoder_forward(const NNModule module, const Tensor tgt, const Tensor memory, const Tensor tgt_mask, const Tensor memory_mask, const Tensor tgt_key_padding_mask, const Tensor memory_key_padding_mask)
{
CATCH_TENSOR((*module)->as<torch::nn::TransformerDecoder>()->forward(
*tgt,
*memory,
(tgt_mask ? *tgt_mask : at::Tensor()),
(memory_mask ? *memory_mask : at::Tensor()),
(tgt_key_padding_mask ? *tgt_key_padding_mask : at::Tensor()),
(memory_key_padding_mask ? *memory_key_padding_mask : at::Tensor()))
);
}
Tensor THSNN_cosine_similarity(const Tensor input1, const Tensor input2, int64_t dim, double eps)
{
CATCH_TENSOR(torch::nn::functional::cosine_similarity(*input1, *input2, torch::nn::functional::CosineSimilarityFuncOptions().dim(dim).eps(eps)));
}
Tensor THSNN_pairwise_distance(const Tensor input1, const Tensor input2, double p, double eps, bool keepdim)
{
CATCH_TENSOR(torch::nn::functional::pairwise_distance(*input1, *input2, torch::nn::functional::PairwiseDistanceFuncOptions().p(p).eps(eps).keepdim(keepdim)));
}
NNModule THSNN_RNN_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const int64_t nonlinearity, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::RNNOptions(input_size, hidden_size)
.num_layers(num_layers)
.bias(bias)
.batch_first(batchFirst)
.dropout(dropout)
.bidirectional(bidirectional);
ApplyRnnActivation(opts, nonlinearity);
res = create_module<torch::nn::RNNImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_RNN_forward(const NNModule module, const Tensor input1, const Tensor input2, Tensor* h_n)
{
Tensor output = nullptr;
*h_n = nullptr;
CATCH(
auto result = (*module)->as<torch::nn::RNN>()->forward(*input1, (input2 ? *input2 : at::Tensor()));
output = new torch::Tensor(std::get<0>(result));
*h_n = new torch::Tensor(std::get<1>(result));
);
return output;
}
PackedSequence THSNN_RNN_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor input2, Tensor* h_n)
{
PackedSequence output = nullptr;
*h_n = nullptr;
CATCH(
auto result = (*module)->as<torch::nn::RNN>()->forward_with_packed_input(*input1, (input2 ? *input2 : at::Tensor()));
output = new torch::nn::utils::rnn::PackedSequence(std::get<0>(result));
*h_n = new torch::Tensor(std::get<1>(result));
);
return output;
}
void THSNN_RNN_flatten_parameters(const NNModule module)
{
CATCH(
(*module)->as<torch::nn::RNN>()->flatten_parameters();
);
}
Tensor THSNN_RNN_bias_ih(const NNModule module, const int64_t idx)
{
return get_bias_ih<torch::nn::RNN>(module, idx);
}
void THSNN_RNN_set_bias_ih(const NNModule module, const Tensor bias, const int64_t idx)
{
set_bias_ih<torch::nn::RNN>(module, bias, idx);
}
Tensor THSNN_RNN_weight_ih(const NNModule module, const int64_t idx)
{
return get_weight_ih<torch::nn::RNN>(module, idx);
}
void THSNN_RNN_set_weight_ih(const NNModule module, const Tensor weight, const int64_t idx)
{
set_weight_ih<torch::nn::RNN>(module, weight, idx);
}
Tensor THSNN_RNN_bias_hh(const NNModule module, const int64_t idx)
{
return get_bias_hh<torch::nn::RNN>(module, idx);
}
void THSNN_RNN_set_bias_hh(const NNModule module, const Tensor bias, const int64_t idx)
{
set_bias_hh<torch::nn::RNN>(module, bias, idx);
}
Tensor THSNN_RNN_weight_hh(const NNModule module, const int64_t idx)
{
return get_weight_hh<torch::nn::RNN>(module, idx);
}
void THSNN_RNN_set_weight_hh(const NNModule module, const Tensor weight, const int64_t idx)
{
set_weight_hh<torch::nn::RNN>(module, weight, idx);
}
NNModule THSNN_GRU_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::GRUOptions(input_size, hidden_size)
.num_layers(num_layers)
.bias(bias)
.batch_first(batchFirst)
.dropout(dropout)
.bidirectional(bidirectional);
res = create_module<torch::nn::GRUImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_GRU_forward(const NNModule module, const Tensor input1, const Tensor input2, Tensor* h_n)
{
Tensor output = nullptr;
*h_n = nullptr;
CATCH(
auto result = (*module)->as<torch::nn::GRU>()->forward(*input1, (input2 ? *input2 : at::Tensor()));
output = new torch::Tensor(std::get<0>(result));
*h_n = new torch::Tensor(std::get<1>(result));
);
return output;
}
PackedSequence THSNN_GRU_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor input2, Tensor* h_n)
{
PackedSequence output = nullptr;
*h_n = nullptr;
CATCH(
auto result = (*module)->as<torch::nn::GRU>()->forward_with_packed_input(*input1, (input2 ? *input2 : at::Tensor()));
output = new torch::nn::utils::rnn::PackedSequence(std::get<0>(result));
*h_n = new torch::Tensor(std::get<1>(result));
);
return output;
}
void THSNN_GRU_flatten_parameters(const NNModule module)
{
CATCH(
(*module)->as<torch::nn::GRU>()->flatten_parameters();
);
}
NNModule THSNN_LSTM_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t num_layers, const bool bias, const bool batchFirst, const double dropout, const bool bidirectional, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::LSTMOptions(input_size, hidden_size)
.num_layers(num_layers)
.bias(bias)
.batch_first(batchFirst)
.dropout(dropout)
.bidirectional(bidirectional);
res = create_module<torch::nn::LSTMImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_LSTM_forward(const NNModule module, const Tensor input1, const Tensor h0, const Tensor c0, Tensor* h_n, Tensor* c_n)
{
const std::tuple<at::Tensor, at::Tensor>& second_arg = (h0 == nullptr || c0 == nullptr) ? std::make_tuple(at::Tensor(), at::Tensor()) : std::make_tuple(*h0, *c0);
Tensor output = nullptr;
*h_n = nullptr;
*c_n = nullptr;
CATCH(
auto result = (*module)->as<torch::nn::LSTM>()->forward(*input1, second_arg);
output = new torch::Tensor(std::get<0>(result));
*h_n = new torch::Tensor(std::get<0>(std::get<1>(result)));
*c_n = new torch::Tensor(std::get<1>(std::get<1>(result)));
);
return output;
}
PackedSequence THSNN_LSTM_forward_with_packed_input(const NNModule module, const PackedSequence input1, const Tensor h0, const Tensor c0, Tensor* h_n, Tensor* c_n)
{
const std::tuple<at::Tensor, at::Tensor>& second_arg = (h0 == nullptr || c0 == nullptr) ? std::make_tuple(at::Tensor(), at::Tensor()) : std::make_tuple(*h0, *c0);
PackedSequence output = nullptr;
*h_n = nullptr;
*c_n = nullptr;
CATCH(
auto result = (*module)->as<torch::nn::LSTM>()->forward_with_packed_input(*input1, second_arg);
output = new torch::nn::utils::rnn::PackedSequence(std::get<0>(result));
*h_n = new torch::Tensor(std::get<0>(std::get<1>(result)));
*c_n = new torch::Tensor(std::get<1>(std::get<1>(result)));
);
return output;
}
void THSNN_LSTM_flatten_parameters(const NNModule module)
{
CATCH(
(*module)->as<torch::nn::LSTM>()->flatten_parameters();
);
}
NNModule THSNN_RNNCell_ctor(const int64_t input_size, const int64_t hidden_size, const int64_t nonlinearity, const bool bias, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::RNNCellOptions(input_size, hidden_size)
.bias(bias);
ApplyRnnActivation(opts, nonlinearity);
res = create_module<torch::nn::RNNCellImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_RNNCell_forward(const NNModule module, const Tensor input1, const Tensor h0)
{
CATCH_TENSOR((*module)->as<torch::nn::RNNCell>()->forward(*input1, (h0 ? *h0 : at::Tensor())));
}
Tensor THSNN_RNNCell_bias_ih(const NNModule module)
{
return get_bias_ih<torch::nn::RNNCell>(module);
}
void THSNN_RNNCell_set_bias_ih(const NNModule module, const Tensor bias)
{
set_bias_ih<torch::nn::RNNCell>(module, bias);
}
Tensor THSNN_RNNCell_weight_ih(const NNModule module)
{
return get_weight_ih<torch::nn::RNNCell>(module);
}
void THSNN_RNNCell_set_weight_ih(const NNModule module, const Tensor weight)
{
set_weight_ih<torch::nn::RNNCell>(module, weight);
}
Tensor THSNN_RNNCell_bias_hh(const NNModule module)
{
return get_bias_hh<torch::nn::RNNCell>(module);
}
void THSNN_RNNCell_set_bias_hh(const NNModule module, const Tensor bias)
{
set_bias_hh<torch::nn::RNNCell>(module, bias);
}
Tensor THSNN_RNNCell_weight_hh(const NNModule module)
{
return get_weight_hh<torch::nn::RNNCell>(module);
}
void THSNN_RNNCell_set_weight_hh(const NNModule module, const Tensor weight)
{
set_weight_hh<torch::nn::RNNCell>(module, weight);
}
NNModule THSNN_GRUCell_ctor(const int64_t input_size, const int64_t hidden_size, const bool bias, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::GRUCellOptions(input_size, hidden_size)
.bias(bias);
res = create_module<torch::nn::GRUCellImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_GRUCell_forward(const NNModule module, const Tensor input1, const Tensor h0)
{
CATCH_TENSOR((*module)->as<torch::nn::GRUCell>()->forward(*input1, (h0 ? *h0 : at::Tensor())));
}
Tensor THSNN_GRUCell_bias_ih(const NNModule module)
{
return get_bias_ih<torch::nn::GRUCell>(module);
}
void THSNN_GRUCell_set_bias_ih(const NNModule module, const Tensor bias)
{
set_bias_ih<torch::nn::GRUCell>(module, bias);
}
Tensor THSNN_GRUCell_weight_ih(const NNModule module)
{
return get_weight_ih<torch::nn::GRUCell>(module);
}
void THSNN_GRUCell_set_weight_ih(const NNModule module, const Tensor weight)
{
set_weight_ih<torch::nn::GRUCell>(module, weight);
}
Tensor THSNN_GRUCell_bias_hh(const NNModule module)
{
return get_bias_hh<torch::nn::GRUCell>(module);
}
void THSNN_GRUCell_set_bias_hh(const NNModule module, const Tensor bias)
{
set_bias_hh<torch::nn::GRUCell>(module, bias);
}
Tensor THSNN_GRUCell_weight_hh(const NNModule module)
{
return get_weight_hh<torch::nn::GRUCell>(module);
}
void THSNN_GRUCell_set_weight_hh(const NNModule module, const Tensor weight)
{
set_weight_hh<torch::nn::GRUCell>(module, weight);
}
NNModule THSNN_LSTMCell_ctor(const int64_t input_size, const int64_t hidden_size, const bool bias, NNAnyModule* outAsAnyModule)
{
CATCH_RETURN_NNModule(
auto opts = torch::nn::LSTMCellOptions(input_size, hidden_size)
.bias(bias);
res = create_module<torch::nn::LSTMCellImpl>(opts, outAsAnyModule);
);
}
Tensor THSNN_LSTMCell_forward(const NNModule module, const Tensor input1, const Tensor h0, const Tensor c0, Tensor* c_n)
{
const std::tuple<at::Tensor, at::Tensor>& second_arg = (h0 == nullptr || c0 == nullptr) ? std::make_tuple(at::Tensor(), at::Tensor()) : std::make_tuple(*h0, *c0);
Tensor output;
CATCH(
auto result = (*module)->as<torch::nn::LSTMCell>()->forward(*input1, second_arg);
output = new torch::Tensor(std::get<0>(result));
*c_n = new torch::Tensor(std::get<1>(result));
);
return output;
}
Tensor THSNN_LSTMCell_bias_ih(const NNModule module)
{
return get_bias_ih<torch::nn::LSTMCell>(module);
}
void THSNN_LSTMCell_set_bias_ih(const NNModule module, const Tensor bias)
{
set_bias_ih<torch::nn::LSTMCell>(module, bias);
}
Tensor THSNN_LSTMCell_weight_ih(const NNModule module)
{
return get_weight_ih<torch::nn::LSTMCell>(module);
}
void THSNN_LSTMCell_set_weight_ih(const NNModule module, const Tensor weight)
{
set_weight_ih<torch::nn::LSTMCell>(module, weight);
}
Tensor THSNN_LSTMCell_bias_hh(const NNModule module)
{
return get_bias_hh<torch::nn::LSTMCell>(module);
}
void THSNN_LSTMCell_set_bias_hh(const NNModule module, const Tensor bias)
{
set_bias_hh<torch::nn::LSTMCell>(module, bias);
}
Tensor THSNN_LSTMCell_weight_hh(const NNModule module)
{
return get_weight_hh<torch::nn::LSTMCell>(module);
}
void THSNN_LSTMCell_set_weight_hh(const NNModule module, const Tensor weight)
{
set_weight_hh<torch::nn::LSTMCell>(module, weight);
}
NNModule THSNN_Sequential_ctor( /* NNAnyModule *submodules, const int length */ )
{
//std::vector<torch::nn::NamedAnyModule> modules;
//for (int i = 0; i < length; i++)
//{
// modules.push_back(*(*submodules[i])->as<torch::nn::NamedAnyModule>());
//}
auto mod = std::make_shared<torch::nn::SequentialImpl>( /* std::begin(modules), std::end(modules) */ );
return new std::shared_ptr<torch::nn::Module>(mod);
}
void THSNN_Sequential_push_back(const NNModule module, const char *name, const NNAnyModule submodule)
{
CATCH (
(*module)->as<torch::nn::Sequential>()->push_back(name, *(*submodule));
)
}
Tensor THSNN_Sequential_forward(const NNModule module, const Tensor tensor)
{
CATCH_TENSOR((*module)->as<torch::nn::Sequential>()->forward(*tensor));
}
Tensor THSNN_one_hot(const Tensor self, const int64_t num_classes)
{
CATCH_RETURN_Tensor(
res = ResultTensor(torch::nn::functional::one_hot(*self, num_classes));
)
}
Tensor THSNN_PackedSequence_data(PackedSequence sequence)
{
CATCH_TENSOR(sequence->data());
}
Tensor THSNN_PackedSequence_batch_sizes(PackedSequence sequence)
{
CATCH_TENSOR(sequence->batch_sizes());
}
Tensor THSNN_PackedSequence_sorted_indices(PackedSequence sequence)
{
CATCH_TENSOR(sequence->sorted_indices());
}
Tensor THSNN_PackedSequence_unsorted_indices(PackedSequence sequence)
{
CATCH_TENSOR(sequence->unsorted_indices());
}
void THSNN_PackedSequence_dispose(PackedSequence sequence)
{
delete sequence;
}
PackedSequence THSNN_pack_padded_sequence(Tensor input, Tensor lengths, bool batch_first, bool enforce_sorted)
{
CATCH_RETURN(
torch::nn::utils::rnn::PackedSequence*,
nullptr,
new torch::nn::utils::rnn::PackedSequence(
torch::nn::utils::rnn::pack_padded_sequence(
*input, *lengths, batch_first, enforce_sorted)));
}
inline static std::tuple<at::Tensor, at::Tensor> pad_packed_sequence_new(
torch::nn::utils::rnn::PackedSequence sequence,
bool batch_first = false,
double padding_value = 0.0,
c10::optional<int64_t> total_length = torch::nullopt) {
int64_t max_seq_length = sequence.batch_sizes().size(0);
if (total_length.has_value()) {
int64_t total_length_val = total_length.value();
TORCH_CHECK(
total_length_val >= max_seq_length,
"Expected total_length to be at least the length "
"of the longest sequence in input, but got "
"total_length=",
total_length_val,
" and max sequence length being ",
max_seq_length);
max_seq_length = total_length_val;
}
at::Tensor padded_output, lengths;
std::tie(padded_output, lengths) = torch::_pad_packed_sequence(
sequence.data(),
sequence.batch_sizes(),