This repository has been archived by the owner on Jun 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
/
models.py
executable file
·3595 lines (2883 loc) · 129 KB
/
models.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
# coding=utf-8
"""model graph.
"""
import cv2
import json
import math
import itertools
import random
import sys
import os
import tensorflow as tf
import numpy as np
from PIL import Image
from utils import Dataset
from utils import get_all_anchors
from utils import draw_boxes
from utils import box_wh_to_x1x2
from utils import get_op_tensor_name
#import tensorflow.contrib.slim as slim
from nn import pretrained_resnet_conv4
from nn import conv2d
from nn import deconv2d
from nn import resnet_conv5
from nn import dense
from nn import pairwise_iou
from nn import get_iou_callable
from nn import resizeImage
from nn import resnet_fpn_backbone
from nn import fpn_model
from nn import decode_bbox_target
from nn import generate_rpn_proposals
from nn import sample_fast_rcnn_targets
from nn import roi_align
from nn import encode_bbox_target
from nn import focal_loss
from nn import wd_cost
from nn import clip_boxes
from nn import person_object_relation
from nn import np_iou
# for multi image batch
from nn import decode_bbox_target_multi
from nn import generate_rpn_proposals_multibatch
from nn import roi_align_multi
# this is for ugly batch norm
from nn import is_training
from nn import add_wd
#from nn import get_so_labels
from nn import group_norm
from efficientdet_wrapper import EfficientDet
from efficientdet_wrapper import EfficientDet_frozen
# need this otherwise No TRTEngineOp when load a trt graph # no use,
#TensorRT doesn"t support FPN ops yet
#import tensorflow.contrib.tensorrt as trt
# ------------------------------ multi gpu stuff
PS_OPS = [
"Variable", "VariableV2", "AutoReloadVariable", "MutableHashTable",
"MutableHashTableOfTensors", "MutableDenseHashTable"
]
# see https://github.com/tensorflow/tensorflow/issues/9517
def assign_to_device(compute_device, controller_device): # ps: paramter server
"""Returns a function to place variables on the ps_device.
Args:
device: Device for everything but variables
ps_device: Device to put the variables on. Example values are /GPU:0
and /CPU:0.
If ps_device is not set then the variables will be placed on the default
device.
The best device for shared varibles depends on the platform as well as the
model. Start with CPU:0 and then test GPU:0 to see if there is an
improvement.
"""
def _assign(op):
node_def = op if isinstance(op, tf.NodeDef) else op.node_def
if node_def.op in PS_OPS:
return controller_device
else:
return compute_device
return _assign
#----------------------------------
# 05/2019, the code will still use other gpu even if we have set visible list;
# seems a v1.13 bug
# yes it is a v1.13 bug, something to do with XLA:
# https://github.com/horovod/horovod/issues/876
def get_model(config, gpuid=0, task=0, controller="/cpu:0", is_multi=False):
with tf.device(assign_to_device("/gpu:%s"%(gpuid), controller)):
# load from frozen model
if config.is_load_from_pb:
if config.is_efficientdet:
model = EfficientDet_frozen(config, config.load_from, gpuid)
else:
model = Mask_RCNN_FPN_frozen(config.load_from, gpuid,
add_mask=config.add_mask,
is_multi=is_multi)
else:
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
#tf.get_variable_scope().reuse_variables()
if config.is_efficientdet:
model = EfficientDet(config)
elif is_multi:
model = Mask_RCNN_FPN_multi(config, gpuid=gpuid)
else:
model = Mask_RCNN_FPN(config, gpuid=gpuid)
return model
def get_model_feat(config, gpuid=0, task=0, controller="/cpu:0"):
# task is not used
#with tf.device("/gpu:%s"%gpuid):
with tf.device(assign_to_device("/gpu:%s"%(gpuid), controller)):
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
#tf.get_variable_scope().reuse_variables()
model = RCNN_FPN_givenbox(config, gpuid=gpuid)
return model
# updated 05/29, pack model
# simple tf frozen graph or TensorRT optimized model
def pack(config):
# the graph var names to be saved
vars_ = [
"final_boxes",
"final_labels",
"final_probs",
"fpn_box_feat"]
if config.add_mask:
vars_.append("final_masks")
if config.is_multi:
vars_.append("final_valid_indices")
model = get_model(config, is_multi=config.is_multi)
tfconfig = tf.ConfigProto(allow_soft_placement=True)
tfconfig.gpu_options.allow_growth = True
with tf.Session(config=tfconfig) as sess:
initialize(load=True, load_best=config.load_best, config=config, sess=sess)
# also save all the model config and note into the model
#assert config.note != "", "please add some note for the model"
if config.note is not None:
# remove some param?
config_json = vars(config)
for k in config_json:
if type(config_json[k]) == type(np.array([1])):
config_json[k] = config_json[k].tolist()
if type(config_json[k]) == type(np.array([1])[0]):
config_json[k] = int(config_json[k])
if type(config_json[k]) == type(np.array([1.0])[0]):
config_json[k] = float(config_json[k])
if type(config_json[k]) == type({}.keys()): # python3 dict_keys
config_json[k] = list(config_json[k])
with open(config.pack_modelconfig_path, "w") as f:
json.dump(config_json, f)
print("saving packed model...")
# put into one big file to save
input_graph_def = tf.get_default_graph().as_graph_def()
#print [n.name for n in input_graph_def.node]
# We use a built-in TF helper to export variables to constants
# output node names
output_graph_def = tf.graph_util.convert_variables_to_constants(
sess, # The session is used to retrieve the weights
input_graph_def, # The graph_def is used to retrieve the nodes
vars_,
)
output_graph = config.pack_model_path
# Finally we serialize and dump the output graph to the filesystem
with tf.gfile.GFile(output_graph, "wb") as f:
f.write(output_graph_def.SerializeToString())
print("%d ops in the final graph." % len(output_graph_def.node))
print("model saved in %s, config record is in %s" % (
config.pack_model_path, config.pack_modelconfig_path))
# load the weights at init time
# this class has the same interface as Mask_RCNN_FPN
class Mask_RCNN_FPN_frozen():
def __init__(self, modelpath, gpuid, add_mask=False, is_multi=False):
self.graph = tf.get_default_graph()
self.is_multi = is_multi
# save path is one.pb file
with tf.gfile.GFile(modelpath, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
#print [n.name for n in graph_def.node]
# need this to load different stuff for different gpu
self.var_prefix = "model_%s" % gpuid
tf.import_graph_def(
graph_def,
name=self.var_prefix,
return_elements=None
)
# input place holders
self.image = self.graph.get_tensor_by_name("%s/image:0" % self.var_prefix)
self.final_boxes = self.graph.get_tensor_by_name(
"%s/final_boxes:0" % self.var_prefix)
self.final_labels = self.graph.get_tensor_by_name(
"%s/final_labels:0" % self.var_prefix)
self.final_probs = self.graph.get_tensor_by_name(
"%s/final_probs:0" % self.var_prefix)
if is_multi:
self.final_valid_indices = self.graph.get_tensor_by_name(
"%s/final_valid_indices:0" % self.var_prefix)
if add_mask:
self.final_masks = self.graph.get_tensor_by_name(
"%s/final_masks:0" % self.var_prefix)
self.fpn_box_feat = self.graph.get_tensor_by_name(
"%s/fpn_box_feat:0" % self.var_prefix)
def get_feed_dict_forward(self, imgdata):
feed_dict = {}
if self.is_multi:
# imgdata: a list of [H, W, 3]
# [B, H, W, 3]
feed_dict[self.image] = np.stack(imgdata, axis=0)
else:
feed_dict[self.image] = imgdata
return feed_dict
def get_feed_dict_forward_multi(self, imgs):
# imgs: a list of [H, W, 3]
feed_dict = {}
# [B, H, W, 3]
feed_dict[self.image] = np.stack(imgs, axis=0)
return feed_dict
class Mask_RCNN_FPN():
def __init__(self, config, gpuid=0):
self.gpuid = gpuid
# for batch_norm
global is_training
is_training = config.is_train # change this before building model
self.config = config
self.num_class = config.num_class
self.global_step = tf.get_variable(
"global_step", shape=[], dtype="int32",
initializer=tf.constant_initializer(0), trainable=False)
# current model get one image at a time
self.image = tf.placeholder(tf.float32, [None, None, 3], name="image")
if not config.is_pack_model:
self.is_train = tf.placeholder("bool", [], name="is_train")
# for training
self.anchor_labels = []
self.anchor_boxes = []
num_anchors = len(config.anchor_ratios)
for k in range(len(config.anchor_strides)):
self.anchor_labels.append(
tf.placeholder(tf.int32, [None, None, num_anchors],
name="anchor_labels_lvl%s" % (k+2)))
self.anchor_boxes.append(
tf.placeholder(tf.float32, [None, None, num_anchors, 4],
name="anchor_boxes_lvl%s" % (k+2)))
self.gt_boxes = tf.placeholder(tf.float32, [None, 4], name="gt_boxes")
self.gt_labels = tf.placeholder(tf.int64, [None, ], name="gt_labels")
self.so_gt_boxes = []
self.so_gt_labels = []
for i in range(len(config.small_objects)):
self.so_gt_boxes.append(
tf.placeholder(tf.float32, [None, 4], name="so_gt_boxes_c%s" % (i+1)))
self.so_gt_labels.append(
tf.placeholder(tf.int64, [None,], name="so_gt_labels_c%s" % (i+1)))
# H,W,v -> {0,1}
self.gt_mask = tf.placeholder(tf.uint8, [None, None, None], name="gt_masks")
# the following will be added in the build_forward and loss
self.logits = None
self.yp = None
self.loss = None
self.build_preprocess()
self.build_forward()
# get feature map anchor and preprocess image
def build_preprocess(self):
config = self.config
image = self.image
# get feature map anchors first
# slower if put on cpu # 1.5it/s vs 1.2it/s
self.multilevel_anchors = []
with tf.name_scope("fpn_anchors"):#,tf.device("/cpu:0"):
#fm_h,fm_w = tf.shape(image)[0] // config.anchor_stride,tf.shape(image)[1]
#// config.anchor_stride
# all posible anchor box coordinates for a given max_size image,
# so for 1920 x 1920 image, 1920/16 = 120, so (120,120,NA,4) box, NA is
#scale*ratio boxes
self.multilevel_anchors = self.get_all_anchors_fpn()
bgr = True # cv2 load image is bgr
p_image = tf.expand_dims(image, 0) # [1,H,W,C]
with tf.name_scope("image_preprocess"): # tf.device("/cpu:0"):
if p_image.dtype.base_dtype != tf.float32:
p_image = tf.cast(p_image, tf.float32)
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
p_image = p_image * (1.0/255)
if bgr:
mean = mean[::-1]
std = std[::-1]
image_mean = tf.constant(mean, dtype=tf.float32)
image_std = tf.constant(std, dtype=tf.float32)
p_image = (p_image - image_mean) / image_std
p_image = tf.transpose(p_image, [0, 3, 1, 2])
self.p_image = p_image
def get_all_anchors_fpn(self):
config = self.config
anchors = []
assert len(config.anchor_strides) == len(config.anchor_sizes)
for stride, size in zip(config.anchor_strides, config.anchor_sizes):
anchors_np = get_all_anchors(
stride=stride, sizes=[size], ratios=config.anchor_ratios,
max_size=config.max_size)
anchors.append(anchors_np)
return anchors
# make the numpy anchor match to the feature shape
def slice_feature_and_anchors(self, image_shape2d, p23456, anchors):
# anchors is the numpy anchors for different levels
config = self.config
# the anchor labels and boxes are grouped into
gt_anchor_labels = self.anchor_labels
gt_anchor_boxes = self.anchor_boxes
self.sliced_anchor_labels = []
self.sliced_anchor_boxes = []
for i, stride in enumerate(config.anchor_strides):
with tf.name_scope("FPN_slice_lvl%s" % (i)):
if i < 3:
# Images are padded for p5, which are too large for p2-p4.
pi = p23456[i]
target_shape = tf.to_int32(tf.ceil(tf.to_float(image_shape2d) * \
(1.0 / stride)))
p23456[i] = tf.slice(
pi, [0, 0, 0, 0], tf.concat([[-1, -1], target_shape], axis=0))
p23456[i].set_shape([1, pi.shape[1], None, None])
shape2d = tf.shape(p23456[i])[2:] # h,W
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
anchors[i] = tf.slice(anchors[i], [0, 0, 0, 0], slice4d)
self.sliced_anchor_labels.append(
tf.slice(gt_anchor_labels[i], [0, 0, 0], slice3d))
self.sliced_anchor_boxes.append(tf.slice(
gt_anchor_boxes[i], [0, 0, 0, 0], slice4d))
def generate_fpn_proposals(self, multilevel_anchors, multilevel_label_logits,
multilevel_box_logits, image_shape2d):
config = self.config
num_lvl = len(config.anchor_strides)
assert num_lvl == len(multilevel_anchors)
assert num_lvl == len(multilevel_box_logits)
assert num_lvl == len(multilevel_label_logits)
all_boxes = []
all_scores = []
fpn_nms_topk = config.rpn_train_post_nms_topk \
if config.is_train else config.rpn_test_post_nms_topk
for lvl in range(num_lvl):
with tf.name_scope("Lvl%s"%(lvl+2)):
anchors = multilevel_anchors[lvl]
pred_boxes_decoded = decode_bbox_target(
multilevel_box_logits[lvl], anchors,
decode_clip=config.bbox_decode_clip)
this_fpn_nms_topk = fpn_nms_topk
proposal_boxes, proposal_scores = generate_rpn_proposals(
tf.reshape(pred_boxes_decoded, [-1, 4]),
tf.reshape(multilevel_label_logits[lvl], [-1]), image_shape2d,
config, pre_nms_topk=this_fpn_nms_topk)
all_boxes.append(proposal_boxes)
all_scores.append(proposal_scores)
proposal_boxes = tf.concat(all_boxes, axis=0) # nx4
proposal_scores = tf.concat(all_scores, axis=0) # n
proposal_topk = tf.minimum(tf.size(proposal_scores), fpn_nms_topk)
proposal_scores, topk_indices = tf.nn.top_k(proposal_scores,
k=proposal_topk, sorted=False)
proposal_boxes = tf.gather(proposal_boxes, topk_indices)
return tf.stop_gradient(proposal_boxes, name="boxes"), \
tf.stop_gradient(proposal_scores, name="scores")
# based on box sizes
def fpn_map_rois_to_levels(self, boxes):
def tf_area(boxes):
x_min, y_min, x_max, y_max = tf.split(boxes, 4, axis=1)
return tf.squeeze((y_max - y_min) * (x_max - x_min), [1])
sqrtarea = tf.sqrt(tf_area(boxes))
level = tf.to_int32(tf.floor(4 + tf.log(sqrtarea * (1. / 224) + 1e-6) * \
(1.0 / np.log(2))))
# RoI levels range from 2~5 (not 6)
level_ids = [
tf.where(level <= 2),
tf.where(tf.equal(level, 3)),# problems with ==?
tf.where(tf.equal(level, 4)),
tf.where(level >= 5)]
level_ids = [tf.reshape(x, [-1], name="roi_level%s_id" % (i + 2))
for i, x in enumerate(level_ids)]
#num_in_levels = [tf.size(x, name="num_roi_level%s" % (i + 2))
# for i, x in enumerate(level_ids)]
level_boxes = [tf.gather(boxes, ids) for ids in level_ids]
return level_ids, level_boxes
# output_shape is the output feature HxW
def multilevel_roi_align(self, features, rcnn_boxes, output_shape):
config = self.config
assert len(features) == 4
# Reassign rcnn_boxes to levels # based on box area size
level_ids, level_boxes = self.fpn_map_rois_to_levels(rcnn_boxes)
all_rois = []
# Crop patches from corresponding levels
for i, boxes, featuremap in zip(itertools.count(), level_boxes, features):
with tf.name_scope("roi_level%s" % (i + 2)):
boxes_on_featuremap = boxes * (1.0 / config.anchor_strides[i])
all_rois.append(
roi_align(featuremap, boxes_on_featuremap, output_shape))
# this can fail if using TF<=1.8 with MKL build
all_rois = tf.concat(all_rois, axis=0) # NCHW
# Unshuffle to the original order, to match the original samples
level_id_perm = tf.concat(level_ids, axis=0) # A permutation of 1~N
level_id_invert_perm = tf.invert_permutation(level_id_perm)
all_rois = tf.gather(all_rois, level_id_invert_perm)
return all_rois
def build_forward(self):
config = self.config
image = self.p_image # [1, C, H, W]
image_shape2d = tf.shape(image)[2:]
# a list of numpy anchors, not sliced
multilevel_anchors = self.multilevel_anchors
# the feature map shared by RPN and fast RCNN
# TODO: fix the batch norm mess
# TODO: fix global param like data_format and
# [1,C,FS,FS]
c2345 = resnet_fpn_backbone(
image, config.resnet_num_block, use_gn=config.use_gn,
resolution_requirement=config.fpn_resolution_requirement,
use_dilations=config.use_dilations,
use_deformable=config.use_deformable, tf_pad_reverse=True,
freeze=config.freeze, use_basic_block=config.use_basic_block,
use_se=config.use_se, use_resnext=config.use_resnext)
# include lateral 1x1 conv and final 3x3 conv
# -> [7, 7, 256]
p23456 = fpn_model(c2345, num_channel=config.fpn_num_channel,
use_gn=config.use_gn, scope="fpn")
if config.freeze_rpn or config.freeze_fastrcnn:
p23456 = [tf.stop_gradient(p) for p in p23456]
# [1, H, W, channel]
self.fpn_feature = tf.image.resize_images(tf.transpose(
p23456[3], perm=[0, 2, 3, 1]), (7, 7)) # p5 # default bilinear
if config.no_obj_detect: # pair with extract_feat, so only extract feature
print("no object detect branch..")
return True
# given the numpy anchor for each stride,
# slice the anchor box and label against the feature map size on each
#level. Again?
self.slice_feature_and_anchors(image_shape2d, p23456, multilevel_anchors)
# now multilevel_anchors are sliced and tf type
# added sliced gt anchor labels and boxes
# so we have each fpn level"s anchor boxes, and the ground truth anchor
# boxes & labels if training
# given [1,256,FS,FS] feature, each level got len(anchor_ratios) anchor
# outputs
rpn_outputs = [
self.rpn_head(pi, config.fpn_num_channel, len(config.anchor_ratios),
data_format="NCHW", scope="rpn") for pi in p23456]
multilevel_label_logits = [k[0] for k in rpn_outputs]
multilevel_box_logits = [k[1] for k in rpn_outputs]
if config.freeze_rpn:
multilevel_label_logits = [tf.stop_gradient(o)
for o in multilevel_label_logits]
multilevel_box_logits = [tf.stop_gradient(o)
for o in multilevel_box_logits]
# each H,W location has a box regression and classification score,
# here combine all positive boxes using NMS
# [N,4]/[N] , N is the number of proposal boxes
proposal_boxes, proposal_scores = self.generate_fpn_proposals(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits,
image_shape2d)
# for getting RPN performance
# K depend on rpn_test_post_nms_topk during testing
# K = 1000
self.proposal_boxes = proposal_boxes # [K, 4]
self.proposal_scores = proposal_scores # [K]
if config.is_train:
gt_boxes = self.gt_boxes
gt_labels = self.gt_labels
# for training, use gt_box and some proposal box as pos and neg
# rcnn_sampled_boxes [N_FG+N_NEG,4]
# fg_inds_wrt_gt -> [N_FG], each is index of gt_boxes
rcnn_boxes, rcnn_labels, fg_inds_wrt_gt = sample_fast_rcnn_targets(
proposal_boxes, gt_boxes, gt_labels, config=config)
else:
rcnn_boxes = proposal_boxes
# NxCx7x7 # (?, 256, 7, 7)
roi_feature_fastrcnn = self.multilevel_roi_align(p23456[:4], rcnn_boxes, 7)
if config.use_frcnn_class_agnostic:
# (N,num_class), (N, 1, 4)
fastrcnn_label_logits, fastrcnn_box_logits = \
self.fastrcnn_2fc_head_class_agnostic(
roi_feature_fastrcnn, config.num_class,
boxes=rcnn_boxes, scope="fastrcnn")
else:
# (N,num_class), (N, num_class - 1, 4)
fastrcnn_label_logits, fastrcnn_box_logits = self.fastrcnn_2fc_head(
roi_feature_fastrcnn, config.num_class,
boxes=rcnn_boxes, scope="fastrcnn")
if config.freeze_fastrcnn:
fastrcnn_label_logits, fastrcnn_box_logits = tf.stop_gradient(
fastrcnn_label_logits), tf.stop_gradient(fastrcnn_box_logits)
if config.use_small_object_head:
# 1. get all the actual boxes coordinates
anchors = tf.tile(tf.expand_dims(rcnn_boxes, 1),
[1, config.num_class-1, 1])
boxes = decode_bbox_target(fastrcnn_box_logits / \
tf.constant(config.fastrcnn_bbox_reg_weights, dtype=tf.float32),
anchors)
probs = tf.nn.softmax(fastrcnn_label_logits)
boxes = tf.transpose(boxes, [1, 0, 2]) # [num_class-1, N, 4]
probs = tf.transpose(probs[:, 1:], [1, 0]) # [num_class-1, N]
small_object_class_ids = [config.classname2id[name] - 1
for name in config.small_objects]
# C is the number of small object class
# [C, N, 4], [C, N]
so_boxes, so_scores = tf.gather(boxes, small_object_class_ids), \
tf.gather(probs, small_object_class_ids)
# 1. we do NMS for each class to get topk
# for each catagory get the top K
# [C, K, 4] / [C, K]
so_boxes, so_scores = tf.map_fn(
self.nms_return_boxes, (so_scores, so_boxes),
dtype=(tf.float32, tf.float32), parallel_iterations=10)
self.so_boxes = so_boxes
so_boxes = tf.reshape(so_boxes, [-1, 4]) # [C*K, 4]
so_scores = tf.reshape(so_scores, [-1]) # [C*K]
# [C*K, 256, 7, 7]
so_feature = self.multilevel_roi_align(p23456[:4], so_boxes, 7)
# share the fc part with fast rcnn head
with tf.variable_scope("fastrcnn", reuse=tf.AUTO_REUSE):
dim = config.fpn_frcnn_fc_head_dim # 1024
initializer = tf.variance_scaling_initializer()
# sharing features
# [C*K, dim]
hidden = dense(so_feature, dim, W_init=initializer,
activation=tf.nn.relu, scope="fc6")
hidden = dense(hidden, dim, W_init=initializer,
activation=tf.nn.relu, scope="fc7")
# [C, K, dim]
hidden = tf.reshape(hidden, [len(config.small_objects), -1, dim])
if config.freeze_fastrcnn:
hidden = tf.stop_gradient(hidden)
if config.use_so_association:
ref_class_id = config.classname2id["Person"] - 1
# [N, 4], [N]
ref_boxes, ref_scores = boxes[ref_class_id], probs[ref_class_id]
# NMS to get a few peron boxes
ref_topk = config.so_person_topk # 10
ref_selection = tf.image.non_max_suppression(
ref_boxes, ref_scores, max_output_size=ref_topk,
iou_threshold=config.fastrcnn_nms_iou_thres)
# [Rr, 4]
ref_boxes = tf.gather(ref_boxes, ref_selection)
ref_scores = tf.gather(ref_scores, ref_selection)
ref_feat = self.multilevel_roi_align(p23456[:4], ref_boxes, 7)
# share the same fc
ref_feat = dense(ref_feat, dim, W_init=initializer,
activation=tf.nn.relu, scope="fc6")
ref_feat = dense(ref_feat, dim, W_init=initializer,
activation=tf.nn.relu, scope="fc7")
if config.freeze_fastrcnn:
ref_feat = tf.stop_gradient(ref_feat)
# new variable for small object
with tf.variable_scope("small_objects"):
so_label_logits = [] # each class a head
for i in range(len(config.small_objects)):
if config.use_so_association:
asso_hidden = hidden[i] + person_object_relation(
hidden[i], self.so_boxes[i], ref_boxes, ref_feat,
group=16, geo_feat_dim=64, scope="person_object_relation")
so_label_logits.append(dense(
asso_hidden, 2,
W_init=tf.random_normal_initializer(stddev=0.01),
scope="small_object_classification_c%s" % (i+1)))
else:
so_label_logits.append(dense(
hidden[i], 2,
W_init=tf.random_normal_initializer(stddev=0.01),
scope="small_object_classification_c%s"%(i+1)))
add_wd(0.0001)
# [C, K, 2]
so_label_logits = tf.stack(so_label_logits, axis=0)
if config.is_train:
rpn_label_loss, rpn_box_loss = self.multilevel_rpn_losses(
multilevel_anchors, multilevel_label_logits, multilevel_box_logits)
# rcnn_labels [N_FG + N_NEG] <- index in [N_FG]
fg_inds_wrt_sample = tf.reshape(tf.where(rcnn_labels > 0), [-1])
# for training, maskRCNN only apply on positive box
# [N_FG, num_class, 14, 14]
# [N_FG, 4]
# sampled boxes are at least iou with a gt_boxes
fg_sampled_boxes = tf.gather(rcnn_boxes, fg_inds_wrt_sample)
fg_fastrcnn_box_logits = tf.gather(fastrcnn_box_logits,
fg_inds_wrt_sample)
# [N_FG, 4] # each proposal box assigned gt box, may repeat
matched_gt_boxes = tf.gather(gt_boxes, fg_inds_wrt_gt)
# fastrcnn also need to regress box (just the FG box)
encoded_boxes = encode_bbox_target(matched_gt_boxes, fg_sampled_boxes) * \
tf.constant(config.fastrcnn_bbox_reg_weights) # [10,10,5,5]?
# fastrcnn input is fg and bg proposal box, do classification to
# num_class(include bg) and then regress on fg boxes
# [N_FG+N_NEG,4] & [N_FG,4]
fastrcnn_label_loss, fastrcnn_box_loss = self.fastrcnn_losses(
rcnn_labels, fastrcnn_label_logits, encoded_boxes,
fg_fastrcnn_box_logits)
# ---------------------------------------------------------
# for debug
self.rpn_label_loss = rpn_label_loss
self.rpn_box_loss = rpn_box_loss
self.fastrcnn_label_loss = fastrcnn_label_loss
self.fastrcnn_box_loss = fastrcnn_box_loss
losses = [rpn_label_loss, rpn_box_loss, fastrcnn_label_loss,
fastrcnn_box_loss]
if config.use_small_object_head:
# assume we have the small gt boxes and labels
# so_boxes [C, K, 4]
# so_label_logits [C, K, 2]
# so_labels [C, K] # [0, 1]
so_labels = get_so_labels(self.so_boxes, self.so_gt_boxes,
self.so_gt_labels, config=config)
so_label_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=so_labels, logits=so_label_logits)
so_label_loss = tf.reduce_mean(so_label_loss, name="label_loss")
self.so_label_loss = so_label_loss
losses.append(so_label_loss)
# mask rcnn loss
if config.add_mask:
fg_inds_wrt_sample = tf.reshape(tf.where(rcnn_labels > 0), [-1])
fg_labels = tf.gather(rcnn_labels, fg_inds_wrt_sample)
# NxCx14x14
# only the fg boxes
roi_feature_fastrcnn = self.multilevel_roi_align(
p23456[:4], fg_sampled_boxes, 14)
mask_logits = self.maskrcnn_up4conv_head(
fg_feature, config.num_class, scope="maskrcnn")
# [N_FG, H,W]
gt_mask = self.gt_mask
gt_mask_for_fg = tf.gather(gt_mask, fg_inds_wrt_gt)
# [N_FG, H, W] -> [N_FG, 14, 14]
target_masks_for_fg = crop_and_resize(
tf.expand_dims(gt_masks, 1),
fg_sampled_boxes,
fg_inds_wrt_gt, 28, pad_border=False) # fg x 1x28x28
target_masks_for_fg = tf.squeeze(target_masks_for_fg, 1)
mrcnn_loss = self.maskrcnn_loss(mask_logits, fg_labels,
target_masks_for_fg)
losses += [mrcnn_loss]
self.wd = None
if config.wd is not None:
wd = wd_cost(".*/W", config.wd, scope="wd_cost")
self.wd = wd
losses.append(wd)
self.loss = tf.add_n(losses, "total_loss")
# l2loss
else:
# inferencing
# K -> proposal box
# [K,num_class]
# image_shape2d, rcnn_boxes, fastrcnn_label_logits, fastrcnn_box_logits
# get the regressed actual boxes
if config.use_frcnn_class_agnostic:
# box regress logits [K, 1, 4], so we tile it to num_class-1 so
# the rest is the same
fastrcnn_box_logits = tf.tile(fastrcnn_box_logits,
[1, config.num_class - 1, 1])
num_class = config.num_class
# COCO has 81 classes, we only need a few
if config.use_partial_classes:
needed_object_classids = [config.classname2id[name]
for name in config.partial_classes]
needed_object_classids_minus_1 = [o - 1 for o in needed_object_classids]
# (N, num_class), (N, num_class - 1, 4)
# -> (num_class, N), (num_class - 1, N, 4)
label_logits_t = tf.transpose(fastrcnn_label_logits, [1, 0])
box_logits_t = tf.transpose(fastrcnn_box_logits, [1, 0, 2])
# [C + 1, N] # 1 is the BG class
partial_label_logits_t = tf.gather(label_logits_t,
[0] + needed_object_classids)
# [C, N, 4]
partial_box_logits_t = tf.gather(box_logits_t,
needed_object_classids_minus_1)
partial_label_logits = tf.transpose(partial_label_logits_t, [1, 0])
partial_box_logits = tf.transpose(partial_box_logits_t, [1, 0, 2])
fastrcnn_label_logits = partial_label_logits
fastrcnn_box_logits = partial_box_logits
num_class = len(needed_object_classids) + 1
# anchor box [K,4] -> [K, num_class - 1, 4] <-
# box regress logits [K, num_class-1, 4]
anchors = tf.tile(tf.expand_dims(rcnn_boxes, 1), [1, num_class-1, 1])
# [K, num_class-1, 4]/ [K, 1, 4]
decoded_boxes = decode_bbox_target(fastrcnn_box_logits / \
tf.constant(config.fastrcnn_bbox_reg_weights, dtype=tf.float32),
anchors)
decoded_boxes = clip_boxes(decoded_boxes, image_shape2d,
name="fastrcnn_all_boxes")
label_probs = tf.nn.softmax(fastrcnn_label_logits)
if config.use_small_object_head:
# so_label_logits: [C, N, 2]
"""
if config.replace_small_object:
# replace some of the scores
small_object_class_ids = [config.classname2id[name]
for name in config.small_objects]
# [N, num_class]
# put each label logit for each class then stack
new_label_logits = []
for classid in config.classid2name:
if classid in small_object_class_ids:
so_idx = small_object_class_ids.index(classid)
# 1 is the class score and 0 is score for BG
new_label_logits.append(so_label_logits[so_idx, :, 1])
else:
new_label_logits.append(fastrcnn_label_logits[:, classid])
fastrcnn_label_logits = tf.stack(new_label_logits, axis=1)
"""
# output the small object boxes separately
# K is result_per_im=100
# 1. so_label_logits is [C, K, 2]
# so_boxes [C, K, 4]
# reconstruct label logit to be [K, C+1]
new_label_logits = []
# BG is ignore anyway
new_label_logits.append(
tf.reduce_mean(so_label_logits[:, :, 0], axis=0)) # [K]
for i in range(len(config.small_objects)):
new_label_logits.append(so_label_logits[i, :, 1])
# [K, C+1]
so_label_logits = tf.stack(new_label_logits, axis=1)
# [K, C, 4]
so_boxes = tf.transpose(self.so_boxes, [1, 0, 2])
so_decoded_boxes = clip_boxes(
so_boxes, image_shape2d, name="so_all_boxes")
so_pred_indices, so_final_probs = self.fastrcnn_predictions(
so_decoded_boxes, so_label_logits,
no_score_filter=not config.use_so_score_thres)
so_final_boxes = tf.gather_nd(
so_decoded_boxes, so_pred_indices, name="so_final_boxes")
so_final_labels = tf.add(
so_pred_indices[:, 1], 1, name="so_final_labels")
# [R,4]
self.so_final_boxes = so_final_boxes
# [R]
self.so_final_labels = so_final_labels
self.so_final_probs = so_final_probs
if config.use_cpu_nms:
boxes = decoded_boxes
probs = label_probs
assert boxes.shape[1] == config.num_class - 1, \
(boxes.shape, config.num_class)
assert probs.shape[1] == config.num_class, \
(probs.shape[1], config.num_class)
# transpose to map_fn along each class
boxes = tf.transpose(boxes, [1, 0, 2]) # [num_class-1, K,4]
probs = tf.transpose(probs[:, 1:], [1, 0]) # [num_class-1, K]
self.final_boxes = boxes
self.final_probs = probs
# just used for compatable with none cpu nms mode
self.final_labels = rcnn_boxes
return None # so no TF GPU NMS
# decoded boxes are [K,num_class-1,4]. so from each proposal
# boxes generate all classses" boxes, with prob, then do nms on these
# pred_indices: [R,2] , each entry (#proposal[1-K],
#catid [0,num_class-1])
# final_probs [R]
# here do nms,
pred_indices, final_probs = self.fastrcnn_predictions(
decoded_boxes, label_probs)
# [R,4]
final_boxes = tf.gather_nd(
decoded_boxes, pred_indices)
# [R] , each is 1-catogory
final_labels = tf.add(pred_indices[:, 1], 1)
if config.add_mask:
roi_feature_maskrcnn = self.multilevel_roi_align(
p23456[:4], final_boxes, 14)
# [R, num_class - 1, 14, 14]
mask_logits = self.maskrcnn_up4conv_head(
roi_feature_maskrcnn, config.num_class, scope="maskrcnn")
if config.use_partial_classes:
# need to select the classes as final_labels
mask_logits_t = tf.transpose(mask_logits, [1, 0, 2, 3])
# [C, R, 14, 14]
partial_mask_logits_t = tf.gather(
mask_logits_t, needed_object_classids)
# [R, C, 14, 14]
partial_mask_logits = tf.transpose(
partial_mask_logits_t, [1, 0, 2, 3])
indices = tf.stack(
[tf.range(tf.size(final_labels)), tf.to_int32(final_labels) - 1],
axis=1)
final_mask_logits = tf.gather_nd(mask_logits, indices)
final_masks = tf.sigmoid(final_mask_logits)
# [R,14,14]
self.final_masks = final_masks
# [R,4]
self.final_boxes = tf.identity(final_boxes, name="final_boxes")
# [R]
self.final_labels = tf.identity(final_labels, name="final_labels")
# add a name so the frozen graph will have that name
self.final_probs = tf.identity(final_probs, name="final_probs")
# [R, 256, 7, 7]
fpn_box_feat = self.multilevel_roi_align(p23456[:4], final_boxes, 7)
self.fpn_box_feat = tf.identity(fpn_box_feat, name="fpn_box_feat")
# ----some model component
# feature map -> [1,1024,FS1,FS2] , FS1 = H/16.0, FS2 = W/16.0
# channle -> 1024
def rpn_head(self, featuremap, channel, num_anchors, data_format,
scope="rpn"):
with tf.variable_scope(scope):
# [1, channel, FS1, FS2] # channel = 1024
# conv0:W -> [3,3,1024,1024]
h = conv2d(
featuremap, channel, kernel=3, activation=tf.nn.relu,
data_format=data_format,
W_init=tf.random_normal_initializer(stddev=0.01), scope="conv0")
# h -> [1,1024(channel),FS1,FS2]
# 1x1 kernel conv to classification on each grid
# [1, 1024, FS1, FS2] -> # [1, num_anchors, FS1, FS2]
label_logits = conv2d(
h, num_anchors, 1, data_format=data_format,
W_init=tf.random_normal_initializer(stddev=0.01), scope="class")
# [1, 1024, FS1, FS2] -> # [1, 4 * num_anchors, FS1, FS2]
box_logits = conv2d(
h, 4*num_anchors, 1, data_format=data_format,
W_init=tf.random_normal_initializer(stddev=0.01), scope="box")
# [1,1024,FS1, FS2] -> [FS1, FS2,1024]