forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRNN.cpp
1961 lines (1777 loc) · 86.4 KB
/
RNN.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
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
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include <ATen/native/RNN.h>
#include <ATen/core/Tensor.h>
#include <ATen/core/List.h>
#include <ATen/Context.h>
#include <ATen/TensorOperators.h>
#include <ATen/mps/MPSDevice.h>
#include <ATen/native/quantized/PackedParams.h>
#include <ATen/native/quantized/cpu/fbgemm_utils.h>
#include <ATen/native/quantized/cpu/QnnpackUtils.h>
#include <c10/core/GradMode.h>
#include <c10/macros/Macros.h>
#include <c10/util/irange.h>
#include <torch/custom_class.h>
#include <torch/library.h>
#include <ATen/Config.h>
#if AT_MKLDNN_ENABLED()
#include <ATen/native/mkldnn/Utils.h>
#endif
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#include <ATen/NativeFunctions.h>
#else
#include <ATen/ops/_lstm_mps.h>
#include <ATen/ops/_thnn_differentiable_gru_cell_backward_native.h>
#include <ATen/ops/_thnn_differentiable_lstm_cell_backward_native.h>
#include <ATen/ops/_thnn_fused_gru_cell.h>
#include <ATen/ops/_thnn_fused_lstm_cell.h>
#include <ATen/ops/_thnn_fused_lstm_cell_backward.h>
#include <ATen/ops/_thnn_fused_lstm_cell_backward_impl.h>
#include <ATen/ops/_thnn_fused_lstm_cell_backward_native.h>
#include <ATen/ops/_use_cudnn_rnn_flatten_weight_native.h>
#include <ATen/ops/cat.h>
#include <ATen/ops/cudnn_is_acceptable.h>
#include <ATen/ops/dropout.h>
#include <ATen/ops/fbgemm_linear_int8_weight_fp32_activation.h>
#include <ATen/ops/fbgemm_linear_quantize_weight_native.h>
#include <ATen/ops/fbgemm_pack_quantized_matrix_native.h>
#include <ATen/ops/gru_cell_native.h>
#include <ATen/ops/gru_native.h>
#include <ATen/ops/linear.h>
#include <ATen/ops/lstm_cell_native.h>
#include <ATen/ops/lstm_native.h>
#include <ATen/ops/matmul.h>
#include <ATen/ops/quantized_gru_cell_native.h>
#include <ATen/ops/quantized_lstm_cell_native.h>
#include <ATen/ops/quantized_rnn_relu_cell_native.h>
#include <ATen/ops/quantized_rnn_tanh_cell_native.h>
#include <ATen/ops/relu.h>
#include <ATen/ops/rnn_relu_cell_native.h>
#include <ATen/ops/rnn_relu_native.h>
#include <ATen/ops/rnn_tanh_cell_native.h>
#include <ATen/ops/rnn_tanh_native.h>
#include <ATen/ops/sigmoid_backward.h>
#include <ATen/ops/stack.h>
#include <ATen/ops/tanh.h>
#include <ATen/ops/tanh_backward.h>
#include <ATen/ops/zeros_like.h>
#include <ATen/ops/zeros_like_ops.h>
#include <utility>
#endif
int register_linear_params();
namespace at::native {
namespace {
// Check if pytorch is compiled with MIOpen.
bool use_miopen(const at::Tensor& input, const double dropout_state) {
bool is_miopen_acceptable = ((input.scalar_type() == at::kFloat)|| (input.scalar_type() == at::kHalf)) &&
(detail::getCUDAHooks().compiledWithMIOpen()) &&
(input.is_cuda()) &&
(at::globalContext().userEnabledCuDNN());
// MIOpen functions returns miopenStatusBadParm on empty
// tensors. Maybe some functions actually support empty tensors, but
// native kernels shouldn't be much slower because the output is also
// likely empty.
if (input.sym_numel() == 0) return false;
return is_miopen_acceptable;
}
bool use_mkldnn(const Tensor& input, TensorList params, TensorList hx) {
#if AT_MKLDNN_ENABLED()
if (!at::globalContext().userEnabledMkldnn()) {
return false;
}
auto is_cpu_backend = [&](const TensorList tensors) {
bool backend_cpu = true;
for (const auto& t : tensors) {
if (!(t.options().backend() == at::Backend::CPU)) {
backend_cpu = false;
break;
}
}
return backend_cpu;
};
return input.options().backend() == at::Backend::CPU &&
is_cpu_backend(params) && is_cpu_backend(hx) &&
(input.scalar_type() == kFloat ||
(input.scalar_type() == kBFloat16 && mkldnn_bf16_device_check()) ||
(input.scalar_type() == kHalf && !at::GradMode::is_enabled() &&
mkldnn_fp16_device_check())) &&
input.numel() != 0;
#endif
return false;
}
template<typename T>
using pair_of = std::pair<T, T>;
template<typename T>
using tpair_of = std::tuple<T, T>;
// Those could have been function pointers, but MSVC chokes on function pointers as template parameters
struct tanh_f {
Tensor operator()(const Tensor& t) const { return at::tanh(t); }
};
struct relu_f {
Tensor operator()(const Tensor& t) const { return at::relu(t); }
};
struct PackedSequence {
PackedSequence() = default;
PackedSequence(Tensor _data, Tensor _batch_sizes)
: data(std::move(_data)), batch_sizes(std::move(_batch_sizes)) {}
Tensor data;
Tensor batch_sizes;
};
// Simple type for __getstate__/__setstate__ serialization
//
// Element 0 is a string key to say what kind of CellParam this is. It
// should be a valid key into cell_params_deserializers
// Element 1 is the Tensors contained within the CellParams instance
// Element 2 is the doubles (if any) contained in the CellParams instance
// Element 3 is the longs (if any) contained within the CellParams instance
using CellParamsSerializationType = std::tuple<
std::string,
std::vector<at::Tensor>,
std::vector<double>,
std::vector<int64_t>,
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>>>;
// Base class so we can polymorphically handle these
struct CellParamsBase : torch::CustomClassHolder {
virtual Tensor matmul_ih(const Tensor& input) const = 0;
virtual Tensor matmul_hh(const Tensor& h) const = 0;
// by default doing nothing. CellParams will override this
// to define correct behavior for LSTMs with projections.
// This function is not pure virtual, because it's useful to
// provide this default implementation, so that all cell params
// that don't support projections work correctly (e.g. QuantizedCellParams variations)
virtual Tensor matmul_hr(const Tensor& h) const {
return h;
}
virtual Tensor linear_ih(const Tensor& input_ih) const = 0;
virtual Tensor linear_hh(const Tensor& input_hh) const = 0;
virtual const Tensor& b_ih() const = 0;
virtual const Tensor& b_hh() const = 0;
virtual CellParamsSerializationType __getstate__() const = 0;
};
// Pretty much all cells we support take the same set of arguments, but threading those
// 4 arguments manually is really annoying. Their lifetime is externally managed, so we only
// pass this struct of references around. LSTMs with projections have 5th argument w_hr, for all
// other models it's always going to be undefined.
struct CellParams : public CellParamsBase {
CellParams(
const Tensor& _w_ih,
const Tensor& _w_hh,
const Tensor& _b_ih,
const Tensor& _b_hh,
const Tensor& _w_hr)
: w_ih(_w_ih), w_hh(_w_hh), b_ih_(_b_ih), b_hh_(_b_hh), w_hr(_w_hr) {}
const Tensor& w_ih;
const Tensor& w_hh;
const Tensor& b_ih_; /* optional */
const Tensor& b_hh_; /* optional */
const Tensor& w_hr; /* only defined for LSTMs with projections */
Tensor matmul_ih(const Tensor& input) const override {
return at::matmul(input, w_ih.t());
}
Tensor matmul_hh(const Tensor& h) const override {
return at::matmul(h, w_hh.t());
}
Tensor matmul_hr(const Tensor& h) const override {
if (w_hr.defined()) {
return at::matmul(h, w_hr.t());
}
return h;
}
Tensor linear_ih(const Tensor& input) const override {
return at::linear(input, w_ih, b_ih_);
}
Tensor linear_hh(const Tensor& h) const override {
return at::linear(h, w_hh, b_hh_);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
TORCH_INTERNAL_ASSERT(false, "Not yet implemented");
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
const CellParamsSerializationType& state) {
TORCH_INTERNAL_ASSERT(false, "Not yet implemented");
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params(
const at::Tensor& w_ih,
const at::Tensor& w_hh,
at::Tensor bias_ih,
at::Tensor bias_hh);
struct QuantizedCellParams : public CellParamsBase {
QuantizedCellParams(
Tensor _w_ih,
Tensor _w_hh,
Tensor _b_ih,
Tensor _b_hh,
Tensor _packed_ih,
Tensor _packed_hh,
Tensor _col_offsets_ih,
Tensor _col_offsets_hh,
Scalar _scale_ih,
Scalar _scale_hh,
Scalar _zero_point_ih,
Scalar _zero_point_hh)
: w_ih(std::move(_w_ih)),
w_hh(std::move(_w_hh)),
b_ih_(std::move(_b_ih)),
b_hh_(std::move(_b_hh)),
packed_ih(std::move(_packed_ih)),
packed_hh(std::move(_packed_hh)),
col_offsets_ih(std::move(_col_offsets_ih)),
col_offsets_hh(std::move(_col_offsets_hh)),
scale_ih(std::move(_scale_ih)),
scale_hh(std::move(_scale_hh)),
zero_point_ih(std::move(_zero_point_ih)),
zero_point_hh(std::move(_zero_point_hh)) {}
const Tensor w_ih;
const Tensor w_hh;
const Tensor b_ih_;
const Tensor b_hh_;
const Tensor packed_ih;
const Tensor packed_hh;
const Tensor col_offsets_ih;
const Tensor col_offsets_hh;
const Scalar scale_ih;
const Scalar scale_hh;
const Scalar zero_point_ih;
const Scalar zero_point_hh;
Tensor matmul_ih(const Tensor& input) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor matmul_hh(const Tensor& h) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor linear_ih(const Tensor& input) const override {
return at::fbgemm_linear_int8_weight_fp32_activation(
input, w_ih, packed_ih, col_offsets_ih, scale_ih, zero_point_ih, b_ih_);
}
Tensor linear_hh(const Tensor& h) const override {
return at::fbgemm_linear_int8_weight_fp32_activation(
h, w_hh, packed_hh, col_offsets_hh, scale_hh, zero_point_hh, b_hh_);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
std::vector<at::Tensor> tensors_to_serialize = {
w_ih, w_hh, b_ih_, b_hh_, col_offsets_ih, col_offsets_hh};
std::vector<double> doubles_to_serialize = {scale_ih.toDouble(),
scale_hh.toDouble()};
std::vector<int64_t> longs_to_serialize = {zero_point_ih.toLong(),
zero_point_hh.toLong()};
return CellParamsSerializationType(
"quantized",
tensors_to_serialize,
doubles_to_serialize,
longs_to_serialize,
{});
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
auto [_, tensors, doubles, longs, __] =
std::move(state);
TORCH_INTERNAL_ASSERT(tensors.size() == 6);
TORCH_INTERNAL_ASSERT(doubles.size() == 2);
TORCH_INTERNAL_ASSERT(longs.size() == 2);
at::Tensor qw_ih = std::move(tensors[0]), qw_hh = std::move(tensors[1]),
b_ih = std::move(tensors[2]), b_hh = std::move(tensors[3]),
col_offsets_ih = std::move(tensors[4]),
col_offsets_hh = std::move(tensors[5]);
double scale_ih = doubles[0], scale_hh = doubles[1];
int64_t zero_point_ih = longs[0], zero_point_hh = longs[1];
at::Tensor packed_ih = at::native::fbgemm_pack_quantized_matrix(qw_ih);
at::Tensor packed_hh = at::native::fbgemm_pack_quantized_matrix(qw_hh);
return c10::make_intrusive<QuantizedCellParams>(
/*w_ih=*/std::move(qw_ih),
/*w_hh=*/std::move(qw_hh),
/*b_ih_=*/std::move(b_ih),
/*b_hh_=*/std::move(b_hh),
/*packed_ih=*/std::move(packed_ih),
/*packed_hh=*/std::move(packed_hh),
/*col_offsets_ih=*/std::move(col_offsets_ih),
/*col_offsets_hh=*/std::move(col_offsets_hh),
/*scale_ih=*/scale_ih,
/*scale_hh=*/scale_hh,
/*zero_point_ih=*/zero_point_ih,
/*zero_point_hh=*/zero_point_hh);
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params(
const at::Tensor& w_ih,
const at::Tensor& w_hh,
at::Tensor b_ih,
at::Tensor b_hh) {
auto make_vals = [&](const at::Tensor& W) {
auto params = at::native::fbgemm_linear_quantize_weight(W);
at::Tensor packed_weight =
at::native::fbgemm_pack_quantized_matrix(std::get<0>(params));
return std::tuple_cat(
std::make_tuple(std::move(packed_weight)), std::move(params));
};
auto [packed_ih, qw_ih, col_offsets_ih, scale_ih, zero_point_ih] =
make_vals(w_ih);
auto [packed_hh, qw_hh, col_offsets_hh, scale_hh, zero_point_hh] =
make_vals(w_hh);
return c10::make_intrusive<QuantizedCellParams>(
/*qw_ih=*/std::move(qw_ih),
/*qw_hh=*/std::move(qw_hh),
/*b_ih=*/std::move(b_ih),
/*b_hh=*/std::move(b_hh),
/*packed_ih=*/std::move(packed_ih),
/*packed_hh=*/std::move(packed_hh),
/*col_offsets_ih=*/std::move(col_offsets_ih),
/*col_offsets_hh=*/std::move(col_offsets_hh),
/*scale_ih=*/scale_ih,
/*scale_hh=*/scale_hh,
/*zero_point_ih=*/zero_point_ih,
/*zero_point_hh=*/zero_point_hh);
}
// QuantizedCellParams vs. QuantizedCellParamsDynamic
//
// QuantizedCellParams uses the legacy
// fbgemm_linear_int8_weight_fp32_activation API, which requires the explicit
// scale and zero point parameters for the weight. QuantizedCellParamsDynamic
// uses the new fbgemm_linear_dynamic API, which doesn't require the explicit
// scale and zero point parameters. These quantization parameters are
// encapsulated in the `PackedLinearWeight` struct in
// aten/src/ATen/native/quantized/cpu/fbgemm_utils.h.
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_dynamic(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed,
at::Tensor bias_ih,
at::Tensor bias_hh,
bool reduce_range);
struct QuantizedCellParamsDynamic : public CellParamsBase {
QuantizedCellParamsDynamic(
c10::intrusive_ptr<LinearPackedParamsBase>
_packed_w_ih, /* Prepacked Weight Tensor */
c10::intrusive_ptr<LinearPackedParamsBase>
_packed_w_hh, /* Prepacked Weight Tensor */
Tensor _b_ih, /* float Bias Tensor */
Tensor _b_hh, /* float Bias Tensor */
bool _reduce_range = false /* Use reduced range for activation tensors */)
: packed_w_ih(std::move(_packed_w_ih)),
packed_w_hh(std::move(_packed_w_hh)),
b_ih_(std::move(_b_ih)),
b_hh_(std::move(_b_hh)),
reduce_range_(_reduce_range) {}
c10::intrusive_ptr<LinearPackedParamsBase> packed_w_ih;
c10::intrusive_ptr<LinearPackedParamsBase> packed_w_hh;
const Tensor b_ih_;
const Tensor b_hh_;
bool reduce_range_;
Tensor matmul_ih(const Tensor& input) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor matmul_hh(const Tensor& h) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor linear_ih(const Tensor& input_ih) const override {
return packed_w_ih->apply_dynamic(input_ih, reduce_range_);
}
Tensor linear_hh(const Tensor& input_hh) const override {
return packed_w_hh->apply_dynamic(input_hh, reduce_range_);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
std::vector<at::Tensor> tensors_to_serialize{
/*b_ih=*/b_ih_,
/*b_hh=*/b_hh_,
};
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>>
packed_params_to_serialize{packed_w_ih, packed_w_hh};
// reduce_range parameter is serialized along with the int field values.
return CellParamsSerializationType(
"quantized_dynamic",
tensors_to_serialize,
{},
{reduce_range_},
packed_params_to_serialize);
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
auto [_, tensors, __, serialized_ints, packed_params] =
std::move(state);
TORCH_INTERNAL_ASSERT(tensors.size() == 2);
TORCH_INTERNAL_ASSERT(packed_params.size() == 2);
bool reduce_range = serialized_ints.empty() ? false : serialized_ints[0];
return make_quantized_cell_params_dynamic(
/*w_ih_packed=*/std::move(packed_params[0]),
/*w_hh_packed=*/std::move(packed_params[1]),
/*bias_ih=*/std::move(tensors[0]),
/*bias_hh=*/std::move(tensors[1]),
/*reduce_range=*/reduce_range);
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_dynamic(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed,
at::Tensor bias_ih,
at::Tensor bias_hh,
bool reduce_range) {
return c10::make_intrusive<QuantizedCellParamsDynamic>(
/*_packed_w_ih=*/std::move(w_ih_packed),
/*_packed_w_hh=*/std::move(w_hh_packed),
/*_b_ih=*/std::move(bias_ih),
/*_b_hh=*/std::move(bias_hh),
/*_reduce_range=*/reduce_range);
}
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_fp16(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed);
struct QuantizedCellParamsFP16 : public CellParamsBase {
QuantizedCellParamsFP16(
c10::intrusive_ptr<LinearPackedParamsBase> _packed_ih,
c10::intrusive_ptr<LinearPackedParamsBase> _packed_hh)
: packed_ih(std::move(_packed_ih)), packed_hh(std::move(_packed_hh)) {}
c10::intrusive_ptr<LinearPackedParamsBase> packed_ih;
c10::intrusive_ptr<LinearPackedParamsBase> packed_hh;
const Tensor b_ih_;
const Tensor b_hh_;
Tensor matmul_ih(const Tensor& /* unused */) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor matmul_hh(const Tensor& /* unused */) const override {
TORCH_CHECK(false, "matmul is not supported with quantized cell params");
}
Tensor linear_ih(const Tensor& input) const override {
return packed_ih->apply_dynamic(input);
}
Tensor linear_hh(const Tensor& h) const override {
return packed_hh->apply_dynamic(h);
}
const Tensor& b_ih() const override {
return b_ih_;
}
const Tensor& b_hh() const override {
return b_hh_;
}
CellParamsSerializationType __getstate__() const override {
std::vector<c10::intrusive_ptr<LinearPackedParamsBase>>
packed_params_to_serialize{packed_ih, packed_hh};
return CellParamsSerializationType(
"quantized_fp16", {}, {}, {}, packed_params_to_serialize);
}
static c10::intrusive_ptr<CellParamsBase> __setstate__(
CellParamsSerializationType state) {
auto packed_params = std::get<4>(std::move(state));
TORCH_INTERNAL_ASSERT(packed_params.size() == 2);
return make_quantized_cell_params_fp16(
/*w_ih_packed=*/std::move(packed_params[0]),
/*w_hh_packed=*/std::move(packed_params[1]));
}
};
c10::intrusive_ptr<CellParamsBase> make_quantized_cell_params_fp16(
c10::intrusive_ptr<LinearPackedParamsBase> w_ih_packed,
c10::intrusive_ptr<LinearPackedParamsBase> w_hh_packed) {
return c10::make_intrusive<QuantizedCellParamsFP16>(
std::move(w_ih_packed), std::move(w_hh_packed));
}
static std::unordered_map<
std::string,
c10::intrusive_ptr<CellParamsBase> (*)(CellParamsSerializationType)>
cell_params_deserializers = {
{"quantized", &QuantizedCellParams::__setstate__},
{"quantized_dynamic", &QuantizedCellParamsDynamic::__setstate__},
{"quantized_fp16", &QuantizedCellParamsFP16::__setstate__}};
// Stupid wrapper to convert from -> to .
struct QRNNCellParamsWrapper {
QRNNCellParamsWrapper(c10::intrusive_ptr<CellParamsBase> param)
: param_(std::move(param)) {}
Tensor matmul_ih(const Tensor& input) const {
return param_->matmul_ih(input);
}
Tensor matmul_hh(const Tensor& h) const {
return param_->matmul_hh(h);
}
Tensor matmul_hr(const Tensor& h) const {
return param_->matmul_hr(h);
}
Tensor linear_ih(const Tensor& input) const {
return param_->linear_ih(input);
}
Tensor linear_hh(const Tensor& h) const {
return param_->linear_hh(h);
}
const Tensor& b_ih() const {
return param_->b_ih();
}
const Tensor& b_hh() const {
return param_->b_hh();
}
c10::intrusive_ptr<CellParamsBase> param_;
};
// Gathers every two elements of a vector in a vector of pairs
template<typename T>
static std::vector<pair_of<T>> pair_vec(const std::vector<T>& vals) {
TORCH_CHECK(vals.size() % 2 == 0, "Odd number of params or hiddens given to a bidirectional RNN");
std::vector<pair_of<T>> result;
result.reserve(vals.size() / 2);
for (size_t i = 0; i < vals.size(); i += 2) {
result.emplace_back(vals[i], vals[i + 1]);
}
return result;
}
// Flattens a vector of pairs
template<typename T>
static std::vector<T> unpair_vec(std::vector<pair_of<T>>&& vals) {
std::vector<T> result;
result.reserve(vals.size() * 2);
for (const auto i : c10::irange(vals.size())) {
result.push_back(std::move(vals[i].first));
result.push_back(std::move(vals[i].second));
}
return result;
}
// Parses a flat list of parameter tensors into a list of CellParams
static std::vector<CellParams> gather_params(TensorList params, bool has_biases, bool has_projections = false) {
static at::Tensor undefined;
std::vector<CellParams> result;
if (has_biases) {
if (has_projections) {
TORCH_CHECK(params.size() % 5 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 5) {
result.emplace_back(params[i], params[i + 1], params[i + 2], params[i + 3], params[i + 4]);
}
} else {
TORCH_CHECK(params.size() % 4 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 4) {
result.emplace_back(params[i], params[i + 1], params[i + 2], params[i + 3], undefined);
}
}
} else {
if (has_projections) {
TORCH_CHECK(params.size() % 3 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 3) {
result.emplace_back(params[i], params[i + 1], undefined, undefined, params[i + 2]);
}
} else {
TORCH_CHECK(params.size() % 2 == 0, "got an incorrect number of RNN parameters");
for (size_t i = 0; i < params.size(); i += 2) {
result.emplace_back(params[i], params[i + 1], undefined, undefined, undefined);
}
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
// HIDDEN STATE FUNCTIONS
//
// Functions implemented below are implemented as templates based on hidden type,
// because they need to work both with simple RNNs and GRU (which use a single Tensor),
// as well as with LSTM (or possibly more complicated architectures in the future).
// Still, there are some operations that need to be performed on the hidden states
// alone, and for this purpose we provide an overloaded set of functions below.
Tensor hidden_as_output(const Tensor& t) { return t; }
Tensor hidden_as_output(const tpair_of<Tensor>& t) { return std::get<0>(t); }
template<size_t index>
std::vector<Tensor> project(at::ArrayRef<tpair_of<Tensor>> tuples) {
std::vector<Tensor> result;
result.reserve(tuples.size());
for (auto & t : tuples) {
result.push_back(std::get<index>(t));
}
return result;
}
Tensor hidden_concat(at::ArrayRef<Tensor> hiddens) { return at::cat(hiddens, 0); }
tpair_of<Tensor> hidden_concat(at::ArrayRef<tpair_of<Tensor>> hiddens) {
return std::make_tuple(hidden_concat(project<0>(hiddens)), hidden_concat(project<1>(hiddens)));
}
Tensor hidden_slice(const Tensor& t, int64_t start, int64_t end) {
return t.narrow(0, start, end - start);
}
tpair_of<Tensor> hidden_slice(const tpair_of<Tensor>& t, int64_t start, int64_t end) {
return std::make_tuple(hidden_slice(std::get<0>(t), start, end),
hidden_slice(std::get<1>(t), start, end));
}
////////////////////////////////////////////////////////////////////////////////
// CELL IMPLEMENTATIONS
//
// Cell is a basic component of an RNN, representing a single application of the
// recurrent function. You can think of it as a function of signature
//
// (Tensor input, hidden_type hidden, CellParams) -> hidden_type
//
// which means that it consumes an input tensor, and updates the previous hidden state.
// It's a struct only because functional programming in C++ is a pain, and it's easier
// to pass around "vtable pointers" than actual function pointers.
void check_rnn_cell_forward_input(const Tensor& input, const c10::SymInt& input_size) {
TORCH_CHECK(
input.sym_size(1) == input_size,
"input has inconsistent input_size: got ", input.sym_size(1), " expected ", input_size);
}
void check_rnn_cell_forward_hidden(const Tensor& input, const Tensor& hx, const c10::SymInt& hidden_size, const c10::SymInt& hidden_label) {
TORCH_CHECK(
input.sym_size(0) == hx.sym_size(0),
"Input batch size ", input.sym_size(0), " doesn't match hidden", hidden_label, " batch size ", hx.sym_size(0));
TORCH_CHECK(
hx.sym_size(1) == hidden_size,
"hidden", hidden_label, " has inconsistent hidden_size: got ", hx.sym_size(1), ", expected ", hidden_size);
}
template<typename hidden_type_tmpl, typename cell_params_tmpl>
struct Cell {
using hidden_type = hidden_type_tmpl;
using cell_params = cell_params_tmpl;
virtual ~Cell() = default; // This is really dumb, but enables projects with
// -Wnon-virtual-dtor to compile...
virtual hidden_type operator()(
const Tensor& input,
const hidden_type& hidden,
const cell_params& params,
bool pre_compute_input = false) const = 0;
};
template<typename nonlinearity, typename cell_params>
struct SimpleCell : Cell<Tensor, cell_params> {
using hidden_type = Tensor;
Tensor operator()(
const Tensor& input,
const Tensor& hidden,
const cell_params& params,
bool pre_compute_input = false) const override {
return nonlinearity{}(params.linear_hh(hidden).add_(
pre_compute_input ? input : params.linear_ih(input)));
}
};
// TODO: can use inplace ops?
template <typename cell_params>
struct LSTMCell : Cell<std::tuple<Tensor, Tensor>, cell_params> {
using hidden_type = std::tuple<Tensor, Tensor>;
hidden_type operator()(
const Tensor& input,
const hidden_type& hidden,
const cell_params& params,
bool pre_compute_input = false) const override {
const auto& hx = std::get<0>(hidden);
const auto& cx = std::get<1>(hidden);
if (input.is_cuda() || input.is_xpu() || input.is_privateuseone()) {
TORCH_CHECK(!pre_compute_input);
auto igates = params.matmul_ih(input);
auto hgates = params.matmul_hh(hx);
auto result = at::_thnn_fused_lstm_cell(
igates, hgates, cx, params.b_ih(), params.b_hh());
// applying projections if w_hr is defined
auto hy = params.matmul_hr(std::get<0>(result));
// Slice off the workspace argument (it's needed only for AD).
return std::make_tuple(std::move(hy), std::move(std::get<1>(result)));
}
const auto gates = params.linear_hh(hx).add_(
pre_compute_input ? input : params.linear_ih(input));
auto chunked_gates = gates.unsafe_chunk(4, 1);
auto ingate = chunked_gates[0].sigmoid_();
auto forgetgate = chunked_gates[1].sigmoid_();
auto cellgate = chunked_gates[2].tanh_();
auto outgate = chunked_gates[3].sigmoid_();
auto cy = (forgetgate * cx).add_(ingate * cellgate);
auto hy = outgate * cy.tanh();
hy = params.matmul_hr(hy);
return std::make_tuple(std::move(hy), std::move(cy));
}
};
template <typename cell_params>
struct GRUCell : Cell<Tensor, cell_params> {
using hidden_type = Tensor;
hidden_type operator()(
const Tensor& input,
const hidden_type& hidden,
const cell_params& params,
bool pre_compute_input = false) const override {
if (input.is_cuda() || input.is_xpu() || input.is_privateuseone()) {
TORCH_CHECK(!pre_compute_input);
auto igates = params.matmul_ih(input);
auto hgates = params.matmul_hh(hidden);
auto result = at::_thnn_fused_gru_cell(
igates, hgates, hidden, params.b_ih(), params.b_hh());
// Slice off the workspace argument (it's needed only for AD).
return std::move(std::get<0>(result));
}
const auto chunked_igates = pre_compute_input
? input.unsafe_chunk(3, 1)
: params.linear_ih(input).unsafe_chunk(3, 1);
auto chunked_hgates = params.linear_hh(hidden).unsafe_chunk(3, 1);
const auto reset_gate =
chunked_hgates[0].add_(chunked_igates[0]).sigmoid_();
const auto input_gate =
chunked_hgates[1].add_(chunked_igates[1]).sigmoid_();
const auto new_gate =
chunked_igates[2].add(chunked_hgates[2].mul_(reset_gate)).tanh_();
return (hidden - new_gate).mul_(input_gate).add_(new_gate);
}
};
////////////////////////////////////////////////////////////////////////////////
// LAYER IMPLEMENTATIONS
//
// Layers are scan-like higher-order functions, which take in cells, and
// transform them to functions of signature
//
// (io_type input, hidden_type hidden, param_type params) -> (io_type, hidden_type)
//
// which can apply the cell over a sequence of inputs, and produce both a new set
// of hidden states, as well as a concatenated output of each step.
template<typename output_type, typename hidden_type>
struct LayerOutput {
output_type outputs;
hidden_type final_hidden;
};
template<typename io_type, typename hidden_type, typename param_type>
struct Layer {
using output_type = LayerOutput<io_type, hidden_type>;
virtual ~Layer() = default; // This is really dumb, but enables projects with
// -Wnon-virtual-dtor to compile...
virtual output_type operator()(
const io_type& input,
const hidden_type& input_hidden,
const param_type& params) const = 0;
};
template<typename hidden_type, typename cell_params>
struct FullLayer : Layer<Tensor, hidden_type, cell_params> {
using output_type =
typename Layer<Tensor, hidden_type, cell_params>::output_type;
using unstacked_output_type = LayerOutput<std::vector<Tensor>, hidden_type>;
FullLayer(Cell<hidden_type, cell_params>& cell)
: cell_(cell) {}
unstacked_output_type operator()(
const std::vector<Tensor>& step_inputs,
const hidden_type& input_hidden,
const cell_params& params,
bool pre_compute_input = false) const {
std::vector<Tensor> step_outputs;
auto hidden = input_hidden;
for (const auto& input : step_inputs) {
hidden = cell_(input, hidden, params, pre_compute_input);
step_outputs.emplace_back(hidden_as_output(hidden));
}
return {step_outputs, hidden};
}
output_type operator()(
const Tensor& inputs,
const hidden_type& input_hidden,
const cell_params& params) const override {
if (inputs.device().is_cpu()) {
const auto inputs_w = params.linear_ih(inputs);
auto unstacked_output =
(*this)(inputs_w.unbind(0), input_hidden, params, true);
TORCH_CHECK(unstacked_output.outputs.size()>0, "Expected sequence length to be larger than 0 in RNN");
return {at::stack(unstacked_output.outputs, 0),
unstacked_output.final_hidden};
}
auto unstacked_output = (*this)(inputs.unbind(0), input_hidden, params);
TORCH_CHECK(unstacked_output.outputs.size()>0, "Expected sequence length to be larger than 0 in RNN");
return {at::stack(unstacked_output.outputs, 0),
unstacked_output.final_hidden};
}
Cell<hidden_type, cell_params>& cell_;
};
template <typename dir_hidden_type, typename cell_params>
struct FullBidirectionalLayer
: Layer<Tensor, pair_of<dir_hidden_type>, pair_of<cell_params>> {
using hidden_type = pair_of<dir_hidden_type>;
using param_type = pair_of<cell_params>;
using output_type = typename Layer<Tensor, hidden_type, param_type>::output_type;
FullBidirectionalLayer(Cell<dir_hidden_type, cell_params>& cell)
: layer_(cell) {}
output_type operator()(
const Tensor& input,
const hidden_type& input_hidden,
const param_type& params) const override {
std::vector<Tensor> step_inputs;
if (input.device().is_cpu()) {
auto input_w = params.first.linear_ih(input);
step_inputs = input_w.unbind(0);
auto fw_result = layer_(
step_inputs, input_hidden.first, params.first, true);
TORCH_CHECK(fw_result.outputs.size() > 0, "Expected sequence length to be larger than 0 in RNN");
auto fw_output = at::stack(fw_result.outputs, 0);
input_w = params.second.linear_ih(input);
step_inputs = input_w.unbind(0);
auto rev_step_inputs = reverse(std::move(step_inputs));
auto rev_result =
layer_(rev_step_inputs, input_hidden.second, params.second, true);
std::reverse(rev_result.outputs.begin(), rev_result.outputs.end());
auto rev_output = at::stack(rev_result.outputs, 0);
return {at::cat({fw_output, rev_output}, fw_output.dim() - 1),
std::make_pair(fw_result.final_hidden, rev_result.final_hidden)};
}
step_inputs = input.unbind(0);
auto fw_result = layer_(step_inputs, input_hidden.first, params.first);
TORCH_CHECK(fw_result.outputs.size() > 0, "Expected sequence length to be larger than 0 in RNN");
auto fw_output = at::stack(fw_result.outputs, 0);
auto rev_step_inputs = reverse(std::move(step_inputs));
auto rev_result =
layer_(rev_step_inputs, input_hidden.second, params.second);
std::reverse(rev_result.outputs.begin(), rev_result.outputs.end());
auto rev_output = at::stack(rev_result.outputs, 0);
return {at::cat({fw_output, rev_output}, fw_output.dim() - 1),
std::make_pair(fw_result.final_hidden, rev_result.final_hidden)};
}
std::vector<Tensor> reverse(std::vector<Tensor>&& x) const {
std::reverse(x.begin(), x.end());
return std::move(x);
}
FullLayer<dir_hidden_type, cell_params> layer_;
};
template<typename hidden_type, typename cell_params>
struct PackedLayer : Layer<PackedSequence, hidden_type, cell_params> {
using output_type =
typename Layer<PackedSequence, hidden_type, cell_params>::output_type;
PackedLayer(Cell<hidden_type, cell_params>& cell)
: cell_(cell) {}
output_type operator()(
const PackedSequence& input,
const hidden_type& input_hidden,
const cell_params& params) const override {
std::vector<at::Tensor> step_outputs;
std::vector<hidden_type> hiddens;
int64_t input_offset = 0;
int64_t num_steps = input.batch_sizes.size(0);
int64_t* batch_sizes = input.batch_sizes.data_ptr<int64_t>();
int64_t last_batch_size = batch_sizes[0];
const Tensor* input_ptr = &input.data;
bool pre_compute_input = false;
Tensor input_w;
if (input.data.device().is_cpu()) {
input_w = params.linear_ih(input.data);
input_ptr = &input_w;
pre_compute_input = true;
}
// Batch sizes is a sequence of decreasing lengths, which are offsets
// into a 1D list of inputs. At every step we slice out batch_size elements,
// and possibly account for the decrease in the batch size since the last step,
// which requires us to slice the hidden state (since some sequences
// are completed now). The sliced parts are also saved, because we will need
// to return a tensor of final hidden state.
auto hidden = input_hidden;
for (const auto i : c10::irange(num_steps)) {
const int64_t batch_size = batch_sizes[i];
auto step_input = input_ptr->narrow(0, input_offset, batch_size);
input_offset += batch_size;
const int64_t dec = last_batch_size - batch_size;
if (dec > 0) {
hiddens.emplace_back(
hidden_slice(hidden, last_batch_size - dec, last_batch_size));
hidden = hidden_slice(hidden, 0, last_batch_size - dec);
}
last_batch_size = batch_size;
hidden = cell_(step_input, hidden, params, pre_compute_input);
step_outputs.push_back(hidden_as_output(hidden));
}
hiddens.emplace_back(hidden);
std::reverse(hiddens.begin(), hiddens.end());
return {PackedSequence{at::cat(step_outputs, 0), input.batch_sizes},
hidden_concat(hiddens)};
}
Cell<hidden_type, cell_params>& cell_;
};
template<typename hidden_type, typename cell_params>
struct ReversedPackedLayer : Layer<PackedSequence, hidden_type, cell_params> {
using output_type =
typename Layer<PackedSequence, hidden_type, cell_params>::output_type;
ReversedPackedLayer(Cell<hidden_type, cell_params>& cell)
: cell_(cell) {}
output_type operator()(
const PackedSequence& input,
const hidden_type& input_hidden,
const cell_params& params) const override {
std::vector<at::Tensor> step_outputs;
int64_t input_offset = input.data.size(0);
int64_t num_steps = input.batch_sizes.size(0);
int64_t* batch_sizes = input.batch_sizes.data_ptr<int64_t>();
int64_t last_batch_size = batch_sizes[num_steps - 1];
const Tensor* input_ptr = &input.data;
bool pre_compute_input = false;
Tensor input_w;