forked from ktorch/ktorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmodel.cpp
More file actions
1939 lines (1796 loc) · 73.6 KB
/
Copy pathkmodel.cpp
File metadata and controls
1939 lines (1796 loc) · 73.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 OPTION(x,k,v) dictadd(x, modelopt(Setting::k), v)
// ---------------------------------------------------------------------------------------
// resetgrad - zero out or set gradient to none if boolean flag set true
// zerograd - zero gradients on tensor, vector of tensors, optimizer, module or model
// nograd - set gradient to none for tensor, vector of tensors, optimizer, module or model
// ---------------------------------------------------------------------------------------
static void resetgrad(const Tensor& t,bool b){
auto &g=t.mutable_grad();
if(g.defined()) {
g=g.detach();
if(b)
g.reset();
else
g.zero_();
}
}
static void resetgrad(const TensorVector& v,bool b){
for(const auto& t:v)
resetgrad(t,b);
}
static void resetgrad(const TensorDict& d,bool b){
for(const auto& i:d)
resetgrad(i.value(),b);
}
static void resetgrad(Module& m,bool b){
m.zero_grad(b);
}
static void resetgrad(Optimizer& o,bool b){
if(b) {
for(const auto& p:o.param_groups())
for(const auto &t:p.params())
resetgrad(t,b);
} else {
o.zero_grad();
}
}
K resetgrad(K x,bool b,const char *c) {
KTRY
auto *g=xtag(x);
TORCH_CHECK(g, c,": not implemented for ",kname(x));
switch(g->a) {
case Class::tensor: resetgrad(g->tensor(),b); break;
case Class::vector: resetgrad(g->vector(),b); break;
case Class::dict: resetgrad(g->dict(),b); break;
case Class::module: resetgrad(g->module(),b); break;
case Class::optimizer:
case Class::model: resetgrad(g->opt(),b); break;
default: TORCH_ERROR(c,": not implemented for ",mapclass(g->a));
}
return (K)0;
KCATCH(c);
}
KAPI nograd(K x) {return resetgrad(x, true, "nograd");}
KAPI zerograd(K x) {return resetgrad(x, false, "zerograd");}
// -------------------------------------------------------------------
// metric - map k symbol <-> metric, e.g. `output -> Metric::output
// -------------------------------------------------------------------
static Metric metric(S s) {
for(const auto& m:env().metric)
if(std::get<0>(m)==s) return std::get<1>(m);
TORCH_ERROR("unrecognized metric: ",s);
}
static S metric(Metric m) {
for(const auto& a:env().metric)
if(std::get<1>(a)==m) return std::get<0>(a);
TORCH_ERROR("unrecognized metric: ",(I)m);
}
// -------------------------------------------------------------------------------------------
// training - query/set training flag given model or module layer
// trainflag - set training flag & return previous setting
// -------------------------------------------------------------------------------------------
KAPI training(K x) {
KTRY
bool b; Ktag *g;
TORCH_CHECK((g=xtag(x)) || ((g=xtag(x,0)) && x->n==2 && xbool(x,1,b)),
"training: unrecognized arg(s), expects module/model and optional flag");
TORCH_CHECK(g->a==Class::module || g->a==Class::model, "training: not implemented for ",mapclass(g->a));
return (x->n==2) ? g->module().train(b),(K)0 : kb(g->module().is_training());
KCATCH("training");
}
static bool trainflag(Module& m,bool b) { bool a=m.is_training(); if(a != b) m.train(b); return a;}
// ------------------------------------------------------------------------------------------
// clipgrad - given vector of tensors, clip gradients by value/norm
// clipgroup - clip norm by optimizer group, return k list
// modelclip - clip using model training options (from within training loop -- no result)
// batchclip - clip using model from k session, return double scalar/list
// kclip - handle input ptr to allocated tensor/vector/dict/module/model and args
// clipv - api function for clipping gradient value from k session
// clip - api function for clipping gradient given model only or w'explicit norm args
// ------------------------------------------------------------------------------------------
static double clipgrad(bool a,F f,F p,const TensorVector& v) {
if(a)
return torch::nn::utils::clip_grad_norm_(v,f,p);
else
return torch::nn::utils::clip_grad_value_(v,f), nf;
}
static K clipgroup(const Optimizer& o,double f,double p) {
const auto& g=o.param_groups();
K r=ktn(KF,g.size()); J i=0;
for(const auto& z:g) kF(r)[i++]=clipgrad(true,f,p,z.params());
return r;
}
static void modelclip(Kmodel *m) {
if(auto a=m->train.clipnorm()) {
const auto& f=a.value();
if(m->train.clipgroup()) {
for(const auto& g:m->opt().param_groups())
clipgrad(true, f[0], f[1], g.params());
} else {
clipgrad(true, f[0], f[1], m->kopt()->module().parameters());
}
} else if(auto a=m->train.clipvalue()) {
clipgrad(false, a.value(), 0, m->kopt()->module().parameters());
}
}
static K batchclip(Kopt* o,bool a,bool b,double f,double p) {
return (a && b) ? clipgroup(o->opt(),f,p) : kf(clipgrad(a,f,p,o->module().parameters()));
}
static K batchclip(Kmodel *m) {
KTRY
if(m->train.clipnorm()) {
const auto& f=*m->train.clipnorm();
return batchclip(m->kopt(),true,m->train.clipgroup(),f[0],f[1]);
} else if(m->train.clipvalue()) {
return batchclip(m->kopt(),false,false,*m->train.clipvalue(),0);
} else {
return (K)0;
}
KCATCH("clip");
}
static K kclip(K x,bool a,const char *c) {
KTRY
Ktag *g=xtag(x,0); F f,p=2.0; bool b=false;
TORCH_CHECK(g, c,": expects tensor(s), module, model or optimizer as 1st of 2",(a ? "-4" : "")," args");
if(a) {
TORCH_CHECK(x->n>1 && x->n<5, c,": expects 2-4 args, (",mapclass(g->a),"; max norm; norm exponent; group flag)");
} else {
TORCH_CHECK(x->n==2, c,": expects 2 args, (",mapclass(g->a),"; value)");
}
TORCH_CHECK(xnum(x,1,f), c,": 2nd arg, ",(a ? "max norm" : "max value"),", is ",kname(x,1),", expecting long/double");
if(x->n==3) {
TORCH_CHECK(xnum(x,2,p) || xbool(x,2,b), c,": 3rd arg, group flag or norm exponent expected, given ",kname(x,2));
} else if(x->n==4) {
TORCH_CHECK(xnum(x,2,p), c,": 3rd arg, norm exponent, is ",kname(x,2),", expecting long/double");
TORCH_CHECK(xbool(x,3,b), c,": 4th arg, group flag, is ",kname(x,3),", expecting boolean");
}
switch(g->a) {
case Class::tensor: return kf(clipgrad(a,f,p,TensorVector{g->tensor()}));
case Class::vector: return kf(clipgrad(a,f,p,g->vector()));
case Class::dict: return kf(clipgrad(a,f,p,g->dict().values()));
case Class::module: return kf(clipgrad(a,f,p,g->module().parameters()));
case Class::model: return batchclip(((Kmodel*)g)->kopt(), a,b,f,p);
case Class::optimizer: return batchclip((Kopt*)g, a,b,f,p);
default: TORCH_ERROR(c,": not implemented for ",mapclass(g->a));
}
KCATCH(c);
}
KAPI clipv(K x) {return kclip(x, false, "clip gradient value");}
KAPI clip(K x) {
if(auto *m=xmodel(x))
return batchclip(m);
else
return kclip(x, true, "clip gradient norm");
}
// -------------------------------------------------------------------------------
// firstdevice - find 1st device of tensor(s) in input(s) or parameters of a model
// -------------------------------------------------------------------------------
static Device firstdevice(const Input& x,const Input& y) {
auto d=firstdevice(x);
return d ? *d : defaultdevice(firstdevice(y));
}
static Device firstdevice(Ktag *g) {
if(g && (g->a==Class::model || g->a==Class::module)) {
if(!g->kmodule()->d)
g->kmodule()->d=defaultdevice(firstdevice(g->module().parameters()));
return g->kmodule()->d.value();
} else {
return defaultdevice(c10::nullopt);
}
}
// -------------------------------------------------------------------------
// tensorinput/vectorinput/dictinput - add tensor/vector/dictionary to input
// -------------------------------------------------------------------------
static void tensorinput(Input& x,const Tensor& y,const char *z) {
if(std::get_if<Empty>(&x)) {
x=y;
} else if(auto a=std::get_if<Tensor>(&x)) {
x=TensorVector({*a,y});
} else if(auto a=std::get_if<TensorVector>(&x)) {
a->emplace_back(y);
} else if(std::get_if<TensorDict>(&x)) {
TORCH_ERROR(z,": unable to merge tensor with previously specified dictionary");
} else {
TORCH_ERROR(z,": unrecognized input state");
}
}
static void vectorinput(Input& x,const TensorVector& y,const char *z) {
if(std::get_if<Empty>(&x)) {
x=y;
} else if(auto a=std::get_if<Tensor>(&x)) {
TensorVector v({*a}); v.insert(v.end(),y.begin(),y.end()); x=v;
} else if(auto a=std::get_if<TensorVector>(&x)) {
a->insert(a->end(),y.begin(),y.end());
} else if(std::get_if<TensorDict>(&x)) {
TORCH_ERROR(z,": unable to merge dictionary with previously specified tensor(s)");
} else {
TORCH_ERROR(z,": unrecognized input state");
}
}
static void dictinput(Input& x,const TensorDict& y,const char *z) {
if(std::get_if<Empty>(&x)) {
x=y;
} else if(std::get_if<Tensor>(&x) || std::get_if<TensorVector>(&x)) {
TORCH_ERROR(z,": unable to merge dictionary with previously specified tensor(s)");
} else if(auto a=std::get_if<TensorDict>(&x)) {
a->update(y);
} else {
TORCH_ERROR(z,": unrecognized input state");
}
}
// --------------------------------------------------------------------
// inputpair: check for vector/dict and index(es)/key(s)
// --------------------------------------------------------------------
static bool inputpair(K x,Input& in,const char* c) {
bool b=false;
if(!x->t && x->n==2) {
K y=kK(x)[1]; auto *v=xvec(x,0); auto *d=v ? nullptr : xtensordict(x,0);
if(v) {
IntArrayRef n; int64_t m=v->size();
TORCH_CHECK(xsize(y,n), c,": vector paired with ",kname(y)," expecting long index or indices");
for(const auto i:n) {
TORCH_CHECK(-1<i && i<m, c,": vector[",i,"] invalid for ",m,"-element vector");
tensorinput(in,v->at(i),c);
}
b=true;
} else if(d) {
SymArrayRef s; Tensor *t;
TORCH_CHECK(xsyms(y,s), c,": dictionary paired with ",kname(y)," expecting symbol key(s)");
for(const auto& k:s) {
TORCH_CHECK(t=d->find(k),"dictionary key: `",k," not found");
tensorinput(in,*t,c);
}
b=true;
}
}
return b;
}
// ----------------------------------------------------------------------------
// modelarg - handle k input(s) for forward calculations
// ----------------------------------------------------------------------------
static void modelarg(K x,const char *c,Ktag *g,Input& in) {
if(auto *a=xten(x)) {
tensorinput(in,*a,c);
} else if(auto *a=xvec(x)) {
vectorinput(in,*a,c);
} else if(auto *a=xtensordict(x)) {
dictinput(in,*a,c);
} else if(xarray(x,7)) {
tensorinput(in,kput(x).to(firstdevice(g)),c);
} else if(inputpair(x,in,c)) {
} else {
TORCH_CHECK(!x->t, c,": unrecognized arg, ",kname(x));
for(J i=0; i<x->n;++i)
modelarg(kK(x)[i],c,g,in);
}
}
Input modelarg(K x,J i,const char *c) {
Ktag *g=xtag(x,0); Input in=Empty();
for(;i<x->n; ++i)
modelarg(kK(x)[i],c,g,in);
return in;
}
// ---------------------------------------------------------------------------
// modelargs - handle k arg parsing for model w'both inputs & targets
// ---------------------------------------------------------------------------
std::tuple<Input,Input> modelargs(K z,const char* c) {
TORCH_CHECK(z->n<4, c,": up to 3 args expected, (",kname(z,0),";inputs;targets) but ",z->n," given");
auto g=xtag(z,0); Input x=Empty(); modelarg(kK(z)[1],c,g,x);
if(z->n==2) {
return std::make_tuple(x, Empty());
} else {
z=kK(z)[2]; Input y=Empty(); modelarg(z,c,g,y);
return std::make_tuple(x,y);
}
}
// -----------------------------------------------------------------------------------------
// submodule - returns a child module referenced by name with additional attributes
// - used in forward call, e.g. forward(m;`k; ..) to avoid managing module ptr
// -----------------------------------------------------------------------------------------
static Kmodule submodule(const Module& m,S s) {
if(strchr((C*)s,'.')) {
const Moduleptr& p=m.named_modules()[s];
return Kmodule(Class::module,mcast(p),p);
} else {
const Moduleptr p=m.named_children()[s]; // named_children needs extra reference
return Kmodule(Class::module,mcast(p),p);
}
}
// -----------------------------------------------------------------------------------------
// qforward - utility fns for managing forward calc in training & evaluation mode
// forward - k api fn for forward calcs given module/model & inputs, returns tensor(s)
// eforward - k api fn for forward calcs with no grad mode & training mode off
// evaluate - same as eforward, but returns k array(s) instead of tensor(s)
// kforward - used in callback fn: calls forward/eforward if module training true/false
// -----------------------------------------------------------------------------------------
static K qforward(Kmodule *m,bool b,bool g,bool k,const Input& x) {
// b-true if training, g-true if gradients, k-true if k value returned
torch::AutoGradMode grad(g);
bool a=trainflag(m->module(),b);
K r=k ? kget(mforward(m,x)) : kout(mforward(m,x));
m->module().train(a);
return r;
}
static K qforward(K x,bool a,bool b,bool g,bool k,const char *c) {
// a-true for k callback, b-true if training, g-true if gradients, k-true if k value returned
KTRY
Kmodel *m=xmodel(x); S s=nullptr;
if(m) {
TORCH_CHECK(!a, "kforward: cannot be called without input(s)");
return qforward(m->kmodule(), b, g, k, (b ? m->data : m->testdata).x);
} else {
m=xmodel(x,0); auto *q=m ? m->kmodule() : xmodule(x,0); J i=xsym(x,1,s) ? 2 : 1;
TORCH_CHECK(q && x->n>i, c,": requires a module or model and at least one input");
// if forward call within a module callback from k, training & gradients set by parent environment
if(a) b=q->module().is_training(), g=torch::GradMode::is_enabled();
if(s) {
auto m=submodule(q->module(),s);
return qforward(&m, b, g, k, modelarg(x,i,c));
} else {
return qforward(q, b, g, k, modelarg(x,i,c));
}
}
KCATCH(c);
}
KAPI forward(K x) { return qforward(x, false, true, true, false, "forward"); } //training, gradients, return tensor(s)
KAPI nforward(K x) { return qforward(x, false, true, false, false, "forward"); } //training w'out gradients, return tensor(s)
KAPI eforward(K x) { return qforward(x, false, false, false, false, "eforward"); } //evaluate, no gradients, return tensor(s)
KAPI evaluate(K x) { return qforward(x, false, false, false, true, "evaluate"); } //evaluate, no gradients, return k arrays
KAPI kforward(K x) { return qforward(x, true, false, false, false, "kforward"); } //k callback: uses parent training/eval & gradients
// -----------------------------------------------------------------------------------------
// mbackward - given model, inputs & targets, calculate loss from model outputs and targets
// tbackward - backprop given tensor, optional tensor & sym for retain/create gradient graph
// backward - k api function for backward calc on model/tensor, return loss/null
// -----------------------------------------------------------------------------------------
K mbackward(Kmodel *m,const Input& x,const Input& y) {
auto t=losscalc(m, mforward(m->kmodule(),x), y);
t.backward();
return kget(t);
}
static K tbackward(K x,Tensor& t) {
bool a=false,b=false; J n=x->n-xbacksym(x,x->n-1,a,b);
if(n==1) {
t.backward({},a,b);
} else if(n==2) {
Tensor g;
if(!xten(x,1,g)) g=kput(x,1).to(t.device());
if(!g.dim() && t.dim()) g.resize_as_(t).fill_(g[0]);
t.backward(g,a,b);
} else {
TORCH_ERROR("backward: unexpected arg(s), expecting (t;s), (t;g) or (t;g;s) with t-tensor, g-tensor, s-sym, e.g. `retain");
}
return (K)0;
}
KAPI backward(K a) {
KTRY
if(auto m=xmodel(a)) {
return mbackward(m,m->data.x,m->data.y);
} else if(auto m=xmodel(a,0)) {
Input x,y; std::tie(x,y)=modelargs(a,"backward");
return mbackward(m,x,y);
} else if(auto t=xten(a)) {
return t->backward(), (K)0;
} else if(auto t=xten(a,0)) {
return tbackward(a,*t);
} else {
TORCH_ERROR("backward: expects tensor or model as 1st arg, e.g. backward(tensor) or backward(model;inputs;targets)");
}
KCATCH("backward");
}
// ----------------------------------------------------------------------------
// fullsize -- undo any batching on input(s) & target(s)
// ----------------------------------------------------------------------------
static int64_t fullinput(const Input& x,int64_t d,int64_t n) {
return std::visit(
c10::overloaded(
[&](const auto& x) {return fullsize(x,d,n);},
[&](const Empty& x) {return int64_t(0);}
),x);
}
static int64_t fullsize(Data& d) {
d.batch(-1); auto n=d.size();
fullinput(d.x, 0, n);
fullinput(d.y, 0, n);
return n;
}
// ----------------------------------------------------------------------------
// reindex - given permutation index, reorder input(s) & target(s)
// reshuffle - create new random permutation, reorder tensor(s)
// ----------------------------------------------------------------------------
static void reindex(Tensor& t,const Tensor& i,int64_t d=0) {
if(t.defined())
t=t.index_select(d,i.to(t.device()));
}
static void reindex(TensorVector& v,const Tensor& i,int64_t d=0) {
for(auto& t:v)
reindex(t,i,d);
}
static void reindex(TensorDict& x,const Tensor& i,int64_t d=0) {
for(auto& y:x.items())
if(y.value().defined())
x[y.key()]=y.value().index_select(d,i.to(y.value().device()));
}
static void reindex(Input& x,const Tensor& i,int64_t d=0) {
std::visit(
c10::overloaded(
[&](Tensor& x) {reindex(x,i,d);},
[&](TensorVector& x) {reindex(x,i,d);},
[&](TensorDict& x) {reindex(x,i,d);},
[&](Empty& x) {}
),x);
}
static Tensor perm(int64_t n,Generator& g) {
return torch::randperm(n, g, torch::dtype(torch::kLong).device(g.device()));
}
static Tensor perm(int64_t n,const Device& d) {
return torch::randperm(n, torch::dtype(torch::kLong).device(d));
}
static void reshuffle(Tensor& t, int64_t d=0) {
if(t.defined())
if(auto n=fullsize(t,d))
reindex(t, perm(n, t.device()), d);
}
template<typename T>static void reshuffle(T& t, int64_t d=0) {
if(t.size()) {
if(auto n=fullsize(t,d))
reindex(t, perm(n, defaultdevice(firstdevice(t))), d);
}
}
static bool reshuffle(const TestOptions& o,Data& d) {return false;}
static bool reshuffle(const TrainOptions& o,Data& d) {
if(o.shuffle()) {
auto n=fullsize(d);
if(n) {
Tensor i; auto c=firstdevice(d.x,d.y);
if(o.tasks()<2) {
i=perm(d.size(), c);
} else {
if(!d.g.defined()) { // set generator so different tasks can use same permutation
d.g=torch::globalContext().defaultGenerator(o.shufflecuda() ? c : Device(DeviceType::CPU)).clone();
d.g.set_current_seed(o.shuffleseed());
}
i=perm(d.size(), d.g);
}
reindex(d.x,i); reindex(d.y,i);
d.p = d.p.defined() ? d.p.index_select(0,i.to(d.p.device())) : i;
}
return true;
} else {
return false;
}
}
// ----------------------------------------------------------------------------
// newmetrics - [re]init a vector of vectors to accumulate tensors per batch
// batchinit - reset any previous batching, shuffle if required, reset metrics
// ----------------------------------------------------------------------------
static void newmetrics(size_t m,int64_t i,int64_t j,Data& d) {
// number of metrics, i-task, j-number of tasks
auto n=d.batches(); // number of batches
d.m = MetricData(m); // vector of tensors for each metric
auto v = n/j + (i < n%j); // number of vector elements for each metric
for(size_t i=0; i<m; ++i)
if(n>-1)
d.m[i]=TensorVector(v); // reserve space for tensors from each batch
}
template<typename O> static void batchinit(const O& o,Data& d) {
if(!reshuffle(o,d)) fullsize(d);
newmetrics(o.metrics().size(), o.task(), o.tasks(), d);
}
KAPI shuffle(K x) {
KTRY
int64_t d=0;
TORCH_CHECK(!x->t, "shuffle: not implemented for ",kname(x));
TORCH_CHECK(0<x->n && x->n<3, "shuffle: expecting 1-2 args, tensor/vector/dictionary/model & optional dimension, but given ",x->n," args");
TORCH_CHECK(x->n==1 || xint64(x,1,d), "shuffle: 2nd arg is dimension, but given ",kname(x,1));
bool b=x->n==1;
if(auto a=b ? xten(x) : xten(x,0)) { reshuffle(*a,d);
} else if (auto a=b ? xvec(x) : xvec(x,0)) { reshuffle(*a,d);
} else if (auto a=b ? xtensordict(x) : xtensordict(x,0)) { reshuffle(*a,d);
} else if (auto a=b ? xmodel(x) : xmodel(x,0)) {
TORCH_CHECK(d==0, "shuffle: model data is only batched on dimension 0, but given dimension ",d);
reshuffle(a->train,a->data);
} else {
TORCH_ERROR("shuffled: expecting tensor,vector,dictionary or model, given ",kname(x));
}
return (K)0;
KCATCH("shuffle");
}
KAPI unshuffle(K x) {
KTRY
Kmodel *m=xmodel(x);
TORCH_CHECK(m, "unshuffle: requires model argument, given ",kname(x));
auto &d=m->data;
fullsize(d);
if(d.p.defined()) {
auto i=d.p.argsort(); reindex(d.x,i); reindex(d.y,i);
d.p=Tensor();
}
return (K)0;
KCATCH("unshuffle");
}
// -----------------------------------------------------------------------------
// batches - calculate number of batches given overall data size & batch size
// datainit - [re]assign input(s) & target(s) for training/testing
// nextbatch - true if more data, setting batch size for model inputs & targets
// batch/testbatch - k api functions to process next batch
// -----------------------------------------------------------------------------
static void batches(Data& d,bool b,int64_t n,int64_t w) {
if(w>n) w=n;
d.size(n); // size of tensors along batch dim (typically 1st dim)
d.batchsize(w); // batch size from specified train/test options
d.batches(batches(w,n,b)); // save number of batches (w'option to omit final partial batch)
d.batch(-1); // current batch set to indicate none selected yet
}
static void batches(Data& d,bool b,int64_t w) {
if(d.size() > -1)
batches(d,b,d.size(),w);
}
template<typename O> static int64_t datainit(O& o,Data& d,const Input& x,const Input &y) {
// both input(s) & target(s) specified for model train/test
batches(d,o.droplast(),checksize(x,y),o.batchsize());
d.x = std::move(x); // model input(s)
d.y = std::move(y); // target(s)
d.p = Tensor(); // permutation index (used if shuffling training data)
d.g = Generator(); // generator used for permutations
return d.batches(); // return number of batches
}
template<typename O> static int64_t datainit(O& o,Data& d,bool b,const Input& z) {
// b flag true if defining input(s) else target(s) for model train/test
batches(d,o.droplast(),checksize(b ? z : d.x, b ? d.y : z),o.batchsize());
if(b) d.x=std::move(z); else d.y=std::move(z);
d.p = Tensor(); // permutation index (used if shuffling training data)
return d.batches(); // return number of batches
}
template<typename O> static bool nextbatch(const O& o,Data &d) {
auto i=d.batch(); bool b=i<0; i=b ? o.task() : i + o.tasks();
if(i < d.batches()) {
if(b) batchinit(o,d);
batch(d.x, i, d.batchsize(), 0, d.size()); // select i'th batch of input(s)
batch(d.y, i, d.batchsize(), 0, d.size()); // select i'th batch of target(s)
d.batch(i); // [re]set current batch index
return true;
} else {
fullsize(d);
return false;
}
}
static K modelbatch(K x,bool b,const char *c) {
KTRY
Kmodel *m=xmodel(x);
TORCH_CHECK(m, c,": expecting model as only argument, given ",kname(x));
return kb(b ? nextbatch(m->train,m->data) : nextbatch(m->test,m->testdata));
KCATCH(c);
}
KAPI trainbatch(K x) {
KTRY
TORCH_CHECK(!x->t && x->n, "batch: not implemented for ",kname(x));
if(x->n==1) {
return modelbatch(x,true,"batch");
} else {
IntArrayRef n;
TORCH_CHECK(x->n>1 && x->n<4, "batch: expecting 2-3 args, given ",x->n);
TORCH_CHECK(xsize(x,1,n), "batch: 2nd arg is batch size or batch size & dimension, but given ",kname(x,1));
TORCH_CHECK(n.size() && n.size()<3, "batch: 2nd arg is batch size or batch size & dimension, but given ",n.size()," elements");
auto w=n[0],d=n.size()==1 ? 0 : n[1];
TORCH_CHECK(d>-1, "batch: dimension cannot be negative");
if(x->n==2) {
return kb(nextbatch(kK(x)[0],w,d));
} else {
int64_t i;
TORCH_CHECK(xint64(x,2,i), "batch: 3rd arg is batch index, but given ",kname(x,2));
return batchindex(kK(x)[0],w,d,i), (K)0;
}
}
KCATCH("batch");
}
KAPI testbatch(K x) {return modelbatch(x, false, "testbatch");}
// ---------------------------------------------------------------------------------
// batchinit - reset batches on train/test data defined for the model
// ---------------------------------------------------------------------------------
static K batchinit(K x,bool b,const char *c) {
KTRY
Kmodel *m=xmodel(x);
TORCH_CHECK(m, c,": expected model as argument, given ",kname(x));
if(b)
batchinit(m->train,m->data);
else
batchinit(m->test,m->testdata);
return kj(b ? m->data.batches() : m->testdata.batches());
KCATCH(c);
}
KAPI Batchinit(K x) {return batchinit(x, true, "batchinit");}
KAPI testinit(K x) {return batchinit(x, false, "testinit");}
// ---------------------------------------------------------------------------
// output - retrieve output tensor from model output (vector,tuple, etc.)
// hidden - retrieve hidden state, hidden cell state from model output
// matches - return count where prediction matches target and overall count
// ---------------------------------------------------------------------------
static Tensor output(Kmodel *m,const Output& x) {
return std::visit(
c10::overloaded(
[&](const Tensor& x) -> Tensor {return x;},
[&](const TensorVector& x) -> Tensor {TORCH_CHECK(x.size(), "unable to retrieve model output from empty vector of tensors"); return x[0];},
[&](const Tuple& x) -> Tensor {return std::get<0>(x);},
[&](const Nested& x) -> Tensor {return std::get<0>(x);},
[&](const auto& x) -> Tensor {TORCH_ERROR("unable to retrieve model output from ",outputname(x)," output");}
),x);
}
static Tensor hidden(Metric m,const Output& x) {
if(auto a=std::get_if<TensorVector>(&x)) {
if(a->size()>1 && m==Metric::hidden) return (*a)[1];
else if(a->size()>2 && m==Metric::hiddencell) return (*a)[2];
else TORCH_ERROR("metric: unable to retrieve ",metric(m)," from vector of tensors with ",a->size()," element(s)");
} else if(auto a=std::get_if<Tuple>(&x)) {
return std::get<1>(*a);
} else if(auto a=std::get_if<Nested>(&x)) {
return m==Metric::hidden ? std::get<0>(std::get<1>(*a)) : std::get<1>(std::get<1>(*a));
} else {
TORCH_ERROR("metric: unable to retrieve ",metric(m)," from ",outputname(x)," output");
}
}
static Tensor matches(Kmodel *m,const Tensor& yhat,const Input &y) {
if(auto a=std::get_if<Tensor>(&y)) {
return torch::stack({a->eq(yhat).sum(),
torch::tensor(a->numel(),torch::device(a->device()))}).view({1,2});
} else {
TORCH_ERROR("unable to calculate matches from ",inputname(y)," of target(s)");
}
}
// -----------------------------------------------------------------------------------
// lossflag - return true if loss calculation required
// metrics - given input(s), target(s) & model output for the batch, calculate metrics
// -----------------------------------------------------------------------------------
static bool lossflag(const Metrics& m) {
for(auto k:m)
if(k==Metric::loss || k==Metric::batchloss) return true;
return false;
}
static void metrics(Kmodel *m,const Metrics& k,int64_t n,Data& d) {
auto j=d.batch() / n; // assign metric[i][j] with n tasks
if(k.size()) { // if metrics defined
size_t i=0; Tensor out,pred; // tensors for output, prediction
for(auto c:k) {
switch(c) {
case Metric::output:
if(!out.defined()) out=output(m,d.z);
// if network is identity function, out -> d.z -> d.x, i.e. a part of input
// without clone, when input(s) resized, stored metric is also resized
d.m[i][j]=(out.defined() && out.use_count()>2) ? out.clone() : out;
break;
case Metric::loss:
case Metric::batchloss:
d.m[i][j]=d.l.detach();
break;
case Metric::predict:
if(!out.defined()) out=output(m,d.z);
if(!pred.defined()) pred=out.argmax(-1);
d.m[i][j]=pred.detach();
break;
case Metric::accuracy:
case Metric::matches:
if(!out.defined()) out=output(m,d.z).detach();
if(!pred.defined()) pred=out.argmax(-1).detach();
d.m[i][j]=matches(m,pred,d.y).detach();
break;
case Metric::hidden:
case Metric::hiddencell:
d.m[i][j]=hidden(c,d.z).detach();
break;
default:
TORCH_ERROR("metric: ",metric(c)," not recognized or not implemented");
}
i++;
}
}
}
// ---------------------------------------------------------------------------
// hiddenstate - combine previous hidden state w'input for model forward calc
// ---------------------------------------------------------------------------
TensorVector hiddenstate (Data& d) {
return std::visit(
c10::overloaded (
[](const Tensor& x,const TensorVector& y) {
switch(y.size()) {
case 2: return TensorVector({x,y[1]});
case 3: return TensorVector({x,y[1],y[2]});
default: TORCH_ERROR("unable to retrieve hidden state from ",y.size(), "-element vector of output(s)");
}
},
[](const Tensor& x,const Tuple& y) {return TensorVector({x,std::get<1>(y)});},
[](const Tensor& x,const Nested& y) {
return TensorVector({x, std::get<0>(std::get<1>(y)), std::get<1>(std::get<1>(y))});},
[](auto x,auto y) {
TORCH_ERROR("unable to retrive hidden state from ",inputname(x)," input & ",outputname(y)," output");
return TensorVector();}
), d.x, d.z);
}
// ---------------------------------------------------------------------------
// batchcalc - run forward calcs, get loss if required, calculate metrics
// trainstep - reset grad,forward,loss,backward & step using closure
// trainloop/testloop - run model in train/evaluate mode, accumulate metrics
// backstep - calculate outputs,loss,gradients and perform optimizer step
// ---------------------------------------------------------------------------
template<typename O> static void batchcalc(Kmodel *m,bool b,const O& o,Data& d) {
d.z=mforward(m->kmodule(), o.hidden() && d.batch() > o.task() ? hiddenstate(d) : d.x);
if(b) d.l=losscalc(m, d.z, d.y);
metrics(m, o.metrics(), o.tasks(), d);
}
static void trainstep(Kmodel *m,const Input& x,const Input& y) {
auto f=[&]() {
auto& d=m->data;
resetgrad(m->opt(),true);
d.z=mforward(m->kmodule(), x);
auto l=losscalc(m, d.z, y);
l.backward();
if(m->train.sync()) sync(l.device());
modelclip(m);
return l;
};
m->data.l=m->opt().step(f);
}
static void trainstep(Kmodel *m) {
auto& d=m->data;
trainstep(m, m->train.hidden() && d.batch() > m->train.task() ? hiddenstate(d) : d.x, d.y);
}
static void trainloop(Kmodel *m) {
bool a=trainflag(m->module(),true); auto& d=m->data; const auto& o=m->train;
while(nextbatch(o,d)) {
trainstep(m);
metrics(m, o.metrics(), o.tasks(), m->data);
}
m->module().train(a); fullsize(d);
}
static void testloop(Kmodel *m) {
torch::NoGradGuard g;
bool a=trainflag(m->module(),false); auto& d=m->testdata; const auto& o=m->test;
bool b=lossflag(o.metrics());
while(nextbatch(o,d))
batchcalc(m,b,o,d);
m->module().train(a); fullsize(d);
}
KAPI backstep(K a) {
KTRY
Tensor t; auto m=xmodel(a);
if(m) {
trainstep(m);
} else {
m=xmodel(a,0);
TORCH_CHECK(m, "backstep: model expected as 1st argument, given ",kname(a,0));
TORCH_CHECK(a->n==3, "backstep expecting (model;inputs;targets), but ",a->n," args given");
Input x,y; std::tie(x,y)=modelargs(a,"backstep");
trainstep(m,x,y);
}
return kget(m->data.l);
KCATCH("backstep");
}
// ---------------------------------------------------------------------------
// getmetrics - catenate/stack batch metrics into vector of tensors
// return as k values or pytorch tensor/vector/dictionary
// ---------------------------------------------------------------------------
TensorVector getmetrics(Data& d) {
TensorVector r;
for(const auto& v:d.m)
if(v.size())
r.emplace_back(v[0].dim() ? torch::cat(v) : torch::stack(v));
else
r.emplace_back(Tensor());
d.m = MetricData();
return r;
}
template<typename O> static K getmetrics(const O& o,Data& d) {
size_t i=0; TensorVector v=getmetrics(d);
if(!v.size()) { // no metrics recorded(no data supplied?)
for(size_t i=0; i<o.metrics().size(); ++i) // for each metric in settings
v.emplace_back(Tensor()); // use undefined tensor
} else {
for(auto m:o.metrics()) {
if(m==Metric::accuracy || m==Metric::matches) {
auto s=v[i].sum(0);
v[i] = m==Metric::accuracy ? 100.0*s[0].div(s[1]) : s;
} else if(m==Metric::loss) {
v[i] = v[i].sum() / d.batches();
}
i++;
}
}
if(o.dictionary()) {
if(o.tensor()) {
TensorDict d; size_t i=0;
for(auto m:o.metrics())
d.insert(metric(m), v[i++]);
return kdict(d);
} else {
K x=KDICT; size_t i=0;
for(auto m:o.metrics())
dictadd(x, metric(m), kget(v[i++]));
return x;
}
} else {
if(o.tensor())
return v.size()==1 ? kten(v[0]) : kvec(v);
else
return v.size()==1 ? kget(v[0]) : kget(v);
}
}
// -----------------------------------------------------------------
// modelopt - translate between model option symbol and enumeration
// -----------------------------------------------------------------
static Setting modelopt(S s,bool t) {
for(const auto& a:env().train)
if(std::get<0>(a)==s && (t ? std::get<2>(a) : std::get<3>(a)))
return std::get<1>(a);
TORCH_ERROR("unrecognized ", (t ? "train" : "test")," setting: ",s);
}
static S modelopt(Setting s) {
for(const auto& a:env().train)
if(std::get<1>(a)==s) return std::get<0>(a);
TORCH_ERROR("unrecognized training/evaluation setting: ",(I)s);
}
// ----------------------------------------------------------------------
// getoption - retrieve individual option, list or full set as dictionary
// ----------------------------------------------------------------------
static K getoption(Kmodel *m,bool t,Setting s) {
switch(s) {
case Setting::batchsize: return kj(t ? m->train.batchsize() : m->test.batchsize());
case Setting::droplast: return kb(t ? m->train.droplast() : m->test.droplast());
case Setting::hidden: return kb(t ? m->train.hidden() : m->test.hidden());
case Setting::tensor: return kb(t ? m->train.tensor() : m->test.tensor());
case Setting::dictionary: return kb(t ? m->train.dictionary() : m->test.dictionary());
case Setting::shuffle: return t ? kb(m->train.shuffle()) : nullptr;
case Setting::shufflecuda: return t ? kb(m->train.shufflecuda()) : nullptr;
case Setting::shuffleseed: return t ? kj(m->train.shuffleseed()) : nullptr;
case Setting::sync: return t ? kb(m->train.sync()) : nullptr;
case Setting::task: return kj(t ? m->train.task() : m->test.task());
case Setting::tasks: return kj(t ? m->train.tasks() : m->test.tasks());
case Setting::clipgroup: return t ? kb(m->train.clipgroup()) : nullptr;
case Setting::clipvalue: return t && m->train.clipvalue() ? kf(*m->train.clipvalue()) : nullptr;
case Setting::clipnorm:
if(t && m->train.clipnorm()) {
K y=ktn(KF,2); const auto& z=*m->train.clipnorm(); kF(y)[0]=z[0]; kF(y)[1]=z[1];
return y;
} else {
return nullptr;
}
case Setting::metrics: {
const auto& v=t ? m->train.metrics() : m->test.metrics();
K y=ktn(KS,v.size()); J j=0; for(auto i:v) kS(y)[j++]=metric(i);
return y;
}
default:
TORCH_ERROR((t ? "train" : "test"),": unrecognized setting");
}
}
static K getoption(Kmodel *m,bool t,SymArrayRef a) {
K y=KDICT;
try {
for(auto k:a) {
K z=getoption(m,t,modelopt(k,t));
dictadd(y, k, z ? z : knull());
}
return resolvedict(y);
} catch(...) {
if(y) r0(y);
throw;
}
}
static K getoption(Kmodel *m,bool t,bool a) {
K x=KDICT; K y;
OPTION(x, batchsize, getoption(m,t,Setting::batchsize));
OPTION(x, task, getoption(m,t,Setting::task));
OPTION(x, tasks, getoption(m,t,Setting::tasks));
OPTION(x, droplast, getoption(m,t,Setting::droplast));
OPTION(x, hidden, getoption(m,t,Setting::hidden));
if(t) {
OPTION(x, shuffle, getoption(m,t,Setting::shuffle));
OPTION(x, shufflecuda, getoption(m,t,Setting::shufflecuda));
OPTION(x, shuffleseed, getoption(m,t,Setting::shuffleseed));
OPTION(x, sync, getoption(m,t,Setting::sync));
OPTION(x, clipgroup, getoption(m,t,Setting::clipgroup));
y=getoption(m,t,Setting::clipnorm); if(a || y) OPTION(x, clipnorm, y ? y : knull());
y=getoption(m,t,Setting::clipvalue); if(a || y) OPTION(x, clipvalue, y ? y : knull());
}
OPTION(x, tensor, getoption(m,t,Setting::tensor));
OPTION(x, dictionary, getoption(m,t,Setting::dictionary));
OPTION(x, metrics, getoption(m,t,Setting::metrics));
return x;
}
// -----------------------------------------------------------------
// clipnorm - handle 1-2 long(s)/double(s) for clipping by norm
// checkopt - check for incompatible train/test options
// setoption - parse k arg(s) to set or reset model options
// -----------------------------------------------------------------
static void clipnorm(Kmodel *m,S a,K x) {
F f,p=2.0;
if(xempty(x)) {
m->train.clipnorm(c10::nullopt);
} else {
if(xnum(x,f) || (xnum(x,0,f) && xnum(x,1,p) && x->n==2)) {
} else if (x->t==KF || x->t==KJ) {
TORCH_CHECK(x->n==2, a,": expecting 1-2 numbers, given ",x->n);
if(x->t==KF)
f=kF(x)[0], p=kF(x)[1];
else
f=kJ(x)[0], p=kJ(x)[1];
} else {
TORCH_ERROR(a,": expecting 1-2 numbers, long integers or doubles, given ",kname(x));
}
m->train.clipnorm({{f,p}}).clipvalue(c10::nullopt);