forked from ktorch/ktorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathktorch.cpp
More file actions
2672 lines (2428 loc) · 97.6 KB
/
Copy pathktorch.cpp
File metadata and controls
2672 lines (2428 loc) · 97.6 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
#include "ktorch.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
// --------------------------------------------------------------------------------------------------
// krrbuf - copy msg to a buffer for signalling error to k
// dictadd - add an entry in a dictionary mapping symbol -> k value
// xind - true if i is valid index of k list (type=0)
// kptr - given void *, add to pointer list & return k list of one long scalar = (intptr_t)void *
// ptrtype - true if x is a 1-element list of a single scalar
// ptrflag - true if x is found in map of pointers
// mapped - true if ptr type and actively mapped
// xptr - given k value, return true if enclosed scalar and in set of maintained pointers
// xtag - if enclosed integer ptr detected from k, return pointer to tag structure
// --------------------------------------------------------------------------------------------------
S krrbuf(const char *s) {
static C thread_local b[4096]; b[0]=0;
return strncat(b, s, sizeof(b)-1);
}
void dictadd(K x, char* s, K v){K *k=kK(x); js(&k[0],cs(s)); jk(&k[1],v);}
void dictadd(K x, const char* s, K v){K *k=kK(x); js(&k[0],cs(s)); jk(&k[1],v);}
bool xind(K x,J i) {return !x->t && -1<i && i<x->n;}
bool xind(K x,J i,Ktype k) {return x->t==k && -1<i && i<x->n;}
K kptr(void *v){J j=(intptr_t)v; pointer().insert(j); return knk(1,kj(j));}
bool ptrtype(K x) {return !x->t && x->n==1 && kK(x)[0]->t==-KJ;}
bool ptrflag(K x) {return pointer().count(kK(x)[0]->j);}
bool mapped(K x) {return ptrtype(x) && ptrflag(x);}
bool xptr(K x) {
if(ptrtype(x)) {
TORCH_CHECK(ptrflag(x), "stale pointer");
return true;
} else {
return false;
}
}
bool xptr(K x,J i) {return xind(x,i) && xptr(kK(x)[i]);}
Ktag* xtag(K x) {return xptr(x) ? (Ktag*)kK(x)[0]->j : nullptr;}
Ktag* xtag(K x,J i) {return xind(x,i) ? xtag(kK(x)[i]) : nullptr;}
// ---------------------------------------------------------------------------------
// null - true if null for given type
// match - return true if scalars match (check long/double value)
// kscalar - return k double/long from torch scalar
// resolve - serialize, then deserialize, to remove k object types created via c-api
// resolvedict - return dict with simple value list if general list of all same type
// Resolve - k api function to call `resolve`
// ---------------------------------------------------------------------------------
bool null(const char* x) { return !x || !strlen(x);}
bool null(const J x) { return x == nj; }
bool match(const Scalar &x,const Scalar &y) {
if(x.isIntegral(false)) {
if(y.isIntegral(false))
return x.toLong() == y.toLong();
else if(y.isFloatingPoint())
return x.toDouble() == y.toDouble();
} else if(x.isFloatingPoint()) {
if(y.isFloatingPoint() || y.isIntegral(false))
return x.toDouble() == y.toDouble();
}
TORCH_ERROR("unexpected scalar type(s), neither integral or floating point, cannot compare");
}
K kscalar(const Scalar &s) {
if(s.isIntegral(false))
return kj(s.toLong());
else if(s.isFloatingPoint())
return kf(s.toDouble());
TORCH_ERROR("unexpected scalar type(s), neither integral or floating point, cannot convert");
}
K resolve(K x) {
K b=b9(-1,x);
TORCH_CHECK(b, "b9: failed to serialize ",kname(x));
K z=d9(b); r0(b);
TORCH_CHECK(z, "d9: failed to deserialize ",kname(x));
return z;
}
K resolvedict(K x) {
K y=kK(x)[1]; auto t=(!y->t && y->n) ? kK(y)[0]->t : 0;
if(t==-KB || t==-KJ || t==-KS || t==-KF) {
for(J i=1; i<y->n; ++i)
if(t != kK(y)[i]->t) return x;
K v=ktn(-t,y->n);
for(J i=0; i<y->n; ++i) {
switch(t) {
case -KB: kG(v)[i]=kK(y)[i]->g; break;
case -KJ: kJ(v)[i]=kK(y)[i]->j; break;
case -KS: kS(v)[i]=kK(y)[i]->s; break;
case -KF: kF(v)[i]=kK(y)[i]->f; break;
}
}
kK(x)[1]=v; r0(y);
}
return x;
}
KAPI Resolve(K x) {
KTRY
return resolve(x);
KCATCH("resolve");
}
// ------------------------------------------------------------------------------------------
// xlen - 1 if scalar else x->n for lists, no. of table rows or dictionary elements
// mapclass - map class enum to symbol
// kname - string from k data type or object
// ------------------------------------------------------------------------------------------
J xlen(K x) {
if(x->t < 0 || x->t > 99) return 1;
else if(x->t < 98) return x->n;
else if(x->t == 98) return xlen(kK(kK(x->k)[1])[0]);
else return xlen(kK(x)[0]);
}
J xlen(K x,J i) {return xind(x,i) ? xlen(kK(x)[i]) : -1;}
S mapclass(Class a) {
for(const auto& m:env().kclass)
if(a==std::get<1>(m)) return std::get<0>(m);
TORCH_ERROR("unrecognized class: ", (I)a);
}
const char* kname(Ktype k) {
Ktype t=abs(k); bool b=k<0;
switch(t) {
case 0: return "general list";
case 1: return b ? "boolean scalar" : "boolean list";
case 2: return b ? "guid scalar" : "guid list";
case 4: return b ? "byte scalar" : "byte list";
case 5: return b ? "short scalar" : "short list";
case 6: return b ? "int scalar" : "int list";
case 7: return b ? "long scalar" : "long list";
case 8: return b ? "real scalar" : "real list";
case 9: return b ? "double scalar" : "double list";
case 10: return b ? "char scalar" : "char list";
case 11: return b ? "symbol scalar" : "symbol list";
case 12: return b ? "timestamp scalar" : "timestamp list";
case 13: return b ? "month scalar" : "month list";
case 14: return b ? "date scalar" : "date list";
case 15: return b ? "datetime scalar" : "datetime list";
case 16: return b ? "timespan scalar" : "timespan list";
case 17: return b ? "minute scalar" : "minute list";
case 18: return b ? "second scalar" : "second list";
case 19: return b ? "time scalar" : "time list";
case 97: return "nested sym enum";
case 98: return "table";
case 99: return "kdictionary";
case 100: return "lambda";
case 101: return "null/unary primitive";
case 102: return "operator";
case 103: return "adverb";
case 104: return "projection";
case 105: return "composition";
case 106: return "f'";
case 107: return "f/";
case 108: return "f\\";
case 109: return "f':";
case 110: return "f/:";
case 111: return "f\\:";
case 112: return "dynamic load fn";
case -128: return "error";
default:
if(t>19 && t<77)
return b ? "enum scalar" : "enum list";
else if(t>76 && t<97)
return "map";
else
return "unrecognized type";
}
}
const char* kname(K x) {return xptr(x) ? mapclass(xtag(x)->a) : kname(x->t);}
const char* kname(K x,J i) {return xind(x,i) ? kname(kK(x)[i]) : kname(x);}
// ----------------------------------------------------------------------------
// ksizeof - given k type, return size of element, e.g. KF -> 8
// maptype - map k data type to/from torch type
// mapattr - make attr enum to symbol
// emap - map sym -> enum (enum used to pick variant member, e.g. torch::kMean)
// input,output - map from Input/Output variant value to symbol
// ----------------------------------------------------------------------------
J ksizeof(Ktype k) {
switch(k) {
case KE: return sizeof(E);
case KF: return sizeof(double);
case KJ: return sizeof(J);
case KI: return sizeof(I);
case KSHORT: return sizeof(H);
case KC: return sizeof(C);
case KB:
case KG: return sizeof(G);
default: TORCH_ERROR("no element size for k ",kname(k)); return -1;
}
}
Ktype maptype(TypeMeta s) {
for(const auto& m:env().dtype)
if(s==std::get<1>(m)) return std::get<2>(m);
TORCH_ERROR("no k data type found for torch type: ",s);
return 0;
}
TypeMeta maptype(Ktype k) {
Ktype t=(k<0) ? -k : k;
for(const auto &m:env().ktype)
if(t==std::get<0>(m)) return std::get<1>(m);
TORCH_ERROR("no torch type found for k: ",kname(k));
}
S mapattr(Attr a) {
for(const auto& m:env().attr)
if(a==std::get<1>(m)) return std::get<0>(m);
TORCH_ERROR("unrecognized attribute: ", (I)a);
}
Enum emap(S s) {
for(const auto& m:env().enums)
if(std::get<0>(m)==s) return std::get<1>(m);
return Enum::undefined;
}
S emap(Enum e) {
for(const auto& m:env().enums)
if(std::get<1>(m)==e) return std::get<0>(m);
TORCH_ERROR("unrecognized enumeration: ",(I)e);
}
S inputname(const Input& x) {return env().in [x.index()];}
S outputname(const Output& x) {return env().out[x.index()];}
// ------------------------------------------------------------------------------------------
// statekey - map from state attribute enumeration to symbol, e.g. State::parms -> `parms
// statefind - search dictionary keys/table colums for symbol matching given enumeration
// statelong - search dict/table for long value
// statesym - given dict/table defining module(s), find symbols for module else null
// statedict - given enumeration, return k dictionary stored at matching key/col else null
// ------------------------------------------------------------------------------------------
S statekey(State e) {
for(const auto& m:env().state)if(e==std::get<1>(m)) return std::get<0>(m);
TORCH_ERROR("unrecognized state attribute: ",(I)e);
}
J statefind(State e,K x,bool r) {
if(!xstate(x))
TORCH_ERROR("expected dictionary or table describing state, given ",kname(x));
S s=statekey(e); K k=kK(x->t == 98 ? x->k : x)[0];
for(J i=0;i<k->n;++i) if(kS(k)[i]==s) return i;
TORCH_CHECK(!r, "unable to find state attribute: ",statekey(e));
return -1;
}
static J statelong(State e,bool r,K x,J j) { //e:enum, e.g. State::depth, r:required flag, x:dict/table, j:table row
J i=statefind(e,x,r);
if(i<0) {
return nj;
} else if(x->t==99) {
K v=kK(x)[1];
if(v->t) {
TORCH_CHECK(v->t==KJ, statekey(e),": expected long, given ",kname(v));
return kJ(v)[i];
} else {
v=kK(v)[i];
TORCH_CHECK(v->t==-KJ, statekey(e),": expected long, given ",kname(v));
return v->j;
}
} else if(x->t==98) {
K v=kK(kK(x->k)[1])[i];
TORCH_CHECK(v->t==KJ, statekey(e),": expected long, given ",kname(v));
TORCH_CHECK(j>-1 && j<v->n, statekey(e),"[", j,"] index beyond ",v->n,"-row table");
return kJ(v)[j];
} else {
TORCH_ERROR("expecting state dictionary or table, given ",kname(x));
}
}
S statesym(State e, bool r,K x,J j) {
// e:enum, e.g. State::module, r:required, x:dict/table, j:table row or -1
J i=statefind(e,x,r);
if(i<0) {
return nullptr;
} else if(x->t==99) {
K v=kK(x)[1];
if(v->t) {
TORCH_CHECK(v->t==KS, statekey(e),": expected symbol, given ",kname(v));
return kS(v)[i];
} else {
v=kK(v)[i];
TORCH_CHECK(v->t==-KS, statekey(e),": expected symbol, given ",kname(v));
return v->s;
}
} else if(x->t==98) {
K v=kK(kK(x->k)[1])[i];
TORCH_CHECK(v->t==KS, statekey(e),": expected symbol, given ",kname(v));
TORCH_CHECK(j>-1 && j<v->n, statekey(e),"[", j,"] index beyond ",v->n,"-row table");
return kS(v)[j];
} else {
TORCH_ERROR("expecting state dictionary or table, given ",kname(x));
}
}
K statedict(State e,K x,J j) {
// e:enum, e.g. State::options, x:dict/table, j:row (if table, else -1)
J i=statefind(e,x);
if(i<0) return nullptr;
K v=x->t == 98 ? kK(kK(x->k)[1])[i] : kK(x)[1];
if(x->t == 99) j=i;
TORCH_CHECK(!v->t, statekey(e),": expected general list, given ",kname(v));
TORCH_CHECK(-1<j && j<v->n, statekey(e),"[",j,"] index beyond ",v->n,"-row table");
v=kK(v)[j];
TORCH_CHECK(v->t==99, statekey(e),": expected dictionary, given ",kname(v));
return v;
}
static K statelist(State e,K x,J j) { // e:enum, e.g. State::size, x:dict/table, j:row (if table)
J i=statefind(e,x);
if(i<0) return nullptr;
K v=x->t == 98 ? kK(kK(x->k)[1])[i] : kK(x)[1];
if(x->t == 99) j=i;
TORCH_CHECK(!v->t, statekey(e),": expected general list, given ",kname(v));
TORCH_CHECK(-1<j && j<v->n, statekey(e),"[",j,"] index beyond ",v->n,"-row table");
v=kK(v)[j];
return v;
}
K statetable(State e,K x) {
J i=statefind(e,x);
if(i<0) return nullptr;
TORCH_CHECK(x->t==99, "expecting dictionary containing ",statekey(e),", given ",kname(x->t));
K v=kK(x)[1]; TORCH_CHECK(!v->t, statekey(e),": expected general list, given ",kname(v));
v=kK(v)[i]; TORCH_CHECK(v->t==98, statekey(e),": expected table, given ",kname(v));
return v;
}
K statecol(State e,K x,short t) {
TORCH_CHECK(x->t==98,"expecting table with ",statekey(e)," column, given ",kname(x->t));
J i=statefind(e,x);
if(i<0) return nullptr;
K v=kK(kK(x->k)[1])[i];
TORCH_CHECK(t==nh || v->t==t, statekey(e)," column expected as ",kname(t),", given as ",kname(v->t));
return v;
}
// --------------------------------------------
// convenience functions to return state value
// --------------------------------------------
J statedepth(K x,J j) {return statelong(State::depth,true,x,j);}
J stategroup(K x,J j) {return statelong(State::parmgroup,true,x,j);}
S statemodule(K x,J j) {return statesym(State::module,true,x,j);}
S statename(K x,J j) {return statesym(State::name,false,x,j);}
K stateoptions(K x,J j) {return statedict(State::options,x,j);}
K stateparms(K x,J j) {return statedict(State::parms,x,j);}
K statebuffers(K x,J j) {return statedict(State::buffers,x,j);}
K statesize(K x,J j) {return statelist(State::size,x,j);}
// ------------------------------------------------------
// nullsym - return null symbol or test for null symbol
// knull - return k null, i.e. (::)
// ------------------------------------------------------
S nullsym() {return env().nullsym;}
bool nullsym(S s) {return s==env().nullsym;}
bool nullsym(K x) {return x->t==-KS && nullsym(x->s);}
K knull() {K x=ka(101); x->g=0; return x;}
// --------------------------------------------------------------------------------------
// xnull - true if null, i.e. (::)
// xempty - true if null or empty K list without type, i.e. :: or ()
// --------------------------------------------------------------------------------------
bool xnull(K x) {return x->t==101 && x->g==0;}
bool xnull(K x,J i) {return xind(x,i) && xnull(kK(x)[i]);}
bool xempty(K x) {return xnull(x) ? true : (x->t ? false : x->n==0);}
bool xempty(K x,J i) {return xind(x,i) && xempty(kK(x)[i]);}
// ---------------------------------------------------------------------------------------
// arraytype - true if k type is mapped to a tensor type
// xarray - true if x is an array that can be converted to a tensor, test up to m elements
// ---------------------------------------------------------------------------------------
static bool arraytype(short t) {
if(t<0) t = -t;
for(const auto &m:env().ktype)
if(t==std::get<0>(m))
return true;
return false;
}
static bool xarray(K x,size_t d,Ksize& s,Ktype& t) {
if(ptrtype(x)) { // no pointers allowed
return false;
} else if(t==-128) { // if no base type yet
if(x->t) { // if type, see if possible tensor type
if(!arraytype(x->t)) return false;
t=x->t; // 1st base type encountered
if(t>0) s.push_back(x->n); // unless scalar, track size
return true; // possible array
} else {
s.push_back(x->n); // no base type yet, track size
return x->n ? xarray(kK(x)[0],d+1,s,t) : (t=0,true);
}
} else if(x->t) { // already defined base type
if(t != x->t || t<0) // type mismatch or subsequent scalar
return false; // not valid array
else // also invalid if not matching size at depth
return d==s.size()-1 && x->n==s.at(d);
} else {
if(d<s.size() && x->n == s[d]) // size at depth matches
return x->n ? xarray(kK(x)[0],d+1,s,t) : true;
else
return false;
}
}
bool xarray(K x,J m) {
Ksize s; Ktype t=-128;
if(x->t) {
return xarray(x,0,s,t);
} else if(ptrtype(x)) {
return false;
} else {
if(x->n < m) m=x->n;
for(J i=0; i<m; ++i)
if(!xarray(kK(x)[i],0,s,t))
return false;
return true;
}
}
// --------------------------------------------------------------------------------------
// xsym - if arg is k symbol, return true and set sym, else false
// xsyms - if sym scalar or non-empty sym list, set 1st sym and return true
// - alternate form using symbol array ref
// --------------------------------------------------------------------------------------
bool xsym(K x) {return x->t==-KS;}
bool xsym(K x,J i) {return xind(x,i,KS) || (xind(x,i) && xsym(kK(x)[i]));}
bool xsym(K x,S &s) {return (x->t==-KS) ? s=x->s,true : false;}
bool xsym(K x,J i,S &s) {
if(xind(x,i,KS))
return s=kS(x)[i], true;
else
return xind(x,i) && xsym(kK(x)[i],s);
}
bool xsyms(K x,S &s) {
if(xsym(x,s)) return true;
else if(x->t == KS && x->n) return s=kS(x)[0],true;
else return false;
}
bool xsyms(K x,SymArrayRef& s) {
if(x->t==-KS)
return s=SymArrayRef(&x->s,1), true;
else if(x->t==KS)
return s=SymArrayRef(kS(x),x->n), true;
else
return false;
}
bool xsyms(K x,J i,SymArrayRef& s) {
return xind(x,i) ? xsyms(kK(x)[i],s) : false;
}
// --------------------------------------------------------------------------------------
// xdev - check sym for map to list of known devices, `cpu`cuda`cuda:0`cuda:1..
// xint64 - check for long scalar/list element and convert to int64_t or optional int64_t
// xlong - check for long scalar/list, set value(s) and return true else false
// xdouble - check for scalar double from k, set value and return true, false else
// xdict - return true if k value is a dictionary
// xstate - check for dictionary/table defining module state
// xsize - check for long(s)/double(s), set array ref/expanding array used for sizing
// --------------------------------------------------------------------------------------
bool xdev(K x,Device &d) {
if(x->t==-KS) {
for(const auto& m:env().device)
if(x->s==std::get<0>(m)) return d=std::get<1>(m),true;
}
return false;
}
bool xdev(K x,J i,Device &d) {return xind(x,i) && xdev(kK(x)[i],d);}
bool xint64(K x,int64_t &j) {return (x->t == -KJ) ? j=x->j,true : false;} //J -> int64_t (linux differentiates)
bool xint64(K x,J i,int64_t &j) {
if(xind(x,i)) // i'th element of general list exists
return xint64(kK(x)[i],j); // check if long scalar, set & return true
else if(xind(x,i,KJ)) // check for long list and valid index i
return j=kJ(x)[i],true;
else
return false;
}
//bool xint64(K x,J i,int64_t &j) {return xind(x,i) && xint64(kK(x)[i],j);}
bool xint64(K x,c10::optional<int64_t> &j) {
int64_t n; j=c10::nullopt;
if(xint64(x,n)) {
if(n != nj) j=n;
return true;
} else {
return false;
}
}
bool xint64(K x,J i,c10::optional<int64_t> &j) {
int64_t n; j=c10::nullopt;
if(xint64(x,i,n)) {
if(n != nj) j=n;
return true;
} else {
return false;
}
}
bool xlong(K x,J &j) {return (x->t == -KJ) ? j=x->j,true : false;} //check k scalar
bool xlong(K x,J i,J &j) {return xind(x,i) && xlong(kK(x)[i],j);} //check k list element
bool xlong(K x,J &n,J *&v){ //check for k list of longs
if(x->t == KJ){ n=x->n; v=kJ(x); return true; //list of long ints
} else if(x->t == -KJ){ n=1; v=&x->j; return true; //scalar long ok too
} else if(x->t == 0 && x->n == 0) { n=0; return true; //empty,no type also ok
} else { return false;
}
}
bool xlong(K x,J i,J &n, J *&v) {return xind(x,i) && xlong(kK(x)[i],n,v);} // check element of k list
bool xdouble(K x,double &f) {return (x->t == -KF) ? f=x->f,true : false;} //check k scalar
bool xdouble(K x,J i,double &f) {return xind(x,i) && xdouble(kK(x)[i],f);} //check k list element
bool xdouble(K x,J &n,double *&v){ //check for k list of doubles
if(x->t == KF){ n=x->n; v=kF(x); return true; //list of doubles
} else if(x->t == -KF){ n=1; v=&x->f; return true; //scalar double ok too
} else if(x->t == 0 && x->n == 0) { n=0; return true; //empty,no type also ok
} else { return false;
}
}
bool xdouble(K x,J i,J &n,double *&v) {return xind(x,i) && xdouble(kK(x)[i],n,v);} // check element of k list
bool xdict(K x) {return x->t==99 && (kK(x)[0]->t==KS || (kK(x)[0]->t==0 && kK(x)[0]->n==0));}
bool xdict(K x,J i) {return xind(x,i) && xdict(kK(x)[i]);}
bool xstate(K x) {return xdict(x) || x->t==98;}
bool xstate(K x,J i) {return xind(x,i) && xstate(kK(x)[i]);}
// retrieve long integers from x -> IntArrayRef (linux clang/gcc require int64_t* from J*)
bool xsize(K x,IntArrayRef &s) {J n,*v; return (xlong(x,n,v)) ? s=IntArrayRef((int64_t*)v,n),true : false;}
bool xsize(K x,J i,IntArrayRef &s) {return xind(x,i) && xsize(kK(x)[i],s);} //check element of k list
// retrieve long integers/doubles from x -> ExpandingArray ptr of longs/floats
bool xsize(K x,J d,int64_t *a) {
bool b=false;
if((b=x->t == -KJ)) {
for(J i=0;i<d;++i) a[i]=x->j;
} else if(x->t == KJ) {
if((b=d == x->n))
for(J i=0;i<d;++i) a[i]=kJ(x)[i];
else
TORCH_ERROR(d,"-element list of long integers expected, ",x->n," supplied");
}
return b;
}
bool xsize(K x,J d,double *a) {
bool b=false;
if((b=x->t == -KF)) {
for(J i=0;i<d;++i) a[i]=x->f;
} else if(x->t == KF) {
if((b=d == x->n))
for(J i=0;i<d;++i) a[i]=kF(x)[i];
else
TORCH_ERROR(d,"-element list of doubles expected, ",x->n," supplied");
}
return b;
}
bool xsize(K x,J i,J d,int64_t *a) {return xind(x,i) && xsize(kK(x)[i],d,a);}
bool xsize(K x,J i,J d,double *a) {return xind(x,i) && xsize(kK(x)[i],d,a);}
// ----------------------------------------------------------------------------------------------
// xten - check arg(s) for allocated ptr to tensor: set tensor & return true if found, else false
// - 2nd form, return tensor pointer if found from k value, else null
// xout - check for tensor at end of list of args, return output tensor pointer
// xvec - check arg(s) for allocated vector of tensors
// xtensordict - check arg(s) for allocated dictionary of tensors
// ----------------------------------------------------------------------------------------------
bool xten(K x,Tensor &t) {
if(auto* a=xtag(x))
if(a->a==Class::tensor && a->c==Cast::tensor)
return t=((Kten*)a)->t, true;
return false;
}
Tensor* xten(K x) {
if(auto* a=xtag(x))
if(a->a==Class::tensor && a->c==Cast::tensor)
return &((Kten*)a)->t;
return nullptr;
}
bool xten(K x,J i,Tensor& t) {return xind(x,i) && xten(kK(x)[i],t);}
Tensor* xten(K x,J i) {return xind(x,i) ? xten(kK(x)[i]) : nullptr;}
Tensor* xout(K x) {return (!x->t && x->n>1) ? xten(x,x->n-1) : nullptr;}
TensorVector* xvec(K x) {
if(auto* a=xtag(x))
if(a->a==Class::vector && a->c==Cast::tensor)
return &((Kvec*)a)->v;
return nullptr;
}
TensorVector* xvec(K x,J i) {return xind(x,i) ? xvec(kK(x)[i]) : nullptr;}
TensorDict* xtensordict(K x) {
if(auto* a=xtag(x))
if(a->a==Class::dict && (a->c==Cast::tensor || a->c==Cast::parameter || a->c==Cast::buffer))
return &((Kdict*)a)->d;
return nullptr;
}
TensorDict* xtensordict(K x,J i) {return xind(x,i) ? xtensordict(kK(x)[i]) : nullptr;}
// ----------------------------------------------------------------------------------------------
// xtenarg - check arg(s) for a list of allocated tensors, or list of input arrays or mix of both
// ----------------------------------------------------------------------------------------------
bool xtenarg(K x,J i,Tensor& a,Tensor& b) {
if(xten(x,i,a)) {
if(!xten(x,i+1,b))
b=kput(x,i+1).to(a.device()); // tensor b from array, move to a's device
return true;
} else if(xten(x,i+1,b)) {
return a=kput(x,i).to(b.device()), true; // tensor a from array, move to b's device
} else {
return a=kput(x,i), b=kput(x,i+1), false; // both a & b from arrays, leave on cpu
}
}
bool xtenarg(K x,J i,Tensor& a,Tensor& b,Tensor &c) {
if(xten(x,i,a)) {
if(!xten(x,i+1,b))
b=kput(x,i+1).to(a.device()); // tensor b from array, move to a's device
if(!xten(x,i+2,c))
c=kput(x,i+2).to(a.device()); // tensor c from array, move to a's device
return true;
} else if(xten(x,i+1,b)) { // tensor b supplied
a=kput(x,i).to(b.device()); // tensor a from array, move to b's device
if(!xten(x,i+2,c))
c=kput(x,i+2).to(b.device()); // tensor c from array, move to b's device
return true;
} else if(xten(x,i+2,c)) { // tensor c supplied
a=kput(x,i).to(c.device()); // tensor a from array, move to c's device
b=kput(x,i+1).to(c.device()); // tensor b from array, move to c's device
return true;
} else { // a,b,c from arrays -> cpu tensors
return a=kput(x,i), b=kput(x,i+1), c=kput(x,i+2), false;
}
}
bool xtenarg(K x,Tensor& a,Tensor &b) {return xtenarg(x,0,a,b);}
bool xtenarg(K x,Tensor& a,Tensor &b,Tensor &c) {return xtenarg(x,0,a,b,c);}
// -----------------------------------------------------
// xtensors - return vector given arrays/tensors/vector
// -----------------------------------------------------
TensorVector xtensors(K x,bool& p,const char* c) {
p=false;
if(auto *a=xten(x)) { p=true; return {*a};
} else if(auto *a=xvec(x)) { p=true; return *a;
} else if(x->t) { return {kput(x)};
} else {
TORCH_CHECK(!x->t, c,": unexpected arg, ",kname(x));
TensorVector v; Device d(DeviceType::CPU);
for(J i=0; i<x->n; ++i) {
K y=kK(x)[i];
if(auto *a=xten(y)) {
if(p) {
TORCH_CHECK(d==a->device(), c,": given tensor on device ",a->device()," but previous tensor(s) on ",d);
} else {
p=true; d=a->device(); // tensor given, set flag and keep track of 1st device encountered
for(auto &t:v) t=t.to(d); // put all k-array inputs so far on given tensor's device
}
v.emplace_back(*a);
} else {
TORCH_CHECK(!ptrtype(y), c,": arg[",i,"] unexpected, given ",kname(y));
v.emplace_back(kput(y).to(d));
}
}
return v;
}
}
// ----------------------------------------------------------------------------
// xmodule - check arg(s) for allocated module pointer
// xloss - check arg(s) for allocated loss module
// xoptim - check arg(s) for allocated optimizer pointer
// xmodel - check arg(s) for allocated model pointer (module, loss & optimizer)
// ----------------------------------------------------------------------------
Kmodule* xmodule(K x) {auto* g=xtag(x); return (g && g->a==Class::module) ? g->kmodule() : nullptr;}
Kmodule* xmodule(K x,J i) {return xind(x,i) ? xmodule(kK(x)[i]) : nullptr;}
Kmodule* xloss(K x) {auto* g=xtag(x); return (g && g->a==Class::loss) ? g->kmodule() : nullptr;}
Kmodule* xloss(K x,J i) {return xind(x,i) ? xloss(kK(x)[i]) : nullptr;}
Kopt* xoptim(K x) {auto* g=xtag(x); return (g && g->a==Class::optimizer) ? (Kopt*)g : nullptr;}
Kopt* xoptim(K x,J i) {return xind(x,i) ? xoptim(kK(x)[i]) : nullptr;}
Kmodel* xmodel(K x) {auto* g=xtag(x); return (g && g->a==Class::model) ? (Kmodel*)g : nullptr;}
Kmodel* xmodel(K x,J i) {return xind(x,i) ? xmodel(kK(x)[i]) : nullptr;}
// ----------------------------------------------------------------------------
// xparm - check for model/module & parm/buffer name
// ----------------------------------------------------------------------------
bool xparm(K x,Cast c,S& s,Tensor& t) {
bool b=false; s=nullptr;
if(xsym(x,1,s)) {
auto *g=xtag(x,0); const Tensor *a=nullptr;
switch(g ? g->a : Class::undefined) {
case Class::dict:
a=g->dict().find(s);
TORCH_CHECK(a, "unable to find dictionary ",tensortype(g->c)," `",s);
break;
case Class::loss:
case Class::module:
case Class::model:
case Class::optimizer:
a=findtensor(g->module(),s,c);
TORCH_CHECK(a, "unable to find ",mapclass(g->a)," ",tensortype(c)," `",s);
break;
default:
TORCH_ERROR("given ",tensortype(c)," name `",s,", expecting 1st arg of model, module or tensor dictionary, not ",kname(x,0));
break;
}
b=true; t=*a;
}
return b;
}
// ------------------------------------------------------------------------------------------------------
// xnum - check for double or long int k scalar, set double & return true, else false
// xnum - check for number(float,double,long,int,short), set torch scalar & return true, else false
// xnumn - similar to xnum, but with optional scalars which remain unset if null scalar from k
// xnumt - similar to xnum, but also attempts to convert tensor to scalar
// xnumlist - take single value from k numeric list -> torch scalar
// xbyte - convert k bool,char,byte -> torch scalar
// xscalar - convert k number or byte -> torch scalar
// ------------------------------------------------------------------------------------------------------
bool xnum(K x,double &f) {
switch(x->t) {
case -KF: return f=x->f,true;
case -KJ: return f=x->j,true;
default: return false;
}
}
bool xnum(K x,J i,double &f) {
if(xind(x,i,KF))
return f=kF(x)[i],true;
else if(xind(x,i,KJ))
return f=kJ(x)[i],true;
else
return xind(x,i) && xnum(kK(x)[i],f);
}
bool xnum(K x,Scalar& s) {
switch(x->t) {
case -KF: return s=x->f, true;
case -KE: return s=x->e, true;
case -KJ: return s=(int64_t)x->j, true;
case -KI: return s=x->i, true;
case -KSHORT: return s=x->h, true;
default: return false;
}
}
bool xnum(K x,J i,Scalar& s) {return xind(x,i) && xnum(kK(x)[i],s);}
bool xnumn(K x,c10::optional<Scalar>& s) {
switch(x->t) {
case -KF: if(x->f==x->f) s=x->f; return true;
case -KE: if(x->e==x->e) s=x->e; return true;
case -KJ: if(x->j!=nj) s=(int64_t)x->j; return true;
case -KI: if(x->i!=ni) s=x->i; return true;
case -KSHORT: if(x->h!=nh) s=x->h; return true;
default: return false;
}
}
bool xnumn(K x,J i,c10::optional<Scalar>& s) {return xind(x,i) && xnumn(kK(x)[i],s);}
bool xnumt(K x,Scalar& s) {
Tensor t;
if(xnum(x,s)) return true;
else if(xten(x,t)) return s=t.item(), true;
else return false;
}
bool xnumt(K x,J i,Scalar& s) {return xind(x,i) && xnumt(kK(x)[i],s);}
bool xnumlist(K x,J i,Scalar &a) {
switch(x->t) {
case KF: return a=kF(x)[i], true;
case KE: return a=kE(x)[i], true;
case KJ: return a=(int64_t)kJ(x)[i], true;
case KI: return a=kI(x)[i], true;
case KSHORT: return a=kH(x)[i], true;
case KB:
case KC: return a=kG(x)[i], true;
default: return false;
}
}
bool xbyte(K x,Scalar &s) { return (x->t==-KB || x->t==-KC || xt==-KG) ? s=x->g,true : false;}
bool xbyte(K x,J i,Scalar &s) {return xind(x,i) && xbyte(kK(x)[i],s);}
bool xscalar(K x,Scalar &s) { return xnum(x,s) || xbyte(x,s);}
bool xscalar(K x,J i,Scalar &s) {return xind(x,i) && xscalar(kK(x)[i],s);}
// ------------------------------------------------------------------------------------------------------
// xbool - if value is boolean, set value and return true, else false
// mtype - match sym to/from TypeMeta(newer datatype from Caffe2)
// stype = match sym to/from TypeMeta to Dtype (torch::Dtype, aka at::ScalarType)
// xtype - symbol to scalar type or type meta, return true if scalar type/type meta set, else false
// xopt - sym(s) -> tensor options, return true if ok, false if not sym(s) or error if unknown sym
// xmode - check if sym, if matches a known tensor creation mode, set mode and return true else false
// xbacksym - check if sym, if matches back prop graph setting, set retain/create graph flags else false
// ------------------------------------------------------------------------------------------------------
bool xbool(K x,bool &b) {return (x->t == -KB) ? b=x->g,true : false;}
bool xbool(K x,J i,bool &b) {return xind(x,i) && xbool(kK(x)[i],b);}
TypeMeta mtype(S s) {
for(const auto& m:env().dtype) if(s==std::get<0>(m)) return std::get<1>(m);
TORCH_ERROR("unrecognized data type: ",(s==nullsym() ? "(null)" : s));
}
S mtype(TypeMeta t) {
for(const auto& m:env().dtype) if(t==std::get<1>(m)) return std::get<0>(m);
TORCH_ERROR("unrecognized data type: ",t);
}
Dtype stype(S s) {return torch::typeMetaToScalarType(mtype(s));}
S stype(Dtype t) {return mtype(torch::scalarTypeToTypeMeta(t));}
S stype(c10::optional<Dtype> t) {return mtype(torch::scalarTypeToTypeMeta(t ? *t : Dtype::Undefined));}
bool xtype(K x,TypeMeta &t) {if(x->t == -KS) return t=mtype(x->s), true; return false;}
bool xtype(K x,Dtype &t) {if(x->t == -KS) return t=stype(x->s), true; return false;}
bool xtype(K x,c10::optional<Dtype> &t) {
if(x->t != -KS)
return false;
if(nullsym(x->s))
t=c10::nullopt;
else
t=stype(x->s);
return true;
}
bool xtype(K x,J i,TypeMeta &t) {return xind(x,i) && xtype(kK(x)[i],t);}
bool xtype(K x,J i,Dtype &t) {return xind(x,i) && xtype(kK(x)[i],t);}
bool xtype(K x,J i,c10::optional<Dtype> &t) {return xind(x,i) && xtype(kK(x)[i],t);}
bool xopt(S s,TensorOptions &o) {
auto &e=env();
for(const auto& m:e.device)
if(s == std::get<0>(m)) return o=o.device(std::get<1>(m)), true;
for(const auto& m:e.dtype)
if(s == std::get<0>(m)) return o=o.dtype(std::get<1>(m)), true;
for(const auto& m:e.layout)
if(s == std::get<0>(m)) return o=o.layout(std::get<1>(m)), true;
for(const auto& m:e.gradient)
if(s == std::get<0>(m)) return o=o.requires_grad(std::get<1>(m)), true;
for(const auto& m:e.pin)
if(s == std::get<0>(m)) return o=o.pinned_memory(std::get<1>(m)), true;
for(const auto& m:e.memory)
if(s == std::get<0>(m)) return o=o.memory_format(std::get<1>(m)), true;
return false;
}
bool xopt(K x,TensorOptions &o) {
if (x->t == -KS || x->t == KS) {
bool a=x->t < 0; I i,n=a ? 1 : x->n;
for(i=0; i<n; ++i) {
S s=a ? x->s : kS(x)[i];
if (!xopt(s,o))
TORCH_ERROR("unrecognized tensor option: `", s);
}
return true;
} else {
return false;
}
}
bool xopt(K x,J i,TensorOptions &o) { return !x->t && 0<x->n && i<x->n && xopt(kK(x)[i],o);}
bool xmode(K x,S &s,Tensormode &m) {
if(x->t == -KS) {
for(const auto& v:env().tensormode)
if(x->s == std::get<0>(v)) return s=x->s,m=std::get<1>(v), true;
TORCH_ERROR("unrecognized tensor creation mode: ",x->s);
}
return false;
}
bool xmode(K x,J i,S &s,Tensormode &m) {return xind(x,i) && xmode(kK(x)[i],s,m);}
S modesym(Tensormode &m) {
for(const auto& a:env().tensormode)
if(m == std::get<1>(a)) return std::get<0>(a);
TORCH_ERROR("unrecognized tensor creation mode: ",(I)m);
}
bool xbacksym(K x,bool& a,bool& b) {
if(x->t == -KS) {
for(const auto& s:env().backsym)
if(x->s == std::get<0>(s)) return a=std::get<1>(s),b=std::get<2>(s), true;
TORCH_ERROR("unrecognized setting for backprop: ",x->s,", expecting one of: free,retain,create or createfree");
}
return false;
}
bool xbacksym(K x,J i,bool& a,bool& b) {return xind(x,i) && xbacksym(kK(x)[i],a,b);}
// ------------------------------------------------------------------------------------------
// xpairs - initialize a set of name-value pairs given as an argument from k
// xpair - check the next name-value pair, set sym,numeric,list or general value
// xargc - return count of args to process given arg(s), offset, pairs structure to initiate
// xnone - return true if, given arg list and offset, no meaningful arg supplied
// ------------------------------------------------------------------------------------------
bool xpairs(K x,Pairs& p) { // initialize Pairs structure from k value
p.a=0, p.i=0, p.n=0; // sets a: 1-dict,2-pairs,3-list,4-syms
if(x->t==99) {
K y=kK(x)[0];
if(y->t==KS || !(y->t || y->n))
p.a=1, p.n=y->n;
else
TORCH_ERROR("unexpected name,value dictionary with ",kname(kK(x)[0]->t)," as keys: ",kstring(x));
} else if(x->t==KS) {
if(x->n%2==0)
p.a=4, p.n=x->n/2;
else
TORCH_ERROR("uneven no. of symbols for name,value pairs: ", kstring(x));
} else if(!x->t) {
if(!x->n) { // empty list
p.a=2, p.n=0;
} else if(kK(x)[0]->t==-KS) { // list of (sym1;val1;sym2;val2..)
if(x->n%2==0)
p.a=3, p.n=x->n/2;
else
TORCH_ERROR("uneven no. of elements for name,value pairs in list: ",kstring(x));
} else { // assume list of pairs if symbol in first pair
K y=kK(x)[0];
if(y->n==2 && (y->t==KS || (!y->t && kK(y)[0]->t==-KS)))
p.a=2, p.n=x->n;
}
}
return p.a ? (p.x=x,true) : false;
}
bool xpairs(K x,J i,Pairs& p) {return xind(x,i) && xpairs(kK(x)[i],p);}
static void xpair(Pairs& p,K x,J i) {
if(x->t<0) {
switch(x->t) {
case -KS: p.s=x->s; p.t=-KS; break;
case -KB: p.b=x->g; p.t=-KB; break;
case -KSHORT: p.j=x->h; p.t=-KJ; break;
case -KI: p.j=x->i; p.t=-KJ; break;
case -KJ: p.j=x->j; p.t=-KJ; break;
case -KE: p.e=x->e; p.t=-KE; break;
case -KF: p.f=x->f; p.t=-KF; break;
default: TORCH_ERROR("name-value pairs not implemented for ",kname(x->t)," value"); break;
}
} else if (i>-1) {
if(i>=x->n)
TORCH_ERROR("name,value index[",i,"] invalid for ",kname(x->t)," with ",x->n," elements");
switch(x->t) {
case 0: xpair(p,kK(x)[i],-1); break;
case KS: p.s=kS(x)[i]; p.t=-KS; break;
case KB: p.b=kG(x)[i]; p.t=-KB; break;
case KSHORT: p.j=kH(x)[i]; p.t=-KJ; break;
case KI: p.j=kI(x)[i]; p.t=-KJ; break;
case KJ: p.j=kJ(x)[i]; p.t=-KJ; break;
case KE: p.e=kE(x)[i]; p.t=-KE; break;
case KF: p.f=kF(x)[i]; p.t=-KF; break;
default: TORCH_ERROR("name-value pairs not implemented for ",kname(x->t)," value"); break;
}
} else {
p.v=x; p.t=x->t;
}
}
bool xpair(Pairs& p) {
if(p.i<0 || p.i>=p.n) return false;
I i=p.i; p.k=nullptr; p.v=nullptr; K y;
switch(p.a) {
case 1: //dictionary
p.k=kS(kK(p.x)[0])[i]; xpair(p,kK(p.x)[1],i); break;
case 2: //list of name-value pairs
y=kK(p.x)[i];
if(xlen(y)!= 2) {
TORCH_ERROR("name,value pair[",i,"] has ",xlen(y)," elements (expected 2)");