-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathweightwatcher.py
More file actions
5903 lines (4324 loc) · 223 KB
/
Copy pathweightwatcher.py
File metadata and controls
5903 lines (4324 loc) · 223 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
# Copyright 2018 Calculation Consulting [calculationconsulting.com]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys, os, re, io
import glob, json
import traceback
import tempfile
#from deprecated import deprecated
import inspect
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
#from sklearn.decomposition import TruncatedSVD
from copy import deepcopy
import importlib
import numbers
import safetensors
from safetensors import safe_open
#
# this is use to allow editing in Eclipse but also
# building on the commend line
# see: https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time
#
from .RMT_Util import *
from .constants import *
from .WW_powerlaw import *
# WW_NAME moved to constants.py
# Configure logging
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(WW_NAME)
logger.setLevel(logging.WARNING)
mpl_logger = logging.getLogger("matplotlib")
mpl_logger.setLevel(logging.WARNING)
def main():
"""
Weight Watcher
"""
print("WeightWatcher command line support coming later. https://calculationconsulting.com")
# TODO: make all these methods abstract
# can't do this until all the class methods are implemented and tested
class FrameworkLayer:
"""Base class for all classes that wrap the layer from each Framework and Format
Each FrameworkLayer is specifically typed to make it easier to manage the different and growing
"""
def __init__(self, layer, layer_id, name, longname="", weights=None, bias=None,
the_type = LAYER_TYPE.UNKNOWN, skipped=False, framework=FRAMEWORK.UNKNOWN,
channels=CHANNELS.UNKNOWN, plot_id=None, has_bias=False, lazy=False):
self.lazy = lazy
self.layer = layer
self.layer_id = layer_id
# read weights and biases
self.name = name
self.longname = longname
self.the_type = the_type
self.skipped = skipped
self.framework = framework
self.channels = channels
self.has_bias = has_bias
if plot_id is None:
self.plot_id = f"{layer_id}"
else:
self.plot_id = plot_id
if self.name is None and hasattr(self.layer, 'name'):
self.name = self.layer.name
elif self.name is None:
self.name = str(self.layer)
self.name = re.sub(r'\(.*', '', self.name)
if self.longname is None and hasattr(self.layer, 'longname'):
self.longname = self.layer.longname
elif self.longname is None:
self.longname = name
def layer_type(self, layer):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE"""
the_type = LAYER_TYPE.UNKNOWN
typestr = (str(type(layer))).lower()
return the_type
@staticmethod
def get_layer_iterator(model):
"""should return an interator over the layer, that builds the subclass object"""
pass
#@abc.abstractmethod:=
def has_biases(self):
return self.has_bias
#@abc.abstractmethod:
def get_weights_and_biases(self):
""" return has_weights, weights, has_biases, biases """
pass
#@abc.abstractmethod:
def replace_layer_weights(self, W, B=None):
pass
class KerasLayer(FrameworkLayer):
def __init__(self, layer, layer_id, name=None, longname = None):
the_type = self.layer_type(layer)
channels = CHANNELS.FIRST
FrameworkLayer.__init__(self, layer, layer_id, name, longname=longname, the_type=the_type,
framework=FRAMEWORK.KERAS, channels=channels)
def layer_type(self, layer):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE
This can detect basic Keras classes by type, and will try to infer the type otherwise. """
the_type = LAYER_TYPE.UNKNOWN
typestr = (str(type(layer))).lower()
# Keras TF 2.x types
if isinstance(layer, keras.layers.Dense) or 'dense' in typestr:
the_type = LAYER_TYPE.DENSE
elif isinstance(layer, keras.layers.Conv1D) or 'conv1d' in typestr:
the_type = LAYER_TYPE.CONV1D
elif isinstance(layer, keras.layers.Conv2D) or 'conv2d' in typestr:
the_type = LAYER_TYPE.CONV2D
#
# elif isinstance(layer, keras.layers.Bidirectional) or 'bidirectional' in typestr:
# the_type = LAYER_TYPE.BIDIRECTIONAL
#
elif isinstance(layer, keras.layers.Flatten) or 'flatten' in typestr:
the_type = LAYER_TYPE.FLATTENED
elif isinstance(layer, keras.layers.Embedding) or 'embedding' in typestr:
the_type = LAYER_TYPE.EMBEDDING
elif isinstance(layer, tf.keras.layers.LayerNormalization) or 'layernorn' in typestr:
the_type = LAYER_TYPE.NORM
return the_type
def has_biases(self):
return hasattr(self.layer, 'use_bias') and self.layer.use_bias is True
#return self.layer.use_bias is True
def get_weights_and_biases(self):
"""extract the original weights (as a tensor) for the layer, and biases for the layer, if present
these wil be set in the enclosing WWLayer
"""
has_weights, has_biases = False, False
weights, biases = None, None
w = self.layer.get_weights()
if self.the_type==LAYER_TYPE.CONV2D:
weights = w[0]
biases = None
has_weights = True
elif self.the_type==LAYER_TYPE.CONV1D:
weights = w[0]
biases = None
has_weights = True
elif self.the_type==LAYER_TYPE.EMBEDDING:
weights = w[0]
biases = None
has_weights = True
elif self.the_type==LAYER_TYPE.DENSE:
weights = w[0]
has_weights = True
if self.has_biases():
biases = w[1]
has_biases = True
### BIDIRECTIONAL added as a hack not fuly tested
# A bidirectional model has 4 distinct matrices,
# each one would need to be treated as a different layer in keras
#
# elif self.the_type==LAYER_TYPE.BIDIRECTIONAL:
# weights = [w[0], w[1], w[3], w[4]]
# has_weights = True
# has_biases = False
## if self.has_biases():
## biases = [w[2], w[6]]
## has_biases = True
#
else:
logger.info("keras layer: {} {} type {} not found ".format(self.layer.name,str(self.layer),str(self.the_type)))
return has_weights, weights, has_biases, biases
# warningL may not work for BIDIRECTIONAL
def replace_layer_weights(self, W, B=None):
"""My not work,, see https://stackoverflow.com/questions/51354186/how-to-update-weights-manually-with-keras"""
if self.has_biases() and B is not None:
W = [W, B]
self.layer.set_weights(W)
@staticmethod
def get_layer_iterator(model, start_id=0):
""" start_id is 0 for back compatbility"""
layer_id = start_id
def layer_iter_():
def traverse_(layer):
"not recursive, just iterate over all submodules if present"
nonlocal layer_id
if not hasattr(layer, 'submodules') or len(layer.submodules)==0:
keras_layer = KerasLayer(layer, layer_id)
layer_id += 1
yield keras_layer
else:
for sublayer in layer.submodules:
keras_layer = KerasLayer(sublayer, layer_id)
layer_id += 1
yield keras_layer
for layer in model.layers:
yield from traverse_(layer)
return layer_iter_()
class PyTorchLayer(FrameworkLayer):
def __init__(self, layer, layer_id, name=None, longname = None):
the_type = self.layer_type(layer)
channels = CHANNELS.LAST
FrameworkLayer.__init__(self, layer, layer_id, name, longname=longname, the_type=the_type,
framework=FRAMEWORK.PYTORCH, channels=channels)
def layer_type(self, layer):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE
This can detect basic PyTorch classes by type, and will try to infer the type otherwise. """
the_type = LAYER_TYPE.UNKNOWN
typestr = (str(type(layer))).lower()
if isinstance(layer, torch.nn.Linear) or 'linear' in typestr:
the_type = LAYER_TYPE.DENSE
elif isinstance(layer, torch.nn.Conv1d) or 'conv1d' in typestr:
the_type = LAYER_TYPE.CONV1D
elif isinstance(layer, torch.nn.Conv2d) or 'conv2d' in typestr:
the_type = LAYER_TYPE.CONV2D
elif isinstance(layer, torch.nn.Embedding) or 'embedding' in typestr:
the_type = LAYER_TYPE.EMBEDDING
elif 'norm' in str(type(layer)).lower() :
the_type = LAYER_TYPE.NORM
return the_type
def has_biases(self):
return hasattr(self.layer, 'bias') and self.layer.bias is not None and self.layer.bias.data is not None
def get_weights_and_biases(self):
"""extract the original weights (as a tensor) for the layer, and biases for the layer, if present
expects self.layer to be set
"""
has_weights, has_biases = False, False
weights, biases = None, None
if hasattr(self.layer, 'weight'):
#w = [np.array(self.layer.weight.data.clone().cpu())]
w = [torch_T_to_np(self.layer.weight.data)]
if self.the_type==LAYER_TYPE.CONV2D:
weights = w[0]
biases = None
has_weights = True
elif self.the_type==LAYER_TYPE.CONV1D:
weights = w[0]
biases = None
has_weights = True
elif self.the_type==LAYER_TYPE.EMBEDDING:
weights = w[0]
biases = None
has_weights = True
elif self.the_type==LAYER_TYPE.DENSE:
weights = w[0]
has_weights = True
biases = None
has_biases = False
if self.has_biases():
#biases = self.layer.bias.data.clone().cpu()
#biases = biases.detach().numpy()
biases = torch_T_to_np(self.layer.bias.data)
has_biases = True
elif self.the_type not in [LAYER_TYPE.NORM]:
logger.info("pytorch layer: {} type {} not found ".format(str(self.layer),str(self.the_type)))
else:
pass
return has_weights, weights, has_biases, biases
def replace_layer_weights(self, W, B=None):
self.layer.weight.data = torch.from_numpy(W)
if self.has_biases() and B is not None:
self.layer.bias.data = torch.from_numpy(B)
@staticmethod
def get_layer_iterator(model,start_id=0):
""" start_id is 0 for back compatbility"""
def layer_iter_():
#for layer in model.modules():
layer_id = start_id
for longname, layer in model.named_modules():
setattr(layer, 'longname', longname)
pytorch_layer = PyTorchLayer(layer, layer_id, longname=longname)
layer_id += 1
yield pytorch_layer
return layer_iter_()
class PyStateDictLayer(FrameworkLayer):
"""Similar to the PyTorch iterator, but the layer ids may be different"""
def __init__(self, model, layer_id, name):
self.model = model # model_state_dict
self.layer = name
the_type = self.layer_type(self.layer)
FrameworkLayer.__init__(self, name, layer_id, name, longname=name, the_type=the_type,
framework=FRAMEWORK.PYSTATEDICT, channels=CHANNELS.LAST)
def has_biases(self):
bias_key = self.layer + '.bias'
if bias_key in self.model:
return True
return False
def layer_type(self, layer):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE"""
the_type = LAYER_TYPE.UNKNOWN
has_weights, weights, has_biases, biases = self.get_weights_and_biases()
if len(weights)<2:
pass
elif len(weights.shape)==2:
the_type = LAYER_TYPE.DENSE
elif len(weights.shape)==4:
the_type = LAYER_TYPE.CONV2D
return the_type
@staticmethod
def get_layer_iterator(model_state_dict, start_id=1, layer_map=None):
from copy import deepcopy
"""model is just a dict, but we need the name of the dict
start_id = 0 is NOT ok since all counting starts at 1 for this layer
layer_map = ordered list of keys (layer names in the file)"""
def layer_iter_(model_state_dict, layer_map):
layer_id = start_id
if layer_map is None or len(layer_map)==0:
layer_map = model_state_dict.keys()
has_weight = any(key.endswith(".weight") for key in layer_map)
if not has_weight:
layer_names = [f"{x}.weight" for x in layer_map]
else:
layer_names = layer_map
for key in layer_names:
# Check if the key corresponds to a weight matrix
if key.endswith('.weight'):
# Extract the weight matrix and layer name
weights = model_state_dict[key]
layer_name = key[:-len('.weight')]
# Check if the layer has a bias vector
bias_key = layer_name + '.bias'
if bias_key in model_state_dict:
biases = model_state_dict[bias_key]
else:
biases = None
if type(weights)==torch.Tensor:
"""We want to store data in float16, not 32"""
weights = torch_T_to_np(weights.data)
if biases is not None:
biases = torch_T_to_np(biases.data)
# we may need to change this, set valid later
# because we want al the layers for describe
if weights is not None:
the_layer = PyStateDictLayer(model_state_dict, layer_id, layer_name)
layer_id += 1 # because we always start at 1 , we increment this after, not before
yield the_layer
return layer_iter_(model_state_dict, layer_map)
def get_weights_and_biases(self):
""" return has_weights, weights, has_biases, biases """
model_state_dict = self.model
weight_key = self.layer+'.weight'
bias_key = self.layer+'.bias'
weights = model_state_dict[weight_key]
biases = None
if self.has_biases():
biases = model_state_dict[bias_key]
if type(weights)==torch.Tensor:
weights = torch_T_to_np(weights.data)
if self.has_biases():
biases = torch_T_to_np(biases.data)
return True, weights, self.has_biases(), biases
def replace_layer_weights(self, W, B=None):
""" replace weights and biases in the underlying layer
expects to replace with torch arrays
"""
model_state_dict = self.model
weight_key = self.layer+'.weight'
bias_key = self.layer + '.bias'
model_state_dict[weight_key] = torch.from_numpy(W)
if self.has_biases() and B is not None:
model_state_dict[bias_key] = torch.from_numpy(B)
return
class PyStateDictDir(PyStateDictLayer):
"""Class that reads a list of pyStateDict .bin files (or .safetensors)
specified by the directory
Expect formats: pytorch_model.#.bin | model.#.safetensors
i.e:
pytorch_model.00001-of-00014.bin
pytorch_model.00002-of-00014.bin
...
and/or
model.00001-of-00014.safetensors
model.00002-of-00014.safetensors
...
If the directory contains both, will selectively pick the safetensors first
This will replace apply_watcher_to_pytorch_bins...
Note: this is only used as a static class
"""
@staticmethod
def get_layer_map(fileglob):
# safetensors keys are stored in sort order, not layer order, so we need the ordering
# so we either need to
# - read a custom layer_map file for each safetensors file, or
# - embed the mapping in the safetensors metadata
# - read the huggingface model.safetensors.index.json file
# Assumes there is 1 filename
layer_map = []
layer_map_filename = None
filenames = glob.glob(fileglob.replace("safetensors", "layer_map"))
if len(filenames)==1:
layer_map_filename = filenames[0]
elif len(filenames)>1:
logger.warning(f"More than 1 layer_map_filename found! {filenames}")
weight_map = []
weight_map_filename = None
filenames = glob.glob(fileglob.replace("safetensors", ".safetensors.index.json"))
if len(filenames)==1:
weight_map_filename = filenames[0]
elif len(filenames)>1:
logger.warning(f"More than 1 weight_map_filename found! {filenames}")
# read layer map if found, otherwise ignore
if layer_map_filename is not None and os.path.exists(layer_map_filename):
logger.info(f"loading layer_map {layer_map_filename}")
with open(layer_map_filename, 'r') as f:
layer_map = [line.strip() for line in f]
if len(layer_map) == 0:
logger.critical(f"no layers found in {layer_map_filename}")
elif weight_map_filename is not None and os.path.exists(weight_map_filename):
logger.info(f"loading weight_map {weight_map_filename}")
with open(weight_map_filename, 'r') as f:
data = json.load(f)
weight_map = data['weight_map']
files = np.unique([x for x in weight_map.values()])
for file in files:
for k, v in weight_map.items():
if v == file:
layer_map.append(k)
# read layer map if found, otherwise ignore
elif layer_map_filename is not None and os.path.exists(layer_map_filename):
logger.info(f"loading layer_map {layer_map_filename}")
with open(layer_map_filename, 'r') as f:
layer_map = [line.strip() for line in f]
if len(layer_map) == 0:
logger.critical(f"no layers found in {layer_map_filename}")
else:
# TODO just ignore state, buld as it goes
logger.info(f"loading {layer_map_filename} not found, ignoring")
return layer_map
@staticmethod
def read_safetensor_state_dict(state_dict_filename):
"""Reads the entire state dict into memory
NOT USED YET """
state_dict = {}
with safe_open(state_dict_filename, framework="pt", device='cpu') as f:
for layer_name in f.keys():
state_dict[layer_name] = f.get_tensor(layer_name)
return state_dict
@staticmethod
def get_layer_iterator(model_dir, start_id=1, layer_map=None):
# TODO: if layer_map is set, use this ordered
# TODO: find layer in the list of layers provided, skip if layer not found
# notice: we could use layer_map from the other model
# need to skip layers if found
logger.debug(f"Buidling Layer for {model_dir}")
if not os.path.exists(model_dir) or not os.path.isdir(model_dir):
logger.fatal(f"Directory {model_dir} not found")
format, fileglob = WeightWatcher.infer_model_file_format(model_dir)
if format not in [MODEL_FILE_FORMATS.SAFETENSORS, MODEL_FILE_FORMATS.PYTORCH]:
logger.fatal(f"Unknown or unsupporteed model format {format}" )
def layer_iter_(fileglob, layer_map=None):
# Track the number of layers already yielded
num_layers_yielded = 0
current_start_id = start_id # Create a copy of start_id
if layer_map is None and format==MODEL_FILE_FORMATS.SAFETENSORS:
logger.info(f"Reading layer map from {fileglob}")
layer_map = PyStateDictDir.get_layer_map(fileglob)
else:
logger.info(f"Using specified layer map")
# loop over stat dict files in sort order
# TODO: open all safetensors files at once
# access layers as requested from map
if (layer_map is not None and len(layer_map)>0) and format==MODEL_FILE_FORMATS.SAFETENSORS:
fileglob = f"{model_dir}/*model*safetensors"
safetensors_dict = SafeTensorDict(fileglob)
current_start_id += num_layers_yielded
sub_layer_iter = PyStateDictLayer.get_layer_iterator(safetensors_dict, start_id = current_start_id, layer_map=layer_map)
for layer in sub_layer_iter:
num_layers_yielded += 1 # Increment the counter
yield layer
elif (layer_map is None or len(layer_map)==0) and format==MODEL_FILE_FORMATS.SAFETENSORS:
for state_dict_filename in sorted(glob.glob(fileglob)):
logger.info(f"loading {state_dict_filename}")
state_dict = SafeTensorDict(state_dict_filename)
#with safe_open(state_dict_filename, framework="pt", device='cpu') as f:
# for layer_name in f.keys():
# state_dict[layer_name] = f.get_tensor(layer_name)
#logger.info(f"Read safetensors file: {state_dict_filename}, len={len(state_dict)}")
# Yield individual layers
current_start_id += num_layers_yielded
sub_layer_iter = PyStateDictLayer.get_layer_iterator(state_dict, start_id = current_start_id)
for layer in sub_layer_iter:
num_layers_yielded += 1 # Increment the counter
yield layer
else: # format is PYTORCH BIN
fileglob = f"{model_dir}/*model*bin"
for state_dict_filename in sorted(glob.glob(fileglob)):
logger.info(f"loading {state_dict_filename}")
# is this correct ?
state_dict = torch.load(state_dict_filename, map_location=torch.device('cpu'))
logger.info(f"Read pytorch model bin file: {state_dict_filename}, len={len(state_dict)}")
# Yield individual layers
current_start_id += num_layers_yielded
sub_layer_iter = PyStateDictLayer.get_layer_iterator(state_dict, start_id = current_start_id)
for layer in sub_layer_iter:
num_layers_yielded += 1 # Increment the counter
yield layer
# for state_dict_filename in sorted(glob.glob(fileglob)):
# logger.info(f"loading {state_dict_filename}")
#
# if format==MODEL_FILE_FORMATS.SAFETENSORS:
# from safetensors import safe_open
#
# #state_dict = {k: f.get_tensor(k) for k in safe_open(state_dict_filename, framework="pt", device='cpu').keys()}
# state_dict = {}
# with safe_open(state_dict_filename, framework="pt", device='cpu') as f:
# if layer_map is not None and len(layer_map)>0:
# if not set(f.keys()).issubset(not compatble set(layer_map)):
# logger.critical(f"safetensors file has keys not found in the layer_map!")
# else:
# for layer_name in f.keys():
# state_dict[layer_name] = f.get_tensor(layer_name)
# #else:
# #
#
# logger.debug(f"Read safetensors: {state_dict_filename}, len={len(state_dict)}")
#
# else:
# state_dict = torch.load(state_dict_filename, map_location=torch.device('cpu'))
# logger.debug(f"Read pytorch model bin file: {state_dict_filename}, len={len(state_dict)}")
#
# # Update the start_id based on the number of layers already yielded
# current_start_id += num_layers_yielded
#
# # Yield individual layers
# sub_layer_iter = PyStateDictLayer.get_layer_iterator(state_dict, current_start_id)
# for layer in sub_layer_iter:
# num_layers_yielded += 1 # Increment the counter
# yield layer
return layer_iter_(fileglob, layer_map=layer_map)
class WWFlatFile(FrameworkLayer):
"""Helper class to support layers directly from pyTorch StateDict
Currently only supports DENSE layers: need to update
initializer reads we logger.info(f"CReating CONFIG {config['layers'][3}")ights and bias file directly from disk
would like to adapt to pystatedict to read off file
we should let the user specify, and then it will create the temp files automatically ?
"""
def __init__(self, layer_id, config, layer_config):
self.config = config
weights_dir = config['weights_dir']
self.layer_config = layer_config
self.layer_id = int(layer_id)
# read weights and biases
name = layer_config['name']
longname = layer_config['longname']
the_type = LAYER_TYPE.UNKNOWN
self.weights = None
self.weightfile = layer_config['weightfile']
self.weightfile = os.path.join(weights_dir, self.weightfile)
self.has_weights = True
self.bias = None
self.biasfile = None
self.has_bias = False
if layer_config['biasfile']:
self.biasfile = layer_config['biasfile']
self.biasfile = os.path.join(weights_dir, self.biasfile)
self.has_bias = True
str_type = layer_config['type']
the_type = WeightWatcher.layer_type_from_str(str_type)
dims = layer_config['dims']
dims = json.loads(dims)
if the_type in [LAYER_TYPE.DENSE, LAYER_TYPE.NORM, LAYER_TYPE.CONV1D]:
self.N = np.max(dims)
self.M = np.min(dims)
self.rf = 1
self.dims = dims
self.weight_dims = dims
self.skipped = False
elif the_type in [LAYER_TYPE.CONV2D]:
# assume channel is not switched
self.N = np.max(dims[0:2])
self.M = np.min(dims[0:2])
self.rf = dims[2]*dims[3]
self.dims = dims
self.weight_dims = dims
self.skipped = False
else:
self.skipped = True
logger.fatal
(f"Sorry, WWFlatFile only supports DENSE and NORM layers currently, not {str_type}")
FrameworkLayer.__init__(self, layer_config, int(layer_id), name, longname=longname, weights=None, bias=None, the_type=the_type,
framework=FRAMEWORK.WW_FLATFILES, channels=CHANNELS.LAST, has_bias=self.has_bias, lazy=True)
return
def lazy_load_weights_and_biases(self):
"""load the weights and biases from the flat files"""
if self.weights is None:
logger.info(f"Loading weights from {self.weightfile}")
self.weights = np.load(self.weightfile)
if self.has_bias:
logger.info(f"Loading biases from {self.biasfile}")
self.bias = np.load(self.biasfile)
return
@staticmethod
def layer_type(weights):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE
This can detect basic PyTorch classes by type, and will try to infer the type otherwise. """
the_type = LAYER_TYPE.UNKNOWN
if len(weights.shape)==1:
the_type = LAYER_TYPE.NORM
elif len(weights.shape)==2:
the_type = LAYER_TYPE.DENSE
elif len(weights.shape)==4:
the_type = LAYER_TYPE.CONV2D
return the_type
@staticmethod
def layer_type_as_str(weights):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE as a STRING
This can detect basic PyTorch classes by type, and will try to infer the type otherwise. """
the_type = UNKNOWN
if len(weights.shape)==1:
the_type = NORM
elif len(weights.shape)==2:
the_type = DENSE
elif len(weights.shape)==4:
the_type = CONV2D
return the_type
def get_weights_and_biases(self):
""" return has_weights, weights, has_biases, biases """
self.lazy_load_weights_and_biases()
return self.has_weights, self.weights, self.has_bias, self.bias
@staticmethod
def get_layer_iterator(config, start_id=0):
def layer_iter_():
weights_dir = config['weights_dir']
logger.debug(f"iterating over layers in {weights_dir}")
for layer_id, layer_config in config['layers'].items():
layer_id = int(layer_id)+start_id
py_layer = WWFlatFile(layer_id, config, layer_config)
yield py_layer
return layer_iter_()
class ONNXLayer(FrameworkLayer):
"""Helper class to support ONNX layers
Turns out the op_type is option, so we have to
infers the layer_ type from the dimension of the weights
[a,b,c,d] -> CONV2D
[a,b] -> DENSE
Warning: this has not been tested in some time
"""
def __init__(self, model, inode, node):
self.model = model
self.dims = node.dims
self.layer = node
self.layer_id = inode
self.name = node.name
longname = self.name
the_type = self.layer_type(self.dims)
channels = CHANNELS.LAST
FrameworkLayer.__init__(self, self.layer, self.layer_id, self.name, longname=longname, the_type=the_type,
framework=FRAMEWORK.ONNX, channels=channels)
def set_weights(self, W):
logger.fatal("Sorry set_weights not yet available for ONNX models")
def get_weights(self):
""" get the weights from the ONNX graph"""
W= None
idx = self.layer_id
node_weights = [self.model.graph.initializer[idx]][0]
if node_weights is not None:
import onnx
W = onnx.numpy_helper.to_array(node_weights)
return W
def get_weights_and_biases(self):
"""extract the original weights (as a tensor) for the layer, and biases for the layer, if present
Hacked together right now for issue #233
"""
W = self.get_weights()
return True, W, False, None
def layer_type(self, dims):
"""Given a framework layer, determine the weightwatcher LAYER_TYPE
This can detect basic PyTorch classes by type, and will try to infer the type otherwise. """
the_type = LAYER_TYPE.UNKNOWN
if len(self.dims) == 4:
the_type = LAYER_TYPE.CONV2D
elif len(self.dims) == 2:
the_type = LAYER_TYPE.DENSE
else:
logger.debug("Unsupported ONNX Layer, dims = {}".format(self.dims))
return the_type
def replace_layer_weights(self, W, B=None):
self.set_weights(W)
if B is not None:
logger.fatal("dont know hownto set Bias on ONNX models, stopping")
@staticmethod
def get_layer_iterator(model):
def layer_iter_():
for inode, node in enumerate(model.graph.initializer):
yield ONNXLayer(model, inode, node)
return layer_iter_()
class WWLayer:
"""WW wrapper layer to Keras and PyTorch Layer layer objects
Uses python metaprogramming to add result columns for the final details dataframe"""
def __init__(self, framework_layer, layer_id=-1, skipped=False, make_weights=True, params=None):
if params is None: params = DEFAULT_PARAMS.copy()
self.framework_layer = framework_layer
self.layer_id = layer_id
self.skipped = skipped
self.is_make_weights = make_weights
self.params = params
self.plot_id = framework_layer.plot_id
self.name = framework_layer.name
self.longname = framework_layer.longname
self.the_type = framework_layer.the_type
self.framework = framework_layer.framework
self.channels = framework_layer.channels
self.fft = False
# original weights (tensor) and biases
self.has_weights = False
self.weights = None
self.has_biases = False
self.biases = None
# extracted weight matrices
self.num_W = 0