-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
caffe_train.py
1841 lines (1579 loc) · 72.9 KB
/
caffe_train.py
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 (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
from __future__ import absolute_import
from collections import OrderedDict
import copy
import math
import operator
import os
import re
import sys
import time
from google.protobuf import text_format
import numpy as np
import platform
import scipy
from .train import TrainTask
import digits
from digits import utils
from digits.config import config_value
from digits.status import Status
from digits.utils import subclass, override, constants
from digits.utils.filesystem import tail
# Must import after importing digit.config
import caffe
import caffe_pb2
# NOTE: Increment this every time the pickled object changes
PICKLE_VERSION = 5
# Constants
CAFFE_SOLVER_FILE = 'solver.prototxt'
CAFFE_ORIGINAL_FILE = 'original.prototxt'
CAFFE_TRAIN_VAL_FILE = 'train_val.prototxt'
CAFFE_SNAPSHOT_PREFIX = 'snapshot'
CAFFE_DEPLOY_FILE = 'deploy.prototxt'
CAFFE_PYTHON_LAYER_FILE = 'digits_python_layers.py'
@subclass
class DigitsTransformer(caffe.io.Transformer):
"""
A subclass of caffe.io.Transformer (an old-style class)
Handles cases when we don't want to resize inputs
"""
def __init__(self, resize, **kwargs):
"""
Arguments:
resize -- whether to resize inputs to the network default
"""
self.resize = resize
caffe.io.Transformer.__init__(self, **kwargs)
def preprocess(self, in_, data):
"""
Preprocess an image
See parent class for details
"""
if not self.resize:
# update target input dimension such that no resize occurs
self.inputs[in_] = self.inputs[in_][:2] + data.shape[:2]
# do we have a mean?
if in_ in self.mean:
# resize mean if necessary
if self.mean[in_].size > 1:
# we are doing mean image subtraction
if self.mean[in_].size != data.size:
# mean image size is different from data size
# => we need to resize the mean image
transpose = self.transpose.get(in_)
if transpose is not None:
# detranspose
self.mean[in_] = self.mean[in_].transpose(
np.argsort(transpose))
self.mean[in_] = caffe.io.resize_image(
self.mean[in_],
data.shape[:2])
if transpose is not None:
# retranspose
self.mean[in_] = self.mean[in_].transpose(transpose)
return caffe.io.Transformer.preprocess(self, in_, data)
@subclass
class Error(Exception):
pass
@subclass
class CaffeTrainSanityCheckError(Error):
"""A sanity check failed"""
pass
@subclass
class CaffeTrainTask(TrainTask):
"""
Trains a caffe model
"""
CAFFE_LOG = 'caffe_output.log'
@staticmethod
def upgrade_network(network):
# TODO
pass
@staticmethod
def set_mode(gpu):
if gpu is not None:
caffe.set_device(gpu)
caffe.set_mode_gpu()
else:
caffe.set_mode_cpu()
def __init__(self, **kwargs):
"""
Arguments:
network -- a caffe NetParameter defining the network
"""
super(CaffeTrainTask, self).__init__(**kwargs)
self.pickver_task_caffe_train = PICKLE_VERSION
self.current_iteration = 0
self.loaded_snapshot_file = None
self.loaded_snapshot_epoch = None
self.image_mean = None
self.solver = None
self.solver_file = CAFFE_SOLVER_FILE
self.model_file = CAFFE_ORIGINAL_FILE
self.train_val_file = CAFFE_TRAIN_VAL_FILE
self.snapshot_prefix = CAFFE_SNAPSHOT_PREFIX
self.deploy_file = CAFFE_DEPLOY_FILE
self.log_file = self.CAFFE_LOG
self.digits_version = digits.__version__
self.caffe_version = config_value('caffe')['version']
self.caffe_flavor = config_value('caffe')['flavor']
def __getstate__(self):
state = super(CaffeTrainTask, self).__getstate__()
# Don't pickle these things
if 'caffe_log' in state:
del state['caffe_log']
if '_transformer' in state:
del state['_transformer']
if '_caffe_net' in state:
del state['_caffe_net']
return state
def __setstate__(self, state):
super(CaffeTrainTask, self).__setstate__(state)
# Upgrade pickle file
if state['pickver_task_caffe_train'] <= 1:
self.caffe_log_file = self.CAFFE_LOG
if state['pickver_task_caffe_train'] <= 2:
if hasattr(self, 'caffe_log_file'):
self.log_file = self.caffe_log_file
else:
self.log_file = None
self.framework_id = 'caffe'
if state['pickver_task_caffe_train'] <= 3:
try:
import caffe.proto.caffe_pb2
if isinstance(self.network, caffe.proto.caffe_pb2.NetParameter):
# Convert from NetParameter to string back to NetParameter
# to avoid this error:
# TypeError: Parameter to MergeFrom() must be instance of
# same class: expected caffe_pb2.NetParameter got
# caffe.proto.caffe_pb2.NetParameter.
fixed = caffe_pb2.NetParameter()
text_format.Merge(
text_format.MessageToString(self.network),
fixed,
)
self.network = fixed
except ImportError:
# If caffe.proto.caffe_pb2 can't be imported, then you're
# probably on a platform where that was never possible.
# So you can't need this upgrade and we can ignore the error.
pass
if state['pickver_task_caffe_train'] <= 4:
if hasattr(self, "original_file"):
self.model_file = self.original_file
del self.original_file
else:
self.model_file = None
self.pickver_task_caffe_train = PICKLE_VERSION
# Make changes to self
self.loaded_snapshot_file = None
self.loaded_snapshot_epoch = None
# These things don't get pickled
self.image_mean = None
# Task overrides
@override
def name(self):
return 'Train Caffe Model'
@override
def before_run(self):
super(CaffeTrainTask, self).before_run()
if isinstance(self.job, digits.model.images.classification.ImageClassificationModelJob):
self.save_files_classification()
elif isinstance(self.job, digits.model.images.generic.GenericImageModelJob):
self.save_files_generic()
else:
raise NotImplementedError
self.caffe_log = open(self.path(self.CAFFE_LOG), 'a')
self.saving_snapshot = False
self.receiving_train_output = False
self.receiving_val_output = False
self.last_train_update = None
return True
def get_mean_image(self, mean_file, resize=False):
mean_image = None
with open(self.dataset.path(mean_file), 'rb') as f:
blob = caffe_pb2.BlobProto()
blob.MergeFromString(f.read())
mean_image = np.reshape(blob.data,
(
self.dataset.get_feature_dims()[2],
self.dataset.get_feature_dims()[0],
self.dataset.get_feature_dims()[1],
)
)
# Resize the mean image if crop_size exists
if mean_image is not None and resize:
# Get the image size needed
network = caffe_pb2.NetParameter()
with open(self.path(self.deploy_file)) as infile:
text_format.Merge(infile.read(), network)
if network.input_shape:
data_shape = network.input_shape[0].dim
else:
data_shape = network.input_dim[:4]
assert len(data_shape) == 4, 'Bad data shape.'
# Get the image
mean_image = mean_image.astype('uint8')
mean_image = mean_image.transpose(1, 2, 0)
shape = list(mean_image.shape)
# imresize will not resize if the depth is anything
# other than 3 or 4. If it's 1, imresize expects an
# array.
if (len(shape) == 2 or (len(shape) == 3 and (shape[2] == 3 or shape[2] == 4))):
mean_image = scipy.misc.imresize(mean_image, (data_shape[2], data_shape[3]))
else:
mean_image = scipy.misc.imresize(mean_image[:, :, 0],
(data_shape[2], data_shape[3]))
mean_image = np.expand_dims(mean_image, axis=2)
mean_image = mean_image.transpose(2, 0, 1)
mean_image = mean_image.astype('float')
return mean_image
def get_mean_pixel(self, mean_file):
mean_image = self.get_mean_image(mean_file)
mean_pixel = None
if mean_image is not None:
mean_pixel = mean_image.mean(1).mean(1)
return mean_pixel
def set_mean_value(self, layer, mean_pixel):
# remove any values that may already be in the network
if layer.transform_param.HasField('mean_file'):
layer.transform_param.ClearField('mean_file')
self.logger.warning('Ignoring mean_file from network ...')
if len(layer.transform_param.mean_value) > 0:
layer.transform_param.ClearField('mean_value')
self.logger.warning('Ignoring mean_value from network ...')
layer.transform_param.mean_value.extend(list(mean_pixel))
def set_mean_file(self, layer, mean_file):
# remove any values that may already be in the network
if layer.transform_param.HasField('mean_file'):
layer.transform_param.ClearField('mean_file')
self.logger.warning('Ignoring mean_file from network ...')
if len(layer.transform_param.mean_value) > 0:
layer.transform_param.ClearField('mean_value')
self.logger.warning('Ignoring mean_value from network ...')
layer.transform_param.mean_file = mean_file
# TODO merge these monolithic save_files functions
def save_files_classification(self):
"""
Save solver, train_val and deploy files to disk
"""
# Save the origin network to file:
with open(self.path(self.model_file), 'w') as outfile:
text_format.PrintMessage(self.network, outfile)
network = cleanedUpClassificationNetwork(self.network, len(self.get_labels()))
data_layers, train_val_layers, deploy_layers = filterLayersByState(network)
# Write train_val file
train_val_network = caffe_pb2.NetParameter()
# Data layers
# TODO clean this up
train_data_layer = None
val_data_layer = None
for layer in data_layers.layer:
for rule in layer.include:
if rule.phase == caffe_pb2.TRAIN:
assert train_data_layer is None, 'cannot specify two train data layers'
train_data_layer = layer
elif rule.phase == caffe_pb2.TEST:
assert val_data_layer is None, 'cannot specify two test data layers'
val_data_layer = layer
if train_data_layer is None:
assert val_data_layer is None, 'cannot specify a test data layer without a train data layer'
dataset_backend = self.dataset.get_backend()
has_val_set = self.dataset.get_entry_count(constants.VAL_DB) > 0
if train_data_layer is not None:
if dataset_backend == 'lmdb':
assert train_data_layer.type == 'Data', 'expecting a Data layer'
elif dataset_backend == 'hdf5':
assert train_data_layer.type == 'HDF5Data', 'expecting an HDF5Data layer'
if dataset_backend == 'lmdb' and train_data_layer.HasField('data_param'):
assert not train_data_layer.data_param.HasField('source'), "don't set the data_param.source"
assert not train_data_layer.data_param.HasField('backend'), "don't set the data_param.backend"
if dataset_backend == 'hdf5' and train_data_layer.HasField('hdf5_data_param'):
assert not train_data_layer.hdf5_data_param.HasField('source'), "don't set the hdf5_data_param.source"
max_crop_size = min(self.dataset.get_feature_dims()[0], self.dataset.get_feature_dims()[1])
if self.crop_size:
assert dataset_backend != 'hdf5', 'HDF5Data layer does not support cropping'
assert self.crop_size <= max_crop_size, 'crop_size is larger than the image size'
train_data_layer.transform_param.crop_size = self.crop_size
elif train_data_layer.transform_param.HasField('crop_size'):
cs = train_data_layer.transform_param.crop_size
if cs > max_crop_size:
# don't throw an error here
cs = max_crop_size
train_data_layer.transform_param.crop_size = cs
self.crop_size = cs
train_val_network.layer.add().CopyFrom(train_data_layer)
train_data_layer = train_val_network.layer[-1]
if val_data_layer is not None and has_val_set:
if dataset_backend == 'lmdb':
assert val_data_layer.type == 'Data', 'expecting a Data layer'
elif dataset_backend == 'hdf5':
assert val_data_layer.type == 'HDF5Data', 'expecting an HDF5Data layer'
if dataset_backend == 'lmdb' and val_data_layer.HasField('data_param'):
assert not val_data_layer.data_param.HasField('source'), "don't set the data_param.source"
assert not val_data_layer.data_param.HasField('backend'), "don't set the data_param.backend"
if dataset_backend == 'hdf5' and val_data_layer.HasField('hdf5_data_param'):
assert not val_data_layer.hdf5_data_param.HasField('source'), "don't set the hdf5_data_param.source"
if self.crop_size:
# use our error checking from the train layer
val_data_layer.transform_param.crop_size = self.crop_size
train_val_network.layer.add().CopyFrom(val_data_layer)
val_data_layer = train_val_network.layer[-1]
else:
layer_type = 'Data'
if dataset_backend == 'hdf5':
layer_type = 'HDF5Data'
train_data_layer = train_val_network.layer.add(type=layer_type, name='data')
train_data_layer.top.append('data')
train_data_layer.top.append('label')
train_data_layer.include.add(phase=caffe_pb2.TRAIN)
if dataset_backend == 'lmdb':
train_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
elif dataset_backend == 'hdf5':
train_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if self.crop_size:
assert dataset_backend != 'hdf5', 'HDF5Data layer does not support cropping'
train_data_layer.transform_param.crop_size = self.crop_size
if has_val_set:
val_data_layer = train_val_network.layer.add(type=layer_type, name='data')
val_data_layer.top.append('data')
val_data_layer.top.append('label')
val_data_layer.include.add(phase=caffe_pb2.TEST)
if dataset_backend == 'lmdb':
val_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
elif dataset_backend == 'hdf5':
val_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if self.crop_size:
val_data_layer.transform_param.crop_size = self.crop_size
if dataset_backend == 'lmdb':
train_data_layer.data_param.source = self.dataset.get_feature_db_path(constants.TRAIN_DB)
train_data_layer.data_param.backend = caffe_pb2.DataParameter.LMDB
if val_data_layer is not None and has_val_set:
val_data_layer.data_param.source = self.dataset.get_feature_db_path(constants.VAL_DB)
val_data_layer.data_param.backend = caffe_pb2.DataParameter.LMDB
elif dataset_backend == 'hdf5':
train_data_layer.hdf5_data_param.source = os.path.join(
self.dataset.get_feature_db_path(constants.TRAIN_DB), 'list.txt')
if val_data_layer is not None and has_val_set:
val_data_layer.hdf5_data_param.source = os.path.join(
self.dataset.get_feature_db_path(constants.VAL_DB), 'list.txt')
if self.use_mean == 'pixel':
assert dataset_backend != 'hdf5', 'HDF5Data layer does not support mean subtraction'
mean_pixel = self.get_mean_pixel(self.dataset.path(self.dataset.get_mean_file()))
self.set_mean_value(train_data_layer, mean_pixel)
if val_data_layer is not None and has_val_set:
self.set_mean_value(val_data_layer, mean_pixel)
elif self.use_mean == 'image':
self.set_mean_file(train_data_layer, self.dataset.path(self.dataset.get_mean_file()))
if val_data_layer is not None and has_val_set:
self.set_mean_file(val_data_layer, self.dataset.path(self.dataset.get_mean_file()))
if self.batch_size:
if dataset_backend == 'lmdb':
train_data_layer.data_param.batch_size = self.batch_size
if val_data_layer is not None and has_val_set:
val_data_layer.data_param.batch_size = self.batch_size
elif dataset_backend == 'hdf5':
train_data_layer.hdf5_data_param.batch_size = self.batch_size
if val_data_layer is not None and has_val_set:
val_data_layer.hdf5_data_param.batch_size = self.batch_size
else:
if dataset_backend == 'lmdb':
if not train_data_layer.data_param.HasField('batch_size'):
train_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if val_data_layer is not None and has_val_set and not val_data_layer.data_param.HasField('batch_size'):
val_data_layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
elif dataset_backend == 'hdf5':
if not train_data_layer.hdf5_data_param.HasField('batch_size'):
train_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if (val_data_layer is not None and has_val_set and
not val_data_layer.hdf5_data_param.HasField('batch_size')):
val_data_layer.hdf5_data_param.batch_size = constants.DEFAULT_BATCH_SIZE
# Non-data layers
train_val_network.MergeFrom(train_val_layers)
# Write to file
with open(self.path(self.train_val_file), 'w') as outfile:
text_format.PrintMessage(train_val_network, outfile)
# network sanity checks
self.logger.debug("Network sanity check - train")
CaffeTrainTask.net_sanity_check(train_val_network, caffe_pb2.TRAIN)
if has_val_set:
self.logger.debug("Network sanity check - val")
CaffeTrainTask.net_sanity_check(train_val_network, caffe_pb2.TEST)
# Write deploy file
deploy_network = caffe_pb2.NetParameter()
# Input
deploy_network.input.append('data')
shape = deploy_network.input_shape.add()
shape.dim.append(1)
shape.dim.append(self.dataset.get_feature_dims()[2])
if self.crop_size:
shape.dim.append(self.crop_size)
shape.dim.append(self.crop_size)
else:
shape.dim.append(self.dataset.get_feature_dims()[0])
shape.dim.append(self.dataset.get_feature_dims()[1])
# Layers
deploy_network.MergeFrom(deploy_layers)
# Write to file
with open(self.path(self.deploy_file), 'w') as outfile:
text_format.PrintMessage(deploy_network, outfile)
# network sanity checks
self.logger.debug("Network sanity check - deploy")
CaffeTrainTask.net_sanity_check(deploy_network, caffe_pb2.TEST)
found_softmax = False
for layer in deploy_network.layer:
if layer.type == 'Softmax':
found_softmax = True
break
assert found_softmax, \
('Your deploy network is missing a Softmax layer! '
'Read the documentation for custom networks and/or look at the standard networks for examples.')
# Write solver file
solver = caffe_pb2.SolverParameter()
# get enum value for solver type
solver.solver_type = getattr(solver, self.solver_type)
solver.net = self.train_val_file
# Set CPU/GPU mode
if config_value('caffe')['cuda_enabled'] and \
bool(config_value('gpu_list')):
solver.solver_mode = caffe_pb2.SolverParameter.GPU
else:
solver.solver_mode = caffe_pb2.SolverParameter.CPU
solver.snapshot_prefix = self.snapshot_prefix
# Batch accumulation
from digits.frameworks import CaffeFramework
if self.batch_accumulation and CaffeFramework().can_accumulate_gradients():
solver.iter_size = self.batch_accumulation
# Epochs -> Iterations
train_iter = int(math.ceil(
float(self.dataset.get_entry_count(constants.TRAIN_DB)) /
(train_data_layer.data_param.batch_size * solver.iter_size)
))
solver.max_iter = train_iter * self.train_epochs
snapshot_interval = self.snapshot_interval * train_iter
if 0 < snapshot_interval <= 1:
solver.snapshot = 1 # don't round down
elif 1 < snapshot_interval < solver.max_iter:
solver.snapshot = int(snapshot_interval)
else:
solver.snapshot = 0 # only take one snapshot at the end
if has_val_set and self.val_interval:
solver.test_iter.append(
int(math.ceil(float(self.dataset.get_entry_count(constants.VAL_DB)) /
val_data_layer.data_param.batch_size)))
val_interval = self.val_interval * train_iter
if 0 < val_interval <= 1:
solver.test_interval = 1 # don't round down
elif 1 < val_interval < solver.max_iter:
solver.test_interval = int(val_interval)
else:
solver.test_interval = solver.max_iter # only test once at the end
# Learning rate
solver.base_lr = self.learning_rate
solver.lr_policy = self.lr_policy['policy']
scale = float(solver.max_iter) / 100.0
if solver.lr_policy == 'fixed':
pass
elif solver.lr_policy == 'step':
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'multistep':
for value in self.lr_policy['stepvalue'].split(','):
# stepvalue = stepvalue * scale
solver.stepvalue.append(int(math.ceil(float(value) * scale)))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'exp':
# gamma = gamma^(1/scale)
solver.gamma = math.pow(self.lr_policy['gamma'], 1.0 / scale)
elif solver.lr_policy == 'inv':
# gamma = gamma / scale
solver.gamma = self.lr_policy['gamma'] / scale
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'poly':
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'sigmoid':
# gamma = -gamma / scale
solver.gamma = -1.0 * self.lr_policy['gamma'] / scale
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
else:
raise Exception('Unknown lr_policy: "%s"' % solver.lr_policy)
# These solver types don't support momentum
unsupported = [solver.ADAGRAD]
try:
unsupported.append(solver.RMSPROP)
except AttributeError:
pass
if solver.solver_type not in unsupported:
solver.momentum = 0.9
solver.weight_decay = solver.base_lr / 100.0
# solver specific values
if solver.solver_type == solver.RMSPROP:
solver.rms_decay = self.rms_decay
# Display 8x per epoch, or once per 5000 images, whichever is more frequent
solver.display = max(1, min(
int(math.floor(float(solver.max_iter) / (self.train_epochs * 8))),
int(math.ceil(5000.0 / (train_data_layer.data_param.batch_size * solver.iter_size)))
))
if self.random_seed is not None:
solver.random_seed = self.random_seed
with open(self.path(self.solver_file), 'w') as outfile:
text_format.PrintMessage(solver, outfile)
self.solver = solver # save for later
return True
def save_files_generic(self):
"""
Save solver, train_val and deploy files to disk
"""
train_feature_db_path = self.dataset.get_feature_db_path(constants.TRAIN_DB)
train_label_db_path = self.dataset.get_label_db_path(constants.TRAIN_DB)
val_feature_db_path = self.dataset.get_feature_db_path(constants.VAL_DB)
val_label_db_path = self.dataset.get_label_db_path(constants.VAL_DB)
assert train_feature_db_path is not None, 'Training images are required'
# Save the origin network to file:
with open(self.path(self.model_file), 'w') as outfile:
text_format.PrintMessage(self.network, outfile)
# Split up train_val and deploy layers
network = cleanedUpGenericNetwork(self.network)
data_layers, train_val_layers, deploy_layers = filterLayersByState(network)
# Write train_val file
train_val_network = caffe_pb2.NetParameter()
# Data layers
# TODO clean this up
train_image_data_layer = None
train_label_data_layer = None
val_image_data_layer = None
val_label_data_layer = None
# Find the existing Data layers
for layer in data_layers.layer:
for rule in layer.include:
if rule.phase == caffe_pb2.TRAIN:
for top_name in layer.top:
if 'data' in top_name:
assert train_image_data_layer is None, \
'cannot specify two train image data layers'
train_image_data_layer = layer
elif 'label' in top_name:
assert train_label_data_layer is None, \
'cannot specify two train label data layers'
train_label_data_layer = layer
elif rule.phase == caffe_pb2.TEST:
for top_name in layer.top:
if 'data' in top_name:
assert val_image_data_layer is None, \
'cannot specify two val image data layers'
val_image_data_layer = layer
elif 'label' in top_name:
assert val_label_data_layer is None, \
'cannot specify two val label data layers'
val_label_data_layer = layer
# Create and add the Data layers
# (uses info from existing data layers, where possible)
train_image_data_layer = self.make_generic_data_layer(
train_feature_db_path, train_image_data_layer, 'data', 'data', caffe_pb2.TRAIN)
if train_image_data_layer is not None:
train_val_network.layer.add().CopyFrom(train_image_data_layer)
train_label_data_layer = self.make_generic_data_layer(
train_label_db_path, train_label_data_layer, 'label', 'label', caffe_pb2.TRAIN)
if train_label_data_layer is not None:
train_val_network.layer.add().CopyFrom(train_label_data_layer)
val_image_data_layer = self.make_generic_data_layer(
val_feature_db_path, val_image_data_layer, 'data', 'data', caffe_pb2.TEST)
if val_image_data_layer is not None:
train_val_network.layer.add().CopyFrom(val_image_data_layer)
val_label_data_layer = self.make_generic_data_layer(
val_label_db_path, val_label_data_layer, 'label', 'label', caffe_pb2.TEST)
if val_label_data_layer is not None:
train_val_network.layer.add().CopyFrom(val_label_data_layer)
# Add non-data layers
train_val_network.MergeFrom(train_val_layers)
# Write to file
with open(self.path(self.train_val_file), 'w') as outfile:
text_format.PrintMessage(train_val_network, outfile)
# network sanity checks
self.logger.debug("Network sanity check - train")
CaffeTrainTask.net_sanity_check(train_val_network, caffe_pb2.TRAIN)
if val_image_data_layer is not None:
self.logger.debug("Network sanity check - val")
CaffeTrainTask.net_sanity_check(train_val_network, caffe_pb2.TEST)
# Write deploy file
deploy_network = caffe_pb2.NetParameter()
# Input
deploy_network.input.append('data')
shape = deploy_network.input_shape.add()
shape.dim.append(1)
shape.dim.append(self.dataset.get_feature_dims()[2]) # channels
if train_image_data_layer.transform_param.HasField('crop_size'):
shape.dim.append(
train_image_data_layer.transform_param.crop_size)
shape.dim.append(
train_image_data_layer.transform_param.crop_size)
else:
shape.dim.append(self.dataset.get_feature_dims()[0]) # height
shape.dim.append(self.dataset.get_feature_dims()[1]) # width
# Layers
deploy_network.MergeFrom(deploy_layers)
# Write to file
with open(self.path(self.deploy_file), 'w') as outfile:
text_format.PrintMessage(deploy_network, outfile)
# network sanity checks
self.logger.debug("Network sanity check - deploy")
CaffeTrainTask.net_sanity_check(deploy_network, caffe_pb2.TEST)
# Write solver file
solver = caffe_pb2.SolverParameter()
# get enum value for solver type
solver.solver_type = getattr(solver, self.solver_type)
solver.net = self.train_val_file
# Set CPU/GPU mode
if config_value('caffe')['cuda_enabled'] and \
bool(config_value('gpu_list')):
solver.solver_mode = caffe_pb2.SolverParameter.GPU
else:
solver.solver_mode = caffe_pb2.SolverParameter.CPU
solver.snapshot_prefix = self.snapshot_prefix
# Batch accumulation
from digits.frameworks import CaffeFramework
if self.batch_accumulation and CaffeFramework().can_accumulate_gradients():
solver.iter_size = self.batch_accumulation
# Epochs -> Iterations
train_iter = int(math.ceil(
float(self.dataset.get_entry_count(constants.TRAIN_DB)) /
(train_image_data_layer.data_param.batch_size * solver.iter_size)
))
solver.max_iter = train_iter * self.train_epochs
snapshot_interval = self.snapshot_interval * train_iter
if 0 < snapshot_interval <= 1:
solver.snapshot = 1 # don't round down
elif 1 < snapshot_interval < solver.max_iter:
solver.snapshot = int(snapshot_interval)
else:
solver.snapshot = 0 # only take one snapshot at the end
if val_image_data_layer:
solver.test_iter.append(int(math.ceil(float(self.dataset.get_entry_count(
constants.VAL_DB)) / val_image_data_layer.data_param.batch_size)))
val_interval = self.val_interval * train_iter
if 0 < val_interval <= 1:
solver.test_interval = 1 # don't round down
elif 1 < val_interval < solver.max_iter:
solver.test_interval = int(val_interval)
else:
solver.test_interval = solver.max_iter # only test once at the end
# Learning rate
solver.base_lr = self.learning_rate
solver.lr_policy = self.lr_policy['policy']
scale = float(solver.max_iter) / 100.0
if solver.lr_policy == 'fixed':
pass
elif solver.lr_policy == 'step':
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'multistep':
for value in self.lr_policy['stepvalue'].split(','):
# stepvalue = stepvalue * scale
solver.stepvalue.append(int(math.ceil(float(value) * scale)))
solver.gamma = self.lr_policy['gamma']
elif solver.lr_policy == 'exp':
# gamma = gamma^(1/scale)
solver.gamma = math.pow(self.lr_policy['gamma'], 1.0 / scale)
elif solver.lr_policy == 'inv':
# gamma = gamma / scale
solver.gamma = self.lr_policy['gamma'] / scale
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'poly':
solver.power = self.lr_policy['power']
elif solver.lr_policy == 'sigmoid':
# gamma = -gamma / scale
solver.gamma = -1.0 * self.lr_policy['gamma'] / scale
# stepsize = stepsize * scale
solver.stepsize = int(math.ceil(float(self.lr_policy['stepsize']) * scale))
else:
raise Exception('Unknown lr_policy: "%s"' % solver.lr_policy)
# These solver types don't support momentum
unsupported = [solver.ADAGRAD]
try:
unsupported.append(solver.RMSPROP)
except AttributeError:
pass
if solver.solver_type not in unsupported:
solver.momentum = 0.9
solver.weight_decay = solver.base_lr / 100.0
# Display 8x per epoch, or once per 5000 images, whichever is more frequent
solver.display = max(1, min(
int(math.floor(float(solver.max_iter) / (self.train_epochs * 8))),
int(math.ceil(5000.0 / (train_image_data_layer.data_param.batch_size * solver.iter_size)))
))
if self.random_seed is not None:
solver.random_seed = self.random_seed
with open(self.path(self.solver_file), 'w') as outfile:
text_format.PrintMessage(solver, outfile)
self.solver = solver # save for later
return True
def make_generic_data_layer(self, db_path, orig_layer, name, top, phase):
"""
Utility within save_files_generic for creating a Data layer
Returns a LayerParameter (or None)
Arguments:
db_path -- path to database (or None)
orig_layer -- a LayerParameter supplied by the user (or None)
"""
if db_path is None:
# TODO allow user to specify a standard data layer even if it doesn't exist in the dataset
return None
layer = caffe_pb2.LayerParameter()
if orig_layer is not None:
layer.CopyFrom(orig_layer)
layer.type = 'Data'
if not layer.HasField('name'):
layer.name = name
if not len(layer.top):
layer.top.append(top)
layer.ClearField('include')
layer.include.add(phase=phase)
# source
if layer.data_param.HasField('source'):
self.logger.warning('Ignoring data_param.source ...')
layer.data_param.source = db_path
if layer.data_param.HasField('backend'):
self.logger.warning('Ignoring data_param.backend ...')
layer.data_param.backend = caffe_pb2.DataParameter.LMDB
# batch size
if not layer.data_param.HasField('batch_size'):
layer.data_param.batch_size = constants.DEFAULT_BATCH_SIZE
if self.batch_size:
layer.data_param.batch_size = self.batch_size
# mean
if name == 'data' and self.dataset.get_mean_file():
if self.use_mean == 'pixel':
mean_pixel = self.get_mean_pixel(self.dataset.path(self.dataset.get_mean_file()))
# remove any values that may already be in the network
self.set_mean_value(layer, mean_pixel)
elif self.use_mean == 'image':
self.set_mean_file(layer, self.dataset.path(self.dataset.get_mean_file()))
# crop size
if name == 'data' and self.crop_size:
max_crop_size = min(self.dataset.get_feature_dims()[0], self.dataset.get_feature_dims()[1])
assert self.crop_size <= max_crop_size, 'crop_size is larger than the image size'
layer.transform_param.crop_size = self.crop_size
return layer
def iteration_to_epoch(self, it):
return float(it * self.train_epochs) / self.solver.max_iter
@override
def task_arguments(self, resources, env):
"""
Generate Caffe command line options or, in certain cases, pycaffe Python script
Returns a list of strings
Arguments:
resources -- dict of available task resources
env -- dict of environment variables
"""
if platform.system() == 'Windows':
if any([layer.type == 'Python' for layer in self.network.layer]):
# Arriving here because the network includes Python Layer and we are running inside Windows.
# We can not invoke caffe.exe and need to fallback to pycaffe
# https://github.com/Microsoft/caffe/issues/87
# TODO: Remove this once caffe.exe works fine with Python Layer
win_python_layer_gpu_id = None
if 'gpus' in resources:
n_gpus = len(resources['gpus'])
if n_gpus > 1:
raise Exception('Please select single GPU when running in Windows with Python layer.')
elif n_gpus == 1:
win_python_layer_gpu_id = resources['gpus'][0][0]
# We know which GPU to use, call helper to create the script
return self._pycaffe_args(win_python_layer_gpu_id)
# Not in Windows, or in Windows but no Python Layer
# This is the normal path
args = [config_value('caffe')['executable'],
'train',
'--solver=%s' % self.path(self.solver_file),
]
if 'gpus' in resources:
identifiers = []
for identifier, value in resources['gpus']:
identifiers.append(identifier)
if len(identifiers) == 1:
args.append('--gpu=%s' % identifiers[0])
elif len(identifiers) > 1:
if config_value('caffe')['flavor'] == 'NVIDIA':
if (utils.parse_version(config_value('caffe')['version']) < utils.parse_version('0.14.0-alpha')):
# Prior to version 0.14, NVcaffe used the --gpus switch
args.append('--gpus=%s' % ','.join(identifiers))
else:
args.append('--gpu=%s' % ','.join(identifiers))
elif config_value('caffe')['flavor'] == 'BVLC':
args.append('--gpu=%s' % ','.join(identifiers))
else:
raise ValueError('Unknown flavor. Support NVIDIA and BVLC flavors only.')
if self.pretrained_model:
args.append('--weights=%s' % ','.join(map(lambda x: self.path(x),
self.pretrained_model.split(os.path.pathsep))))
return args
def _pycaffe_args(self, gpu_id):
"""
Helper to generate pycaffe Python script
Returns a list of strings
Throws ValueError if self.solver_type is not recognized
Arguments:
gpu_id -- the GPU device id to use
"""
# TODO: Remove this once caffe.exe works fine with Python Layer
solver_type_mapping = {
'ADADELTA': 'AdaDeltaSolver',
'ADAGRAD': 'AdaGradSolver',
'ADAM': 'AdamSolver',
'NESTEROV': 'NesterovSolver',
'RMSPROP': 'RMSPropSolver',
'SGD': 'SGDSolver'}
try:
solver_type = solver_type_mapping[self.solver_type]
except KeyError:
raise ValueError("Unknown solver type {}.".format(self.solver_type))
if gpu_id is not None:
gpu_script = "caffe.set_device({id});caffe.set_mode_gpu();".format(id=gpu_id)
else:
gpu_script = "caffe.set_mode_cpu();"
loading_script = ""
if self.pretrained_model:
weight_files = map(lambda x: self.path(x), self.pretrained_model.split(os.path.pathsep))
for weight_file in weight_files:
loading_script = loading_script + "solv.net.copy_from('{weight}');".format(weight=weight_file)
command_script =\
"import caffe;" \
"{gpu_script}" \
"solv=caffe.{solver}('{solver_file}');" \
"{loading_script}" \
"solv.solve()" \
.format(gpu_script=gpu_script,
solver=solver_type,
solver_file=self.solver_file, loading_script=loading_script)
args = [sys.executable + ' -c ' + '\"' + command_script + '\"']
return args
@override
def process_output(self, line):
float_exp = '(NaN|[-+]?[0-9]*\.?[0-9]+(e[-+]?[0-9]+)?)'
self.caffe_log.write('%s\n' % line)
self.caffe_log.flush()
# parse caffe output
timestamp, level, message = self.preprocess_output_caffe(line)