-
Notifications
You must be signed in to change notification settings - Fork 43
/
varstore.go
1275 lines (1085 loc) · 35.2 KB
/
varstore.go
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
package nn
import (
"fmt"
"log"
"reflect"
"sort"
"strings"
"sync"
"github.com/sugarme/gotch"
"github.com/sugarme/gotch/ts"
)
// SEP is a separator to separate path elements in the tensor names.
const SEP = "."
type Var struct {
Tensor *ts.Tensor
Group uint // optimizer parameter group
Type string // can be "parameter" or "buffer"
Trainable bool // marked this variable is either trainable or not.For "buffer" type, it's always `false`
Persitent bool // only applied to "buffer" type. All parameters are persistent (when do VarStore.Save()).
}
// VarStore is used to store variables used by one or multiple layers.
// It specifies a SINGLE device where all variables are stored.
type VarStore struct {
sync.Mutex
device gotch.Device
vars map[string]Var
}
// Path is variable store with an associated path for variables naming.
type Path struct {
path []string
varstore *VarStore
group uint // optimizer parameter group
}
// Entry holds an entry corresponding to a given name in Path.
type Entry struct {
name string
path *Path
}
// NewVarStore creates a new variable store located on the specified device
func NewVarStore(device gotch.Device) *VarStore {
return &VarStore{
device: device,
vars: make(map[string]Var, 0),
}
}
// NOTE:
// To get (initiate) a path, call vs.Root()
// VarStore methods:
// =================
// Device returns device for this VarStore.
func (vs *VarStore) Device() gotch.Device {
return vs.device
}
// Len returns the number of tensors currently kept in this VarStore.
func (vs *VarStore) Len() int {
vs.Lock()
defer vs.Unlock()
return len(vs.vars)
}
// IsEmpty returns true if no tensors currently kept in this VarStore.
func (vs *VarStore) IsEmpty() bool {
vs.Lock()
defer vs.Unlock()
return (len(vs.vars) == 0)
}
// TrainableVariabless returns reference to all trainable variables kept in VarStore.
func (vs *VarStore) TrainableVariables() []*ts.Tensor {
vs.Lock()
defer vs.Unlock()
var trainables []*ts.Tensor
for _, v := range vs.vars {
x := v.Tensor
if x.MustRequiresGrad() {
trainables = append(trainables, x)
}
}
return trainables
}
// Variables returns reference of all variables and their names in a map[variable_name]Tensor
//
// NOTE. returned map includes all variables of "parameter" and "buffer" type.
func (vs *VarStore) Variables() map[string]ts.Tensor {
vs.Lock()
defer vs.Unlock()
namedTensors := make(map[string]ts.Tensor, 0)
for k, v := range vs.vars {
namedTensors[k] = *v.Tensor
}
return namedTensors
}
// Root gets the root path for this VarStore.
//
// NOTE: Variables are named and organized using paths. This function returns
// the top level path for the var store and can be combined with '/'
// to create sub-paths.
func (vs *VarStore) Root() *Path {
return &Path{
path: []string{},
varstore: vs,
group: 0,
}
}
// Save saves the VarStore variable values to a file.
//
// NOTE: Weight values for all the tensors currently stored in the
// var-store gets saved in the given file.
func (vs *VarStore) Save(filepath string) error {
vs.Lock()
defer vs.Unlock()
var namedTensors []ts.NamedTensor
for k, v := range vs.vars {
if v.Type == "parameter" || (v.Type == "buffer" && v.Persitent) {
namedTensors = append(namedTensors, ts.NamedTensor{
Name: k,
Tensor: v.Tensor,
})
}
}
// return ts.SaveMulti(namedTensors, filepath)
return ts.SaveMultiNew(namedTensors, filepath)
}
// Load loads VarStore variable values from a file.
//
// NOTE: Weight values for all the tensors currently stored in the
// VarStore gets loaded from the given file. Note that the set of
// variables stored in the VarStore is not changed, only the values
// for these tensors are modified.
// It will throw error if name of the loaded tensors can not find
// in the current VarStore named tensors set.
func (vs *VarStore) Load(filepath string) error {
namedTensors, err := ts.LoadMultiWithDevice(filepath, vs.device)
if err != nil {
return err
}
var namedTensorsMap map[string]*ts.Tensor = make(map[string]*ts.Tensor, 0)
for _, namedTensor := range namedTensors {
namedTensorsMap[namedTensor.Name] = namedTensor.Tensor
}
// Match and in-place copy value (update) from newly loaded tensors
// to existing named tensors if name is matched. Throw error otherwise.
vs.Lock()
defer vs.Unlock()
for name, v := range vs.vars {
// missing variable
currTs, ok := namedTensorsMap[name]
if !ok {
err = fmt.Errorf("VarStore.Load() failed: there's a tensor with name %q in VarStore, but not found in the loaded weights.\n", name)
return err
}
// mismatched shape
sourceShape := currTs.MustSize()
destShape := v.Tensor.MustSize()
if !reflect.DeepEqual(destShape, sourceShape) {
err = fmt.Errorf("Mismatched shape error for variable name: %v - At store: %v - At source %v\n", name, destShape, sourceShape)
return err
}
ts.NoGrad(func() {
v.Tensor.Copy_(currTs)
})
}
for _, x := range namedTensors {
x.Tensor.MustDrop()
}
ts.CleanUp()
return nil
}
// LoadWeights loads pretrained weights to VarStore.
func (vs *VarStore) LoadWeights(namedTensors []ts.NamedTensor) error {
var namedTensorsMap map[string]*ts.Tensor = make(map[string]*ts.Tensor, 0)
for _, namedTensor := range namedTensors {
namedTensorsMap[namedTensor.Name] = namedTensor.Tensor
}
// Match and in-place copy value (update) from newly loaded tensors
// to existing named tensors if name is matched. Throw error otherwise.
vs.Lock()
defer vs.Unlock()
for name, v := range vs.vars {
// missing variable
currTs, ok := namedTensorsMap[name]
if !ok {
err := fmt.Errorf("VarStore.LoadWeights() failed: there's a tensor with name %q in VarStore, but not found in the loaded weights.\n", name)
return err
}
// mismatched shape
sourceShape := currTs.MustSize()
destShape := v.Tensor.MustSize()
if !reflect.DeepEqual(destShape, sourceShape) {
err := fmt.Errorf("VarStore.LoadWeights() failed. Mismatched shape error for variable name: %v - At store: %v - At source %v\n", name, destShape, sourceShape)
return err
}
ts.NoGrad(func() {
v.Tensor.Copy_(currTs)
})
}
ts.CleanUp()
return nil
}
// LoadPartial loads the VarStore variable values from a file if it exists.
//
// Weight values for the tensors currently stored in the var-store and the given file get
// loaded from the given file. If a variable in the var store is not present in the given file,
// it is skipped and its values are not updated. This method should be used if pre-trained
// weight for only parts of the model are available.
// Note that the set of variables stored in the var-store is not changed, only the values
// for these tensors are modified.
//
// Returns a String Vector containing the names of missing variables.
func (vs *VarStore) LoadPartial(filepath string) ([]string, error) {
namedTensors, err := ts.LoadMultiWithDevice(filepath, vs.device)
if err != nil {
return nil, err
}
var namedTensorsMap map[string]*ts.Tensor = make(map[string]*ts.Tensor, 0)
for _, namedTensor := range namedTensors {
namedTensorsMap[namedTensor.Name] = namedTensor.Tensor
}
var missingVariables []string
// Match and in-place copy value (update) from newly loaded tensors
// to existing named tensors if name is matched. Throw error otherwise.
vs.Lock()
defer vs.Unlock()
for name, v := range vs.vars {
var currTs *ts.Tensor
var ok bool
// missing variable
if currTs, ok = namedTensorsMap[name]; !ok {
missingVariables = append(missingVariables, name)
continue
}
// mismatched shape
destShape := currTs.MustSize()
sourceShape := v.Tensor.MustSize()
if !reflect.DeepEqual(destShape, sourceShape) {
fmt.Printf("WARNING: Mismatched shape error for variable name: %v - At store: %v - At source %v. Skip loading this weight...\n", name, destShape, sourceShape)
missingVariables = append(missingVariables, name)
continue
}
ts.NoGrad(func() {
v.Tensor.Copy_(currTs)
})
}
for _, x := range namedTensors {
x.Tensor.MustDrop()
}
ts.CleanUp()
return missingVariables, nil
}
// LoadWeightsPartial loads the VarStore variable values from a file if it exists.
//
// Weight values for the tensors currently stored in the var-store and the given file get
// loaded from the given file. If a variable in the var store is not present in the given file,
// it is skipped and its values are not updated. This method should be used if pre-trained
// weight for only parts of the model are available.
// Note that the set of variables stored in the var-store is not changed, only the values
// for these tensors are modified.
//
// Returns a String Vector containing the names of missing variables.
func (vs *VarStore) LoadWeightsPartial(namedTensors []ts.NamedTensor) ([]string, error) {
var namedTensorsMap map[string]*ts.Tensor = make(map[string]*ts.Tensor, 0)
for _, namedTensor := range namedTensors {
namedTensorsMap[namedTensor.Name] = namedTensor.Tensor
}
var missingVariables []string
// Match and in-place copy value (update) from newly loaded tensors
// to existing named tensors if name is matched. Throw error otherwise.
vs.Lock()
defer vs.Unlock()
for name, v := range vs.vars {
var currTs *ts.Tensor
var ok bool
// missing variable
if currTs, ok = namedTensorsMap[name]; !ok {
missingVariables = append(missingVariables, name)
continue
}
// mismatched shape
destShape := currTs.MustSize()
sourceShape := v.Tensor.MustSize()
if !reflect.DeepEqual(destShape, sourceShape) {
fmt.Printf("WARNING: Mismatched shape error for variable name: %v - At store: %v - At source %v. Skip loading this weight...\n", name, destShape, sourceShape)
missingVariables = append(missingVariables, name)
continue
}
ts.NoGrad(func() {
v.Tensor.Copy_(currTs)
})
}
ts.CleanUp()
return missingVariables, nil
}
// Freeze freezes this VarStore.
//
// Gradients for the variables in this store are not tracked anymore.
func (vs *VarStore) Freeze() error {
vs.Lock()
defer vs.Unlock()
for name, v := range vs.vars {
err := v.Tensor.RequiresGrad_(false)
if err != nil {
err = fmt.Errorf("VarStore.Freeze() set 'requiresGrad' for tensor %q failed.", name)
return err
}
}
return nil
}
// Unfreeze unfreezes a VarStore.
//
// Gradients for the variables in this store are tracked again.
func (vs *VarStore) Unfreeze() error {
vs.Lock()
defer vs.Unlock()
for name, v := range vs.vars {
if v.Type == "parameter" && v.Trainable {
err := v.Tensor.RequiresGrad_(true)
err = fmt.Errorf("VarStore.Freeze() set 'requiresGrad' for tensor %q failed.", name)
return err
}
}
return nil
}
// Copy copies variable values from a source VarStore to this VarStore.
//
// All the variables in this var store have to exist with the same
// name in the source var store, otherwise an error is returned.
func (vs *VarStore) Copy(src *VarStore) error {
vs.Lock()
defer vs.Unlock()
src.Lock()
defer src.Unlock()
srcVars := src.vars
device := vs.device
for k := range vs.vars {
if _, ok := srcVars[k]; !ok {
err := fmt.Errorf("VarStore.Copy() failed: cannot find %q in the source VarStore.\n", k)
return err
}
}
for k, v := range vs.vars {
srcV := srcVars[k]
srcDevTs, err := srcV.Tensor.To(device, false)
if err != nil {
return err
}
ts.NoGrad(func() {
v.Tensor.Copy_(srcDevTs)
})
srcDevTs.MustDrop()
}
ts.CleanUp()
return nil
}
// Summary prints a simple list of all named variables with their shapes.
func (vs *VarStore) Summary() {
vars := vs.vars
layers := make([]string, 0, len(vars))
for name := range vars {
layers = append(layers, name)
}
sort.Strings(layers)
var dtype gotch.DType
isFirst := true
for _, l := range layers {
var x *ts.Tensor
var isBuffer bool
for name, v := range vars {
if name == l {
x = v.Tensor
// Get DType of first tensor for representation only
if isFirst {
dtype = x.DType()
}
isFirst = false
isBuffer = v.Type == "buffer"
break
}
}
if isBuffer {
fmt.Printf("%s - [buffer] - %+v\n", l, x.MustSize())
} else {
fmt.Printf("%s - %+v\n", l, x.MustSize())
}
}
fmt.Printf("Num of layers: %v\n", len(vars))
fmt.Printf("DType: %v\n", dtype)
}
// Destroy deletes all tensors in varstore and set it to nil.
func (vs *VarStore) Destroy() {
vs.Lock()
for n, v := range vs.vars {
v.Tensor.MustDrop()
delete(vs.vars, n)
}
vs.Unlock()
vs = nil
}
// ToDType casts all variables in VarStore to specified DType.
//
// NOTE. only float-like types (Half, BFloat16, Float, Double) can ensure convertible.
func (vs *VarStore) ToDType(dtype gotch.DType) {
vs.Root().ToDType(dtype)
}
// ToFloat casts all float-like variables in VarStore to `Float` dtype.
//
// NOTE. float-like includes `Half`,`BFloat16`, `Float` and `Double` dtype.
func (vs *VarStore) ToFloat() {
vs.Root().ToFloat()
}
// ToDouble casts all float-like variables in VarStore to `Double` dtype.
//
// NOTE. float-like includes `Half`, `Float` and `Double` dtype.
func (vs *VarStore) ToDouble() {
vs.Root().ToDouble()
}
// ToHalf casts all float-like variables in VarStore to `Half` dtype.
//
// NOTE. float-like includes `Half`, `Float` and `Double` dtype.
func (vs *VarStore) ToHalf() {
vs.Root().ToHalf()
}
// ToBFloat16 casts all float-like variables in VarStore to `BFloat16` dtype.
//
// NOTE. float-like includes `Half`, `Float` and `Double` dtype.
func (vs *VarStore) ToBFloat16() {
vs.Root().ToBFloat16()
}
func (vs *VarStore) ToDevice(device gotch.Device) {
p := vs.Root()
p.ToDevice(device)
}
// Path methods:
// =============
// Sub gets a sub-path of the given path.
func (p *Path) Sub(str string) *Path {
if strings.Contains(str, SEP) {
log.Fatalf("Path.Sub() failed: name cannot contain %v (%v)\n", SEP, str)
}
path := p.path
path = append(path, str)
return &Path{
path: path,
varstore: p.varstore,
group: p.group,
}
}
// Paths returns all sub paths from current path.
func (p *Path) Paths() []string {
return p.path
}
// Device gets the device where the VarStore variables are stored.
func (p *Path) Device() gotch.Device {
return p.varstore.device
}
// NOTE: Cannot name as `path` as having a field name `path`
func (p *Path) getpath(name string) string {
if strings.Contains(name, SEP) {
log.Fatalf("Sub name cannot contain %v (%v)\n", SEP, name)
}
if len(p.path) == 0 {
return name
} else {
return fmt.Sprintf("%v%v%v", strings.Join(p.path, SEP), SEP, name)
}
}
func (p *Path) add(name string, newTs *ts.Tensor, trainable bool, varType string, persistent bool) (*ts.Tensor, error) {
path := p.getpath(name)
p.varstore.Lock()
defer p.varstore.Unlock()
if _, ok := p.varstore.vars[path]; ok {
path = fmt.Sprintf("%v__%v", path, len(p.varstore.vars))
}
var (
tensor *ts.Tensor
err error
)
if trainable {
tensor, err = newTs.SetRequiresGrad(true, false)
if err != nil {
return nil, err
}
} else {
tensor = newTs.MustShallowClone()
}
v := Var{
Tensor: tensor,
Group: p.group,
Trainable: trainable,
Type: varType,
Persitent: persistent,
}
p.varstore.vars[path] = v
return tensor, nil
}
type AddOpts struct {
VarType string
Persistent bool
}
type AddOpt func(*AddOpts)
func defaultAddOpts() *AddOpts {
return &AddOpts{
VarType: "parameter",
Persistent: true,
}
}
func WithVarType(v string) AddOpt {
if v != "parameter" && v != "buffer" {
log.Fatalf("WithVarType() failed(): invalid option variable type. Input must be either 'parameter' or 'buffer'.")
}
return func(o *AddOpts) {
o.VarType = v
}
}
func WithPersistent(v bool) AddOpt {
return func(o *AddOpts) {
o.Persistent = v
}
}
// Add adds a tensor to a given path.
//
// Args
// - name: intention name of variable in VarStore (if duplicated, it will be added a suffix number)
// - x: tensor holding values to keep in VarStore
// - trainable: marked whether tensor is trainable.
// - o.VarType: variable type, i.e., either "parameter" or "buffer"
// - o.Persistent: whether to save this variables when `VarStore.Save()` is called. Only applied to `buffer` type.
// Returns a reference to a tensor stored in VarStore and error if occurred.
func (p *Path) Add(name string, x *ts.Tensor, trainable bool, opts ...AddOpt) (*ts.Tensor, error) {
o := defaultAddOpts()
for _, opt := range opts {
opt(o)
}
return p.add(name, x, trainable, o.VarType, o.Persistent)
}
// MustAdd adds a tensor to a given path.
//
// Args
// - name: intention name of variable in VarStore (if duplicated, it will be added a suffix number)
// - x: tensor holding values to keep in VarStore
// - trainable: marked whether tensor is trainable.
// - o.VarType: variable type, i.e., either "parameter" or "buffer"
// - o.Persistent: whether to save this variables when `VarStore.Save()` is called. Only applied to `buffer` type.
// Returns a reference to a tensor stored in VarStore.
func (p *Path) MustAdd(name string, x *ts.Tensor, trainable bool, opts ...AddOpt) *ts.Tensor {
x, err := p.Add(name, x, trainable, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// Remove removes a variable from `VarStore`
func (p *Path) Remove(name string) error {
p.varstore.Lock()
defer p.varstore.Unlock()
_, ok := p.varstore.vars[name]
if !ok {
err := fmt.Errorf("Path.Remove() failed: cannot find a variable with name %q in VarStore.", name)
return err
}
delete(p.varstore.vars, name)
return nil
}
// MustRemove removes a variable from `VarStore`
func (p *Path) MustRemove(name string) {
err := p.Remove(name)
if err != nil {
err = fmt.Errorf("Path.MustRemove() failed: %w", err)
log.Fatal(err)
}
}
func (p *Path) getOrAddWithLock(name string, tensor *ts.Tensor, trainable bool, opts ...AddOpt) (*ts.Tensor, error) {
path := p.getpath(name)
// if found, return it
if v, ok := p.varstore.vars[path]; ok {
return v.Tensor, nil
}
// not found, add it
return p.Add(name, tensor, trainable, opts...)
}
func (p *Path) SetGroup(g uint) {
p.varstore.Lock()
defer p.varstore.Unlock()
// TODO. set group for individual variables.
// TBD. variables of current path only or all sub paths as well?
// For now, just set group for all variable at the path
path := strings.Join(p.path, SEP)
for name, v := range p.varstore.vars {
vpaths := strings.Split(name, SEP)
vpath := strings.Join(vpaths[:len(vpaths)-1], SEP)
if vpath == path {
v.Group = g
p.varstore.vars[name] = v
}
}
p.group = g
}
// ToDType casts all variables in this path and its sub-paths to the specified dtype.
//
// NOTE. this method should be used for floating-point conversion, i.e.,
// "gotch.Float", "gotch.Half", "gotch.BFloat16", "gotch.Double".
func (p *Path) ToDType(dtype gotch.DType) {
p.varstore.Lock()
defer p.varstore.Unlock()
path := strings.Join(p.path, SEP)
for name, v := range p.varstore.vars {
if strings.Contains(name, path) {
newVar := v
newVar.Tensor = v.Tensor.MustTotype(dtype, true)
p.varstore.vars[name] = newVar
}
}
}
// toFloat casts all float-like variables in this current path and sub-paths to specified dtype.
func (p *Path) toFloat(dtype gotch.DType) {
p.varstore.Lock()
defer p.varstore.Unlock()
path := strings.Join(p.path, SEP)
for name, v := range p.varstore.vars {
if strings.Contains(name, path) {
dtype := v.Tensor.DType()
if gotch.IsFloatDType(dtype) {
newVar := v
newVar.Tensor = v.Tensor.MustTotype(dtype, true)
p.varstore.vars[name] = newVar
}
}
}
ts.CleanUp()
}
// ToFloat casts all variables in current path and subpaths to `Float` precision.
func (p *Path) ToFloat(floatDTypeOpt ...gotch.DType) {
dtype := gotch.Float
if len(floatDTypeOpt) > 0 {
dt := floatDTypeOpt[0]
if !gotch.IsFloatDType(dt) {
// Ingore the option
if gotch.Debug {
log.Printf("WARNING: nn.Path.ToFloat() input dtype is invalid float DType %v. Just ignoring...\n", dt)
}
} else {
dtype = dt
}
}
p.toFloat(dtype)
}
// ToDouble casts all variables in current path and subpaths to `Double` precision dtype.
func (p *Path) ToDouble() {
p.toFloat(gotch.Double)
}
// ToHalf casts all variables in current path and subpaths to `Half` precision dtype.
func (p *Path) ToHalf() {
p.toFloat(gotch.Half)
}
// ToBFloat16() converts all variables in current path and subpaths to `BFloat16` dtype.
func (p *Path) ToBFloat16() {
p.toFloat(gotch.BFloat16)
}
func (p *Path) ToDevice(device gotch.Device) {
p.varstore.Lock()
defer p.varstore.Unlock()
path := strings.Join(p.path, SEP)
for name, v := range p.varstore.vars {
if strings.Contains(name, path) {
newVar := v
newVar.Tensor = v.Tensor.MustTo(device, true)
p.varstore.vars[name] = newVar
}
}
ts.CleanUp()
}
// ZerosNoTrain creates a new variable initialized with zeros.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable will not be trainable so
// gradients will not be tracked.
// The variable uses a float tensor initialized with zeros.
func (p *Path) ZerosNoTrain(name string, dims []int64, opts ...AddOpt) (*ts.Tensor, error) {
device := p.Device()
dtype := gotch.DefaultDType
z, err := ts.Zeros(dims, dtype, device)
if err != nil {
err = fmt.Errorf("Path.ZerosNoTrain() failed: %w", err)
return nil, err
}
out, err := p.Add(name, z, false, opts...)
if err != nil {
return nil, err
}
z.MustDrop()
return out, nil
}
// MustZerosNoTrain creates a new variable initialized with zeros.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable will not be trainable so
// gradients will not be tracked.
// The variable uses a float tensor initialized with zeros.
func (p *Path) MustZerosNoTrain(name string, dims []int64, opts ...AddOpt) *ts.Tensor {
x, err := p.ZerosNoTrain(name, dims, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// OnesNoTrain creates a new variable initialized with ones.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable will not be trainable so
// gradients will not be tracked.
// The variable uses a float tensor initialized with ones.
func (p *Path) OnesNoTrain(name string, dims []int64, opts ...AddOpt) (*ts.Tensor, error) {
device := p.Device()
dtype := gotch.DefaultDType
z, err := ts.Ones(dims, dtype, device)
if err != nil {
err = fmt.Errorf("Path.OneNoTrain() failed: %w", err)
return nil, err
}
out, err := p.Add(name, z, false, opts...)
if err != nil {
return nil, err
}
z.MustDrop()
return out, nil
}
// MustOnesNoTrain creates a new variable initialized with ones.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable will not be trainable so
// gradients will not be tracked.
// The variable uses a float tensor initialized with ones.
func (p *Path) MustOnesNoTrain(name string, dims []int64, opts ...AddOpt) *ts.Tensor {
x, err := p.OnesNoTrain(name, dims, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// NewVar creates a new variable.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable is trainable, its gradient
// will be tracked.
// The variable uses a float tensor initialized as per the
// related argument.
func (p *Path) NewVar(name string, dims []int64, ini Init, opts ...AddOpt) (*ts.Tensor, error) {
dtype := gotch.DefaultDType
// v := ini.InitTensor(dims, p.varstore.device, dtype)
var v *ts.Tensor
v = ini.InitTensor(dims, p.varstore.device, dtype)
out, err := p.Add(name, v, true, opts...)
if err != nil {
return nil, err
}
v.MustDrop()
return out, err
}
// MustNewVar create a new variable. It panics if error.
func (p *Path) MustNewVar(name string, dims []int64, ini Init, opts ...AddOpt) *ts.Tensor {
x, err := p.NewVar(name, dims, ini, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// Zeros creates a new variable initialized with zeros.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable is trainable, its gradient
// will be tracked.
// The variable uses a float tensor initialized with zeros.
func (p *Path) Zeros(name string, dims []int64, opts ...AddOpt) (*ts.Tensor, error) {
return p.NewVar(name, dims, NewConstInit(0.0), opts...)
}
// MustZeros create a new variables with zero values. It panics if error.
func (p *Path) MustZeros(name string, dims []int64, opts ...AddOpt) *ts.Tensor {
x, err := p.Zeros(name, dims, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// Ones creates a new variable initialized with ones.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable is trainable, its gradient
// will be tracked.
// The variable uses a float tensor initialized with ones.
func (p *Path) Ones(name string, dims []int64, opts ...AddOpt) (*ts.Tensor, error) {
return p.NewVar(name, dims, NewConstInit(1.0), opts...)
}
// MustOnes creates a new variable initialized with ones. It panics if error occurred.
func (p *Path) MustOnes(name string, dims []int64, opts ...AddOpt) *ts.Tensor {
x, err := p.Ones(name, dims, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// RandnStandard creates a new variable initialized randomly with normal distribution.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable is trainable, its gradient
// will be tracked.
// The variable uses a float tensor initialized randomly using a
// standard normal distribution.
func (p *Path) RandnStandard(name string, dims []int64, opts ...AddOpt) (*ts.Tensor, error) {
return p.NewVar(name, dims, NewRandnInit(0.0, 1.0), opts...)
}
// MustRandnStandard creates a new variable initialized randomly with normal distribution. It panics if error occurred.
func (p *Path) MustRandnStandard(name string, dims []int64, opts ...AddOpt) *ts.Tensor {
x, err := p.RandnStandard(name, dims, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// Randn creates a new variable initialized randomly with normal distribution.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable is trainable, its gradient
// will be tracked.
// The variable uses a float tensor initialized randomly using a
// normal distribution with the specified mean and standard deviation.
func (p *Path) Randn(name string, dims []int64, mean float64, stdev float64, opts ...AddOpt) (*ts.Tensor, error) {
return p.NewVar(name, dims, NewRandnInit(mean, stdev), opts...)
}
// MustRandn creates a new variable initialized randomly with normal distribution. It panics if error occurred.
func (p *Path) MustRandn(name string, dims []int64, mean float64, stdev float64, opts ...AddOpt) *ts.Tensor {
x, err := p.Randn(name, dims, mean, stdev, opts...)
if err != nil {
log.Fatal(err)
}
return x
}
// Uniform creates a new variable initialized randomly with uniform distribution.
//
// The new variable is named according to the name parameter and
// has the specified shape. The variable is trainable, its gradient
// will be tracked.
// The variable uses a float tensor initialized randomly using a
// uniform distribution between the specified bounds.
func (p *Path) Uniform(name string, dims []int64, lo, up float64, opts ...AddOpt) (*ts.Tensor, error) {
return p.NewVar(name, dims, NewUniformInit(lo, up), opts...)
}
// MustUniform creates a new variable initialized randomly with uniform distribution. It panics if error occurred.
func (p *Path) MustUniform(name string, dims []int64, lo, up float64, opts ...AddOpt) *ts.Tensor {
x, err := p.Uniform(name, dims, lo, up, opts...)
if err != nil {
log.Fatal(err)