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 135
/
nn.py
executable file
·1848 lines (1513 loc) · 62.8 KB
/
nn.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
import cv2
import math
import re
import tensorflow as tf
import numpy as np
from operator import mul
from deformable_helper import _tf_batch_map_offsets
from contextlib import contextmanager
import functools
VERY_NEGATIVE_NUMBER = -1e30
# f(64,2) -> 32, f(32,2) -> 16
def conv_out_size_same(size, stride):
return int(math.ceil(float(size) / float(stride)))
# softnms
# 06/2019; removed. I"m not using it anyway.
# Experiments show no significant improvement.
#try:
# from softnms.nms import cpu_soft_nms, cpu_nms
#except Exception as e:
# from softnms.cpu_nms import cpu_soft_nms, cpu_nms # Uhuh
# given a list of boxes,
# dets : [N, 5], in (x1,y1,x2,y2, score)
# kevin sigma uses 1.0
# method 1 -> linear, 2 -> gaussian(paper)
#def soft_nms(dets, sigma=0.5, Nt=0.3, threshold=0.001, method=1):
def soft_nms(dets, sigma=0.3, Nt=0.4, threshold=0.001, method=2):
keep = cpu_soft_nms(np.ascontiguousarray(dets, dtype=np.float32),
np.float32(sigma), np.float32(Nt),
np.float32(threshold),
np.uint8(method))
return keep
# cpu nms
def nms(dets, thresh):
return cpu_nms(dets, thresh)
# given regex to get the parameter to do regularization
def wd_cost(regex,wd,scope):
params = tf.trainable_variables()
with tf.name_scope(scope):
costs = []
names = []
for p in params:
para_name = p.op.name
# freeze backbone, temp fix
if para_name.startswith("conv0") or para_name.startswith("group0"):
continue
if re.search(regex, para_name):
regloss = tf.multiply(tf.convert_to_tensor(
wd, dtype=p.dtype.base_dtype, name="scale"),
tf.nn.l2_loss(p), name="%s/wd" % p.op.name)
assert regloss.dtype.is_floating, regloss
# Some variables may not be fp32, but it should
# be fine to assume regularization in fp32
if regloss.dtype != tf.float32:
regloss = tf.cast(regloss, tf.float32)
costs.append(regloss)
names.append(para_name)
# print(the names?
print("found %s variables for weight reg" % (len(costs)))
if not costs:
return tf.constant(0, dtype=tf.float32, name="empty_"+scope)
else:
return tf.add_n(costs, name=scope)
def group_norm(x, group=32, gamma_init=tf.constant_initializer(1.), scope="gn"):
with tf.variable_scope(scope):
shape = x.get_shape().as_list()
ndims = len(shape)
assert ndims == 4, shape
chan = shape[1]
assert chan % group == 0, chan
group_size = chan // group
orig_shape = tf.shape(x)
h, w = orig_shape[2], orig_shape[3]
x = tf.reshape(x, tf.stack([-1, group, group_size, h, w]))
mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True)
new_shape = [1, group, group_size, 1, 1]
beta = tf.get_variable(
"beta", [chan], initializer=tf.constant_initializer())
beta = tf.reshape(beta, new_shape)
gamma = tf.get_variable("gamma", [chan], initializer=gamma_init)
gamma = tf.reshape(gamma, new_shape)
out = tf.nn.batch_normalization(
x, mean, var, beta, gamma, 1e-5, name="output")
return tf.reshape(out, orig_shape, name="output")
# relation network head, for enhancing the boxes features
# boxe_feat: [K,1024]
# boxes:[K,4]
# group is the same as multi-head in the self attention paper
def relation_network(box_appearance_feat, boxes, group=16, geo_feat_dim=64,
scope="RM"):
fc_dim = group # the geo feature for each group
with tf.variable_scope(scope):
box_feat_dim = box_appearance_feat.get_shape().as_list()[-1] # 1024
group_feat_dim = box_feat_dim / group
# [K,4] -> [K,K,4]
# given the absolute box, get the pairwise relative geometric coordinates
box_geo_encoded = geometric_encoding(boxes, scope="geometric_encoding")
# [K,K,4] -> [K,K,geo_feat_dim]
box_geo_feat = dense(
box_geo_encoded, geo_feat_dim, activation=tf.nn.tanh,
use_bias=True, wd=None, keep_first=False, scope="geo_emb")
# [K,K,geo_feat_dim]
box_geo_feat = tf.transpose(box_geo_feat, perm=[2, 0, 1])
box_geo_feat = tf.expand_dims(box_geo_feat, axis=0) # [1,geo_feat_dim,K,K]
# [1,fc_dim,K,K]
box_geo_feat_wg = conv2d(
box_geo_feat, fc_dim, kernel=1, stride=1, data_format="NCHW",
scope="geo_conv")
box_geo_feat_wg = tf.squeeze(box_geo_feat_wg)
box_geo_feat_wg = tf.transpose(box_geo_feat_wg, perm=[1, 2, 0])
# -> [K,K,fc_dim]
box_geo_feat_wg_relu = tf.nn.relu(box_geo_feat_wg)
# [K,fc_dim,K]
box_geo_feat_wg_relu = tf.transpose(box_geo_feat_wg_relu, perm=[0, 2, 1])
# now we get the appearance stuff
#[K,1024]
query = dense(
box_appearance_feat, box_feat_dim, activation=tf.identity,
use_bias=False, wd=None, keep_first=False, scope="query_linear")
# split head
#[K,16,1024/16]
query = tf.reshape(query, (-1, group, group_feat_dim))
query = tf.transpose(query, perm=[1, 0, 2]) # [16,K,1024/16]
key = dense(
box_appearance_feat, box_feat_dim, activation=tf.identity,
use_bias=False, wd=None, keep_first=False, scope="key_linear")
# split head
#[K,16,1024/16]
key = tf.reshape(key, (-1, group, group_feat_dim))
key = tf.transpose(key, perm=[1, 0, 2]) # [16,K,1024/16]
value = box_appearance_feat
# [16,K,K]
logits = tf.matmul(query, key, transpose_b=True)
logits_scaled = (1.0 / math.sqrt(float(group_feat_dim))) * logits
logits_scaled = tf.transpose(logits_scaled, perm=[1, 0, 2]) # [K,16,K]
# [K,16,K]
weighted_logits = tf.log(tf.maximum(box_geo_feat_wg_relu, 1e-6)) + \
logits_scaled
weighted_softmax = tf.nn.softmax(weighted_logits)
# need to reshape for matmul
weighted_softmax = tf.reshape(
weighted_softmax,
(tf.shape(weighted_softmax)[0]*group, tf.shape(weighted_softmax)[-1]))
#[K*16,K] * [K,1024] -> [K*16,1024]
output = tf.matmul(weighted_softmax, value)
#[K,16,1024]
output = tf.reshape(output, (-1, group, box_feat_dim))
#[K,1024]
output = dense(
output, box_feat_dim, activation=tf.identity, use_bias=False,
wd=None, keep_first=True, scope="output_linear")
return output
# [K, 1024] / [K, 4] / [R, 4] / [R, 1024]
# returns [K, 1024], attended for each K to all R
def person_object_relation(box_appearance_feat, boxes, ref_boxes, ref_feat,
group=16, geo_feat_dim=64, scope="RM"):
fc_dim = group # the geo feature for each group
with tf.variable_scope(scope):
box_feat_dim = box_appearance_feat.get_shape().as_list()[-1] # 1024
group_feat_dim = box_feat_dim / group
# [K,4], [R, 4] -> [K, R, 4]
# given the absolute box, get the pairwise relative geometric coordinates
box_geo_encoded = geometric_encoding_pair(
boxes, ref_boxes, scope="geometric_encoding_pair")
# [K, R, 4] -> [K, R, geo_feat_dim]
box_geo_feat = dense(
box_geo_encoded, geo_feat_dim, activation=tf.nn.tanh, use_bias=True,
wd=None, keep_first=False, scope="geo_emb")
# [geo_feat_dim, K, R]
box_geo_feat = tf.transpose(box_geo_feat, perm=[2, 0, 1])
box_geo_feat = tf.expand_dims(box_geo_feat, axis=0) # [1,geo_feat_dim,K,R]
# [1,fc_dim,K,R]
box_geo_feat_wg = conv2d(
box_geo_feat, fc_dim, kernel=1, stride=1, data_format="NCHW",
scope="geo_conv")
box_geo_feat_wg = tf.squeeze(box_geo_feat_wg)
box_geo_feat_wg = tf.transpose(box_geo_feat_wg, perm=[1, 2, 0])
# -> [K,R,fc_dim]
box_geo_feat_wg_relu = tf.nn.relu(box_geo_feat_wg)
# [K,fc_dim,R]
box_geo_feat_wg_relu = tf.transpose(box_geo_feat_wg_relu, perm=[0, 2, 1])
# now we get the appearance stuff
#[K,1024]
query = dense(
box_appearance_feat, box_feat_dim, activation=tf.identity,
use_bias=False, wd=None, keep_first=False, scope="query_linear")
# split head
#[K,16,1024/16]
query = tf.reshape(query, (-1, group, group_feat_dim))
query = tf.transpose(query, perm=[1, 0, 2]) # [16,K,1024/16]
#[R, 1024]
key = dense(ref_feat, box_feat_dim, activation=tf.identity, use_bias=False,
wd=None, keep_first=False, scope="key_linear")
# split head
#[R,16,1024/16]
key = tf.reshape(key, (-1, group, group_feat_dim))
key = tf.transpose(key, perm=[1, 0, 2]) # [16,R,1024/16]
value = ref_feat
# [16,K,R]
logits = tf.matmul(query, key, transpose_b=True)
logits_scaled = (1.0 / math.sqrt(float(group_feat_dim))) * logits
logits_scaled = tf.transpose(logits_scaled, perm=[1, 0, 2]) # [K,16,R]
# [K,16,R]
weighted_logits = tf.log(tf.maximum(box_geo_feat_wg_relu, 1e-6)) + \
logits_scaled
weighted_softmax = tf.nn.softmax(weighted_logits)
# need to reshape for matmul
weighted_softmax = tf.reshape(
weighted_softmax,
(tf.shape(weighted_softmax)[0]*group, tf.shape(weighted_softmax)[-1]))
#[K*16,R] * [R,1024] -> [K*16,1024]
output = tf.matmul(weighted_softmax, value)
#[K,16,1024]
output = tf.reshape(output, (-1, group, box_feat_dim))
#[K,1024]
output = dense(
output, box_feat_dim, activation=tf.identity,
use_bias=False, wd=None, keep_first=True, scope="output_linear")
return output
# [K,4] -> [K,K,4] # get the pairwise box geometric feature
def geometric_encoding(boxes, scope="geometric_encoding"):
with tf.variable_scope(scope):
x1, y1, x2, y2 = tf.split(boxes, 4, axis=1)
w = x2 - x1
h = y2 - y1
center_x = 0.5 * (x1+x2)
center_y = 0.5 * (y1+y2)
# [K,K]
delta_x = center_x - tf.transpose(center_x)
delta_x = delta_x / w
delta_x = tf.log(tf.maximum(tf.abs(delta_x), 1e-3))
delta_y = center_y - tf.transpose(center_y)
delta_y = delta_y / w
delta_y = tf.log(tf.maximum(tf.abs(delta_y), 1e-3))
delta_w = tf.log(w / tf.transpose(w))
delta_h = tf.log(h / tf.transpose(h))
#[K,K,4]
output = tf.stack([delta_x, delta_y, delta_w, delta_h], axis=2)
return output
def geometric_encoding_pair(boxes1, boxes2, scope="geometric_encoding_pair"):
with tf.variable_scope(scope):
x11, y11, x12, y12 = tf.split(boxes1, 4, axis=1)
w1 = x12 - x11
h1 = y12 - y11
center1_x = 0.5 * (x11+x12)
center1_y = 0.5 * (y11+y12)
x21, y21, x22, y22 = tf.split(boxes2, 4, axis=1)
w2 = x22 - x21
h2 = y22 - y21
center2_x = 0.5 * (x21+x22)
center2_y = 0.5 * (y21+y22)
# [K, R]
delta_x = center1_x - tf.transpose(center2_x)
delta_x = delta_x / tf.tile(tf.transpose(w2), [tf.shape(delta_x)[0], 1])
delta_x = tf.log(tf.maximum(tf.abs(delta_x), 1e-3))
delta_y = center1_y - tf.transpose(center2_y)
delta_y = delta_y / tf.tile(tf.transpose(w2), [tf.shape(delta_y)[0], 1])
delta_y = tf.log(tf.maximum(tf.abs(delta_y), 1e-3))
delta_w = tf.log(w1 / tf.transpose(w2))
delta_h = tf.log(h1 / tf.transpose(h2))
#[K, R,4]
output = tf.stack([delta_x, delta_y, delta_w, delta_h], axis=2)
return output
def GlobalAvgPooling(x, data_format="NHWC"):
axis = [1, 2] if data_format == "NHWC" else [2, 3]
return tf.reduce_mean(x, axis, name="output")
def conv2d(x, out_channel, kernel, padding="SAME", stride=1,
activation=tf.identity, dilations=1, use_bias=True,
data_format="NHWC", W_init=None, split=1, scope="conv"):
with tf.variable_scope(scope):
in_shape = x.get_shape().as_list()
channel_axis = 3 if data_format == "NHWC" else 1
in_channel = in_shape[channel_axis]
assert in_channel is not None
kernel_shape = [kernel, kernel]
filter_shape = kernel_shape + [in_channel, out_channel]
# group conv implementation
if split != 1:
assert out_channel % split == 0
filter_shape = kernel_shape + [in_channel / split, out_channel]
if data_format == "NHWC":
stride = [1, stride, stride, 1]
dilations = [1, dilations, dilations, 1]
else:
stride = [1, 1, stride, stride]
dilations = [1, 1, dilations, dilations]
if W_init is None:
W_init = tf.variance_scaling_initializer(scale=2.0)
W = tf.get_variable("W", filter_shape, initializer=W_init)
conv = tf.nn.conv2d(
x, W, stride, padding, dilations=dilations, data_format=data_format)
assert conv is not None, "Group conv needs tf 1.14+"
if use_bias:
b_init = tf.constant_initializer()
b = tf.get_variable("b", [out_channel], initializer=b_init)
conv = tf.nn.bias_add(conv, b, data_format=data_format)
ret = activation(conv, name="output")
return ret
def deconv2d(x, out_channel, kernel,padding="SAME", stride=1,
activation=tf.identity, use_bias=True, data_format="NHWC",
W_init=None, scope="deconv"):
with tf.variable_scope(scope):
in_shape = x.get_shape().as_list()
channel_axis = 3 if data_format == "NHWC" else 1
in_channel = in_shape[channel_axis]
assert in_channel is not None
kernel_shape = [kernel, kernel]
if W_init is None:
W_init = tf.variance_scaling_initializer(scale=2.0)
b_init = tf.constant_initializer()
with rename_get_variable({"kernel": "W", "bias": "b"}):
layer = tf.layers.Conv2DTranspose(
out_channel, kernel_shape,
strides=stride, padding=padding,
data_format="channels_last" \
if data_format == "NHWC" else "channels_first",
activation=lambda x: activation(x, name="output"),
use_bias=use_bias,
kernel_initializer=W_init,
bias_initializer=b_init,
trainable=True)
ret = layer.apply(x, scope=tf.get_variable_scope())
return ret
def rename_get_variable(mapping):
"""
Args:
mapping(dict): an old -> new mapping for variable basename.
e.g. {"kernel": "W"}
"""
def custom_getter(getter, name, *args, **kwargs):
splits = name.split("/")
basename = splits[-1]
if basename in mapping:
basename = mapping[basename]
splits[-1] = basename
name = "/".join(splits)
return getter(name, *args, **kwargs)
return custom_getter_scope(custom_getter)
@contextmanager
def custom_getter_scope(custom_getter):
scope = tf.get_variable_scope()
with tf.variable_scope(scope, custom_getter=custom_getter):
yield
def resnet_basicblock(l, ch_out, stride, dilations=1, deformable=False,
tf_pad_reverse=False, use_gn=False, use_se=False):
shortcut = l
if use_gn:
NormReLU = GNReLU
else:
NormReLU = BNReLU
l = conv2d(
l, ch_out, 3, stride=stride, activation=NormReLU, use_bias=False,
data_format="NCHW", scope="conv1")
l = conv2d(
l, ch_out, 3, use_bias=False,
activation=get_bn(use_gn, zero_init=True), data_format="NCHW",
scope="conv2")
out = l + resnet_shortcut(
shortcut, ch_out, stride,
activation=get_bn(use_gn, zero_init=False), data_format="NCHW")
return out
def resnet_bottleneck(l, ch_out, stride, dilations=1, deformable=False,
tf_pad_reverse=False, use_gn=False, use_se=False):
shortcut = l
if use_gn:
NormReLU = GNReLU
else:
NormReLU = BNReLU
l = conv2d(
l, ch_out, 1, activation=NormReLU, scope="conv1", use_bias=False,
data_format="NCHW")
if stride == 2:
if deformable:
# l [1, C, H, W]
# 1. get the offset from conv2d [1, 18, H, W]
offset = conv2d(
l, 2*3*3, 3, stride=1, padding="SAME", scope="conv2_offset",
data_format="NCHW")
# for testing, use all zero offset, so this should be the same
#as regular conv2d
#input_h = tf.shape(l)[2]
#input_w = tf.shape(l)[3]
#offset = tf.fill(value=0.0, dims=[1, 2*3*3, input_h, input_w])
# get [1, ch_out, H/2, w/2]
l = deformable_conv2d(
l, offset, ch_out, 3, scope="conv2", data_format="NCHW",
use_bias=False)
else:
l = tf.pad(
l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1, tf_pad_reverse),
maybe_reverse_pad(0, 1, tf_pad_reverse)])
l = conv2d(
l, ch_out, 3, dilations=dilations, stride=2, activation=NormReLU,
padding="VALID", scope="conv2", use_bias=False, data_format="NCHW")
if dilations != 1: # weird shit
# [H+1, W+1]
l = tf.pad(
l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1, tf_pad_reverse),
maybe_reverse_pad(0, 1, tf_pad_reverse)])
else:
l = conv2d(
l, ch_out, 3, dilations=dilations, stride=stride,
activation=NormReLU, scope="conv2", use_bias=False, data_format="NCHW")
l = conv2d(
l, ch_out * 4, 1, activation=get_bn(use_gn, zero_init=True),
scope="conv3", use_bias=False, data_format="NCHW")
if use_se:
squeeze = GlobalAvgPooling(l, data_format="NCHW")
squeeze = dense(
squeeze, ch_out // 4, activation=tf.nn.relu,
W_init=tf.variance_scaling_initializer(), scope="fc1")
squeeze = dense(
squeeze, ch_out * 4, activation=tf.nn.sigmoid,
W_init=tf.variance_scaling_initializer(), scope="fc2")
ch_ax = 1
shape = [-1, 1, 1, 1]
shape[ch_ax] = ch_out * 4
l = l * tf.reshape(squeeze, shape)
return l + resnet_shortcut(
shortcut, ch_out * 4, stride,
activation=get_bn(use_gn, zero_init=False), data_format="NCHW")
def resnext_32x4d_bottleneck(l, ch_out, stride, dilations=1, deformable=False,
tf_pad_reverse=False, use_gn=False, use_se=False):
shortcut = l
if use_gn:
NormReLU = GNReLU
else:
NormReLU = BNReLU
l = conv2d(
l, ch_out * 2, 1, stride=1, activation=NormReLU, scope="conv1",
use_bias=False, data_format="NCHW")
l = conv2d(
l, ch_out * 2, 3, dilations=dilations, stride=stride,
activation=NormReLU, scope="conv2", split=32, use_bias=False,
data_format="NCHW")
l = conv2d(
l, ch_out * 4, 1, activation=get_bn(use_gn, zero_init=True),
scope="conv3", use_bias=False, data_format="NCHW")
out = l + resnet_shortcut(
shortcut, ch_out * 4, stride, activation=get_bn(use_gn, zero_init=False),
data_format="NCHW")
return out
def resnet_shortcut(l, n_out, stride, activation=tf.identity,
data_format="NCHW", use_gn=False):
n_in = l.get_shape().as_list()[1 if data_format == "NCHW" else 3]
if n_in != n_out: # change dimension when channel is not the same
if stride == 2:
l = l[:, :, :-1, :-1]
return conv2d(
l, n_out, 1, stride=stride, padding="VALID",
activation=activation, use_bias=False, data_format=data_format,
scope="convshortcut")
else:
return conv2d(
l, n_out, 1, stride=stride, activation=activation,
use_bias=False, data_format=data_format, scope="convshortcut")
else:
return l
def resnet_group(l, name, block_func, features, count, stride, dilations=1,
use_deformable=False, modified_block_num=3, reuse=False,
tf_pad_reverse=False, use_gn=False, use_se=False):
with tf.variable_scope(name):
if reuse:
tf.get_variable_scope().reuse_variables()
for i in range(0, count):
with tf.variable_scope("block{}".format(i)):
dilations_ = 1
deformable_ = False
if i in range(count)[-modified_block_num:]:
dilations_ = dilations
deformable_ = use_deformable
l = block_func(
l, features, stride if i == 0 else 1, dilations=dilations_,
deformable=deformable_, use_gn=use_gn,
tf_pad_reverse=tf_pad_reverse, use_se=use_se)
# end of each block need an activation
l = tf.nn.relu(l)
return l
def get_bn(use_gn=False, zero_init=False):
if use_gn:
if zero_init:
return lambda x, name: group_norm(
x, gamma_init=tf.zeros_initializer(), scope="gn")
else:
return lambda x, name: group_norm(x, scope="gn")
else:
if zero_init:
return lambda x, name: BatchNorm(
x, gamma_init=tf.zeros_initializer(), scope="bn")
else:
return lambda x, name: BatchNorm(x, scope="bn")
def BNReLU(x, name=None):
"""
A shorthand of Normalization + ReLU.
"""
x = BatchNorm(x, scope="bn")
x = tf.nn.relu(x, name=name)
return x
def GNReLU(x, name=None):
"""
A shorthand of Normalization + ReLU.
"""
x = group_norm(x, scope="gn")
x = tf.nn.relu(x, name=name)
return x
# add weight decay to the current varaible scope
def add_wd(wd, scope=None):
if wd != 0.0:
# for all variable in the current scope
scope = scope or tf.get_variable_scope().name
variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope)
with tf.name_scope("weight_decay"):
for var in variables:
weight_decay = tf.multiply(
tf.nn.l2_loss(var), wd, name="%s/wd" % var.op.name)
tf.add_to_collection("losses", weight_decay)
# flatten a tensor
# [N,M,JI,JXP,dim] -> [N*M*JI,JXP,dim]
# keep how many dimension in the end, so final rank is keep + 1
def flatten(tensor, keep):
# get the shape
fixed_shape = tensor.get_shape().as_list() #[N, JQ, di] # [N, M, JX, di]
# len([N, JQ, di]) - 2 = 1 # len([N, M, JX, di] ) - 2 = 2
start = len(fixed_shape) - keep
# each num in the [] will a*b*c*d...
# so [0] -> just N here for left
# for [N, M, JX, di] , left is N*M
left = functools.reduce(
mul, [fixed_shape[i] or tf.shape(tensor)[i] for i in range(start)])
# [N, JQ,di]
# [N*M, JX, di]
out_shape = [left] + [fixed_shape[i] or tf.shape(tensor)[i]
for i in range(start, len(fixed_shape))]
# reshape
flat = tf.reshape(tensor, out_shape)
return flat
def reconstruct(tensor, ref, keep): # reverse the flatten function
ref_shape = ref.get_shape().as_list()
tensor_shape = tensor.get_shape().as_list()
ref_stop = len(ref_shape) - keep
tensor_start = len(tensor_shape) - keep
pre_shape = [ref_shape[i] or tf.shape(ref)[i] for i in range(ref_stop)]
keep_shape = [tensor_shape[i] or tf.shape(tensor)[i]
for i in range(tensor_start, len(tensor_shape))]
# keep_shape = tensor.get_shape().as_list()[-keep:]
target_shape = pre_shape + keep_shape
out = tf.reshape(tensor, target_shape)
return out
# boxes are x1y1,x2y2
def pairwise_iou(boxes1, boxes2):
def area(boxes): # [N,4] -> [N]
x1, y1, x2, y2 = tf.split(boxes, 4, axis=1)
return tf.squeeze((y2 - y1) * (x2 - x1), [1])
# two box list, get intersected boxes area [N,M]
def pairwise_intersection(b1, b2):
x_min1, y_min1, x_max1, y_max1 = tf.split(b1, 4, axis=1)
x_min2, y_min2, x_max2, y_max2 = tf.split(b2, 4, axis=1)
all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))
all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))
intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)
all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))
all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))
intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)
return intersect_heights * intersect_widths
interarea = pairwise_intersection(boxes1, boxes2)
areas1 = area(boxes1)#[N]
areas2 = area(boxes2)#[M]
unions = tf.expand_dims(areas1, 1) + tf.expand_dims(areas2, 0) - interarea
# avoid zero divide?
return tf.truediv(interarea, unions)
import pycocotools.mask as cocomask
def np_iou(A, B):
def to_xywh(box):
box = box.copy()
box[:, 2] -= box[:, 0]
box[:, 3] -= box[:, 1]
return box
ret = cocomask.iou(
to_xywh(A), to_xywh(B),
np.zeros((len(B),), dtype=np.bool))
# can accelerate even more, if using float32
return ret.astype("float32")
#@memorized
def get_iou_callable():
with tf.Graph().as_default(), tf.device("/cpu:0"):
A = tf.placeholder(tf.float32, shape=[None, 4])
B = tf.placeholder(tf.float32, shape=[None, 4])
iou = pairwise_iou(A, B)
sess = tf.Session()
return sess.make_callable(iou, [A, B])
# simple linear layer, without activatation # remember to add it
def dense(x, output_size, W_init=None, b_init=None, activation=tf.identity,
use_bias=True, wd=None, keep_first=True, scope="dense"):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
# tensorpack"s fully connected keep the first dim and flatten the rest,
# apply W on the rest
if keep_first:
shape = x.get_shape().as_list()[1:]
if None not in shape:
flat_x = tf.reshape(x, [-1, int(np.prod(shape))])
else:
flat_x = tf.reshape(x, tf.stack([tf.shape(x)[0], -1]))
else:
# we used to apply W on the last dimention
# since the input here is not two rank, we flat the input
# while keeping the last dims
keep = 1
#print(x.get_shape().as_list()
flat_x = flatten(x, keep) # keeping the last one dim # [N,M,JX,JQ,d]
# => [N*M*JX*JQ,d]
if W_init is None:
W_init = tf.variance_scaling_initializer(2.0)
W = tf.get_variable(
"W", [flat_x.get_shape().as_list()[-1], output_size],
initializer=W_init)
flat_out = tf.matmul(flat_x, W)
if use_bias:
if b_init is None:
b_init = tf.constant_initializer()
b = tf.get_variable("b", [output_size], initializer=b_init)
flat_out = tf.nn.bias_add(flat_out, b)
flat_out = activation(flat_out)
if wd is not None:
add_wd(wd)
if not keep_first:
out = reconstruct(flat_out, x, keep)
else:
out = flat_out
return out
def maybe_reverse_pad(topleft, bottomright, reverse=False):
if reverse:
return [bottomright, topleft]
else:
return [topleft, bottomright]
def MaxPooling(x, shape, stride=None, padding="VALID", data_format="NHWC",
scope="maxpooling"):
with tf.variable_scope(scope):
if stride is None:
stride = shape
ret = tf.layers.max_pooling2d(
x, shape, stride, padding,
"channels_last" if data_format == "NHWC" else "channels_first")
return tf.identity(ret, name="output")
def pretrained_resnet_conv4(image, num_blocks, tf_pad_reverse=False):
assert len(num_blocks) == 3
# pad 2 zeros to front of H and 3 zeros to back of H, same for W
# so 2-3lines of zeros outside the data center
# original H,W will be H+5,W+5
l = tf.pad(
image, [[0, 0], [0, 0],
maybe_reverse_pad(2, 3, tf_pad_reverse),
maybe_reverse_pad(2, 3, tf_pad_reverse)])
l = conv2d(
l, 64, 7, stride=2, activation=BNReLU, padding="VALID",
scope="conv0", use_bias=False, data_format="NCHW")
#print(l.get_shape()# (1,64,?,?)
l = tf.pad(
l, [[0, 0], [0, 0],
maybe_reverse_pad(0, 1, tf_pad_reverse),
maybe_reverse_pad(0, 1, tf_pad_reverse)])
l = MaxPooling(
l, shape=3, stride=2, padding="VALID",
scope="pool0", data_format="NCHW")
#print(l.get_shape()# (1,64,?,?)
l = resnet_group(
l, "group0", resnet_bottleneck, 64, num_blocks[0], stride=1,
tf_pad_reverse=tf_pad_reverse)
#print(l.get_shape()# (1,256,?,?)
# TODO replace var by const to enable folding
#l = tf.stop_gradient(l) # froze outside
l = resnet_group(
l, "group1", resnet_bottleneck, 128, num_blocks[1], stride=2,
tf_pad_reverse=tf_pad_reverse)
#print(l.get_shape()# (1,512,?,?)
l = resnet_group(
l, "group2", resnet_bottleneck, 256, num_blocks[2], stride=2,
tf_pad_reverse=tf_pad_reverse)
return l
def resnet_conv5(image, num_block, reuse=False, tf_pad_reverse=False):
l = resnet_group(
image, "group3", resnet_bottleneck, 512, num_block, stride=2, reuse=reuse,
tf_pad_reverse=tf_pad_reverse)
return l
# fpn_resolution_requirement is 32 by default FPN
def resnet_fpn_backbone(image, num_blocks,resolution_requirement,
use_deformable=False, use_dilations=False,
tf_pad_reverse=False, finer_resolution=False,
freeze=0, use_gn=False, use_basic_block=False,
use_se=False, use_resnext=False):
assert len(num_blocks) == 4
shape2d = tf.shape(image)[2:]
# this gets the nearest H, W that is a multiplier of 32
# 720 -> 736, 1080 -> 1088
mult = resolution_requirement * 1.0
new_shape2d = tf.to_int32(tf.ceil(tf.to_float(shape2d) / mult) * mult)
pad_shape2d = new_shape2d - shape2d
channel = image.shape[1] # [B, C, H, W]
if use_gn:
NormReLU = GNReLU
else:
NormReLU = BNReLU
block_func = resnet_bottleneck
if use_basic_block:
block_func = resnet_basicblock
if use_resnext:
block_func = resnext_32x4d_bottleneck
# tf_pad_reverse= True
pad_base = maybe_reverse_pad(2, 3, tf_pad_reverse)
l = tf.pad(
image, [
[0, 0], [0, 0],
[pad_base[0], pad_base[1] + pad_shape2d[0]],
[pad_base[0], pad_base[1] + pad_shape2d[1]]])
l.set_shape([None, channel, None, None])
# 720, 1280 -> 736, 1280 / 1080, 1920 -> 1088, 1920, a multiplier of 32
# actually 741/1093 due to the pad_base of [2, 3]
# pad_base is for first conv and max pool
#l = tf.Print(l, data=[tf.shape(l)], summarize=10)
# rest is the same as c4 backbone
l = conv2d(
l, 64, 7, stride=2, activation=NormReLU, padding="VALID",
scope="conv0", use_bias=False, data_format="NCHW")
c1 = l
l = tf.pad(
l, [[0, 0], [0, 0], maybe_reverse_pad(0, 1, tf_pad_reverse),
maybe_reverse_pad(0, 1, tf_pad_reverse)]) # H+1,W+1
l = MaxPooling(
l, shape=3, stride=2, padding="VALID",
scope="pool0", data_format="NCHW")
# here 4x down already, so smallest anchor box can on use these
# 4X down from 1088 and 1920
#l = tf.Print(l, data=[tf.shape(l)], summarize=10) # [1 64 272 480]
# resnet_group output channel is 64*4
c2 = resnet_group(
l, "group0", block_func, 64, num_blocks[0], stride=1,
tf_pad_reverse=tf_pad_reverse, use_gn=use_gn, use_se=use_se)
if freeze >= 0: # tensorpack setting
c2 = tf.stop_gradient(c2)
#c2 = tf.Print(c2, data=[tf.shape(c2)], summarize=10) # [1 256 272 480] #
# for dilated conv and deformable conv, we will add to the last 3
# block in each group
mbn = 3 # modify the last 3 conv block
# [4]
c3 = resnet_group(
c2, "group1", block_func, 128, num_blocks[1], dilations=1,
modified_block_num=mbn, stride=2, use_deformable=use_deformable,
tf_pad_reverse=tf_pad_reverse, use_gn=use_gn, use_se=use_se)
if freeze >= 1:
c3 = tf.stop_gradient(c3)
# [23]
c4 = resnet_group(
c3, "group2", block_func, 256, num_blocks[2], dilations=1,
modified_block_num=mbn, stride=2, use_deformable=use_deformable,
tf_pad_reverse=tf_pad_reverse, use_gn=use_gn, use_se=use_se)
if freeze >= 2:
c4 = tf.stop_gradient(c4)
#c4 = tf.Print(c4, data=[tf.shape(c4)], summarize=10) # [1 1024 68 120]
# [3]
# people change the last stride to 1 and with dilations 2?
c5 = resnet_group(
c4, "group3", block_func, 512, num_blocks[3],
dilations=2 if use_dilations else 1,
use_deformable=use_deformable, modified_block_num=mbn,
stride=2, tf_pad_reverse=tf_pad_reverse, use_gn=use_gn, use_se=use_se)
# [1 2048 34 60] same for dilation or not
#c5 = tf.Print(c5, data=[tf.shape(c5)], summarize=10)
if freeze >= 3:
c5 = tf.stop_gradient(c5)
## 32x downsampling up to now
# size of c5: ceil(input/32)
return c2, c3, c4, c5
# the FPN model
def fpn_model(c2345, num_channel, scope, use_gn=False):
def upsample2x(x, scope):
with tf.name_scope(scope):
# FPN paper uses nearest neighbour
# a outer product with 2x2 , makes x upsampled
unpool_mat = np.ones((2, 2), dtype="float32")
shape = (2, 2)
output_shape = x.get_shape().as_list() # [N,C,H,W]
unpool_mat = tf.constant(unpool_mat, name="unpool_mat")
assert unpool_mat.get_shape().as_list() == list(shape)
# outer product with ones, so just duplicate stuff
x = tf.expand_dims(x, -1) # NxCxHxWx1
mat = tf.expand_dims(unpool_mat, 0) # 1xSHxSW
ret = tf.tensordot(x, mat, axes=1) # NxCxHxWxSHxSW
ret = tf.transpose(ret, [0, 1, 2, 4, 3, 5]) # NxCxHxSHxWxSW
ret = tf.reshape(
ret,
tf.stack([
-1, output_shape[1],
tf.shape(x)[2] * shape[0],
tf.shape(x)[3] * shape[1]])) # [N,C,H*2,W*2]
return ret
with tf.variable_scope(scope):
# each conv feature go through 1x1 conv, then add to 2x upsampled feature, then add 3x3 conv to get final feature
lat_2345 = [conv2d(
c, num_channel, 1, stride=1, activation=tf.identity, padding="SAME",
scope="lateral_1x1_c%s"%(i+2), use_bias=True, data_format="NCHW",
W_init=tf.variance_scaling_initializer(scale=1.0))
for i, c in enumerate(c2345)]
if use_gn:
lat_2345 = [
group_norm(c, scope="gn_c{}".format(i + 2))
for i, c in enumerate(lat_2345)]
lat_sum_5432 = []
for idx, lat in enumerate(lat_2345[::-1]):
if idx == 0:
lat_sum_5432.append(lat)
else:
lat = lat + \
upsample2x(lat_sum_5432[-1], scope="upsample_lat%s" % (6 - idx))
lat_sum_5432.append(lat)