forked from ktorch/ktorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathktensor.cpp
2315 lines (2164 loc) · 94.2 KB
/
ktensor.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
#include "ktorch.h"
#include <torch/csrc/autograd/function.h>
namespace nn=torch::nn;
// ---------------------------------------------------------------------------
// kten - given tensor ref, return ptr to struct w'attrs, void ptr to tensor
// kvec - given reference to vector of tensors, return ptr to struct w'attrs
// kdict - given tensor dictionary reference, return ptr to containing struct
// ---------------------------------------------------------------------------
K kten(const Tensor& t) {return kptr(new Kten(t));}
K kvec(const TensorVector& v) {return kptr(new Kvec(v));}
K kdict(const TensorDict &d,Cast c) {return kptr(new Kdict(d,c));}
// -------------------------------------------------------------------------
// razeflag - check if general list made up entirely of scalars
// razelist - if general list is all scalars, raze to simple list
// -------------------------------------------------------------------------
static bool razeflag(K x) {
if(!x->t && x->n>0) {
auto t=kK(x)[0]->t;
if(t>=0)
return false;
for(J i=1; i<x->n; ++i)
if(kK(x)[i]->t != t)
return false;;
return true;
} else {
return false;
}
}
static K razelist(K x) {
if(razeflag(x)) {
J i; K y=ktn(-kK(x)[0]->t, x->n);
switch(y->t) {
case KE: for(i=0; i<y->n; ++i) kE(y)[i]=kK(x)[i]->e; break;
case KF: for(i=0; i<y->n; ++i) kF(y)[i]=kK(x)[i]->f; break;
case KJ: for(i=0; i<y->n; ++i) kJ(y)[i]=kK(x)[i]->j; break;
case KI: for(i=0; i<y->n; ++i) kI(y)[i]=kK(x)[i]->i; break;
case KSHORT: for(i=0; i<y->n; ++i) kH(y)[i]=kK(x)[i]->h; break;
case KB:
case KC:
case KG: for(i=0; i<y->n; ++i) kG(y)[i]=kK(x)[i]->g; break;
default: TORCH_ERROR("unable to raze general list -> ",kname(y));
}
return r0(x), y;
} else {
return x;
}
}
// -----------------------------------------------------------------------------------------
// cpermute - permute real representation of complex tensor from (real,'imag) -> (real;imag)
// sparsereal - convert sparse complex tensor to sparse real representation (real,'imag)
// toreal - convert complex tensor to real representation, 1 complex number to real & imag
// -----------------------------------------------------------------------------------------
static Tensor cpermute(const Tensor& x) {
std::vector<int64_t> d;
for(int64_t i=0; i<x.dim(); ++i) d.push_back(i-1);
return x.permute(d);
}
static Tensor sparsereal(const Tensor& t) {
// asof version 1.8.1, cannot go from sparse complex -> dense complex
// so attempt sparse complex -> sparse real representation -> dense real representation
auto n=t.sizes().vec(); n.push_back(2);
return torch::sparse_coo_tensor(t._indices(),torch::view_as_real(t._values()),n);
}
static Tensor toreal(const Tensor& t, c10::optional<bool> b=c10::nullopt);
static Tensor toreal(const Tensor& t, c10::optional<bool> b) {
bool c=b ? *b : env().complexfirst;
return c ? cpermute(t.is_sparse() ? sparsereal(t).to_dense() : torch::view_as_real(t.resolve_conj()))
: t.is_sparse() ? sparsereal(t).to_dense() : torch::view_as_real(t.resolve_conj());
}
// -------------------------------------------------------------------------
// kgetscalar - return k scalar given a scalar tensor
// kgets - process tensor at depth, creating k array
// kget - take tensor reference, return k scalar/array
// - take reference to vector of longs/doubles, return k list
// - take reference to vector/deque of tensors, return k lists
// - take reference to dictionary of tensors, return k dictionary
// -------------------------------------------------------------------------
static K kgetscalar(const Tensor &t){
auto s=t.item();
switch(t.scalar_type()) {
case torch::kFloat: return ke(s.toFloat());
case torch::kDouble: return kf(s.toDouble());
case torch::kHalf: return ke(s.toFloat());
case torch::kShort: return kh(s.toShort());
case torch::kInt: return ki(s.toInt());
case torch::kLong: return kj(s.toLong());
case torch::kBool: return kb(s.toBool());
case torch::kByte: return kg(s.toByte());
case torch::kChar: return kc(s.toChar());
default: TORCH_ERROR("unrecognized scalar tensor type: ", t.dtype(), ", cannot return k scalar"); return (K)0;
}
}
static K kgets(I i,I j,Ktype k,J b,const int64_t *s,S &p) {
//i:depth, j:max depth, k:k type, b:bytes to copy, s:sizes, p:data ptr
K x=ktn((i<j) ? 0 : k,s[i]); //create k list
if(x->t) { //if base type
if(x->n) { // and non-zero length
memcpy(kG(x),p,b); //copy k <- tensor
p+=b; // and incr data ptr
}
} else { // else
for(J y=0;y<x->n;++y) // call down a level
kK(x)[y]=kgets(i+1,j,k,b,s,p); // until base data type
}
return x;
}
K kget(const Tensor &t) {
if(!t.defined())
return knull();
else if (t.is_complex())
return kget(toreal(t));
else if (!t.dim()) // if 0-dimensional
return kgetscalar(t); // return scalar
Tensor c;
if(t.dtype()==torch::kHalf)
c=t.toType(torch::kFloat).contiguous().toBackend(torch::Backend::CPU);
else if (t.layout()==torch::kSparse)
c=t.to_dense().toBackend(torch::Backend::CPU);
else
c=t.contiguous().toBackend(torch::Backend::CPU);
I j=c.dim()-1; const int64_t *s=c.sizes().data(); // dimension & sizes at each dim
J b=s[j]*c.element_size(); // bytes to copy at lowest depth
S p=(S)c.data_ptr(); // contiguous data pointer
return kgets(0,j,maptype(t.dtype()),b,s,p);
}
K kget(const LongVector& v) {return klist(v.size(),v.data());}
K kget(const DoubleVector& v) {return klist(v.size(),v.data());}
K kget(const TensorDeque& v) {
bool b=true;
for(const auto& t:v)
if(t.dim()) {
b=false;
break;
}
if(b) std::cerr << "deque is all scalars..\n";
K x=ktn(0,v.size());
for(size_t i=0; i<v.size(); ++i) kK(x)[i]=kget(v[i]);
return x;
}
K kget(const TensorVector& v,K x) { // x-nullptr by default, else indices
if(!x) {
K r=ktn(0,v.size());
for(J i=0; i<r->n; ++i) kK(r)[i]=kget(v[i]);
return razelist(r);
} else if(x->t == -KJ) {
return kget(v.at(x->j));
} else if(x->t == KJ) {
K r=ktn(0,x->n);
for(J i=0; i<x->n; ++i) kK(r)[i]=kget(v.at(kJ(x)[i]));
return razelist(r);
} else {
TORCH_ERROR("vector: expecting 2nd arg of long indices, given ",kname(x));
}
}
K kget(const TensorDict& d,K x) { // x-nullptr by default, can contain sym(s) for indexing
if(!x) {
J i=0; K k=ktn(KS,d.size()),v=ktn(0,d.size());
for(const auto &a:d) {
kS(k)[i]=cs(a.key().c_str());
kK(v)[i]=kget(a.value());
++i;
}
return xD(k,razelist(v));
} else if(x->t == -KS) {
return kget(d[x->s]);
} else if(x->t == KS) {
K r=ktn(0,x->n);
for(J i=0; i<x->n; ++i)
kK(r)[i]=kget(d[kS(x)[i]]);
return razelist(r);
} else {
TORCH_ERROR("dict: expecting 2nd arg of symbol(s) for indexing, given ",kname(x));
}
}
// ------------------------------------------------------------------------
// kget - return module input/output as array or list/dict of arrays
// kin - return module input as tensor,vector/dictionary of tensors
// kout - return module output as tensor or vector of tensors
// ------------------------------------------------------------------------
K kget(const Tuple& t) {
return kget(TensorVector{std::get<0>(t),std::get<1>(t)});
}
K kget(const Nested& t) {
return kget(TensorVector{std::get<0>(t),
std::get<0>(std::get<1>(t)),
std::get<1>(std::get<1>(t))});
}
K kget(const Input& x) {
if (auto a=std::get_if<Tensor>(&x)) { return kget(*a);
} else if(auto a=std::get_if<TensorVector>(&x)) { return kget(*a);
} else if(auto a=std::get_if<TensorDict>(&x)) { return kget(*a);
} else if( std::get_if<Empty>(&x)) { return knull();
} else { TORCH_ERROR("unrecognized input");
}
}
K kget(const Output& x) {
if (auto a=std::get_if<Tensor>(&x)) { return kget(*a);
} else if(auto a=std::get_if<TensorVector>(&x)) { return kget(*a);
} else if(auto a=std::get_if<Tuple>(&x)) { return kget(*a);
} else if(auto a=std::get_if<Nested>(&x)) { return kget(*a);
} else { TORCH_ERROR("unrecognized output");
}
}
K kin(const Input& x) {
if (auto a=std::get_if<Tensor>(&x)) { return kten(*a);
} else if(auto a=std::get_if<TensorVector>(&x)) { return kvec(*a);
} else if(auto a=std::get_if<TensorDict>(&x)) { return kdict(*a);
} else if( std::get_if<Empty>(&x)) { return knull();
} else { TORCH_ERROR("unrecognized input");
}
}
K kout(const Output& o) {
if(auto a=std::get_if<Tensor>(&o)) {
return kten(*a);
} else if(auto a=std::get_if<TensorVector>(&o)) {
return kvec(*a);
} else if(auto a=std::get_if<Tuple>(&o)) {
return kvec({std::get<0>(*a),std::get<1>(*a)});
} else if(auto a=std::get_if<Nested>(&o)) {
return kvec({std::get<0>(*a), std::get<0>(std::get<1>(*a)), std::get<1>(std::get<1>(*a))});
} else {
TORCH_ERROR("unrecognized output from forward calculation");
}
}
// -------------------------------------------------------------------------------
// checkint - check options for modes not implemented for integral types
// checksparse - check options for sparse tensor, signal nyi combinations
// to - change tensor/vector device/type, create new tensor if copy flag set
// -------------------------------------------------------------------------------
static bool checkint(const TensorOptions& o,Tensormode m=Tensormode::undefined);
static bool checkint(const TensorOptions& o,Tensormode m) {
if(o.has_dtype() && torch::isIntegralType(torch::typeMetaToScalarType(o.dtype()),true)) {
switch(m) {
case Tensormode::rand:
case Tensormode::randn:
TORCH_ERROR(modesym(m), ": not implemented for ",optdtype(o.dtype())," tensors");
default: break;
}
return true;
} else {
return false;
}
}
static bool checksparse(const TensorOptions& o,Tensormode m=Tensormode::undefined);
static bool checksparse(const TensorOptions& o,Tensormode m) {
if(o.layout()==torch::kSparse || m==Tensormode::sparse) {
TORCH_CHECK(!o.has_layout() || o.layout()==torch::kSparse, "tensor: sparse mode incompatible with layout set to ",optlayout(o.layout()));
TORCH_CHECK(!o.pinned_memory(), "sparse tensors cannot have pinned memory");
TORCH_CHECK(!(o.has_memory_format() && (o.memory_format_opt().value()==torch::MemoryFormat::ChannelsLast ||
o.memory_format_opt().value()==torch::MemoryFormat::ChannelsLast3d)),
"sparse tensors cannot use memory formats with channels as last dimension");
switch(m) {
case Tensormode::undefined:
case Tensormode::complex:
case Tensormode::empty:
case Tensormode::sparse:
case Tensormode::zeros:
break;
default: TORCH_ERROR(modesym(m), ": not implemented for sparse tensors");
}
return true;
} else {
return false;
}
}
static Tensor to(const Tensor& t,const TensorOptions& o,bool a=false,bool b=false);
static Tensor to(const Tensor& t,const TensorOptions& o,bool a,bool b) {
// as of version 1.8.0, errors using to() with sparse or gradients:
// pinned memory doesn't seem to be handled from within any .to() method
//"Operators taking TensorOptions cannot take a TensorOptions with options.requires_grad set as true. This isn't implemented yet."
//"to(options) doesn't support converting to a different layout, but got self.layout being Strided and options.layout set as Sparse"
if(!t.defined())
return t;
else if(checksparse(o))
return t.to_sparse().to(o.requires_grad(false),a,b).set_requires_grad(o.requires_grad());
else if(t.is_sparse() && o.has_layout() && o.layout()==torch::kStrided)
return to(t.to_dense(),o);
else if(o.pinned_memory())
return t.to(o.requires_grad(false),a,b).pin_memory().set_requires_grad(o.requires_grad());
else
return t.to(o.requires_grad(false),a,b).set_requires_grad(o.requires_grad());
}
K to(Kten* t,const TensorOptions& o,bool a,bool b) {
TORCH_CHECK(t->t.defined(),"to: cannot change attribute(s) of an undefined tensor");
auto r=to(t->t,o,a,b);
if(b) // if copy flag set
return kten(r); // return new tensor
if(!t->t.is_same(r)) // else if device/dtype caused new tensor
t->t=r; // replace tensor in k ptr
return (K)0;
}
void to(TensorDict& d,const TensorOptions& o,bool a) {
for(auto& i:d) {
if(i.value().defined()) {
auto t=i.value().to(o,a);
if(!i.value().is_same(t)) i.value()=std::move(t);
}
}
}
void to(TensorVector& v,const TensorOptions& o,bool a) {
for(auto& t:v) {
if(t.defined()) {
auto r=t.to(o,a);
if(!t.is_same(r)) t=std::move(r);
}
}
}
// ---------------------------------------------------------------------------------------
// kputscalar - copy single k value to CPU tensor scalar
// kdepth - check k array at depth for consistent datatype, size, etc, throw errors
// kputs - descend depth of k array, determining dim & sizes, copying data types to tensor
// kput - controlling function to read k array, create tensor and copy data at depth
// ---------------------------------------------------------------------------------------
void kputscalar(K x,Tensor &t) {
Scalar s;
TORCH_CHECK(xscalar(x,s), "unable to translate k ",kname(x->t)," to scalar tensor");
t=torch::full({},s,maptype(x->t));
}
static void kdepth(K x,I i,H k,Ksize &s){
if(x->t < 0) {
TORCH_ERROR("unable to map mixed array to tensor: ",kname(x->t)," encountered at depth ",i);
} else if(k != nh) { // if base type already encountered
I j=s.size()-1; // last size index
if(x->n != s[i]) { // check that dimensions are consistent
TORCH_ERROR("dimension mismatch at depth ",i,", ",s[i]," vs ",x->n);
} else if(x->t != (i<j ? 0 : k)) { // check for same data type at same depth
TORCH_ERROR("type mismatch at depth ",i,", ",kname(i<j ? 0 : k)," vs ",kname(x->t));
}
} else {
s.push_back(x->n); // no error, no base type yet, accumulate sizes
}
}
static void kputs(K x,I i,H &k,Ksize &s,J &b,S &p,Tensor &t) {
kdepth(x,i,k,s);
if(x->t || !x->n) { // if base data type or empty
if(k==nh) { // if first encounter w'base data type
k=x->t;
t=k ? torch::empty(s, maptype(k)) : torch::empty(s);
b=t.element_size() * s[i]; // bytes to copy
p=(S)t.data_ptr(); // contiguous data pointer
}
memcpy(p,kG(x),b); p+=b;
} else {
for(I j=0;j<x->n;++j) kputs(kK(x)[j],i+1,k,s,b,p,t);
}
}
Tensor kput(K x) {
H k=nh; // fill w'base data type for nested k value
J b=0; // fill w'bytes to copy
Ksize s; // fill w'k array size at each depth
S p=nullptr; // data pointer for created tensor
Tensor t; // undefined tensor
if(x->t < 0) // if scalar
kputscalar(x,t); // create scalar backed by tensor
else if(!xnull(x)) // else go through the depth of the array
kputs(x,0,k,s,b,p,t); // until base data type encountered
return t;
}
Tensor kput(K x,J i) {
if(xind(x,i))
return kput(kK(x)[i]);
else
TORCH_ERROR("unable to index ",kname(x->t),", element: ",i);
}
// --------------------------------------------------------------------
// broadcast - true if tensor y can be broadcast to fill tensor x
// --------------------------------------------------------------------
bool broadcast(const Tensor& x,const Tensor& y) {
if(x.dim()<y.dim())
return false;
int64_t j=x.dim()-y.dim();
for(int64_t i=0; i<y.dim(); ++i)
if(x.size(i+j) != y.size(i) && y.size(i) != 1)
return false;
return true;
}
// --------------------------------------------------------------------
// kput - given indices & values from k, [re]set TensorVector elements
// --------------------------------------------------------------------
static void kput(TensorVector& v,J i,const Tensor& t) {
if(i == nj || i == -1)
v.emplace_back(t);
else
v.at(i)=t;
}
static bool kput(TensorVector& v,J i,K x) {
Tensor *t=nullptr;
if(xptr(x)) {
t=xten(x);
TORCH_CHECK(t, "vector: not implemented for ",kname(x));
}
kput(v, i, t ? *t : kput(x));
return t;
}
static void kput(TensorVector& v,K x,K y) {
if(x->t == -KJ) {
if(kput(v,x->j,y))
kfree(y);
} else if(x->t == KJ) {
if(y->t) {
Tensor t=kput(y);
TORCH_CHECK(x->n == t.numel(), "vector: length error, index count of ", x->n, " with ", t.numel(), " value(s)");
for(J i=0; i<x->n; ++i)
kput(v,kJ(x)[i],t.dim() ? t[i].clone() : t);
} else {
TORCH_CHECK(x->n == y->n, "vector: length error, index count of ", x->n, " with ", y->n, " value(s)");
bool b=false; TensorVector w;
for(J i=0; i<x->n; ++i) if(kput(w, -1, kK(y)[i])) b=true; // put k values/tensor ptrs in temp vector
for(J i=0; i<x->n; ++i) kput(v,kJ(x)[i],w[i]); // if no error, add to existing vector
if(b) // if any tensor pointers, free
for(J i=0; i<y->n; ++i)
if(xten(y,i)) kfree(y,i);
}
} else {
TORCH_ERROR("vector: expecting long indices as 2nd arg, given ",kname(x));
}
}
// ------------------------------------------------------------------------
// kput - put tensors/array in dictionary using symbols and arrays/tensors
// ------------------------------------------------------------------------
static void kput(Cast c,TensorDict& d,S s,const Tensor& t) {
if(auto a=d.find(s)) {
// attempt to update in place if gradient required or dictionary built as parameter/buffer list
if(a->requires_grad() || c==Cast::parameter || c==Cast::buffer) {
torch::NoGradGuard g;
TORCH_CHECK(broadcast(*a,t), "dict[`",s,"] with size of ",a->sizes()," cannot be updated with new values of size ",t.sizes());
a->copy_(t);
} else {
d[s]=std::move(t);
}
} else {
d.insert(s,std::move(t));
}
}
static bool kput(Cast c,TensorDict& d,S s,K x) {
Tensor* t=nullptr;
if(xptr(x)) {
t=xten(x);
TORCH_CHECK(t, "dict: not implemented for ",kname(x));
}
kput(c,d,s,t ? *t : kput(x));
return t;
}
static void kput(Cast c,TensorDict& d,K x,K y) {
if(x->t == -KS) {
if(kput(c,d,x->s,y))
kfree(y);
} else if(x->t == KS) {
if(y->t) {
Tensor t=kput(y);
TORCH_CHECK(x->n == t.numel(), "dict: length error, ", x->n, " key(s) with ", t.numel(), " value(s)");
for(J i=0; i<x->n; ++i)
kput(c,d,kS(x)[i],t.dim() ? t[i].clone() : t);
} else {
TORCH_CHECK(x->n == y->n, "dict: length error, ", x->n, " key(s) with ", y->n, " value(s)");
bool b=false; TensorVector w;
for(J i=0; i<x->n; ++i) if(kput(w, -1, kK(y)[i])) b=true; // add tensors/arrays to temp vector
for(J i=0; i<x->n; ++i) kput(c, d, kS(x)[i], w[i]); // if no error, add to dictionary
if(b) // if any tensor pointers, free
for(J i=0; i<y->n; ++i)
if(xten(y,i)) kfree(y,i);
}
} else {
TORCH_ERROR("dict: given ptr, expecting symbol keys & values, but 2nd arg is ",kname(x));
}
}
TensorDict kputd(K x) {
TensorDict d;
if(xdict(x) || (!x->t && x->n==2 && (kK(x)[0]->t==KS || kK(x)[0]->t==-KS)))
kput(Cast::tensor,d,kK(x)[0],kK(x)[1]);
else if(!xempty(x))
TORCH_ERROR("dict: expecting k dictionary or (syms;vals), given ",kname(x));
return d;
}
// --------------------------------------------------------------------------------------
// complextype - get component data type from complex data type or default data type
// complexdim - determine first/last dim on which to split for real/imaginary
// --------------------------------------------------------------------------------------
static ScalarType complextype(c10::optional<TypeMeta> t,ScalarType a=ScalarType::Undefined, ScalarType b=ScalarType::Undefined);
static ScalarType complextype(c10::optional<TypeMeta> t,ScalarType a,ScalarType b) {
ScalarType d;
if(torch::isFloatingType(a) && torch::isFloatingType(b)) {
TORCH_CHECK(a==b, "complex: real input is ",optdtype(a),", imaginary input is ",optdtype(b));
}
if(t) {
switch(torch::typeMetaToScalarType(*t)) {
case torch::kComplexHalf: d=torch::kHalf; break;
case torch::kComplexFloat: d=torch::kFloat; break;
case torch::kComplexDouble: d=torch::kDouble; break;
default:
TORCH_ERROR("unable to create complex tensor with given datatype: ",optdtype(*t));
}
} else if(torch::isFloatingType(a)) {
d=a;
} else if(torch::isFloatingType(b)) {
d=b;
} else {
d=torch::get_default_dtype_as_scalartype();
if(!isFloatingType(d)) d=torch::kFloat;
}
return d;
}
static int64_t complexdim(const Tensor& a,c10::optional<bool> b) {
bool c=b ? *b : env().complexfirst; int64_t d=c ? 0 : -1;
TORCH_CHECK(a.dim(), "complex: single input array must have one or more dimensions");
TORCH_CHECK(a.size(d)==2, "complex: single input array must have a ",
(c ? "first" : "last")," dimension of size 2 (real",(c ? ";" : ",'"),
"imaginary), given size of ",a.sizes());
return d;
}
// --------------------------------------------------------------------------------------
// complex1 - make a complex tensor from single input: (real,'imag) or (real;imag)
// --------------------------------------------------------------------------------------
static Tensor complex1(const Tensor& a,int64_t d,Tensor& r) { // w'output tensor
return torch::complex_out(r, a.select(d,0), a.select(d,1));
}
static Tensor complex1(const Tensor& a,Tensor& r,c10::optional<bool> b=c10::nullopt);
static Tensor complex1(const Tensor& a,Tensor& r,c10::optional<bool> b) {
return complex1(a.to(complextype(r.dtype())), complexdim(a,b), r);
}
static Tensor complex1(const Tensor& a,int64_t d) { // no output tensor
return torch::complex(a.select(d,0), a.select(d,1));
}
static Tensor complex1(const Tensor& a,const TensorOptions& o,c10::optional<bool> b=c10::nullopt);
static Tensor complex1(const Tensor& a,const TensorOptions& o,c10::optional<bool> b) {
return complex1(a.to(complextype(o.dtype_opt(),a.scalar_type())), complexdim(a,b)).to(o);
}
// --------------------------------------------------------------------------------------
// complex2 - make a complex tensor from real & imaginary inputs
// --------------------------------------------------------------------------------------
static Tensor complex2(const Tensor& a,const Tensor& b,Tensor& r) { // w'output tensor
auto t=complextype(r.dtype(), a.scalar_type(), b.scalar_type());
return torch::complex_out(r,a.to(t),b.to(t));
}
static Tensor complex2(const Tensor& a,const Tensor& b,TensorOptions& o) {
auto t=complextype(o.dtype_opt(), a.scalar_type(), b.scalar_type());
return torch::complex(a.to(t), b.to(t));
}
// ----------------------------------------------------------------------------------------
// tensorlike - tensor creation routines, e.g. ones_like() where tensor given as template
// tensorout - tensor creation routines, e.g. ones_out(), where output tensor is given
// tensoropt - tensor creation routines where tensor size and option(s) given
// tensormode - determines whether a template tensor or output tensor given w'other args
// tensorput - put k value(s) -> tensor, return new tensor ptr unless output tensor given
// tensorget - given tensor ptr and optional flag & indexing args, get result for k array
// vectorptr - given vector ptr, return tensor pointers, or single pointer if index given
// dictptr - given dictionary ptr, return dictionary of tensor pointers, or single pointer
// tensor - high level function to create/retrieve/move/recast tensor from k
// ----------------------------------------------------------------------------------------
static void tensorlike(K x,Tensormode m,const Tensor &t,Tensor &r) { // t:input, r:result tensor
J i,j; Scalar s; TensorOptions o;
bool b=xopt(x,x->n-1,o); I nx=x->n-b; //set flag if options given, count non-option args
switch(m) {
case Tensormode::empty: if(nx==2) r=torch::empty_like(t,o); break;
case Tensormode::zeros: if(nx==2) r=torch::zeros_like(t,o); break;
case Tensormode::ones: if(nx==2) r=torch::ones_like(t,o); break;
case Tensormode::rand: if(nx==2) r=torch::rand_like(t,o); break;
case Tensormode::randn: if(nx==2) r=torch::randn_like(t,o); break;
case Tensormode::full:
if(nx==3 && xscalar(x,2,s))
r=torch::full_like(t,s,o.has_dtype() ? o : o.dtype(maptype(kK(x)[2]->t)));
break;
case Tensormode::randint:
if (nx==3 && xlong(x,2,j)) r=torch::randint_like(t,j,o);
else if(nx==4 && xlong(x,2,i) && xlong(x,3,j)) r=torch::randint_like(t,i,j,o);
break;
default:
TORCH_ERROR("tensor: mode `",kK(x)[0]->s," not implemented with input tensors");
break;
}
}
static void tensorout(K x,Tensormode m,Tensor &t,Tensor &r) { // t:output, r:result tensor
double e; J i,j; Scalar a,z,n; IntArrayRef s;
bool b=xsize(x,1,s); //true if size is given as 2nd arg (last arg is output tensor)
switch(m) {
case Tensormode::empty: if(b && x->n==3) r=torch::empty_out(t,s); break;
case Tensormode::zeros: if(b && x->n==3) r=torch::zeros_out(t,s); break;
case Tensormode::ones: if(b && x->n==3) r=torch::ones_out(t,s); break;
case Tensormode::rand: if(b && x->n==3) r=torch::rand_out(t,s); break;
case Tensormode::randn: if(b && x->n==3) r=torch::randn_out(t,s); break;
case Tensormode::full: if(b && x->n==4 && xscalar(x,2,a)) r=torch::full_out(t,s,a); break;
case Tensormode::randperm: if (x->n==3 && xlong(x,1,i)) r=torch::randperm_out(t,i); break;
case Tensormode::randint:
b=xsize(x,x->n-2,s);
if (b && x->n==4 && xlong(x,1,j)) r=torch::randint_out(t,j,s);
else if(b && x->n==5 && xlong(x,1,i) && xlong(x,2,j)) r=torch::randint_out(t,i,j,s);
break;
case Tensormode::eye:
if (x->n==3 && xlong(x,1,i)) r=torch::eye_out(t,i);
else if(x->n==4 && xlong(x,1,i) && xlong(x,2,j)) r=torch::eye_out(t,i,j);
break;
case Tensormode::range:
case Tensormode::arange:
b=m==Tensormode::range;
if (x->n==3 && xnum(x,1,z)) r = b ? torch::range_out(t,0,z) : torch::arange_out(t,z);
else if(x->n==4 && xnum(x,1,a) && xnum(x,2,z)) r = b ? torch::range_out(t,a,z) : torch::arange_out(t,a,z,1);
else if(x->n==5 && xnum(x,1,a) && xnum(x,2,z) && xnum(x,3,n))r = b ? torch::range_out(t,a,z,n) : torch::arange_out(t,a,z,n);
break;
case Tensormode::linspace:
case Tensormode::logspace:
b=m==Tensormode::logspace; i=100; e=10.0; //default of 100 steps, base 10
if(xnum(x,1,a) && xnum(x,2,z) && (x->n==4 || (xlong(x,3,i) && (x->n==5 || (x->n==6 && b && xnum(x,4,e))))))
r = b ? torch::logspace_out(t,a,z,i,e) : torch::linspace_out(t,a,z,i);
break;
case Tensormode::complex:
if(x->n==3) {
r=complex1(kput(x,1),t);
} else if(x->n==4) {
if(xbool(x,2,b))
r=complex1(kput(x,1),b,t);
else
r=complex2(kput(x,1),kput(x,2),t);
}
break;
case Tensormode::sparse:
TORCH_ERROR("tensor: sparse not implemented with output tensors");
break;
default:
TORCH_ERROR("tensor: unexpected tensor mode `",kK(x)[0]->s," supplied with output tensor");
break;
}
}
static void tensoropt(K x,Tensormode m,Tensor &r) {
double e; J i,j,nx=x->n; Scalar a,z,n; IntArrayRef s; TensorOptions o;
bool b=xopt(x,x->n-1,o); if(b) nx--; //track if options in last arg
bool sz=xsize(x,1,s) && nx==((m==Tensormode::full) ? 3 : 2); //2nd arg is size & correct arg count
checksparse(o,m); checkint(o,m);
switch(m) {
case Tensormode::empty: if(sz) r=torch::empty(s,o); break;
case Tensormode::zeros: if(sz) r=torch::zeros(s,o); break;
case Tensormode::ones: if(sz) r=torch::ones(s,o); break;
case Tensormode::rand: if(sz) r=torch::rand(s,o); break;
case Tensormode::randn: if(sz) r=torch::randn(s,o); break;
case Tensormode::full:
if(sz && xscalar(x,2,a))
r=torch::full(s,a,o.has_dtype() ? o : o.dtype(maptype(kK(x)[2]->t)));
break;
case Tensormode::randperm:
if(!o.has_dtype()) o=o.dtype(torch::kLong);
if(nx==2 && xlong(x,1,i)) r = torch::randperm(i,o);
break;
case Tensormode::randint:
sz=xsize(x,nx-1,s); // true if size is supplied as last non-options arg
if(!o.has_dtype()) o=o.dtype(torch::kLong);
if (sz && nx==3 && xlong(x,1,j)) r=torch::randint(j,s,o);
else if(sz && nx==4 && xlong(x,1,i) && xlong(x,2,j)) r=torch::randint(i,j,s,o);
break;
case Tensormode::eye:
if (nx==2 && xlong(x,1,i)) r=torch::eye(i,o);
else if(nx==3 && xlong(x,1,i) && xlong(x,2,j)) r=torch::eye(i,j,o);
break;
case Tensormode::range:
if (nx==3 && xnum(x,1,a) && xnum(x,2,z)) r=torch::range(a,z,o);
else if(nx==4 && xnum(x,1,a) && xnum(x,2,z) && xnum(x,3,n))r=torch::range(a,z,n,o);
break;
case Tensormode::arange:
b=!o.has_dtype();
if(nx==2 && xnum(x,1,z)) {
if(b && z.isIntegral(false)) o=o.dtype(torch::kLong);
r=torch::arange(z,o);
} else if(nx==3 && xnum(x,1,a) && xnum(x,2,z)) {
if(b && a.isIntegral(false) && z.isIntegral(false)) o=o.dtype(torch::kLong);
r=torch::arange(a,z,o);
} else if(nx==4 && xnum(x,1,a) && xnum(x,2,z) && xnum(x,3,n)) {
if(b && a.isIntegral(false) && z.isIntegral(false) && n.isIntegral(false)) o=o.dtype(torch::kLong);
r=torch::arange(a,z,n,o);
}
break;
case Tensormode::linspace:
case Tensormode::logspace:
b=m==Tensormode::logspace; i=100; e=10.0; //default of 100 steps, base 10
if(xnum(x,1,a) && xnum(x,2,z) && (nx==3 || (xlong(x,3,i) && (nx==4 || (nx==5 && b && xnum(x,4,e))))))
r = b ? torch::logspace(a,z,i,e,o) : torch::linspace(a,z,i,o);
break;
case Tensormode::complex:
if(nx==2) {
r=complex1(kput(x,1), o);
} else if(nx==3) {
if(xbool(x,2,b))
r=complex1(kput(x,1), o, b);
else
r=complex2(kput(x,1), kput(x,2), o);
}
break;
case Tensormode::sparse:
// as of version 1.8.1, sparse_coo_tensor seems to ignore tensor options if indices & values supplied
// there is a check if explicit strided setting and gradient required throws nyi, requiring workaround below
// https://github.com/pytorch/pytorch/issues/55453
checksparse(o,m);
if(nx==2 && xsize(x,1,s))
r=torch::sparse_coo_tensor(s,o);
else if(nx==3)
r=to(torch::sparse_coo_tensor(kput(x,1),kput(x,2),o.requires_grad(false)), o);
else if(nx==4 && xsize(x,3,s))
r=to(torch::sparse_coo_tensor(kput(x,1),kput(x,2),s,o.requires_grad(false)), o);
break;
default: break;
}
// most tensor creation functions don't support newer memory format options yet (as of version 1.8.1)
if(o.has_memory_format() && r.suggest_memory_format() != o.memory_format_opt().value()) {
torch::NoGradGuard g;
r=r.is_pinned() ? r.contiguous(*o.memory_format_opt()).pin_memory() : r.contiguous(*o.memory_format_opt());
if(o.requires_grad()) r.set_requires_grad(true);
}
}
static K tensormode(K x,S s,Tensormode m) {
Tensor t,r; bool in=false,out=false;
if((in=xten(x,1,t))) tensorlike(x,m,t,r); // input tensor is 2nd arg
else if((out=xten(x,x->n-1,t))) tensorout(x,m,t,r); // output tensor is final arg
else tensoropt(x,m,r); // no input/output tensor
TORCH_CHECK(r.defined(),"unrecognized argument(s) for tensor creation mode: ",s);
return out ? (K)0 : kten(r);
}
static K tensorput(K x) {
Tensor r,t; TensorOptions o;
t=((xopt(x,1,o) || xten(x,1,r)) && x->n==2) ? kput(x,0) : kput(x);
if(r.defined()) {
r.resize_(t.sizes()).copy_(t,true);
return (K)0;
} else {
//return kten(to(t,o)); // NULL TENSOR
return kten(t.defined() ? to(t,o) : t);
}
}
static Tensor tensorget(const Tensor& t,J d,K x) { // d:dimension, x:index/indices
if(x->t == -KJ)
return t.select(d,x->j);
else if(x->t == KJ)
return torch::index_select(t,d,kput(x).to(t.device()));
else
TORCH_ERROR("tensor: last arg expected to be long(s) for indexing, given ",kname(x));
}
Tensor tensorget(const Tensor& t,K x) {
bool b=false,c; J d=0; Tensor r;
if((c=xbool(x,1,b)))
TORCH_CHECK(t.is_complex(), "tensor: optional flag is only for complex tensors");
if(x->n == 1+c) { // ptr or (ptr;flag)
r=t;
} else if(x->n == 2+c) { // (ptr;ind) or (ptr;flag;ind)
r=tensorget(t,d,kK(x)[x->n-1]);
} else if(x->n == 3+c) { // (ptr;dim;ind) or (ptr;flag;dim;ind)
TORCH_CHECK(xlong(x,1+c,d), "tensor: ",(c ? "2nd" : "3rd")," arg of dimension expected as a long scalar, given ",kname(x,1+c));
r=tensorget(t,d,kK(x)[x->n-1]);
} else {
TORCH_ERROR("tensor: up to ",3+c," args expected, (tensor;", (c ? "flag;" : ""),"dim;ind), but ",x->n," args given");
}
return c ? toreal(r,b) : r;
}
static K vectorptr(const TensorVector& v,K x) {
if(x->n==1) { // no additional args, return list of tensor ptrs
J i=0; K r=ktn(0,v.size());
for(const auto& t:v) kK(r)[i++]=kten(t);
return r;
} else if(x->n==2) { // 2nd arg of single index or list of indices
K y=kK(x)[1];
if(y->t == -KJ) {
return kten(v.at(y->j)); // single index, return tensor ptr
} else if(y->t == KJ) { // indices, return list of selected tensor ptrs
K r=ktn(0,y->n);
for(J i=0; i<y->n;++i) kK(r)[i]=kten(v.at(kJ(y)[i]));
return r;
} else {
TORCH_ERROR("tensor: given vector, 2nd arg expected to be long(s) for indexing, not ",kname(y));
}
} else {
TORCH_ERROR("tensor: given vector, expecting no more than one additional indexing argument but given ",x->n-1," additional args");
}
}
static K dictptr(const TensorDict& d,K x) {
if(x->n==1) { // no additional args, return k dict of tensor ptrs
J i=0; K k=ktn(KS,d.size()),v=ktn(0,d.size());
for(const auto &a:d) {
kS(k)[i]=cs(a.key().c_str());
kK(v)[i]=kten(a.value());
++i;
}
return xD(k,v);
} else if(x->n==2) { // additional indexing arg
K y=kK(x)[1];
if(y->t == -KS) { // single symbol, return tensor pointer
return kten(d[y->s]);
} else if(y->t == KS) { // list of symbols, return k dict of selected tensor ptrs
K r=ktn(0,y->n);
for(J i=0; i<y->n;++i) kK(r)[i]=kten(d[kS(y)[i]]);
return r;
} else {
TORCH_ERROR("tensor: given dictionary, 2nd arg expected to be symbols(s) for indexing, not ",kname(y));
}
} else {
TORCH_ERROR("tensor: given dictionary, expecting no more than one additional indexing argument but given ",x->n-1," additional args");
}
}
KAPI tensor(K x) {
KTRY
S s; Tensormode m; Ktag *g;
if((g=xtag(x)) || (g=xtag(x,0))) {
switch(g->a) {
case Class::tensor: return kget(tensorget(g->tensor(),x));
case Class::vector: return vectorptr(g->vector(), x);
case Class::dict: return dictptr(g->dict(), x);
default: TORCH_ERROR("tensor not implemented for ",mapclass(g->a));
}
} else if(xmode(x,0,s,m)) {
return tensormode(x,s,m);
} else {
return tensorput(x);
}
KCATCH("tensor");
}
// ------------------------------------------------------------------------------------------
// tensor vector fns:
// ------------------------------------------------------------------------------------------
// vec - initialize vector of tensors from k array, tensor ptr(s) or some mix of both
// vector - create vector of tensors, or return vector or vector element, or replace element
// dict - create dictionary of tensors, or return dictionary value(s)
// ------------------------------------------------------------------------------------------
TensorVector vec(K x,bool b) { // b: true if any encountered tensor ptr to be de-referenced
TensorVector v;
if(x->t) {
Tensor t=kput(x);
if(t.dim())
for(int64_t i=0;i<t.size(0);++i)
v.emplace_back(t[i].clone());
else
v.emplace_back(t);
} else if(xptr(x)) {
if(kput(v,-1,x))
if(b) kfree(x);
} else {
bool a=false;
for(J i=0;i<x->n;++i)
if(kput(v, -1, kK(x)[i])) a=true;
if(a && b)
for(J i=0;i<x->n;++i) if(xptr(x,i)) kfree(x,i);
}
return v;
}
KAPI vector(K x) {
KTRY
if(auto* v=xvec(x)) { // if previously created vector, return as k list
return kget(*v);
} else if(auto* v=xvec(x,0)) { // if previously created vector
if(x->n==2) { // 2 args
if(auto *w=xvec(x,1)) { // add additional vector
for(size_t i=0,n=w->size(); i<n; ++i)
v->emplace_back(w->at(i)); // add via index in case vector added to self
if(v!=w) kfree(x,1); // free vector added unless same
return (K)0;
} else { // else index into vector via 2nd arg of index/indices
return kget(*v,kK(x)[1]);
}
} else if(x->n==3) { // if indices and values supplied
kput(*v, kK(x)[1], kK(x)[2]);
return (K)0;
} else {
TORCH_ERROR("vector: given ptr, expecting indices, vector ptr or (indices;values), but given ",x->n-1," additional arg(s)");
}
} else {
return kvec(vec(x,true));
}
KCATCH("vector");
}
KAPI dict(K x) {
KTRY
TORCH_CHECK(x->t==0 || x->t==99, "dict: not implemented for ",kname(x));
Ktag *g=xtag(x); if(!g) g=xtag(x,0); Cast c=g ? g->c : Cast::undefined;
if(g && g->a == Class::dict) {
TensorDict& d=g->dict();
if(x->n==1) { // dict ptr is only argument
return kget(d); // return dictionary of syms!values to k
} else if(x->n==2) {
if(xdict(x,1)) // dict(ptr;kdict)
return kput(c,d,kK(kK(x)[1])[0],kK(kK(x)[1])[1]), (K)0;
else // dict(ptr;sym(s))
return kget(d,kK(x)[1]);
} else if(x->n==3) {
return kput(c,d,kK(x)[1],kK(x)[2]), (K)0;
} else {
TORCH_ERROR("dict: expecting 1-3 args, but ",x->n," args supplied, not one of ptr, (ptr;dict), (ptr;syms), (ptr;syms;vals)");
}
} else {
return kdict(kputd(x));
}
KCATCH("dict");
}
// --------------------------------------------------------------------------------------
// complex tensors
// --------------------------------------------------------------------------------------
// kreal - handle api calls to extract real & imaginary parts of tensor
// real,imag - return real & imaginary parts of tensor as tensor or k value
// isreal - return boolean with 1's where value is real
// --------------------------------------------------------------------------------------
static K kreal(K x,Tensor(f)(const Tensor&),const char* nm) {
KTRY
bool b=false; Tensor *t=xten(x);
if(!t) b=true, t=xten(x,0); // enlisted tensor, return as k array
TORCH_CHECK(t && t->is_complex() && x->n==1, nm, ": expects a complex tensor (enlist to return tensor ptr), given ",kname(x));
// as of version 1.8.1, complex sparse tensors must be made sparse real -> dense -> back to complex
return kresult(b,f(t->is_sparse() ? torch::view_as_complex(sparsereal(*t).to_dense()) : *t));
KCATCH(nm);
}
KAPI real(K x) {return kreal(x, torch::real, "real");}
KAPI imag(K x) {return kreal(x, torch::imag, "imag");}
KAPI isreal(K x) {return kreal(x, torch::isreal, "isreal");}
// ------------------------------------------------------------------------------------------
// sparse tensors
// ------------------------------------------------------------------------------------------
// getsparse - handle api calls to extract indices & values from sparse tensor
// coalesce - colaesce a sparse tensor
// dense - return dense tensor given sparse tensor
// sparse - return sparse tensor given array, tensor, (array/tensor;dim), (array/tensor;mask)
// sparseindex - return non-zero indices of input as matrix/tensor, allow sparse dimension
// ------------------------------------------------------------------------------------------
static K getsparse(K x,bool i,const char* nm) {
KTRY
bool b=false; Tensor *t=xten(x);
if(!t) b=true, t=xten(x,0); // enlisted tensor, return as k array
TORCH_CHECK(t && t->is_sparse() && x->n==1, nm, ": expects a sparse tensor (enlist to return tensor ptr), given ",kname(x));
return kresult(b, i ? t->_indices() : t->_values());
KCATCH(nm);
}
KAPI indices(K x) {return getsparse(x, true, "indices");}
KAPI values(K x) {return getsparse(x, false, "values");}
KAPI coalesce(K x) {
KTRY
Tensor *t=xten(x);
TORCH_CHECK(t && t->is_sparse(), "coalesce: expecting sparse tensor, given ",kname(x));
if(!t->is_coalesced())
xtag(x)->set(t->coalesce());
return (K)0;
KCATCH("coalesce");
}
KAPI dense(K x) {