-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmy_pycaffe_utils.py
More file actions
2247 lines (2044 loc) · 74 KB
/
my_pycaffe_utils.py
File metadata and controls
2247 lines (2044 loc) · 74 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
## @package my_pycaffe_utils
# Miscellaneous Util Functions
#
import my_pycaffe as mp
import my_pycaffe_io as mpio
import numpy as np
import pdb
import os
import scipy.io as sio
import matplotlib.pyplot as plt
import subprocess
import collections as co
import other_utils as ou
import shutil
import copy
from pycaffe_config import cfg
import scipy.misc as scm
try:
import h5py as h5
except:
print ('WARNING: h5py not found, some functions may not work')
CAFFE_PATH = cfg.CAFFE_PATH
get_defaults = ou.get_defaults
def zf_saliency(net, imBatch, numOutputs, opName, ipName='data', stride=2, patchSz=11):
'''
Takes as input a network and set of images imBatch
net: Instance of MyNet
imBatch: the images for which saliency needs to be computed. (expects: N * ch * h * w)
numOutputs: Number of output units in the blob named opName
Produces the saliency map of im
net is of type MyNet
'''
assert(np.mod(patchSz,2)==1), 'patchSz needs to an odd Num'
p = int(np.floor(patchSz/2.0))
N = imBatch.shape[0]
if isinstance(opName, basestring):
opName = [opName]
numOutputs = [numOutputs]
#Transform the image
imT = net.preprocess_batch(imBatch)
#Find the Original Scores
dataLayer = {}
dataLayer[ipName] = imT
batchSz,ch,nr,nc = imT.shape
dType = imT.dtype
nrNew = len(range(p, nr-p-1, stride))
ncNew = len(range(p, nc-p-1, stride))
origScore = np.copy(net.net.forward_all(**dataLayer))
for op in opName:
assert op in origScore.keys(), "Some outputs not found"
imSalient = {}
for (op, num) in zip(opName, numOutputs):
imSalient[op] = np.zeros((N, num, nrNew, ncNew))
for (imCount,im) in enumerate(imT[0:N]):
count = 0
imIdx = []
ims = np.zeros(imT.shape).astype(dType)
for (ir,r) in enumerate(range(p, nr-p-1, stride)):
for (ic,c) in enumerate(range(p, nc-p-1, stride)):
imPatched = np.copy(im)
#Make an image patch 0
imPatched[:, r-p:r+p+1, c-p:c+p+1] = 0
ims[count,:,:,:] = imPatched
imIdx.append((ir,ic))
count += 1
#If count is batch size compute the features
if count==batchSz or (ir == nrNew-1 and ic == ncNew-1):
dataLayer = {}
dataLayer[ipName] = net.preprocess_batch(ims)
allScores = net.net.forward(**dataLayer)
for (op,num) in zip(opName, numOutputs):
scores = origScore[op][imCount] - allScores[op][0:count]
scores = scores.reshape((count, num))
for idx,coords in enumerate(imIdx):
y, x = coords
imSalient[op][imCount, :, y, x] = scores[idx,:].reshape(num,)
count = 0
imIdx = []
return imSalient, origScore
def mapILSVRC12_labels_wnids(metaFile):
dat = sio.loadmat(metaFile, struct_as_record=False, squeeze_me=True)
dat = dat['synsets']
labels, wnid = [],[]
for dd in dat:
labels.append(dd.ILSVRC2012_ID - 1)
wnid.append(dd.WNID)
labels = labels[0:1000]
wnid = wnid[0:1000]
return labels, wnid
##
# Read ILSVRC Data
class ILSVRC12Reader:
def __init__(self, caffeDir=CAFFE_PATH):
labelFile = '/data1/pulkitag/ILSVRC-2012-raw/devkit-1.0/data/ILSVRC2012_validation_ground_truth.txt'
metaFile = '/data1/pulkitag/ILSVRC-2012-raw/devkit-1.0/data/meta.mat'
self.imFile_ = '/data1/pulkitag/ILSVRC-2012-raw/256/val/ILSVRC2012_val_%08d.JPEG'
self.count_ = 0
#Load the groundtruth labels from Imagenet
fid = open(labelFile)
data = fid.readlines()
valLabels = [int(i)-1 for i in data] #-1 for python formatting
#Load the Synsets
synFile = os.path.join(caffeDir, 'data/ilsvrc12/synsets.txt')
fid = open(synFile, 'r')
self.synsets_ = [s.strip() for s in fid.readlines()]
fid.close()
#Align the Imagenet Labels to the Synset order on which the BVLC reference model was trained.
modLabels, modWnid = mapILSVRC12_labels_wnids(metaFile)
self.labels_ = np.zeros((len(valLabels),)).astype(np.int)
for (i,lb) in enumerate(valLabels):
lIdx = modLabels.index(lb)
syn = modWnid[lIdx]
sIdx = self.synsets_.index(syn)
self.labels_[i] = sIdx
#Load the synset words
synWordFile = os.path.join(caffeDir, 'data/ilsvrc12/synset_words.txt')
fid = open(synWordFile, 'r')
data = fid.readlines()
self.words_ = {}
for l in data:
synNames = l.split()
syn = synNames[0]
words = [w for w in synNames[1:]]
self.words_[syn] = words
fid.close()
def reset(self):
self.count_ = 0
def set_count(self, count):
self.count_ = count
def read(self):
imFile = self.imFile_ % (self.count_ + 1)
#im = mp.caffe.io.load_image(imFile)
im = scm.imread(imFile)
lb = self.labels_[self.count_]
syn = self.synsets_[lb]
words = self.words_[syn]
self.count_ += 1
return im, lb, syn, words
def word_label(self, lb):
return self.words_[self.synsets_[lb]]
def modelname_2_solvername(modelName):
#Remove .caffemodel
solverName = modelName[0:-11] + '.solverstate'
return solverName
def read_layerdefs_from_proto(fName):
'''
Reads the definitions of layers from a protoFile
'''
fid = open(fName,'r')
lines = fid.readlines()
fid.close()
layerNames, topNames = [], []
layerDef = []
stFlag = True
layerFlag = False
tmpDef = []
for (idx,l) in enumerate(lines):
isLayerSt = 'layer' in l
if isLayerSt:
if stFlag:
stFlag = False
layerNames.append('init')
topNames.append('')
else:
layerNames.append(layerName)
topNames.append(topName)
layerDef.append(tmpDef)
tmpDef = []
layerName, topName = mp.find_layer_name(lines[idx:])
tmpDef.append(l)
return layerNames, topNames, layerDef
## Produces names for layers
class LayerNameGenerator:
def __init__(self):
self.count_ = 0 # counts the total number of layers
self.nc_ = {} #Naming convention
self.nc_['InnerProduct'] = 'fc'
self.nc_['ReLU'] = 'relu'
self.nc_['Sigmoid'] = 'sigmoid'
self.nc_['Concat'] = 'concat'
self.nc_['EuclideanLoss'] = 'loss'
self.nc_['SoftmaxWithLoss'] = 'loss'
self.nc_['Dropout'] = 'drop'
self.nc_['Convolution'] = 'conv'
self.nc_['Accuracy'] = 'accuracy'
self.nc_['Pooling'] = 'pool'
self.nc_['RandomNoise'] = 'rn'
self.lastType_ = None
def next_name(self, layerType):
assert layerType in self.nc_.keys(), 'layerType %s not found' % layerType
prefix = self.nc_[layerType]
if layerType in ['ReLU','Pooling','Sigmoid'] and self.lastType_ in ['InnerProduct', 'Convolution']:
pass
elif layerType in ['Pooling'] and self.lastType_ in ['ReLU', 'Sigmoid']:
pass
elif layerType == 'Concat':
#Don't increment the counter for concatenation layer.
pass
else:
self.count_ += 1
name = '%s%d' % (prefix, self.count_)
self.lastType_ = layerType
return name
##
# Get protos for different objects needed in netdef .prototxt
def get_proto_dict(protoType, key, **kwargs):
'''
protoType: Type of proto to generate
key : the key to look for in kwargs
'''
#Initt the proto
if kwargs.has_key(key):
pArgs = kwargs[key]
else:
pArgs = {}
pDict = co.OrderedDict()
#Make the proto
if protoType in ['param_w', 'param_b']:
if protoType == 'param_w':
defVals = {'lr_mult': str(1), 'decay_mult': str(1)}
else:
defVals = {'lr_mult': str(2), 'decay_mult': str(0)}
#Name is not necessary
if pArgs.has_key('name'):
pDict['name'] = '"%s"' % pArgs['name']
for key in defVals:
if key in pArgs:
pDict[key] = pArgs[key]
else:
pDict[key] = defVals[key]
else:
raise Exception('Prototype %s not recognized' % protoType)
return copy.deepcopy(pDict)
##
# Generate String for writing down a protofile for a layer.
def get_layerdef_for_proto(layerType, layerName, bottom, numOutput=1, **kwargs):
'''
I recommend the following strategy for making layers:
a. Make the basic layer architecture using this function.
b. Modify this architecture as needed to change the layers.
##numOutput is depreciated. Instead use num_output in kwargs
##kwargs will override all other parameters
'''
layerDef = co.OrderedDict()
layerDef['name'] = '"%s"' % layerName
layerDef['type'] = '"%s"' % layerType
layerDef['bottom'] = '"%s"' % bottom
#The prms for different layers.
if layerType == 'InnerProduct':
layerDef['top'] = '"%s"' % layerName
layerDef['param'] = get_proto_dict('param_w', 'param', **kwargs)
paramDup = make_key('param', layerDef.keys())
layerDef[paramDup] = get_proto_dict('param_b', paramDup, **kwargs)
ipKey = 'inner_product_param'
layerDef[ipKey] = co.OrderedDict()
if kwargs.has_key('num_output'):
layerDef[ipKey]['num_output'] = kwargs['num_output']
else:
layerDef[ipKey]['num_output'] = str(numOutput)
layerDef[ipKey]['weight_filler'] = {}
layerDef[ipKey]['weight_filler']['type'] = '"gaussian"'
layerDef[ipKey]['weight_filler']['std'] = str(0.005)
layerDef[ipKey]['bias_filler'] = {}
layerDef[ipKey]['bias_filler']['type'] = '"constant"'
layerDef[ipKey]['bias_filler']['value'] = str(1.)
elif layerType == 'Convolution':
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
layerDef['param'] = get_proto_dict('param_w', 'param', **kwargs)
paramDup = make_key('param', layerDef.keys())
layerDef[paramDup] = get_proto_dict('param_b', paramDup, **kwargs)
ipKey = 'convolution_param'
layerDef[ipKey] = co.OrderedDict()
if kwargs.has_key('num_output'):
layerDef[ipKey]['num_output'] = kwargs['num_output']
else:
layerDef[ipKey]['num_output'] = str(numOutput)
layerDef[ipKey]['kernel_size'] = kwargs['kernel_size']
layerDef[ipKey]['stride'] = kwargs['stride']
if kwargs.has_key('pad'):
layerDef[ipKey]['pad'] = kwargs['pad']
if kwargs.has_key('group'):
layerDef[ipKey]['group'] = kwargs['group']
layerDef[ipKey]['weight_filler'] = {}
layerDef[ipKey]['weight_filler']['type'] = '"gaussian"'
#If weight/bias filler magnitudes are specified or not
if kwargs.has_key('wf_std'):
std = kwargs['wf_std']
else:
std = 0.01
if kwargs.has_key('bf_value'):
bfValue = kwargs['bf_value']
else:
bfValue = 0.
layerDef[ipKey]['weight_filler']['std'] = str(std)
layerDef[ipKey]['bias_filler'] = {}
layerDef[ipKey]['bias_filler']['type'] = '"constant"'
layerDef[ipKey]['bias_filler']['value'] = str(bfValue)
elif layerType in ['ReLU', 'Sigmoid']:
if kwargs.has_key('top'):
topName = kwargs['top']
else:
topName = layerName
layerDef['top'] = '"%s"' % topName
elif layerType == 'Pooling':
if kwargs.has_key('top'):
topName = kwargs['top']
else:
topName = layerName
layerDef['top'] = '"%s"' % topName
layerDef['pooling_param'] = {}
if kwargs.has_key('pool'):
poolType = kwargs['pool']
else:
poolType = 'MAX'
layerDef['pooling_param']['pool'] = poolType
layerDef['pooling_param']['kernel_size'] = kwargs['kernel_size']
layerDef['pooling_param']['stride'] = kwargs['stride']
if kwargs.has_key('pad'):
layerDef['pooling_param']['pad'] = kwargs['pad']
elif layerType == 'LRN':
if kwargs.has_key('top'):
topName = kwargs['top']
else:
topName = layerName
layerDef['top'] = '"%s"' % topName
layerDef['lrn_param'] = {}
layerDef['lrn_param']['local_size'] = kwargs['local_size']
layerDef['lrn_param']['alpha'] = kwargs['alpha']
layerDef['lrn_param']['beta'] = kwargs['beta']
layerDef['lrn_param']['k'] = kwargs['k']
elif layerType=='Silence':
#Nothing to be done
pass
elif layerType=='Dropout':
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
layerDef['dropout_param'] = co.OrderedDict()
layerDef['dropout_param']['dropout_ratio'] = str(kwargs['dropout_ratio'])
elif layerType in ['Accuracy']:
assert kwargs.has_key('bottom2')
bottom2 = make_key('bottom', layerDef.keys())
layerDef[bottom2] = '"%s"' % kwargs['bottom2']
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
elif layerType in ['EuclideanLoss', 'SoftmaxWithLoss']:
assert kwargs.has_key('bottom2')
bottom2 = make_key('bottom', layerDef.keys())
layerDef[bottom2] = '"%s"' % kwargs['bottom2']
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
layerDef['loss_weight'] = 1
elif layerType in ['ContrastiveLoss']:
assert kwargs.has_key('bottom2') and kwargs.has_key('bottom3')
bottom2 = make_key('bottom', layerDef.keys())
layerDef[bottom2] = '"%s"' % kwargs['bottom2']
bottom3 = make_key('bottom', layerDef.keys())
layerDef[bottom3] = '"%s"' % kwargs['bottom3']
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
#Add the contrastive loss margin
layerDef['contrastive_loss_param'] = co.OrderedDict()
if kwargs.has_key('margin'):
layerDef['constrastive_loss_param']['margin'] = kwargs['margin']
else:
layerDef['constrastive_loss_param']['margin'] = 1.0
layerDef['loss_weight'] = 1
elif layerType == 'Concat':
assert kwargs.has_key('bottom2')
assert kwargs.has_key('concat_dim')
if type(kwargs['bottom2'])==list:
for bot in kwargs['bottom2']:
bottom2 = make_key('bottom', layerDef.keys())
layerDef[bottom2] = '"%s"' % bot
else:
bottom2 = make_key('bottom', layerDef.keys())
layerDef[bottom2] = '"%s"' % kwargs['bottom2']
layerDef['concat_param'] = co.OrderedDict()
layerDef['concat_param']['concat_dim'] = kwargs['concat_dim']
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
elif layerType in ['DeployData']:
layerDef['input'] = '"%s"' % layerName
ipDims = kwargs['ipDims'] #(batch_size, channels, h, w)
layerDef['input_dim'] = ipDims[0]
key = make_key('input_dim', layerDef.keys())
layerDef[key] = ipDims[1]
layerDef[make_key('input_dim', layerDef.keys())] = ipDims[2]
layerDef[make_key('input_dim', layerDef.keys())] = ipDims[3]
elif layerType in ['MemoryData']:
del layerDef['bottom']
#First top
assert kwargs.has_key('top')
layerDef['top'] = '"%s"' % kwargs['top']
#Second top
key = make_key('top', layerDef.keys())
if kwargs.has_key('top2'):
keyVal = kwargs['top2']
else:
keyVal = 'ignore'
layerDef[key] = '"%s"' % keyVal
#Input dimensions
ipDims = kwargs['ipDims'] #(batch_size, channels, h, w)
layerDef['memory_data_param'] = dict()
layerDef['memory_data_param']['batch_size'] = ipDims[0]
layerDef['memory_data_param']['channels'] = ipDims[1]
layerDef['memory_data_param']['height'] = ipDims[2]
layerDef['memory_data_param']['width'] = ipDims[3]
elif layerType in ['RandomNoise']:
layerDef['top'] = '"%s"' % layerName
if kwargs.has_key('adaptive_sigma'):
layerDef['random_noise_param'] = co.OrderedDict()
layerDef['random_noise_param']['adaptive_sigma'] = kwargs['adaptive_sigma']
layerDef['random_noise_param']['adaptive_factor'] = kwargs['adaptive_factor']
elif layerType in ['gaussRender']:
if kwargs.has_key('top'):
layerDef['top'] = '"%s"' % kwargs['top']
else:
layerDef['top'] = '"%s"' % layerName
layerDef['type'] = '"Python"'
layerDef['python_param'] = co.OrderedDict()
layerDef['python_param']['module'] = '"python_ief"'
layerDef['python_param']['layer'] = '"GaussRenderLayer"'
paramStr = ou.make_python_param_str(kwargs, ignoreKeys=['top'])
layerDef['python_param']['param_str'] = '"%s"' % paramStr
else:
raise Exception('%s layer type not found' % layerType)
return layerDef
##
# Get the layerdefs for siamese layers
def get_siamese_layerdef_for_proto(layerType, layerName, bottom, numOutput=1, **kwargs):
if layerType in ['InnerProduct', 'Convolution']:
paramKey = 'param'
paramDupKey = make_key('param', [paramKey])
#Weight param name
wName = ou.get_item_dict(kwargs, [paramKey] + ['name'])
if wName is None:
wName = layerName + '_w'
#Bias param name
bName = ou.get_item_dict(kwargs, [paramDupKey] + ['name'])
if bName is None:
bName = layerName + '_b'
#Set the info
kwargs['param'] = {}
kwargs['param']['name'] = wName
kwargs[paramDupKey] = {}
kwargs[paramDupKey]['name'] = bName
elif layerType in ['ReLU', 'Pooling']:
pass
else:
raise Exception('Siamese layer not supported for %s' % layerType)
#First Siamese layer
def1 = get_layerdef_for_proto(layerType, layerName, bottom, numOutput=numOutput, **kwargs)
#Second Siamese layer
layerName = layerName + '_p'
bottom = bottom + '_p'
def2 = get_layerdef_for_proto(layerType, layerName, bottom, numOutput=numOutput, **kwargs)
return def1, def2
##
#Make a siamese counter part
def siamese_from_layerdef(lDef, botName=None):
name, top, bot = lDef['name'], lDef['top'], lDef['bottom']
suffix = '_p'
smName = '"%s"' % (name[1:-1] + suffix)
smTop = '"%s"' % (top[1:-1] + suffix)
if botName is not None:
smBot = '"%s"' % botName
else:
smBot = '"%s"' % (bot[1:-1] + suffix)
smDef = co.OrderedDict(lDef)
smDef['name'] = smName
smDef['top'] = smTop
smDef['bottom'] = smBot
return smDef
##
#Helper fucntion for process_debug_log - helps find specific things in the line
def find_in_line(l, findType):
if findType == 'iterNum':
assert 'Iteration' in l, 'Iteration word must be present in the line'
ss = l.split()
idx = ss.index('Iteration')
return int(ss[idx+1][0:-1])
elif findType == 'layerName':
assert 'Layer' in l, 'Layer word must be present in the line'
ss = l.split()
idx = ss.index('Layer')
return ss[idx+1][:-1]
else:
raise Exception('Unrecognized findType')
##
# Debug log that contatins how the parameters and features are changing during
# forward, backward and update stages.
def process_debug_log(logFile, setName='train'):
'''
The debug file contains infromation in the following format
Forward Pass
Backward Pass
#The loss of the the network (Since, backward pass has not been used to update,
the loss corresponds to previous iteration.
Update log.
'''
assert setName in ['train','test'], 'Unrecognized set-name'
fid = open(logFile, 'r')
lines = fid.readlines()
#Find the layerNames
layerNames = []
for (count, l) in enumerate(lines):
if 'Setting up' in l and 'Setting up crop layers' not in l:
name = l.split()[-1]
if name not in layerNames:
layerNames.append(name)
if 'Solver scaffolding' in l:
break
lines = lines[count:]
#Start collecting the required stats.
iters = []
#Variable Intialization
allBlobOp, allBlobParam, allBlobDiff, allBlobUpdate = {}, {}, {}, {}
blobOp, blobParam, blobDiff, blobUpdate = {}, {}, {}, {}
for name in layerNames:
allBlobOp[name], allBlobParam[name], allBlobDiff[name], allBlobUpdate[name] = [], [], [], []
blobOp[name], blobParam[name], blobDiff[name], blobUpdate[name] = [], [], [], []
#Only when seeFlag is set to True, we will collect the required data stats.
seeFlag = False
updateFlag = False
appendFlag = False
writeFlag = False
for (count, l) in enumerate(lines):
#Find the start of a new and relevant iteration
if 'Forward' in l and writeFlag == True:
for name in layerNames:
allBlobOp[name].append(blobOp[name])
allBlobParam[name].append(blobParam[name])
allBlobDiff[name].append(blobDiff[name])
allBlobUpdate[name].append(blobUpdate[name])
blobOp[name], blobParam[name], blobDiff[name], blobUpdate[name] = [], [], [], []
writeFlag = False
#The training log starts after the line Test Net Output
if setName=='train' and ('Test' in l and 'output' in l):
seeFlag = True
print "Setting to true"
#If there is a testing network then set the seeFlag to False
if setName=='train' and 'Testing' in l:
seeFlag = False
if seeFlag and 'Iteration' in l and 'lr' in l:
iterNum = find_in_line(l, 'iterNum')
iters.append(iterNum)
if seeFlag and 'Forward' in l:
lName = find_in_line(l, 'layerName')
print lName
if 'top blob' in l:
blobOp[lName].append(float(l.split()[-1]))
if 'param blob' in l:
blobParam[lName].append(float(l.split()[-1]))
#Find the back propogated diffs
if seeFlag and ('Backward' in l) and ('Layer' in l):
lName = find_in_line(l, 'layerName')
if 'param blob' in l:
blobDiff[lName].append(float(l.split()[-1]))
#Find the update
if seeFlag and 'Update' in l and 'Layer' in l:
#Forward after the update is the time when we need to write.
writeFlag = True
lName = find_in_line(l, 'layerName')
assert 'diff' in l
assert l.split()[-2] == 'diff:', 'I Found %s instead of diff:' % l.split()[-2]
blobUpdate[lName].append(float(l.split()[-1]))
fid.close()
for name in layerNames:
print name
pdb.set_trace()
data = [np.array(a).reshape(1,len(a)) for a in allBlobOp[name]]
allBlobOp[name] = np.concatenate(data, axis=0)
data = [np.array(a).reshape(1,len(a)) for a in allBlobParam[name]]
allBlobParam[name] = np.concatenate(data, axis=0)
data = [np.array(a).reshape(1,len(a)) for a in allBlobDiff[name]]
allBlobDiff[name] = np.concatenate(data, axis=0)
data = [np.array(a).reshape(1,len(a)) for a in allBlobUpdate[name]]
allBlobUpdate[name] = np.concatenate(data, axis=0)
#If there are K blobs in a layer, then the size will N * K where N is the number of samples
# and K is the number of blobs.
return allBlobOp, allBlobParam, allBlobDiff, allBlobUpdate, layerNames, iters
##
# Helper function for plot_debug_log
def plot_debug_subplots_(data, subPlotNum, label, col, fig,
numPlots=3):
'''
data: N * K where N is the number of points and K
is the number of outputs
subPlotNum: The subplot Number
label : The label to put
col : The color of the line
fig : The figure to use for plotting
numPlots : number of plots
'''
plt.figure(fig.number)
if data.ndim > 0:
data = np.abs(data)
'''
#print data.shape
#if data.ndim > 1:
data = np.sum(data, axis=tuple(range(1,data.ndim)))
#print label, data.shape
'''
for i in range(data.shape[1]):
plt.subplot(numPlots,1,subPlotNum + i)
print label + '_blob%d' % i
plt.plot(range(data.shape[0]), data[:,i],
label=label + '_blob%d' % i, color=col)
plt.legend()
##
# Plots the weight and features values from a debug enabled log file.
def plot_debug_log(logFile, setName='train', plotNames=None):
'''
blobOp: The output of the blob
blobParam : The weight of the blobs
blobDiff : The gradients of the blob
blobUpdate: The update for the blob.
'''
blobOp, blobParam, blobDiff, blobUpdate, layerNames, iterNum\
= process_debug_log(logFile, setName=setName)
if plotNames is not None:
for p in plotNames:
assert p in layerNames, '%s layer not found' % p
else:
plotNames = [l for l in layerNames]
colIdx = np.linspace(0,255,len(plotNames)).astype(int)
plt.ion()
print colIdx
print layerNames
for count,name in enumerate(plotNames):
fig = plt.figure()
col = plt.cm.jet(colIdx[count])
#Number of plots
numPlots = blobOp[name].shape[1] + blobParam[name].shape[1] +\
blobDiff[name].shape[1] + blobUpdate[name].shape[1]
#Plot the data
plot_debug_subplots_(blobOp[name], 1, name + '_data', col,
fig, numPlots=numPlots)
#Plot the norms of the weights.
plot_debug_subplots_(blobParam[name], 1 + blobOp[name].shape[1],
name + '_weights', col, fig, numPlots=numPlots)
#Norms of the gradient
plot_debug_subplots_(blobDiff[name],
1 + blobOp[name].shape[1] + blobParam[name].shape[1],
name + '_diff', col, fig, numPlots=numPlots)
#The ratio of update/weights
lUpdate = blobUpdate[name]
ratio = np.zeros(lUpdate.shape)
if lUpdate.shape[1]>0:
for d in range(lUpdate.shape[1]):
idx = blobParam[name][:,d] == 0
ratio[:,d] = lUpdate[:,d] / blobParam[name][:,d]
ratio[idx,d] = 0
plot_debug_subplots_(ratio,
1 + blobOp[name].shape[1] + blobParam[name].shape[1] + blobDiff[name].shape[1],
name + '_ration', col, fig, numPlots=numPlots)
plt.show()
##
# Get the accuracy from the test log
def test_log2acc(logFile):
acc = None
with open(logFile, 'r') as fid:
lines = fid.readlines()
data = lines[-2].split()
assert data[-3] == 'accuracy', 'Something is wrong in the way the accuracy is being read'
acc = float(data[-1])
return acc
##
# Get useful caffe paths
# Set the paths over here for using the utils code.
def get_caffe_paths():
paths = {}
paths['caffeMain'] = CAFFE_PATH
paths['tools'] = os.path.join(paths['caffeMain'], 'build', 'tools')
paths['pythonTest'] = os.path.join(paths['caffeMain'], 'python', 'test')
return paths
def give_run_permissions_(fileName):
args = ['chmod u+x %s' % fileName]
subprocess.check_call(args,shell=True)
##
#Make a new key if there are duplicates.
def make_key(key, keyNames, dupStr='_$dup$'):
'''
The new string is made by concatenating the dupStr,
until a unique name is found.
'''
if key not in keyNames:
return key
else:
key = key + dupStr
return make_key(key, keyNames, dupStr)
##
# If the key has dupStr, strip it off.
def strip_key(key, dupStr='_$dup$'):
if dupStr in key:
idx = key.find(dupStr)
key = key[:idx]
return key
##
# Extracts message parameters of a .prototxt from a list of strings.
def get_proto_param(lines):
#The String to use in case of duplicate names
dupStr = '_$dup$'
data = co.OrderedDict()
braCount = 0
readFlag = True
i = 0
while readFlag:
if i>=len(lines):
break
l = lines[i]
#print l.strip()
if l in ['', '\n']:
#Continue if empty line encountered.
print 'Skipping empty line: %s ' % l.strip()
elif '#' in l:
#In case of comments
print 'Ignoring line: %s' % l.strip()
elif '{' in l and '}' in l:
raise Exception('Reformat the file, both "{" and "}" cannot be present on the same line %s' % l)
elif '{' in l:
name = l.split()[0]
if '{' in name:
assert name[-1] == '{'
name = name[:-1]
name = make_key(name, data.keys(), dupStr=dupStr)
data[name], skipI = get_proto_param(lines[i+1:])
braCount += 1
i += skipI
elif '}' in l:
braCount -= 1
else:
#print l
splitVals = l.strip().split(':')
if len(splitVals) > 2:
raise Exception('Improper format for: %s, l.split() should only produce 2 values' % l)
name, val = splitVals
name = name.strip()
val = val.strip()
name = make_key(name, data.keys(), dupStr=dupStr)
data[name] = val
if braCount == -1:
break
i += 1
return data, i
##
# Write the proto information into a file.
def write_proto_param(fid, protoData, numTabs=0):
'''
fid : The file handle to which data needs to be written.
data: The data to be written.
numTabs: Is for the proper alignment.
'''
tabStr = '\t ' * numTabs
for (key, data) in protoData.iteritems():
if data is None:
continue
key = strip_key(key)
if isinstance(data, dict):
line = '%s %s { \n' % (tabStr,key)
fid.write(line)
write_proto_param(fid, data, numTabs=numTabs + 1)
line = '%s } \n' % (tabStr)
fid.write(line)
else:
line = '%s %s: %s \n' % (tabStr, key, data)
fid.write(line)
##
# Write proto param for a layer
def write_proto_param_layer(fid, protoData):
'''
fid : File Handle
protoData: The data that needs to be written
'''
assert protoData.has_key('name') and protoData.has_key('type'),\
'layer must have a name and a type'
name, layerType = protoData['name'][1:-1], protoData['type'][1:-1]
if layerType =='DeployData':
layerProto = copy.deepcopy(protoData)
del layerProto['name'], layerProto['bottom'], layerProto['type']
#print (layerProto)
write_proto_param(fid, layerProto, 0)
else:
fid.write('layer { \n')
write_proto_param(fid, protoData, numTabs=0)
fid.write('} \n')
##
# Reads the architecture definition file and converts it into a nice, programmable format.
class ProtoDef():
ProtoPhases = ['TRAIN', 'TEST']
def __init__(self, defFile=None, layerDict=None):
if layerDict is not None:
assert layerDict.has_key('TRAIN') and layerDict.has_key('TEST')
self.layers_ = co.OrderedDict(layerDict)
self.initData_ = []
return
#Lines that are there before the layers start.
self.initData_ = []
self.layers_ = {}
self.layers_['TRAIN'] = co.OrderedDict()
self.layers_['TEST'] = co.OrderedDict()
self.siameseConvert_ = False #If the def has been convered to siamese or not.
if defFile is None:
return
#If initializing from a file
fid = open(defFile, 'r')
lines = fid.readlines()
i = 0
layerInit = False
while True:
l = lines[i]
if not layerInit:
self.initData_.append(l)
if ('layers' in l) or ('layer' in l):
layerInit = True
layerName,_ = mp.find_layer_name(lines[i:])
layerData, skipI = get_proto_param(lines[i+1:])
if layerData.has_key('include'):
phase = layerData['include']['phase']
assert phase in ['TRAIN', 'TEST'], '%s phase not recognized' % phase
assert layerName not in self.layers_[phase].keys(), 'Duplicate LayerName Found'
self.layers_[phase][layerName] = layerData
else:
#Default Phase is Train
assert layerName not in self.layers_['TRAIN'].keys(),\
'Duplicate LayerName: %s found' % layerName
self.layers_['TRAIN'][layerName] = layerData
i += skipI
i += 1
if i >= len(lines):
break
#The last line of iniData_ is going to be "layer {", so remove it.
self.initData_ = self.initData_[:-1]
@classmethod
def deploy_from_proto(cls, initDef, dataLayerNames=['data'], imSz=[[3,128,128]], **kwargs):
if isinstance(initDef, ProtoDef):
netDef = copy.deepcopy(initDef)
else:
assert isinstance(initDef, str), 'Invalid format of netDef'
netDef = cls(initDef)
netDef.make_deploy(dataLayerNames=dataLayerNames, imSz=imSz, **kwargs)
return netDef
##
# Protofile useful for reconstruction
@classmethod
def recproto_from_proto(cls, initDef, featDims=(10,64,112,112),
lossType = 'l2', recLayer='conv1', lossWeight=1.0,
**kwargs):
netDef = cls.deploy_from_proto(initDef, **kwargs)
#Add the Memory data layer for inputting the current image
lDef = get_layerdef_for_proto('MemoryData', 'gt_feat', None, top='gt_feat',
ipDims=featDims)
netDef.del_all_layers_above(recLayer)
#Add the memory data layer
recLayers = co.OrderedDict()
for ph in ProtoDef.ProtoPhases:
recLayers[ph] = co.OrderedDict()
stFlag = False
for lName, l in netDef.layers_[ph].iteritems():
if stFlag:
recLayers[ph]['gt_feat'] = lDef
stFlag = False
lType = netDef.get_layer_property(lName, 'type')[1:-1]
print lType
if ph == 'TRAIN' and lType == 'DeployData':
stFlag = True
recLayers[ph][lName] = copy.deepcopy(l)
#Add the Loss Layer
if lossType == 'l1':
pass
elif lossType == 'l2':
lArgs = {}
lArgs['bottom'] = recLayer
lArgs['bottom2'] = 'gt_feat'
lArgs['lossWeight'] = lossWeight
lDef = get_layerdef_for_proto('EuclideanLoss', 'loss', **lArgs)
else:
raise Exception ('Loss Type %s not recognized' % lossType)
recLayers['TRAIN']['loss'] = lDef
netDef.layers_ = copy.deepcopy(recLayers)
return netDef
@classmethod
def visproto_from_proto(cls, initDef, dataLayerNames=['window_data'],
imSz=[[3,101,101]], delAbove='conv1'):
if isinstance(initDef, ProtoDef):
netDef = copy.deepcopy(initDef)
else:
assert isinstance(initDef, str), 'Invalid format of netDef'
netDef = cls(initDef)
for ph in ['TRAIN', 'TEST']:
delFlag = False
lNames = netDef.get_all_layernames(phase=ph)