tianma commited on
Commit
bed503a
·
1 Parent(s): bd543a6

Add official task teachers and align TAIC train/eval configs.

Browse files

Wire official backbone/neck teachers, freeze_base_codec support, and task-network configs so training and metric eval match the paper setup.

checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic.py ADDED
@@ -0,0 +1,778 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ auto_scale_lr = dict(base_batch_size=16, enable=False)
2
+ backbone_embed_multi = dict(decay_mult=0.0, lr_mult=0.1)
3
+ backbone_norm_multi = dict(decay_mult=0.0, lr_mult=0.1)
4
+ backend_args = None
5
+ batch_augments = [
6
+ dict(
7
+ img_pad_value=0,
8
+ mask_pad_value=0,
9
+ pad_mask=True,
10
+ pad_seg=True,
11
+ seg_pad_value=255,
12
+ size=(
13
+ 1024,
14
+ 1024,
15
+ ),
16
+ type='BatchFixedSizePad'),
17
+ ]
18
+ custom_keys = dict({
19
+ 'absolute_pos_embed':
20
+ dict(decay_mult=0.0, lr_mult=0.1),
21
+ 'backbone':
22
+ dict(decay_mult=1.0, lr_mult=0.1),
23
+ 'backbone.norm':
24
+ dict(decay_mult=0.0, lr_mult=0.1),
25
+ 'backbone.patch_embed.norm':
26
+ dict(decay_mult=0.0, lr_mult=0.1),
27
+ 'backbone.stages.0.blocks.0.norm':
28
+ dict(decay_mult=0.0, lr_mult=0.1),
29
+ 'backbone.stages.0.blocks.1.norm':
30
+ dict(decay_mult=0.0, lr_mult=0.1),
31
+ 'backbone.stages.0.downsample.norm':
32
+ dict(decay_mult=0.0, lr_mult=0.1),
33
+ 'backbone.stages.1.blocks.0.norm':
34
+ dict(decay_mult=0.0, lr_mult=0.1),
35
+ 'backbone.stages.1.blocks.1.norm':
36
+ dict(decay_mult=0.0, lr_mult=0.1),
37
+ 'backbone.stages.1.downsample.norm':
38
+ dict(decay_mult=0.0, lr_mult=0.1),
39
+ 'backbone.stages.2.blocks.0.norm':
40
+ dict(decay_mult=0.0, lr_mult=0.1),
41
+ 'backbone.stages.2.blocks.1.norm':
42
+ dict(decay_mult=0.0, lr_mult=0.1),
43
+ 'backbone.stages.2.blocks.10.norm':
44
+ dict(decay_mult=0.0, lr_mult=0.1),
45
+ 'backbone.stages.2.blocks.11.norm':
46
+ dict(decay_mult=0.0, lr_mult=0.1),
47
+ 'backbone.stages.2.blocks.12.norm':
48
+ dict(decay_mult=0.0, lr_mult=0.1),
49
+ 'backbone.stages.2.blocks.13.norm':
50
+ dict(decay_mult=0.0, lr_mult=0.1),
51
+ 'backbone.stages.2.blocks.14.norm':
52
+ dict(decay_mult=0.0, lr_mult=0.1),
53
+ 'backbone.stages.2.blocks.15.norm':
54
+ dict(decay_mult=0.0, lr_mult=0.1),
55
+ 'backbone.stages.2.blocks.16.norm':
56
+ dict(decay_mult=0.0, lr_mult=0.1),
57
+ 'backbone.stages.2.blocks.17.norm':
58
+ dict(decay_mult=0.0, lr_mult=0.1),
59
+ 'backbone.stages.2.blocks.2.norm':
60
+ dict(decay_mult=0.0, lr_mult=0.1),
61
+ 'backbone.stages.2.blocks.3.norm':
62
+ dict(decay_mult=0.0, lr_mult=0.1),
63
+ 'backbone.stages.2.blocks.4.norm':
64
+ dict(decay_mult=0.0, lr_mult=0.1),
65
+ 'backbone.stages.2.blocks.5.norm':
66
+ dict(decay_mult=0.0, lr_mult=0.1),
67
+ 'backbone.stages.2.blocks.6.norm':
68
+ dict(decay_mult=0.0, lr_mult=0.1),
69
+ 'backbone.stages.2.blocks.7.norm':
70
+ dict(decay_mult=0.0, lr_mult=0.1),
71
+ 'backbone.stages.2.blocks.8.norm':
72
+ dict(decay_mult=0.0, lr_mult=0.1),
73
+ 'backbone.stages.2.blocks.9.norm':
74
+ dict(decay_mult=0.0, lr_mult=0.1),
75
+ 'backbone.stages.2.downsample.norm':
76
+ dict(decay_mult=0.0, lr_mult=0.1),
77
+ 'backbone.stages.3.blocks.0.norm':
78
+ dict(decay_mult=0.0, lr_mult=0.1),
79
+ 'backbone.stages.3.blocks.1.norm':
80
+ dict(decay_mult=0.0, lr_mult=0.1),
81
+ 'level_embed':
82
+ dict(decay_mult=0.0, lr_mult=1.0),
83
+ 'query_embed':
84
+ dict(decay_mult=0.0, lr_mult=1.0),
85
+ 'query_feat':
86
+ dict(decay_mult=0.0, lr_mult=1.0),
87
+ 'relative_position_bias_table':
88
+ dict(decay_mult=0.0, lr_mult=0.1)
89
+ })
90
+ data_preprocessor = dict(
91
+ batch_augments=[
92
+ dict(
93
+ img_pad_value=0,
94
+ mask_pad_value=0,
95
+ pad_mask=True,
96
+ pad_seg=True,
97
+ seg_pad_value=255,
98
+ size=(
99
+ 1024,
100
+ 1024,
101
+ ),
102
+ type='BatchFixedSizePad'),
103
+ ],
104
+ bgr_to_rgb=True,
105
+ mask_pad_value=0,
106
+ mean=[
107
+ 123.675,
108
+ 116.28,
109
+ 103.53,
110
+ ],
111
+ pad_mask=True,
112
+ pad_seg=True,
113
+ pad_size_divisor=32,
114
+ seg_pad_value=255,
115
+ std=[
116
+ 58.395,
117
+ 57.12,
118
+ 57.375,
119
+ ],
120
+ type='DetDataPreprocessor')
121
+ data_root = 'data/coco/'
122
+ dataset_type = 'CocoPanopticDataset'
123
+ default_hooks = dict(
124
+ checkpoint=dict(
125
+ by_epoch=False,
126
+ interval=5000,
127
+ max_keep_ckpts=3,
128
+ save_last=True,
129
+ type='CheckpointHook'),
130
+ logger=dict(interval=50, type='LoggerHook'),
131
+ param_scheduler=dict(type='ParamSchedulerHook'),
132
+ sampler_seed=dict(type='DistSamplerSeedHook'),
133
+ timer=dict(type='IterTimerHook'),
134
+ visualization=dict(type='DetVisualizationHook'))
135
+ default_scope = 'mmdet'
136
+ depths = [
137
+ 2,
138
+ 2,
139
+ 18,
140
+ 2,
141
+ ]
142
+ dynamic_intervals = [
143
+ (
144
+ 365001,
145
+ 368750,
146
+ ),
147
+ ]
148
+ embed_multi = dict(decay_mult=0.0, lr_mult=1.0)
149
+ env_cfg = dict(
150
+ cudnn_benchmark=False,
151
+ dist_cfg=dict(backend='nccl'),
152
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0))
153
+ image_size = (
154
+ 1024,
155
+ 1024,
156
+ )
157
+ interval = 5000
158
+ load_from = None
159
+ log_level = 'INFO'
160
+ log_processor = dict(by_epoch=False, type='LogProcessor', window_size=50)
161
+ max_iters = 368750
162
+ model = dict(
163
+ backbone=dict(
164
+ attn_drop_rate=0.0,
165
+ convert_weights=True,
166
+ depths=[
167
+ 2,
168
+ 2,
169
+ 18,
170
+ 2,
171
+ ],
172
+ drop_path_rate=0.3,
173
+ drop_rate=0.0,
174
+ embed_dims=128,
175
+ frozen_stages=-1,
176
+ init_cfg=dict(
177
+ checkpoint=
178
+ 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window12_384_22k.pth',
179
+ type='Pretrained'),
180
+ mlp_ratio=4,
181
+ num_heads=[
182
+ 4,
183
+ 8,
184
+ 16,
185
+ 32,
186
+ ],
187
+ out_indices=(
188
+ 0,
189
+ 1,
190
+ 2,
191
+ 3,
192
+ ),
193
+ patch_norm=True,
194
+ pretrain_img_size=384,
195
+ qk_scale=None,
196
+ qkv_bias=True,
197
+ type='SwinTransformer',
198
+ window_size=12,
199
+ with_cp=False),
200
+ data_preprocessor=dict(
201
+ batch_augments=[
202
+ dict(
203
+ img_pad_value=0,
204
+ mask_pad_value=0,
205
+ pad_mask=True,
206
+ pad_seg=True,
207
+ seg_pad_value=255,
208
+ size=(
209
+ 1024,
210
+ 1024,
211
+ ),
212
+ type='BatchFixedSizePad'),
213
+ ],
214
+ bgr_to_rgb=True,
215
+ mask_pad_value=0,
216
+ mean=[
217
+ 123.675,
218
+ 116.28,
219
+ 103.53,
220
+ ],
221
+ pad_mask=True,
222
+ pad_seg=True,
223
+ pad_size_divisor=32,
224
+ seg_pad_value=255,
225
+ std=[
226
+ 58.395,
227
+ 57.12,
228
+ 57.375,
229
+ ],
230
+ type='DetDataPreprocessor'),
231
+ init_cfg=None,
232
+ panoptic_fusion_head=dict(
233
+ init_cfg=None,
234
+ loss_panoptic=None,
235
+ num_stuff_classes=53,
236
+ num_things_classes=80,
237
+ type='MaskFormerFusionHead'),
238
+ panoptic_head=dict(
239
+ enforce_decoder_input_project=False,
240
+ feat_channels=256,
241
+ in_channels=[
242
+ 128,
243
+ 256,
244
+ 512,
245
+ 1024,
246
+ ],
247
+ loss_cls=dict(
248
+ class_weight=[
249
+ 1.0,
250
+ 1.0,
251
+ 1.0,
252
+ 1.0,
253
+ 1.0,
254
+ 1.0,
255
+ 1.0,
256
+ 1.0,
257
+ 1.0,
258
+ 1.0,
259
+ 1.0,
260
+ 1.0,
261
+ 1.0,
262
+ 1.0,
263
+ 1.0,
264
+ 1.0,
265
+ 1.0,
266
+ 1.0,
267
+ 1.0,
268
+ 1.0,
269
+ 1.0,
270
+ 1.0,
271
+ 1.0,
272
+ 1.0,
273
+ 1.0,
274
+ 1.0,
275
+ 1.0,
276
+ 1.0,
277
+ 1.0,
278
+ 1.0,
279
+ 1.0,
280
+ 1.0,
281
+ 1.0,
282
+ 1.0,
283
+ 1.0,
284
+ 1.0,
285
+ 1.0,
286
+ 1.0,
287
+ 1.0,
288
+ 1.0,
289
+ 1.0,
290
+ 1.0,
291
+ 1.0,
292
+ 1.0,
293
+ 1.0,
294
+ 1.0,
295
+ 1.0,
296
+ 1.0,
297
+ 1.0,
298
+ 1.0,
299
+ 1.0,
300
+ 1.0,
301
+ 1.0,
302
+ 1.0,
303
+ 1.0,
304
+ 1.0,
305
+ 1.0,
306
+ 1.0,
307
+ 1.0,
308
+ 1.0,
309
+ 1.0,
310
+ 1.0,
311
+ 1.0,
312
+ 1.0,
313
+ 1.0,
314
+ 1.0,
315
+ 1.0,
316
+ 1.0,
317
+ 1.0,
318
+ 1.0,
319
+ 1.0,
320
+ 1.0,
321
+ 1.0,
322
+ 1.0,
323
+ 1.0,
324
+ 1.0,
325
+ 1.0,
326
+ 1.0,
327
+ 1.0,
328
+ 1.0,
329
+ 1.0,
330
+ 1.0,
331
+ 1.0,
332
+ 1.0,
333
+ 1.0,
334
+ 1.0,
335
+ 1.0,
336
+ 1.0,
337
+ 1.0,
338
+ 1.0,
339
+ 1.0,
340
+ 1.0,
341
+ 1.0,
342
+ 1.0,
343
+ 1.0,
344
+ 1.0,
345
+ 1.0,
346
+ 1.0,
347
+ 1.0,
348
+ 1.0,
349
+ 1.0,
350
+ 1.0,
351
+ 1.0,
352
+ 1.0,
353
+ 1.0,
354
+ 1.0,
355
+ 1.0,
356
+ 1.0,
357
+ 1.0,
358
+ 1.0,
359
+ 1.0,
360
+ 1.0,
361
+ 1.0,
362
+ 1.0,
363
+ 1.0,
364
+ 1.0,
365
+ 1.0,
366
+ 1.0,
367
+ 1.0,
368
+ 1.0,
369
+ 1.0,
370
+ 1.0,
371
+ 1.0,
372
+ 1.0,
373
+ 1.0,
374
+ 1.0,
375
+ 1.0,
376
+ 1.0,
377
+ 1.0,
378
+ 1.0,
379
+ 1.0,
380
+ 1.0,
381
+ 1.0,
382
+ 0.1,
383
+ ],
384
+ loss_weight=2.0,
385
+ reduction='mean',
386
+ type='CrossEntropyLoss',
387
+ use_sigmoid=False),
388
+ loss_dice=dict(
389
+ activate=True,
390
+ eps=1.0,
391
+ loss_weight=5.0,
392
+ naive_dice=True,
393
+ reduction='mean',
394
+ type='DiceLoss',
395
+ use_sigmoid=True),
396
+ loss_mask=dict(
397
+ loss_weight=5.0,
398
+ reduction='mean',
399
+ type='CrossEntropyLoss',
400
+ use_sigmoid=True),
401
+ num_queries=100,
402
+ num_stuff_classes=53,
403
+ num_things_classes=80,
404
+ num_transformer_feat_level=3,
405
+ out_channels=256,
406
+ pixel_decoder=dict(
407
+ act_cfg=dict(type='ReLU'),
408
+ encoder=dict(
409
+ layer_cfg=dict(
410
+ ffn_cfg=dict(
411
+ act_cfg=dict(inplace=True, type='ReLU'),
412
+ embed_dims=256,
413
+ feedforward_channels=1024,
414
+ ffn_drop=0.0,
415
+ num_fcs=2),
416
+ self_attn_cfg=dict(
417
+ batch_first=True,
418
+ dropout=0.0,
419
+ embed_dims=256,
420
+ num_heads=8,
421
+ num_levels=3,
422
+ num_points=4)),
423
+ num_layers=6),
424
+ norm_cfg=dict(num_groups=32, type='GN'),
425
+ num_outs=3,
426
+ positional_encoding=dict(normalize=True, num_feats=128),
427
+ type='MSDeformAttnPixelDecoder'),
428
+ positional_encoding=dict(normalize=True, num_feats=128),
429
+ strides=[
430
+ 4,
431
+ 8,
432
+ 16,
433
+ 32,
434
+ ],
435
+ transformer_decoder=dict(
436
+ init_cfg=None,
437
+ layer_cfg=dict(
438
+ cross_attn_cfg=dict(
439
+ batch_first=True, dropout=0.0, embed_dims=256,
440
+ num_heads=8),
441
+ ffn_cfg=dict(
442
+ act_cfg=dict(inplace=True, type='ReLU'),
443
+ embed_dims=256,
444
+ feedforward_channels=2048,
445
+ ffn_drop=0.0,
446
+ num_fcs=2),
447
+ self_attn_cfg=dict(
448
+ batch_first=True, dropout=0.0, embed_dims=256,
449
+ num_heads=8)),
450
+ num_layers=9,
451
+ return_intermediate=True),
452
+ type='Mask2FormerHead'),
453
+ test_cfg=dict(
454
+ filter_low_score=True,
455
+ instance_on=True,
456
+ iou_thr=0.8,
457
+ max_per_image=100,
458
+ panoptic_on=True,
459
+ semantic_on=False),
460
+ train_cfg=dict(
461
+ assigner=dict(
462
+ match_costs=[
463
+ dict(type='ClassificationCost', weight=2.0),
464
+ dict(
465
+ type='CrossEntropyLossCost', use_sigmoid=True, weight=5.0),
466
+ dict(eps=1.0, pred_act=True, type='DiceCost', weight=5.0),
467
+ ],
468
+ type='HungarianAssigner'),
469
+ importance_sample_ratio=0.75,
470
+ num_points=12544,
471
+ oversample_ratio=3.0,
472
+ sampler=dict(type='MaskPseudoSampler')),
473
+ type='Mask2Former')
474
+ num_classes = 133
475
+ num_stuff_classes = 53
476
+ num_things_classes = 80
477
+ optim_wrapper = dict(
478
+ clip_grad=dict(max_norm=0.01, norm_type=2),
479
+ optimizer=dict(
480
+ betas=(
481
+ 0.9,
482
+ 0.999,
483
+ ),
484
+ eps=1e-08,
485
+ lr=0.0001,
486
+ type='AdamW',
487
+ weight_decay=0.05),
488
+ paramwise_cfg=dict(
489
+ custom_keys=dict({
490
+ 'absolute_pos_embed':
491
+ dict(decay_mult=0.0, lr_mult=0.1),
492
+ 'backbone':
493
+ dict(decay_mult=1.0, lr_mult=0.1),
494
+ 'backbone.norm':
495
+ dict(decay_mult=0.0, lr_mult=0.1),
496
+ 'backbone.patch_embed.norm':
497
+ dict(decay_mult=0.0, lr_mult=0.1),
498
+ 'backbone.stages.0.blocks.0.norm':
499
+ dict(decay_mult=0.0, lr_mult=0.1),
500
+ 'backbone.stages.0.blocks.1.norm':
501
+ dict(decay_mult=0.0, lr_mult=0.1),
502
+ 'backbone.stages.0.downsample.norm':
503
+ dict(decay_mult=0.0, lr_mult=0.1),
504
+ 'backbone.stages.1.blocks.0.norm':
505
+ dict(decay_mult=0.0, lr_mult=0.1),
506
+ 'backbone.stages.1.blocks.1.norm':
507
+ dict(decay_mult=0.0, lr_mult=0.1),
508
+ 'backbone.stages.1.downsample.norm':
509
+ dict(decay_mult=0.0, lr_mult=0.1),
510
+ 'backbone.stages.2.blocks.0.norm':
511
+ dict(decay_mult=0.0, lr_mult=0.1),
512
+ 'backbone.stages.2.blocks.1.norm':
513
+ dict(decay_mult=0.0, lr_mult=0.1),
514
+ 'backbone.stages.2.blocks.10.norm':
515
+ dict(decay_mult=0.0, lr_mult=0.1),
516
+ 'backbone.stages.2.blocks.11.norm':
517
+ dict(decay_mult=0.0, lr_mult=0.1),
518
+ 'backbone.stages.2.blocks.12.norm':
519
+ dict(decay_mult=0.0, lr_mult=0.1),
520
+ 'backbone.stages.2.blocks.13.norm':
521
+ dict(decay_mult=0.0, lr_mult=0.1),
522
+ 'backbone.stages.2.blocks.14.norm':
523
+ dict(decay_mult=0.0, lr_mult=0.1),
524
+ 'backbone.stages.2.blocks.15.norm':
525
+ dict(decay_mult=0.0, lr_mult=0.1),
526
+ 'backbone.stages.2.blocks.16.norm':
527
+ dict(decay_mult=0.0, lr_mult=0.1),
528
+ 'backbone.stages.2.blocks.17.norm':
529
+ dict(decay_mult=0.0, lr_mult=0.1),
530
+ 'backbone.stages.2.blocks.2.norm':
531
+ dict(decay_mult=0.0, lr_mult=0.1),
532
+ 'backbone.stages.2.blocks.3.norm':
533
+ dict(decay_mult=0.0, lr_mult=0.1),
534
+ 'backbone.stages.2.blocks.4.norm':
535
+ dict(decay_mult=0.0, lr_mult=0.1),
536
+ 'backbone.stages.2.blocks.5.norm':
537
+ dict(decay_mult=0.0, lr_mult=0.1),
538
+ 'backbone.stages.2.blocks.6.norm':
539
+ dict(decay_mult=0.0, lr_mult=0.1),
540
+ 'backbone.stages.2.blocks.7.norm':
541
+ dict(decay_mult=0.0, lr_mult=0.1),
542
+ 'backbone.stages.2.blocks.8.norm':
543
+ dict(decay_mult=0.0, lr_mult=0.1),
544
+ 'backbone.stages.2.blocks.9.norm':
545
+ dict(decay_mult=0.0, lr_mult=0.1),
546
+ 'backbone.stages.2.downsample.norm':
547
+ dict(decay_mult=0.0, lr_mult=0.1),
548
+ 'backbone.stages.3.blocks.0.norm':
549
+ dict(decay_mult=0.0, lr_mult=0.1),
550
+ 'backbone.stages.3.blocks.1.norm':
551
+ dict(decay_mult=0.0, lr_mult=0.1),
552
+ 'level_embed':
553
+ dict(decay_mult=0.0, lr_mult=1.0),
554
+ 'query_embed':
555
+ dict(decay_mult=0.0, lr_mult=1.0),
556
+ 'query_feat':
557
+ dict(decay_mult=0.0, lr_mult=1.0),
558
+ 'relative_position_bias_table':
559
+ dict(decay_mult=0.0, lr_mult=0.1)
560
+ }),
561
+ norm_decay_mult=0.0),
562
+ type='OptimWrapper')
563
+ param_scheduler = dict(
564
+ begin=0,
565
+ by_epoch=False,
566
+ end=368750,
567
+ gamma=0.1,
568
+ milestones=[
569
+ 327778,
570
+ 355092,
571
+ ],
572
+ type='MultiStepLR')
573
+ pretrained = 'https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_base_patch4_window12_384_22k.pth'
574
+ resume = False
575
+ test_cfg = dict(type='TestLoop')
576
+ test_dataloader = dict(
577
+ batch_size=1,
578
+ dataset=dict(
579
+ ann_file='annotations/panoptic_val2017.json',
580
+ backend_args=None,
581
+ data_prefix=dict(img='val2017/', seg='annotations/panoptic_val2017/'),
582
+ data_root='data/coco/',
583
+ pipeline=[
584
+ dict(backend_args=None, type='LoadImageFromFile'),
585
+ dict(keep_ratio=True, scale=(
586
+ 1333,
587
+ 800,
588
+ ), type='Resize'),
589
+ dict(backend_args=None, type='LoadPanopticAnnotations'),
590
+ dict(
591
+ meta_keys=(
592
+ 'img_id',
593
+ 'img_path',
594
+ 'ori_shape',
595
+ 'img_shape',
596
+ 'scale_factor',
597
+ ),
598
+ type='PackDetInputs'),
599
+ ],
600
+ test_mode=True,
601
+ type='CocoPanopticDataset'),
602
+ drop_last=False,
603
+ num_workers=2,
604
+ persistent_workers=True,
605
+ sampler=dict(shuffle=False, type='DefaultSampler'))
606
+ test_evaluator = [
607
+ dict(
608
+ ann_file='data/coco/annotations/panoptic_val2017.json',
609
+ backend_args=None,
610
+ seg_prefix='data/coco/annotations/panoptic_val2017/',
611
+ type='CocoPanopticMetric'),
612
+ dict(
613
+ ann_file='data/coco/annotations/instances_val2017.json',
614
+ backend_args=None,
615
+ metric=[
616
+ 'bbox',
617
+ 'segm',
618
+ ],
619
+ type='CocoMetric'),
620
+ ]
621
+ test_pipeline = [
622
+ dict(backend_args=None, type='LoadImageFromFile'),
623
+ dict(keep_ratio=True, scale=(
624
+ 1333,
625
+ 800,
626
+ ), type='Resize'),
627
+ dict(backend_args=None, type='LoadPanopticAnnotations'),
628
+ dict(
629
+ meta_keys=(
630
+ 'img_id',
631
+ 'img_path',
632
+ 'ori_shape',
633
+ 'img_shape',
634
+ 'scale_factor',
635
+ ),
636
+ type='PackDetInputs'),
637
+ ]
638
+ train_cfg = dict(
639
+ dynamic_intervals=[
640
+ (
641
+ 365001,
642
+ 368750,
643
+ ),
644
+ ],
645
+ max_iters=368750,
646
+ type='IterBasedTrainLoop',
647
+ val_interval=5000)
648
+ train_dataloader = dict(
649
+ batch_sampler=dict(type='AspectRatioBatchSampler'),
650
+ batch_size=2,
651
+ dataset=dict(
652
+ ann_file='annotations/panoptic_train2017.json',
653
+ backend_args=None,
654
+ data_prefix=dict(
655
+ img='train2017/', seg='annotations/panoptic_train2017/'),
656
+ data_root='data/coco/',
657
+ filter_cfg=dict(filter_empty_gt=True, min_size=32),
658
+ pipeline=[
659
+ dict(backend_args=None, to_float32=True, type='LoadImageFromFile'),
660
+ dict(
661
+ backend_args=None,
662
+ type='LoadPanopticAnnotations',
663
+ with_bbox=True,
664
+ with_mask=True,
665
+ with_seg=True),
666
+ dict(prob=0.5, type='RandomFlip'),
667
+ dict(
668
+ keep_ratio=True,
669
+ ratio_range=(
670
+ 0.1,
671
+ 2.0,
672
+ ),
673
+ scale=(
674
+ 1024,
675
+ 1024,
676
+ ),
677
+ type='RandomResize'),
678
+ dict(
679
+ allow_negative_crop=True,
680
+ crop_size=(
681
+ 1024,
682
+ 1024,
683
+ ),
684
+ crop_type='absolute',
685
+ recompute_bbox=True,
686
+ type='RandomCrop'),
687
+ dict(type='PackDetInputs'),
688
+ ],
689
+ type='CocoPanopticDataset'),
690
+ num_workers=2,
691
+ persistent_workers=True,
692
+ sampler=dict(shuffle=True, type='DefaultSampler'))
693
+ train_pipeline = [
694
+ dict(backend_args=None, to_float32=True, type='LoadImageFromFile'),
695
+ dict(
696
+ backend_args=None,
697
+ type='LoadPanopticAnnotations',
698
+ with_bbox=True,
699
+ with_mask=True,
700
+ with_seg=True),
701
+ dict(prob=0.5, type='RandomFlip'),
702
+ dict(
703
+ keep_ratio=True,
704
+ ratio_range=(
705
+ 0.1,
706
+ 2.0,
707
+ ),
708
+ scale=(
709
+ 1024,
710
+ 1024,
711
+ ),
712
+ type='RandomResize'),
713
+ dict(
714
+ allow_negative_crop=True,
715
+ crop_size=(
716
+ 1024,
717
+ 1024,
718
+ ),
719
+ crop_type='absolute',
720
+ recompute_bbox=True,
721
+ type='RandomCrop'),
722
+ dict(type='PackDetInputs'),
723
+ ]
724
+ val_cfg = dict(type='ValLoop')
725
+ val_dataloader = dict(
726
+ batch_size=1,
727
+ dataset=dict(
728
+ ann_file='annotations/panoptic_val2017.json',
729
+ backend_args=None,
730
+ data_prefix=dict(img='val2017/', seg='annotations/panoptic_val2017/'),
731
+ data_root='data/coco/',
732
+ pipeline=[
733
+ dict(backend_args=None, type='LoadImageFromFile'),
734
+ dict(keep_ratio=True, scale=(
735
+ 1333,
736
+ 800,
737
+ ), type='Resize'),
738
+ dict(backend_args=None, type='LoadPanopticAnnotations'),
739
+ dict(
740
+ meta_keys=(
741
+ 'img_id',
742
+ 'img_path',
743
+ 'ori_shape',
744
+ 'img_shape',
745
+ 'scale_factor',
746
+ ),
747
+ type='PackDetInputs'),
748
+ ],
749
+ test_mode=True,
750
+ type='CocoPanopticDataset'),
751
+ drop_last=False,
752
+ num_workers=2,
753
+ persistent_workers=True,
754
+ sampler=dict(shuffle=False, type='DefaultSampler'))
755
+ val_evaluator = [
756
+ dict(
757
+ ann_file='data/coco/annotations/panoptic_val2017.json',
758
+ backend_args=None,
759
+ seg_prefix='data/coco/annotations/panoptic_val2017/',
760
+ type='CocoPanopticMetric'),
761
+ dict(
762
+ ann_file='data/coco/annotations/instances_val2017.json',
763
+ backend_args=None,
764
+ metric=[
765
+ 'bbox',
766
+ 'segm',
767
+ ],
768
+ type='CocoMetric'),
769
+ ]
770
+ vis_backends = [
771
+ dict(type='LocalVisBackend'),
772
+ ]
773
+ visualizer = dict(
774
+ name='visualizer',
775
+ type='DetLocalVisualizer',
776
+ vis_backends=[
777
+ dict(type='LocalVisBackend'),
778
+ ])
checkpoints/task_networks/pose/ae_hrnet-w32_8xb24-300e_coco-512x512.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ auto_scale_lr = dict(base_batch_size=192)
2
+ backend_args = dict(backend='local')
3
+ codec = dict(
4
+ decode_center_shift=0.5,
5
+ decode_keypoint_order=[
6
+ 0,
7
+ 1,
8
+ 2,
9
+ 3,
10
+ 4,
11
+ 5,
12
+ 6,
13
+ 11,
14
+ 12,
15
+ 7,
16
+ 8,
17
+ 9,
18
+ 10,
19
+ 13,
20
+ 14,
21
+ 15,
22
+ 16,
23
+ ],
24
+ decode_max_instances=30,
25
+ decode_topk=30,
26
+ heatmap_size=(
27
+ 128,
28
+ 128,
29
+ ),
30
+ input_size=(
31
+ 512,
32
+ 512,
33
+ ),
34
+ sigma=2,
35
+ type='AssociativeEmbedding')
36
+ custom_hooks = [
37
+ dict(type='SyncBuffersHook'),
38
+ ]
39
+ data_mode = 'bottomup'
40
+ data_root = 'data/coco/'
41
+ dataset_type = 'CocoDataset'
42
+ default_hooks = dict(
43
+ badcase=dict(
44
+ badcase_thr=5,
45
+ enable=False,
46
+ metric_type='loss',
47
+ out_dir='badcase',
48
+ type='BadCaseAnalysisHook'),
49
+ checkpoint=dict(
50
+ interval=50,
51
+ rule='greater',
52
+ save_best='coco/AP',
53
+ type='CheckpointHook'),
54
+ logger=dict(interval=50, type='LoggerHook'),
55
+ param_scheduler=dict(type='ParamSchedulerHook'),
56
+ sampler_seed=dict(type='DistSamplerSeedHook'),
57
+ timer=dict(type='IterTimerHook'),
58
+ visualization=dict(enable=False, type='PoseVisualizationHook'))
59
+ default_scope = 'mmpose'
60
+ env_cfg = dict(
61
+ cudnn_benchmark=False,
62
+ dist_cfg=dict(backend='nccl'),
63
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0))
64
+ load_from = None
65
+ log_level = 'INFO'
66
+ log_processor = dict(
67
+ by_epoch=True, num_digits=6, type='LogProcessor', window_size=50)
68
+ model = dict(
69
+ backbone=dict(
70
+ extra=dict(
71
+ stage1=dict(
72
+ block='BOTTLENECK',
73
+ num_blocks=(4, ),
74
+ num_branches=1,
75
+ num_channels=(64, ),
76
+ num_modules=1),
77
+ stage2=dict(
78
+ block='BASIC',
79
+ num_blocks=(
80
+ 4,
81
+ 4,
82
+ ),
83
+ num_branches=2,
84
+ num_channels=(
85
+ 32,
86
+ 64,
87
+ ),
88
+ num_modules=1),
89
+ stage3=dict(
90
+ block='BASIC',
91
+ num_blocks=(
92
+ 4,
93
+ 4,
94
+ 4,
95
+ ),
96
+ num_branches=3,
97
+ num_channels=(
98
+ 32,
99
+ 64,
100
+ 128,
101
+ ),
102
+ num_modules=4),
103
+ stage4=dict(
104
+ block='BASIC',
105
+ num_blocks=(
106
+ 4,
107
+ 4,
108
+ 4,
109
+ 4,
110
+ ),
111
+ num_branches=4,
112
+ num_channels=(
113
+ 32,
114
+ 64,
115
+ 128,
116
+ 256,
117
+ ),
118
+ num_modules=3)),
119
+ in_channels=3,
120
+ init_cfg=dict(
121
+ checkpoint=
122
+ 'https://download.openmmlab.com/mmpose/pretrain_models/hrnet_w32-36af842e.pth',
123
+ type='Pretrained'),
124
+ type='HRNet'),
125
+ data_preprocessor=dict(
126
+ bgr_to_rgb=True,
127
+ mean=[
128
+ 123.675,
129
+ 116.28,
130
+ 103.53,
131
+ ],
132
+ std=[
133
+ 58.395,
134
+ 57.12,
135
+ 57.375,
136
+ ],
137
+ type='PoseDataPreprocessor'),
138
+ head=dict(
139
+ decoder=dict(
140
+ decode_center_shift=0.5,
141
+ decode_keypoint_order=[
142
+ 0,
143
+ 1,
144
+ 2,
145
+ 3,
146
+ 4,
147
+ 5,
148
+ 6,
149
+ 11,
150
+ 12,
151
+ 7,
152
+ 8,
153
+ 9,
154
+ 10,
155
+ 13,
156
+ 14,
157
+ 15,
158
+ 16,
159
+ ],
160
+ decode_max_instances=30,
161
+ decode_topk=30,
162
+ heatmap_size=(
163
+ 512,
164
+ 512,
165
+ ),
166
+ input_size=(
167
+ 512,
168
+ 512,
169
+ ),
170
+ sigma=2,
171
+ type='AssociativeEmbedding'),
172
+ deconv_out_channels=None,
173
+ in_channels=32,
174
+ keypoint_loss=dict(type='KeypointMSELoss', use_target_weight=True),
175
+ num_keypoints=17,
176
+ tag_dim=1,
177
+ tag_loss=dict(loss_weight=0.001, type='AssociativeEmbeddingLoss'),
178
+ tag_per_keypoint=True,
179
+ type='AssociativeEmbeddingHead'),
180
+ test_cfg=dict(
181
+ align_corners=False,
182
+ flip_test=True,
183
+ multiscale_test=False,
184
+ restore_heatmap_size=True,
185
+ shift_heatmap=False),
186
+ type='BottomupPoseEstimator')
187
+ optim_wrapper = dict(optimizer=dict(lr=0.0015, type='Adam'))
188
+ param_scheduler = [
189
+ dict(
190
+ begin=0, by_epoch=False, end=500, start_factor=0.001, type='LinearLR'),
191
+ dict(
192
+ begin=0,
193
+ by_epoch=True,
194
+ end=300,
195
+ gamma=0.1,
196
+ milestones=[
197
+ 200,
198
+ 260,
199
+ ],
200
+ type='MultiStepLR'),
201
+ ]
202
+ resume = False
203
+ test_cfg = dict()
204
+ test_dataloader = dict(
205
+ batch_size=1,
206
+ dataset=dict(
207
+ ann_file='annotations/person_keypoints_val2017.json',
208
+ data_mode='bottomup',
209
+ data_prefix=dict(img='val2017/'),
210
+ data_root='data/coco/',
211
+ pipeline=[
212
+ dict(type='LoadImage'),
213
+ dict(
214
+ input_size=(
215
+ 512,
216
+ 512,
217
+ ),
218
+ resize_mode='expand',
219
+ size_factor=64,
220
+ type='BottomupResize'),
221
+ dict(
222
+ meta_keys=(
223
+ 'id',
224
+ 'img_id',
225
+ 'img_path',
226
+ 'crowd_index',
227
+ 'ori_shape',
228
+ 'img_shape',
229
+ 'input_size',
230
+ 'input_center',
231
+ 'input_scale',
232
+ 'flip',
233
+ 'flip_direction',
234
+ 'flip_indices',
235
+ 'raw_ann_info',
236
+ 'skeleton_links',
237
+ ),
238
+ type='PackPoseInputs'),
239
+ ],
240
+ test_mode=True,
241
+ type='CocoDataset'),
242
+ drop_last=False,
243
+ num_workers=2,
244
+ persistent_workers=True,
245
+ sampler=dict(round_up=False, shuffle=False, type='DefaultSampler'))
246
+ test_evaluator = dict(
247
+ ann_file='data/coco/annotations/person_keypoints_val2017.json',
248
+ nms_mode='none',
249
+ score_mode='bbox',
250
+ type='CocoMetric')
251
+ train_cfg = dict(by_epoch=True, max_epochs=300, val_interval=10)
252
+ train_dataloader = dict(
253
+ batch_size=24,
254
+ dataset=dict(
255
+ ann_file='annotations/person_keypoints_train2017.json',
256
+ data_mode='bottomup',
257
+ data_prefix=dict(img='train2017/'),
258
+ data_root='data/coco/',
259
+ pipeline=[],
260
+ type='CocoDataset'),
261
+ num_workers=2,
262
+ persistent_workers=True,
263
+ sampler=dict(shuffle=True, type='DefaultSampler'))
264
+ train_pipeline = []
265
+ val_cfg = dict()
266
+ val_dataloader = dict(
267
+ batch_size=1,
268
+ dataset=dict(
269
+ ann_file='annotations/person_keypoints_val2017.json',
270
+ data_mode='bottomup',
271
+ data_prefix=dict(img='val2017/'),
272
+ data_root='data/coco/',
273
+ pipeline=[
274
+ dict(type='LoadImage'),
275
+ dict(
276
+ input_size=(
277
+ 512,
278
+ 512,
279
+ ),
280
+ resize_mode='expand',
281
+ size_factor=64,
282
+ type='BottomupResize'),
283
+ dict(
284
+ meta_keys=(
285
+ 'id',
286
+ 'img_id',
287
+ 'img_path',
288
+ 'crowd_index',
289
+ 'ori_shape',
290
+ 'img_shape',
291
+ 'input_size',
292
+ 'input_center',
293
+ 'input_scale',
294
+ 'flip',
295
+ 'flip_direction',
296
+ 'flip_indices',
297
+ 'raw_ann_info',
298
+ 'skeleton_links',
299
+ ),
300
+ type='PackPoseInputs'),
301
+ ],
302
+ test_mode=True,
303
+ type='CocoDataset'),
304
+ drop_last=False,
305
+ num_workers=2,
306
+ persistent_workers=True,
307
+ sampler=dict(round_up=False, shuffle=False, type='DefaultSampler'))
308
+ val_evaluator = dict(
309
+ ann_file='data/coco/annotations/person_keypoints_val2017.json',
310
+ nms_mode='none',
311
+ score_mode='bbox',
312
+ type='CocoMetric')
313
+ val_pipeline = [
314
+ dict(type='LoadImage'),
315
+ dict(
316
+ input_size=(
317
+ 512,
318
+ 512,
319
+ ),
320
+ resize_mode='expand',
321
+ size_factor=64,
322
+ type='BottomupResize'),
323
+ dict(
324
+ meta_keys=(
325
+ 'id',
326
+ 'img_id',
327
+ 'img_path',
328
+ 'crowd_index',
329
+ 'ori_shape',
330
+ 'img_shape',
331
+ 'input_size',
332
+ 'input_center',
333
+ 'input_scale',
334
+ 'flip',
335
+ 'flip_direction',
336
+ 'flip_indices',
337
+ 'raw_ann_info',
338
+ 'skeleton_links',
339
+ ),
340
+ type='PackPoseInputs'),
341
+ ]
342
+ vis_backends = [
343
+ dict(type='LocalVisBackend'),
344
+ ]
345
+ visualizer = dict(
346
+ name='visualizer',
347
+ type='PoseLocalVisualizer',
348
+ vis_backends=[
349
+ dict(type='LocalVisBackend'),
350
+ ])
checkpoints/task_networks/semantic/swin-base-patch4-window7-in22k-pre_upernet_8xb2-160k_ade20k-512x512.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ backbone_norm_cfg = dict(requires_grad=True, type='LN')
2
+ checkpoint_file = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_base_patch4_window7_224_22k_20220317-4f79f7c0.pth'
3
+ crop_size = (
4
+ 512,
5
+ 512,
6
+ )
7
+ data_preprocessor = dict(
8
+ bgr_to_rgb=True,
9
+ mean=[
10
+ 123.675,
11
+ 116.28,
12
+ 103.53,
13
+ ],
14
+ pad_val=0,
15
+ seg_pad_val=255,
16
+ size=(
17
+ 512,
18
+ 512,
19
+ ),
20
+ std=[
21
+ 58.395,
22
+ 57.12,
23
+ 57.375,
24
+ ],
25
+ type='SegDataPreProcessor')
26
+ data_root = 'data/ade/ADEChallengeData2016'
27
+ dataset_type = 'ADE20KDataset'
28
+ default_hooks = dict(
29
+ checkpoint=dict(by_epoch=False, interval=16000, type='CheckpointHook'),
30
+ logger=dict(interval=50, log_metric_by_epoch=False, type='LoggerHook'),
31
+ param_scheduler=dict(type='ParamSchedulerHook'),
32
+ sampler_seed=dict(type='DistSamplerSeedHook'),
33
+ timer=dict(type='IterTimerHook'),
34
+ visualization=dict(type='SegVisualizationHook'))
35
+ default_scope = 'mmseg'
36
+ env_cfg = dict(
37
+ cudnn_benchmark=True,
38
+ dist_cfg=dict(backend='nccl'),
39
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0))
40
+ img_ratios = [
41
+ 0.5,
42
+ 0.75,
43
+ 1.0,
44
+ 1.25,
45
+ 1.5,
46
+ 1.75,
47
+ ]
48
+ load_from = None
49
+ log_level = 'INFO'
50
+ log_processor = dict(by_epoch=False)
51
+ model = dict(
52
+ auxiliary_head=dict(
53
+ align_corners=False,
54
+ channels=256,
55
+ concat_input=False,
56
+ dropout_ratio=0.1,
57
+ in_channels=512,
58
+ in_index=2,
59
+ loss_decode=dict(
60
+ loss_weight=0.4, type='CrossEntropyLoss', use_sigmoid=False),
61
+ norm_cfg=dict(requires_grad=True, type='SyncBN'),
62
+ num_classes=150,
63
+ num_convs=1,
64
+ type='FCNHead'),
65
+ backbone=dict(
66
+ act_cfg=dict(type='GELU'),
67
+ attn_drop_rate=0.0,
68
+ depths=[
69
+ 2,
70
+ 2,
71
+ 18,
72
+ 2,
73
+ ],
74
+ drop_path_rate=0.3,
75
+ drop_rate=0.0,
76
+ embed_dims=128,
77
+ init_cfg=dict(
78
+ checkpoint=
79
+ 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_base_patch4_window7_224_22k_20220317-4f79f7c0.pth',
80
+ type='Pretrained'),
81
+ mlp_ratio=4,
82
+ norm_cfg=dict(requires_grad=True, type='LN'),
83
+ num_heads=[
84
+ 4,
85
+ 8,
86
+ 16,
87
+ 32,
88
+ ],
89
+ out_indices=(
90
+ 0,
91
+ 1,
92
+ 2,
93
+ 3,
94
+ ),
95
+ patch_norm=True,
96
+ patch_size=4,
97
+ pretrain_img_size=224,
98
+ qk_scale=None,
99
+ qkv_bias=True,
100
+ strides=(
101
+ 4,
102
+ 2,
103
+ 2,
104
+ 2,
105
+ ),
106
+ type='SwinTransformer',
107
+ use_abs_pos_embed=False,
108
+ window_size=7),
109
+ data_preprocessor=dict(
110
+ bgr_to_rgb=True,
111
+ mean=[
112
+ 123.675,
113
+ 116.28,
114
+ 103.53,
115
+ ],
116
+ pad_val=0,
117
+ seg_pad_val=255,
118
+ size=(
119
+ 512,
120
+ 512,
121
+ ),
122
+ std=[
123
+ 58.395,
124
+ 57.12,
125
+ 57.375,
126
+ ],
127
+ type='SegDataPreProcessor'),
128
+ decode_head=dict(
129
+ align_corners=False,
130
+ channels=512,
131
+ dropout_ratio=0.1,
132
+ in_channels=[
133
+ 128,
134
+ 256,
135
+ 512,
136
+ 1024,
137
+ ],
138
+ in_index=[
139
+ 0,
140
+ 1,
141
+ 2,
142
+ 3,
143
+ ],
144
+ loss_decode=dict(
145
+ loss_weight=1.0, type='CrossEntropyLoss', use_sigmoid=False),
146
+ norm_cfg=dict(requires_grad=True, type='SyncBN'),
147
+ num_classes=150,
148
+ pool_scales=(
149
+ 1,
150
+ 2,
151
+ 3,
152
+ 6,
153
+ ),
154
+ type='UPerHead'),
155
+ pretrained=None,
156
+ test_cfg=dict(mode='whole'),
157
+ train_cfg=dict(),
158
+ type='EncoderDecoder')
159
+ norm_cfg = dict(requires_grad=True, type='SyncBN')
160
+ optim_wrapper = dict(
161
+ optimizer=dict(
162
+ betas=(
163
+ 0.9,
164
+ 0.999,
165
+ ), lr=6e-05, type='AdamW', weight_decay=0.01),
166
+ paramwise_cfg=dict(
167
+ custom_keys=dict(
168
+ absolute_pos_embed=dict(decay_mult=0.0),
169
+ norm=dict(decay_mult=0.0),
170
+ relative_position_bias_table=dict(decay_mult=0.0))),
171
+ type='OptimWrapper')
172
+ optimizer = dict(lr=0.01, momentum=0.9, type='SGD', weight_decay=0.0005)
173
+ param_scheduler = [
174
+ dict(
175
+ begin=0, by_epoch=False, end=1500, start_factor=1e-06,
176
+ type='LinearLR'),
177
+ dict(
178
+ begin=1500,
179
+ by_epoch=False,
180
+ end=160000,
181
+ eta_min=0.0,
182
+ power=1.0,
183
+ type='PolyLR'),
184
+ ]
185
+ resume = False
186
+ test_cfg = dict(type='TestLoop')
187
+ test_dataloader = dict(
188
+ batch_size=1,
189
+ dataset=dict(
190
+ data_prefix=dict(
191
+ img_path='images/validation',
192
+ seg_map_path='annotations/validation'),
193
+ data_root='data/ade/ADEChallengeData2016',
194
+ pipeline=[
195
+ dict(type='LoadImageFromFile'),
196
+ dict(keep_ratio=True, scale=(
197
+ 2048,
198
+ 512,
199
+ ), type='Resize'),
200
+ dict(reduce_zero_label=True, type='LoadAnnotations'),
201
+ dict(type='PackSegInputs'),
202
+ ],
203
+ type='ADE20KDataset'),
204
+ num_workers=4,
205
+ persistent_workers=True,
206
+ sampler=dict(shuffle=False, type='DefaultSampler'))
207
+ test_evaluator = dict(
208
+ iou_metrics=[
209
+ 'mIoU',
210
+ ], type='IoUMetric')
211
+ test_pipeline = [
212
+ dict(type='LoadImageFromFile'),
213
+ dict(keep_ratio=True, scale=(
214
+ 2048,
215
+ 512,
216
+ ), type='Resize'),
217
+ dict(reduce_zero_label=True, type='LoadAnnotations'),
218
+ dict(type='PackSegInputs'),
219
+ ]
220
+ train_cfg = dict(
221
+ max_iters=160000, type='IterBasedTrainLoop', val_interval=16000)
222
+ train_dataloader = dict(
223
+ batch_size=2,
224
+ dataset=dict(
225
+ data_prefix=dict(
226
+ img_path='images/training', seg_map_path='annotations/training'),
227
+ data_root='data/ade/ADEChallengeData2016',
228
+ pipeline=[
229
+ dict(type='LoadImageFromFile'),
230
+ dict(reduce_zero_label=True, type='LoadAnnotations'),
231
+ dict(
232
+ keep_ratio=True,
233
+ ratio_range=(
234
+ 0.5,
235
+ 2.0,
236
+ ),
237
+ scale=(
238
+ 2048,
239
+ 512,
240
+ ),
241
+ type='RandomResize'),
242
+ dict(
243
+ cat_max_ratio=0.75, crop_size=(
244
+ 512,
245
+ 512,
246
+ ), type='RandomCrop'),
247
+ dict(prob=0.5, type='RandomFlip'),
248
+ dict(type='PhotoMetricDistortion'),
249
+ dict(type='PackSegInputs'),
250
+ ],
251
+ type='ADE20KDataset'),
252
+ num_workers=4,
253
+ persistent_workers=True,
254
+ sampler=dict(shuffle=True, type='InfiniteSampler'))
255
+ train_pipeline = [
256
+ dict(type='LoadImageFromFile'),
257
+ dict(reduce_zero_label=True, type='LoadAnnotations'),
258
+ dict(
259
+ keep_ratio=True,
260
+ ratio_range=(
261
+ 0.5,
262
+ 2.0,
263
+ ),
264
+ scale=(
265
+ 2048,
266
+ 512,
267
+ ),
268
+ type='RandomResize'),
269
+ dict(cat_max_ratio=0.75, crop_size=(
270
+ 512,
271
+ 512,
272
+ ), type='RandomCrop'),
273
+ dict(prob=0.5, type='RandomFlip'),
274
+ dict(type='PhotoMetricDistortion'),
275
+ dict(type='PackSegInputs'),
276
+ ]
277
+ tta_model = dict(type='SegTTAModel')
278
+ tta_pipeline = [
279
+ dict(backend_args=None, type='LoadImageFromFile'),
280
+ dict(
281
+ transforms=[
282
+ [
283
+ dict(keep_ratio=True, scale_factor=0.5, type='Resize'),
284
+ dict(keep_ratio=True, scale_factor=0.75, type='Resize'),
285
+ dict(keep_ratio=True, scale_factor=1.0, type='Resize'),
286
+ dict(keep_ratio=True, scale_factor=1.25, type='Resize'),
287
+ dict(keep_ratio=True, scale_factor=1.5, type='Resize'),
288
+ dict(keep_ratio=True, scale_factor=1.75, type='Resize'),
289
+ ],
290
+ [
291
+ dict(direction='horizontal', prob=0.0, type='RandomFlip'),
292
+ dict(direction='horizontal', prob=1.0, type='RandomFlip'),
293
+ ],
294
+ [
295
+ dict(type='LoadAnnotations'),
296
+ ],
297
+ [
298
+ dict(type='PackSegInputs'),
299
+ ],
300
+ ],
301
+ type='TestTimeAug'),
302
+ ]
303
+ val_cfg = dict(type='ValLoop')
304
+ val_dataloader = dict(
305
+ batch_size=1,
306
+ dataset=dict(
307
+ data_prefix=dict(
308
+ img_path='images/validation',
309
+ seg_map_path='annotations/validation'),
310
+ data_root='data/ade/ADEChallengeData2016',
311
+ pipeline=[
312
+ dict(type='LoadImageFromFile'),
313
+ dict(keep_ratio=True, scale=(
314
+ 2048,
315
+ 512,
316
+ ), type='Resize'),
317
+ dict(reduce_zero_label=True, type='LoadAnnotations'),
318
+ dict(type='PackSegInputs'),
319
+ ],
320
+ type='ADE20KDataset'),
321
+ num_workers=4,
322
+ persistent_workers=True,
323
+ sampler=dict(shuffle=False, type='DefaultSampler'))
324
+ val_evaluator = dict(
325
+ iou_metrics=[
326
+ 'mIoU',
327
+ ], type='IoUMetric')
328
+ vis_backends = [
329
+ dict(type='LocalVisBackend'),
330
+ ]
331
+ visualizer = dict(
332
+ name='visualizer',
333
+ type='SegLocalVisualizer',
334
+ vis_backends=[
335
+ dict(type='LocalVisBackend'),
336
+ ])
configs/ctaic/s1_det_instance.yaml CHANGED
@@ -2,7 +2,7 @@
2
  root: "logs"
3
  exp_name: "ctaic_s1"
4
  scenario: "s1"
5
- dataset_path: "/data/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  # trained base-layer TAIC for detection (provides y_b_hat)
8
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
@@ -24,3 +24,8 @@ seed: 42
24
  pretrained_backbone: true
25
  out_channels: 128 # extension = Cascade Mask R-CNN + Swin-B
26
  align_mode: "fpn"
 
 
 
 
 
 
2
  root: "logs"
3
  exp_name: "ctaic_s1"
4
  scenario: "s1"
5
+ dataset_path: "/data/Dataset/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  # trained base-layer TAIC for detection (provides y_b_hat)
8
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
 
24
  pretrained_backbone: true
25
  out_channels: 128 # extension = Cascade Mask R-CNN + Swin-B
26
  align_mode: "fpn"
27
+
28
+ # Official task-network teacher (backbone/neck) for feature alignment D
29
+ use_official_teacher: true
30
+ task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
31
+ task_checkpoint: "./checkpoints/task_networks/instance/model_mmdet3.pth"
configs/ctaic/s2_sem_panoptic.yaml CHANGED
@@ -2,7 +2,7 @@
2
  root: "logs"
3
  exp_name: "ctaic_s2"
4
  scenario: "s2"
5
- dataset_path: "/data/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  base_taic_checkpoint: "./checkpoints/taic/semantic/1/checkpoint_best_loss.pth.tar"
8
  taic_init: "./checkpoints/taic/panoptic/1/checkpoint_best_loss.pth.tar"
@@ -20,3 +20,8 @@ cuda: true
20
  save: true
21
  seed: 42
22
  pretrained_backbone: true
 
 
 
 
 
 
2
  root: "logs"
3
  exp_name: "ctaic_s2"
4
  scenario: "s2"
5
+ dataset_path: "/data/Dataset/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  base_taic_checkpoint: "./checkpoints/taic/semantic/1/checkpoint_best_loss.pth.tar"
8
  taic_init: "./checkpoints/taic/panoptic/1/checkpoint_best_loss.pth.tar"
 
20
  save: true
21
  seed: 42
22
  pretrained_backbone: true
23
+
24
+ # Official task-network teacher (backbone/neck) for feature alignment D
25
+ use_official_teacher: true
26
+ task_config: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic.py"
27
+ task_checkpoint: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic_20220329_230021-05ec7315.pth"
configs/ctaic/s3_det_pose.yaml CHANGED
@@ -2,7 +2,7 @@
2
  root: "logs"
3
  exp_name: "ctaic_s3"
4
  scenario: "s3"
5
- dataset_path: "/data/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
8
  taic_init: "./checkpoints/taic/pose/1/checkpoint_best_loss.pth.tar"
@@ -22,3 +22,8 @@ seed: 42
22
  pretrained_backbone: true
23
  out_channels: 32
24
  align_mode: "stages"
 
 
 
 
 
 
2
  root: "logs"
3
  exp_name: "ctaic_s3"
4
  scenario: "s3"
5
+ dataset_path: "/data/Dataset/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
8
  taic_init: "./checkpoints/taic/pose/1/checkpoint_best_loss.pth.tar"
 
22
  pretrained_backbone: true
23
  out_channels: 32
24
  align_mode: "stages"
25
+
26
+ # Official task-network teacher (backbone/neck) for feature alignment D
27
+ use_official_teacher: true
28
+ task_config: "./checkpoints/task_networks/pose/ae_hrnet-w32_8xb24-300e_coco-512x512.py"
29
+ task_checkpoint: "./checkpoints/task_networks/pose/hrnet_w32_coco_512x512-bcb8c247_20200816.pth"
configs/eval/ctaic_s1.yaml CHANGED
@@ -1,5 +1,5 @@
1
  scenario: "s1"
2
- dataset_path: "/data/coco2017"
3
  split: "val2017"
4
  ann_file: "annotations/instances_val2017.json"
5
  quality_level: 1
@@ -7,10 +7,13 @@ lmbda: 0.0035
7
  checkpoint: "./checkpoints/ctaic/s1_det_instance/stage2/1/checkpoint_best_loss.pth.tar"
8
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
- task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
11
- task_checkpoint: "./checkpoints/task_networks/instance/model.pth"
12
  gpu_id: 0
13
  cuda: true
14
  test_batch_size: 1
15
  num_workers: 4
16
  pretrained_backbone: true
 
 
 
 
 
 
1
  scenario: "s1"
2
+ dataset_path: "/data/Dataset/coco2017"
3
  split: "val2017"
4
  ann_file: "annotations/instances_val2017.json"
5
  quality_level: 1
 
7
  checkpoint: "./checkpoints/ctaic/s1_det_instance/stage2/1/checkpoint_best_loss.pth.tar"
8
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
 
 
10
  gpu_id: 0
11
  cuda: true
12
  test_batch_size: 1
13
  num_workers: 4
14
  pretrained_backbone: true
15
+
16
+ # Official task-network teacher (backbone/neck) for feature alignment D
17
+ use_official_teacher: true
18
+ task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
19
+ task_checkpoint: "./checkpoints/task_networks/instance/model_mmdet3.pth"
configs/eval/ctaic_s2.yaml CHANGED
@@ -1,5 +1,5 @@
1
  scenario: "s2"
2
- dataset_path: "/data/coco2017"
3
  split: "val2017"
4
  ann_file: "annotations/panoptic_val2017.json"
5
  quality_level: 1
@@ -7,11 +7,14 @@ lmbda: 0.0035
7
  checkpoint: "./checkpoints/ctaic/s2_sem_panoptic/stage2/1/checkpoint_best_loss.pth.tar"
8
  base_taic_checkpoint: "./checkpoints/taic/semantic/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
- task_config: "./configs/task_networks/maskformer_swin-b_coco.py"
11
- task_checkpoint: "./checkpoints/task_networks/panoptic/model.pth"
12
  panoptic_gt_folder: "/data/coco2017/annotations/panoptic_val2017"
13
  gpu_id: 0
14
  cuda: true
15
  test_batch_size: 1
16
  num_workers: 4
17
  pretrained_backbone: true
 
 
 
 
 
 
1
  scenario: "s2"
2
+ dataset_path: "/data/Dataset/coco2017"
3
  split: "val2017"
4
  ann_file: "annotations/panoptic_val2017.json"
5
  quality_level: 1
 
7
  checkpoint: "./checkpoints/ctaic/s2_sem_panoptic/stage2/1/checkpoint_best_loss.pth.tar"
8
  base_taic_checkpoint: "./checkpoints/taic/semantic/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
 
 
10
  panoptic_gt_folder: "/data/coco2017/annotations/panoptic_val2017"
11
  gpu_id: 0
12
  cuda: true
13
  test_batch_size: 1
14
  num_workers: 4
15
  pretrained_backbone: true
16
+
17
+ # Official task-network teacher (backbone/neck) for feature alignment D
18
+ use_official_teacher: true
19
+ task_config: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic.py"
20
+ task_checkpoint: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic_20220329_230021-05ec7315.pth"
configs/eval/ctaic_s3.yaml CHANGED
@@ -1,5 +1,5 @@
1
  scenario: "s3"
2
- dataset_path: "/data/coco2017"
3
  split: "val2017"
4
  ann_file: "annotations/coco_wholebody_val_v1.0.json"
5
  quality_level: 1
@@ -7,10 +7,13 @@ lmbda: 0.0035
7
  checkpoint: "./checkpoints/ctaic/s3_det_pose/stage2/1/checkpoint_best_loss.pth.tar"
8
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
- task_config: "./configs/task_networks/higherhrnet_w32_coco_wholebody.py"
11
- task_checkpoint: "./checkpoints/task_networks/pose/model.pth"
12
  gpu_id: 0
13
  cuda: true
14
  test_batch_size: 1
15
  num_workers: 4
16
  pretrained_backbone: true
 
 
 
 
 
 
1
  scenario: "s3"
2
+ dataset_path: "/data/Dataset/coco2017"
3
  split: "val2017"
4
  ann_file: "annotations/coco_wholebody_val_v1.0.json"
5
  quality_level: 1
 
7
  checkpoint: "./checkpoints/ctaic/s3_det_pose/stage2/1/checkpoint_best_loss.pth.tar"
8
  base_taic_checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
 
 
10
  gpu_id: 0
11
  cuda: true
12
  test_batch_size: 1
13
  num_workers: 4
14
  pretrained_backbone: true
15
+
16
+ # Official task-network teacher (backbone/neck) for feature alignment D
17
+ use_official_teacher: true
18
+ task_config: "./checkpoints/task_networks/pose/ae_hrnet-w32_8xb24-300e_coco-512x512.py"
19
+ task_checkpoint: "./checkpoints/task_networks/pose/hrnet_w32_coco_512x512-bcb8c247_20200816.pth"
configs/eval/taic_detection.yaml CHANGED
@@ -1,17 +1,20 @@
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "detection"
3
- dataset_path: "/data/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/instances_val2017.json"
6
  quality_level: 1
7
  lmbda: 0.0035
8
- checkpoint: "./checkpoints/taic/detection/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
11
- task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
12
- task_checkpoint: "./checkpoints/task_networks/detection/model.pth"
13
  gpu_id: 0
14
  cuda: true
15
  test_batch_size: 1
16
  num_workers: 4
17
  pretrained_backbone: true
 
 
 
 
 
 
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "detection"
3
+ dataset_path: "/data/Dataset/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/instances_val2017.json"
6
  quality_level: 1
7
  lmbda: 0.0035
8
+ checkpoint: "./logs/taic_detection/1/checkpoint_0.1040.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
 
 
11
  gpu_id: 0
12
  cuda: true
13
  test_batch_size: 1
14
  num_workers: 4
15
  pretrained_backbone: true
16
+
17
+ # Official task-network teacher (backbone/neck) for feature alignment D
18
+ use_official_teacher: true
19
+ task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
20
+ task_checkpoint: "./checkpoints/task_networks/detection/model_mmdet3.pth"
configs/eval/taic_instance.yaml CHANGED
@@ -1,6 +1,6 @@
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "instance"
3
- dataset_path: "/data/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/instances_val2017.json"
6
  quality_level: 1
@@ -8,10 +8,13 @@ lmbda: 0.0035
8
  checkpoint: "./checkpoints/taic/instance/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
11
- task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
12
- task_checkpoint: "./checkpoints/task_networks/instance/model.pth"
13
  gpu_id: 0
14
  cuda: true
15
  test_batch_size: 1
16
  num_workers: 4
17
  pretrained_backbone: true
 
 
 
 
 
 
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "instance"
3
+ dataset_path: "/data/Dataset/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/instances_val2017.json"
6
  quality_level: 1
 
8
  checkpoint: "./checkpoints/taic/instance/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
 
 
11
  gpu_id: 0
12
  cuda: true
13
  test_batch_size: 1
14
  num_workers: 4
15
  pretrained_backbone: true
16
+
17
+ # Official task-network teacher (backbone/neck) for feature alignment D
18
+ use_official_teacher: true
19
+ task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
20
+ task_checkpoint: "./checkpoints/task_networks/instance/model_mmdet3.pth"
configs/eval/taic_panoptic.yaml CHANGED
@@ -1,6 +1,6 @@
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "panoptic"
3
- dataset_path: "/data/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/panoptic_val2017.json"
6
  quality_level: 1
@@ -8,10 +8,13 @@ lmbda: 0.0035
8
  checkpoint: "./checkpoints/taic/panoptic/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
11
- task_config: "./configs/task_networks/maskformer_swin-b_coco.py"
12
- task_checkpoint: "./checkpoints/task_networks/panoptic/model.pth"
13
  gpu_id: 0
14
  cuda: true
15
  test_batch_size: 1
16
  num_workers: 4
17
  pretrained_backbone: true
 
 
 
 
 
 
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "panoptic"
3
+ dataset_path: "/data/Dataset/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/panoptic_val2017.json"
6
  quality_level: 1
 
8
  checkpoint: "./checkpoints/taic/panoptic/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
 
 
11
  gpu_id: 0
12
  cuda: true
13
  test_batch_size: 1
14
  num_workers: 4
15
  pretrained_backbone: true
16
+
17
+ # Official task-network teacher (backbone/neck) for feature alignment D
18
+ use_official_teacher: true
19
+ task_config: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic.py"
20
+ task_checkpoint: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic_20220329_230021-05ec7315.pth"
configs/eval/taic_pose.yaml CHANGED
@@ -1,6 +1,6 @@
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "pose"
3
- dataset_path: "/data/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/coco_wholebody_val_v1.0.json"
6
  quality_level: 1
@@ -8,10 +8,13 @@ lmbda: 0.0035
8
  checkpoint: "./checkpoints/taic/pose/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
11
- task_config: "./configs/task_networks/higherhrnet_w32_coco_wholebody.py"
12
- task_checkpoint: "./checkpoints/task_networks/pose/model.pth"
13
  gpu_id: 0
14
  cuda: true
15
  test_batch_size: 1
16
  num_workers: 4
17
  pretrained_backbone: true
 
 
 
 
 
 
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "pose"
3
+ dataset_path: "/data/Dataset/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/coco_wholebody_val_v1.0.json"
6
  quality_level: 1
 
8
  checkpoint: "./checkpoints/taic/pose/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
 
 
11
  gpu_id: 0
12
  cuda: true
13
  test_batch_size: 1
14
  num_workers: 4
15
  pretrained_backbone: true
16
+
17
+ # Official task-network teacher (backbone/neck) for feature alignment D
18
+ use_official_teacher: true
19
+ task_config: "./checkpoints/task_networks/pose/ae_hrnet-w32_8xb24-300e_coco-512x512.py"
20
+ task_checkpoint: "./checkpoints/task_networks/pose/hrnet_w32_coco_512x512-bcb8c247_20200816.pth"
configs/eval/taic_semantic.yaml CHANGED
@@ -1,6 +1,6 @@
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "semantic"
3
- dataset_path: "/data/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/panoptic_val2017.json"
6
  quality_level: 1
@@ -8,10 +8,13 @@ lmbda: 0.0035
8
  checkpoint: "./checkpoints/taic/semantic/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
11
- task_config: "./configs/task_networks/upernet_swin-b_coco.py"
12
- task_checkpoint: "./checkpoints/task_networks/semantic/model.pth"
13
  gpu_id: 0
14
  cuda: true
15
  test_batch_size: 1
16
  num_workers: 4
17
  pretrained_backbone: true
 
 
 
 
 
 
1
  # TAIC eval: codec test + optional --with-metrics
2
  task: "semantic"
3
+ dataset_path: "/data/Dataset/coco2017"
4
  split: "val2017"
5
  ann_file: "annotations/panoptic_val2017.json"
6
  quality_level: 1
 
8
  checkpoint: "./checkpoints/taic/semantic/1/checkpoint_best_loss.pth.tar"
9
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
10
  # official task network (required for --with-metrics)
 
 
11
  gpu_id: 0
12
  cuda: true
13
  test_batch_size: 1
14
  num_workers: 4
15
  pretrained_backbone: true
16
+
17
+ # Official task-network teacher (backbone/neck) for feature alignment D
18
+ use_official_teacher: true
19
+ task_config: "./checkpoints/task_networks/semantic/swin-base-patch4-window7-in22k-pre_upernet_8xb2-160k_ade20k-512x512.py"
20
+ task_checkpoint: "./checkpoints/task_networks/semantic/upernet_swin_base_patch4_window7_512x512_160k_ade20k_pretrain_224x224_22K_20210526_211650-762e2178.pth"
configs/taic/detection.yaml CHANGED
@@ -2,17 +2,18 @@
2
  root: "logs"
3
  exp_name: "taic_detection"
4
  task: "detection"
5
- dataset_path: "/data/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar" # quality matches lmbda mapping
7
- checkpoint: null
8
- epochs: 35
 
9
  learning_rate: 1.0e-4
10
  gpu_id: 0
11
  quality_level: 1
12
  # paper lambda set: {0.0035, 0.0067, 0.0130, 0.0250}
13
- lmbda: 0.0035
14
  num_workers: 8
15
- batch_size: 80
16
  test_batch_size: 1
17
  patch_size: 256
18
  cuda: true
@@ -21,3 +22,8 @@ seed: 42
21
  pretrained_backbone: true
22
  out_channels: 128
23
  align_mode: "fpn"
 
 
 
 
 
 
2
  root: "logs"
3
  exp_name: "taic_detection"
4
  task: "detection"
5
+ dataset_path: "/data/Dataset/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar" # quality matches lmbda mapping
7
+ checkpoint: null # "./logs/taic_detection/1/checkpoint_60.pth.tar"
8
+ freeze_base_codec: false # false = fine-tune the entire TIC + SFMA + Task Connector
9
+ epochs: 999
10
  learning_rate: 1.0e-4
11
  gpu_id: 0
12
  quality_level: 1
13
  # paper lambda set: {0.0035, 0.0067, 0.0130, 0.0250}
14
+ lmbda: 0.2050
15
  num_workers: 8
16
+ batch_size: 32
17
  test_batch_size: 1
18
  patch_size: 256
19
  cuda: true
 
22
  pretrained_backbone: true
23
  out_channels: 128
24
  align_mode: "fpn"
25
+
26
+ # Official task-network teacher (backbone/neck) for feature alignment D
27
+ use_official_teacher: true
28
+ task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
29
+ task_checkpoint: "./checkpoints/task_networks/detection/model_mmdet3.pth"
configs/taic/instance.yaml CHANGED
@@ -2,7 +2,7 @@
2
  root: "logs"
3
  exp_name: "taic_instance"
4
  task: "instance"
5
- dataset_path: "/data/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  checkpoint: null
8
  epochs: 35
@@ -20,3 +20,8 @@ seed: 42
20
  pretrained_backbone: true
21
  out_channels: 128 # Cascade Mask R-CNN + Swin-B F1
22
  align_mode: "fpn"
 
 
 
 
 
 
2
  root: "logs"
3
  exp_name: "taic_instance"
4
  task: "instance"
5
+ dataset_path: "/data/Dataset/coco2017"
6
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
7
  checkpoint: null
8
  epochs: 35
 
20
  pretrained_backbone: true
21
  out_channels: 128 # Cascade Mask R-CNN + Swin-B F1
22
  align_mode: "fpn"
23
+
24
+ # Official task-network teacher (backbone/neck) for feature alignment D
25
+ use_official_teacher: true
26
+ task_config: "./configs/task_networks/cascade_mask_rcnn_swin_base_coco.py"
27
+ task_checkpoint: "./checkpoints/task_networks/instance/model_mmdet3.pth"
configs/taic/panoptic.yaml CHANGED
@@ -1,7 +1,7 @@
1
  root: "logs"
2
  exp_name: "taic_panoptic"
3
  task: "panoptic"
4
- dataset_path: "/data/coco2017"
5
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
6
  checkpoint: null
7
  epochs: 35
@@ -19,3 +19,8 @@ seed: 42
19
  pretrained_backbone: true
20
  out_channels: 128
21
  align_mode: "stages"
 
 
 
 
 
 
1
  root: "logs"
2
  exp_name: "taic_panoptic"
3
  task: "panoptic"
4
+ dataset_path: "/data/Dataset/coco2017"
5
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
6
  checkpoint: null
7
  epochs: 35
 
19
  pretrained_backbone: true
20
  out_channels: 128
21
  align_mode: "stages"
22
+
23
+ # Official task-network teacher (backbone/neck) for feature alignment D
24
+ use_official_teacher: true
25
+ task_config: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic.py"
26
+ task_checkpoint: "./checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic_20220329_230021-05ec7315.pth"
configs/taic/pose.yaml CHANGED
@@ -1,7 +1,7 @@
1
  root: "logs"
2
  exp_name: "taic_pose"
3
  task: "pose"
4
- dataset_path: "/data/coco2017"
5
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
6
  checkpoint: null
7
  epochs: 35
@@ -19,3 +19,8 @@ seed: 42
19
  pretrained_backbone: true
20
  out_channels: 32
21
  align_mode: "stages"
 
 
 
 
 
 
1
  root: "logs"
2
  exp_name: "taic_pose"
3
  task: "pose"
4
+ dataset_path: "/data/Dataset/coco2017"
5
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
6
  checkpoint: null
7
  epochs: 35
 
19
  pretrained_backbone: true
20
  out_channels: 32
21
  align_mode: "stages"
22
+
23
+ # Official task-network teacher (backbone/neck) for feature alignment D
24
+ use_official_teacher: true
25
+ task_config: "./checkpoints/task_networks/pose/ae_hrnet-w32_8xb24-300e_coco-512x512.py"
26
+ task_checkpoint: "./checkpoints/task_networks/pose/hrnet_w32_coco_512x512-bcb8c247_20200816.pth"
configs/taic/semantic.yaml CHANGED
@@ -1,7 +1,7 @@
1
  root: "logs"
2
  exp_name: "taic_semantic"
3
  task: "semantic"
4
- dataset_path: "/data/coco2017"
5
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
6
  checkpoint: null
7
  epochs: 35
@@ -19,3 +19,8 @@ seed: 42
19
  pretrained_backbone: true
20
  out_channels: 128
21
  align_mode: "fpn"
 
 
 
 
 
 
1
  root: "logs"
2
  exp_name: "taic_semantic"
3
  task: "semantic"
4
+ dataset_path: "/data/Dataset/coco2017"
5
  base_codec: "./checkpoints/base_codec/base_codec_1.pth.tar"
6
  checkpoint: null
7
  epochs: 35
 
19
  pretrained_backbone: true
20
  out_channels: 128
21
  align_mode: "fpn"
22
+
23
+ # Official task-network teacher (backbone/neck) for feature alignment D
24
+ use_official_teacher: true
25
+ task_config: "./checkpoints/task_networks/semantic/swin-base-patch4-window7-in22k-pre_upernet_8xb2-160k_ade20k-512x512.py"
26
+ task_checkpoint: "./checkpoints/task_networks/semantic/upernet_swin_base_patch4_window7_512x512_160k_ade20k_pretrain_224x224_22K_20210526_211650-762e2178.pth"
configs/task_networks/cascade_mask_rcnn_swin_base_coco.py CHANGED
@@ -1,19 +1,251 @@
1
- # STUB / pointer config for Cascade Mask R-CNN + Swin-B (official Swin detection zoo).
2
- #
3
- # Source repo: https://github.com/SwinTransformer/Swin-Transformer-Object-Detection
4
- # Official config:
5
- # configs/swin/cascade_mask_rcnn_swin_base_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py
6
- # Official checkpoint:
7
- # https://github.com/SwinTransformer/storage/releases/download/v1.0.2/cascade_mask_rcnn_swin_base_patch4_window7.pth
8
- #
9
- # Replace this file by copying/symlinking the real config from that repo, then set
10
- # task_checkpoint to the downloaded .pth under checkpoints/task_networks/detection/.
11
- #
12
- # Used for FlexICM detection (mAP-bbox) and instance segmentation (mAP-mask).
13
- # Backbone F1 channels = 128 (Swin-B).
14
 
15
- raise RuntimeError(
16
- "Replace configs/task_networks/cascade_mask_rcnn_swin_base_coco.py with the official "
17
- "Swin-Transformer-Object-Detection config: "
18
- "cascade_mask_rcnn_swin_base_patch4_window7_mstrain_480-800_giou_4conv1f_adamw_3x_coco.py"
19
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cascade Mask R-CNN + Swin-B for FlexICM metric eval (mmdet 3.x).
2
+ # Matches the official Swin-Transformer-Object-Detection paper checkpoint:
3
+ # cascade_mask_rcnn_swin_base_patch4_window7.pth
4
+ # Use the converted weights:
5
+ # checkpoints/task_networks/detection/model_mmdet3.pth
6
+ # (produced by scripts/convert_swin_det_ckpt_to_mmdet3.py)
 
 
 
 
 
 
 
7
 
8
+ _base_ = [] # self-contained for FlexICM
9
+
10
+ model = dict(
11
+ type='CascadeRCNN',
12
+ data_preprocessor=dict(
13
+ type='DetDataPreprocessor',
14
+ mean=[123.675, 116.28, 103.53],
15
+ std=[58.395, 57.12, 57.375],
16
+ bgr_to_rgb=True,
17
+ pad_mask=True,
18
+ pad_size_divisor=32),
19
+ backbone=dict(
20
+ type='SwinTransformer',
21
+ embed_dims=128,
22
+ depths=[2, 2, 18, 2],
23
+ num_heads=[4, 8, 16, 32],
24
+ window_size=7,
25
+ mlp_ratio=4,
26
+ qkv_bias=True,
27
+ qk_scale=None,
28
+ drop_rate=0.0,
29
+ attn_drop_rate=0.0,
30
+ drop_path_rate=0.3,
31
+ patch_norm=True,
32
+ out_indices=(0, 1, 2, 3),
33
+ with_cp=False,
34
+ convert_weights=False,
35
+ init_cfg=None),
36
+ neck=dict(
37
+ type='FPN',
38
+ in_channels=[128, 256, 512, 1024],
39
+ out_channels=256,
40
+ num_outs=5),
41
+ rpn_head=dict(
42
+ type='RPNHead',
43
+ in_channels=256,
44
+ feat_channels=256,
45
+ anchor_generator=dict(
46
+ type='AnchorGenerator',
47
+ scales=[8],
48
+ ratios=[0.5, 1.0, 2.0],
49
+ strides=[4, 8, 16, 32, 64]),
50
+ bbox_coder=dict(
51
+ type='DeltaXYWHBBoxCoder',
52
+ target_means=[.0, .0, .0, .0],
53
+ target_stds=[1.0, 1.0, 1.0, 1.0]),
54
+ loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0),
55
+ loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
56
+ roi_head=dict(
57
+ type='CascadeRoIHead',
58
+ num_stages=3,
59
+ stage_loss_weights=[1, 0.5, 0.25],
60
+ bbox_roi_extractor=dict(
61
+ type='SingleRoIExtractor',
62
+ roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
63
+ out_channels=256,
64
+ featmap_strides=[4, 8, 16, 32]),
65
+ bbox_head=[
66
+ dict(
67
+ type='Shared4Conv1FCBBoxHead',
68
+ in_channels=256,
69
+ conv_out_channels=256,
70
+ fc_out_channels=1024,
71
+ roi_feat_size=7,
72
+ num_classes=80,
73
+ bbox_coder=dict(
74
+ type='DeltaXYWHBBoxCoder',
75
+ target_means=[0.0, 0.0, 0.0, 0.0],
76
+ target_stds=[0.1, 0.1, 0.2, 0.2]),
77
+ reg_class_agnostic=False,
78
+ reg_decoded_bbox=True,
79
+ norm_cfg=dict(type='BN', requires_grad=True),
80
+ loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
81
+ loss_bbox=dict(type='GIoULoss', loss_weight=10.0)),
82
+ dict(
83
+ type='Shared4Conv1FCBBoxHead',
84
+ in_channels=256,
85
+ conv_out_channels=256,
86
+ fc_out_channels=1024,
87
+ roi_feat_size=7,
88
+ num_classes=80,
89
+ bbox_coder=dict(
90
+ type='DeltaXYWHBBoxCoder',
91
+ target_means=[0.0, 0.0, 0.0, 0.0],
92
+ target_stds=[0.05, 0.05, 0.1, 0.1]),
93
+ reg_class_agnostic=False,
94
+ reg_decoded_bbox=True,
95
+ norm_cfg=dict(type='BN', requires_grad=True),
96
+ loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
97
+ loss_bbox=dict(type='GIoULoss', loss_weight=10.0)),
98
+ dict(
99
+ type='Shared4Conv1FCBBoxHead',
100
+ in_channels=256,
101
+ conv_out_channels=256,
102
+ fc_out_channels=1024,
103
+ roi_feat_size=7,
104
+ num_classes=80,
105
+ bbox_coder=dict(
106
+ type='DeltaXYWHBBoxCoder',
107
+ target_means=[0.0, 0.0, 0.0, 0.0],
108
+ target_stds=[0.033, 0.033, 0.067, 0.067]),
109
+ reg_class_agnostic=False,
110
+ reg_decoded_bbox=True,
111
+ norm_cfg=dict(type='BN', requires_grad=True),
112
+ loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0),
113
+ loss_bbox=dict(type='GIoULoss', loss_weight=10.0)),
114
+ ],
115
+ mask_roi_extractor=dict(
116
+ type='SingleRoIExtractor',
117
+ roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0),
118
+ out_channels=256,
119
+ featmap_strides=[4, 8, 16, 32]),
120
+ mask_head=[
121
+ dict(
122
+ type='FCNMaskHead',
123
+ num_convs=4,
124
+ in_channels=256,
125
+ conv_out_channels=256,
126
+ num_classes=80,
127
+ loss_mask=dict(type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)),
128
+ dict(
129
+ type='FCNMaskHead',
130
+ num_convs=4,
131
+ in_channels=256,
132
+ conv_out_channels=256,
133
+ num_classes=80,
134
+ loss_mask=dict(type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)),
135
+ dict(
136
+ type='FCNMaskHead',
137
+ num_convs=4,
138
+ in_channels=256,
139
+ conv_out_channels=256,
140
+ num_classes=80,
141
+ loss_mask=dict(type='CrossEntropyLoss', use_mask=True, loss_weight=1.0)),
142
+ ]),
143
+ train_cfg=dict(
144
+ rpn=dict(
145
+ assigner=dict(
146
+ type='MaxIoUAssigner',
147
+ pos_iou_thr=0.7,
148
+ neg_iou_thr=0.3,
149
+ min_pos_iou=0.3,
150
+ match_low_quality=True,
151
+ ignore_iof_thr=-1),
152
+ sampler=dict(
153
+ type='RandomSampler',
154
+ num=256,
155
+ pos_fraction=0.5,
156
+ neg_pos_ub=-1,
157
+ add_gt_as_proposals=False),
158
+ allowed_border=0,
159
+ pos_weight=-1,
160
+ debug=False),
161
+ rpn_proposal=dict(
162
+ nms_pre=2000,
163
+ max_per_img=2000,
164
+ nms=dict(type='nms', iou_threshold=0.7),
165
+ min_bbox_size=0),
166
+ rcnn=[
167
+ dict(
168
+ assigner=dict(
169
+ type='MaxIoUAssigner',
170
+ pos_iou_thr=0.5,
171
+ neg_iou_thr=0.5,
172
+ min_pos_iou=0.5,
173
+ match_low_quality=False,
174
+ ignore_iof_thr=-1),
175
+ sampler=dict(
176
+ type='RandomSampler',
177
+ num=512,
178
+ pos_fraction=0.25,
179
+ neg_pos_ub=-1,
180
+ add_gt_as_proposals=True),
181
+ mask_size=28,
182
+ pos_weight=-1,
183
+ debug=False),
184
+ dict(
185
+ assigner=dict(
186
+ type='MaxIoUAssigner',
187
+ pos_iou_thr=0.6,
188
+ neg_iou_thr=0.6,
189
+ min_pos_iou=0.6,
190
+ match_low_quality=False,
191
+ ignore_iof_thr=-1),
192
+ sampler=dict(
193
+ type='RandomSampler',
194
+ num=512,
195
+ pos_fraction=0.25,
196
+ neg_pos_ub=-1,
197
+ add_gt_as_proposals=True),
198
+ mask_size=28,
199
+ pos_weight=-1,
200
+ debug=False),
201
+ dict(
202
+ assigner=dict(
203
+ type='MaxIoUAssigner',
204
+ pos_iou_thr=0.7,
205
+ neg_iou_thr=0.7,
206
+ min_pos_iou=0.7,
207
+ match_low_quality=False,
208
+ ignore_iof_thr=-1),
209
+ sampler=dict(
210
+ type='RandomSampler',
211
+ num=512,
212
+ pos_fraction=0.25,
213
+ neg_pos_ub=-1,
214
+ add_gt_as_proposals=True),
215
+ mask_size=28,
216
+ pos_weight=-1,
217
+ debug=False),
218
+ ]),
219
+ test_cfg=dict(
220
+ rpn=dict(
221
+ nms_pre=1000,
222
+ max_per_img=1000,
223
+ nms=dict(type='nms', iou_threshold=0.7),
224
+ min_bbox_size=0),
225
+ rcnn=dict(
226
+ score_thr=0.05,
227
+ nms=dict(type='nms', iou_threshold=0.5),
228
+ max_per_img=100,
229
+ mask_thr_binary=0.5)))
230
+
231
+ # Minimal dataset meta required by mmdet.apis.init_detector
232
+ test_dataloader = dict(
233
+ dataset=dict(
234
+ type='CocoDataset',
235
+ ann_file='annotations/instances_val2017.json',
236
+ data_prefix=dict(img='val2017/'),
237
+ metainfo=dict(
238
+ classes=('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
239
+ 'train', 'truck', 'boat', 'traffic light', 'fire hydrant',
240
+ 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog',
241
+ 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe',
242
+ 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',
243
+ 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat',
244
+ 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
245
+ 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
246
+ 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot',
247
+ 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',
248
+ 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop',
249
+ 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave',
250
+ 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock',
251
+ 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'))))
flexicm/models/taic.py CHANGED
@@ -374,7 +374,7 @@ class TAIC(nn.Module):
374
  ["_quantized_cdf", "_offset", "_cdf_length", "scale_table"],
375
  state_dict,
376
  )
377
- super().load_state_dict(state_dict, strict=strict)
378
 
379
  def load_base_codec(self, state_dict, strict=False):
380
  """Load pretrained TIC / TIC-SFMA weights into matching modules."""
 
374
  ["_quantized_cdf", "_offset", "_cdf_length", "scale_table"],
375
  state_dict,
376
  )
377
+ return super().load_state_dict(state_dict, strict=strict)
378
 
379
  def load_base_codec(self, state_dict, strict=False):
380
  """Load pretrained TIC / TIC-SFMA weights into matching modules."""
flexicm/tasks/__init__.py CHANGED
@@ -21,6 +21,41 @@ import torch.nn.functional as F
21
 
22
  from flexicm.tasks.losses import freeze_module
23
  from flexicm.tasks.swin_teacher import SwinStageTeacher
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
 
26
  class DetectionTeacher(nn.Module):
@@ -179,15 +214,64 @@ class HigherHRNetTeacher(nn.Module):
179
  def build_teacher(task: str, **kwargs) -> nn.Module:
180
  task = task.lower()
181
  pretrained = kwargs.pop("pretrained_backbone", kwargs.pop("pretrained", True))
182
- if task in ("detection", "object_detection", "det"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  return DetectionTeacher(task="detection", pretrained_backbone=pretrained, **kwargs)
184
- if task in ("instance", "instance_seg", "instance_segmentation"):
185
  return DetectionTeacher(task="instance", pretrained_backbone=pretrained, **kwargs)
186
- if task in ("semantic", "semantic_seg", "semantic_segmentation"):
187
  return SemanticSegTeacher(pretrained_backbone=pretrained, **kwargs)
188
- if task in ("panoptic", "panoptic_seg", "panoptic_segmentation"):
189
  return PanopticSegTeacher(pretrained_backbone=pretrained, **kwargs)
190
- if task in ("pose", "pose_estimation"):
191
  return HigherHRNetTeacher(pretrained=pretrained, **kwargs)
192
  raise ValueError(f"Unknown task: {task}")
193
 
 
21
 
22
  from flexicm.tasks.losses import freeze_module
23
  from flexicm.tasks.swin_teacher import SwinStageTeacher
24
+ from flexicm.tasks.official_teachers import OfficialHRNetTeacher, OfficialSwinTeacher
25
+
26
+ # Default official task-network assets (used when use_official_teacher=True)
27
+ DEFAULT_TEACHER_ASSETS = {
28
+ "detection": {
29
+ "task_config": "configs/task_networks/cascade_mask_rcnn_swin_base_coco.py",
30
+ "task_checkpoint": "checkpoints/task_networks/detection/model_mmdet3.pth",
31
+ "framework": "mmdet",
32
+ "align_mode": "fpn",
33
+ },
34
+ "instance": {
35
+ "task_config": "configs/task_networks/cascade_mask_rcnn_swin_base_coco.py",
36
+ "task_checkpoint": "checkpoints/task_networks/instance/model_mmdet3.pth",
37
+ "framework": "mmdet",
38
+ "align_mode": "fpn",
39
+ },
40
+ "semantic": {
41
+ "task_config": "checkpoints/task_networks/semantic/swin-base-patch4-window7-in22k-pre_upernet_8xb2-160k_ade20k-512x512.py",
42
+ "task_checkpoint": "checkpoints/task_networks/semantic/upernet_swin_base_patch4_window7_512x512_160k_ade20k_pretrain_224x224_22K_20210526_211650-762e2178.pth",
43
+ "framework": "mmseg",
44
+ "align_mode": "fpn",
45
+ },
46
+ "panoptic": {
47
+ "task_config": "checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic.py",
48
+ "task_checkpoint": "checkpoints/task_networks/panoptic/mask2former_swin-b-p4-w12-384-in21k_8xb2-lsj-50e_coco-panoptic_20220329_230021-05ec7315.pth",
49
+ "framework": "mmdet",
50
+ "align_mode": "stages",
51
+ },
52
+ "pose": {
53
+ "task_config": "checkpoints/task_networks/pose/ae_hrnet-w32_8xb24-300e_coco-512x512.py",
54
+ "task_checkpoint": "checkpoints/task_networks/pose/hrnet_w32_coco_512x512-bcb8c247_20200816.pth",
55
+ "framework": "mmpose",
56
+ "align_mode": "stages",
57
+ },
58
+ }
59
 
60
 
61
  class DetectionTeacher(nn.Module):
 
214
  def build_teacher(task: str, **kwargs) -> nn.Module:
215
  task = task.lower()
216
  pretrained = kwargs.pop("pretrained_backbone", kwargs.pop("pretrained", True))
217
+ use_official = kwargs.pop("use_official_teacher", True)
218
+ task_config = kwargs.pop("task_config", None)
219
+ task_checkpoint = kwargs.pop("task_checkpoint", None)
220
+ device = kwargs.pop("device", "cpu")
221
+
222
+ # Normalize aliases
223
+ alias = {
224
+ "object_detection": "detection",
225
+ "det": "detection",
226
+ "instance_seg": "instance",
227
+ "instance_segmentation": "instance",
228
+ "semantic_seg": "semantic",
229
+ "semantic_segmentation": "semantic",
230
+ "panoptic_seg": "panoptic",
231
+ "panoptic_segmentation": "panoptic",
232
+ "pose_estimation": "pose",
233
+ }
234
+ task = alias.get(task, task)
235
+
236
+ if use_official:
237
+ assets = DEFAULT_TEACHER_ASSETS.get(task)
238
+ if assets is None:
239
+ raise ValueError(f"Unknown task for official teacher: {task}")
240
+ cfg = task_config or assets["task_config"]
241
+ ckpt = task_checkpoint or assets["task_checkpoint"]
242
+ align_mode = kwargs.pop("align_mode", assets["align_mode"])
243
+ framework = assets["framework"]
244
+ if framework in ("mmdet", "mmseg"):
245
+ teacher = OfficialSwinTeacher(
246
+ config_path=cfg,
247
+ checkpoint_path=ckpt,
248
+ align_mode=align_mode,
249
+ framework=framework,
250
+ device=device,
251
+ )
252
+ freeze_module(teacher)
253
+ return teacher
254
+ if framework == "mmpose":
255
+ width = kwargs.pop("width", 32)
256
+ teacher = OfficialHRNetTeacher(
257
+ config_path=cfg,
258
+ checkpoint_path=ckpt,
259
+ device=device,
260
+ width=width,
261
+ )
262
+ freeze_module(teacher)
263
+ return teacher
264
+
265
+ # Legacy timm / in-repo teachers (ImageNet Swin / stem HRNet)
266
+ if task == "detection":
267
  return DetectionTeacher(task="detection", pretrained_backbone=pretrained, **kwargs)
268
+ if task == "instance":
269
  return DetectionTeacher(task="instance", pretrained_backbone=pretrained, **kwargs)
270
+ if task == "semantic":
271
  return SemanticSegTeacher(pretrained_backbone=pretrained, **kwargs)
272
+ if task == "panoptic":
273
  return PanopticSegTeacher(pretrained_backbone=pretrained, **kwargs)
274
+ if task == "pose":
275
  return HigherHRNetTeacher(pretrained=pretrained, **kwargs)
276
  raise ValueError(f"Unknown task: {task}")
277
 
flexicm/tasks/metric_eval.py CHANGED
@@ -73,7 +73,10 @@ def run_task_metric_eval(
73
  else:
74
  out = codec(x)
75
 
76
- h = crop_feature_to_image(out["h"], (H, W))
 
 
 
77
  pred = runner.predict_from_h(h, meta)
78
  predictions.append(pred)
79
 
 
73
  else:
74
  out = codec(x)
75
 
76
+ h = out["h"]
77
+ meta = dict(meta)
78
+ meta["pad_height"] = int(x.shape[-2])
79
+ meta["pad_width"] = int(x.shape[-1])
80
  pred = runner.predict_from_h(h, meta)
81
  predictions.append(pred)
82
 
flexicm/tasks/metric_runners.py CHANGED
@@ -85,7 +85,9 @@ def _require_mmpose():
85
  def swin_feats_from_h(backbone: nn.Module, h: torch.Tensor) -> Tuple[torch.Tensor, ...]:
86
  """Treat h as Swin F1 (stage-0 output) and run remaining stages.
87
 
88
- Compatible with MMDet/MMSeg SwinTransformer that exposes `.stages` / `.layers`.
 
 
89
  """
90
  stages = None
91
  for name in ("stages", "layers"):
@@ -95,36 +97,77 @@ def swin_feats_from_h(backbone: nn.Module, h: torch.Tensor) -> Tuple[torch.Tenso
95
  if stages is None:
96
  raise RuntimeError("Backbone has no stages/layers; cannot inject h as F1")
97
 
 
 
 
 
98
  outs = [h]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  x = h
100
- # Stage 0 already produced F1 (=h); run stages 1..N-1
101
  for i in range(1, len(stages)):
102
  x = stages[i](x)
103
  if isinstance(x, (tuple, list)):
104
  x = x[0]
105
- # MMDet Swin may return NCHW already
106
- if x.dim() == 4 and x.shape[1] < x.shape[-1] and x.shape[-1] in (96, 128, 192, 256, 384, 512, 768, 1024):
107
- # likely NHWC
108
  x = x.permute(0, 3, 1, 2).contiguous()
109
  outs.append(x)
110
 
111
- # Apply per-stage norms if present (mmdet Swin)
112
  if hasattr(backbone, "num_features") or hasattr(backbone, "out_indices"):
113
  norm_outs = []
114
  for i, out in enumerate(outs):
115
  norm_name = f"norm{i}"
116
  if hasattr(backbone, norm_name):
117
  nchw = out
118
- # LayerNorm over channel last in some impls
119
  norm = getattr(backbone, norm_name)
120
- if nchw.shape[1] == getattr(norm, "normalized_shape", [nchw.shape[1]])[0] if hasattr(norm, "normalized_shape") else True:
121
- # try NCHW LayerNorm via transpose
122
- try:
123
- y = nchw.permute(0, 2, 3, 1)
124
- y = norm(y)
125
- nchw = y.permute(0, 3, 1, 2).contiguous()
126
- except Exception:
127
- nchw = out
128
  norm_outs.append(nchw)
129
  else:
130
  norm_outs.append(out)
@@ -149,39 +192,39 @@ class DetectionMetricRunner(TaskMetricRunner):
149
  @torch.no_grad()
150
  def predict_from_h(self, h: torch.Tensor, img_meta: Dict[str, Any]) -> Dict[str, Any]:
151
  assert self.model is not None
152
- # h: 1xCx(H/4)x(W/4)
153
  backbone = self.model.backbone
154
  feats = swin_feats_from_h(backbone, h)
155
  if hasattr(self.model, "neck") and self.model.neck is not None:
156
  feats = self.model.neck(feats)
157
 
158
  # Build a minimal img_metas / data_samples for mmdet 3.x or 2.x
159
- H, W = int(img_meta["height"]), int(img_meta["width"])
 
 
 
 
160
  try:
161
  # MMDet 3.x style
162
  from mmdet.structures import DetDataSample
163
- from mmengine.structures import InstanceData
164
 
165
  data_sample = DetDataSample()
166
  data_sample.set_metainfo(
167
  dict(
168
- img_shape=(H, W),
169
- ori_shape=(H, W),
170
- pad_shape=(H, W),
171
  scale_factor=(1.0, 1.0),
172
  img_id=img_meta.get("image_id"),
173
  )
174
  )
175
- # Use RPN + ROI heads with injected feats
176
- if hasattr(self.model, "extract_feat"):
177
- # bypass extract_feat by calling predict with feats if supported
178
- pass
179
  rpn_results_list = self.model.rpn_head.predict(feats, [data_sample], rescale=False)
180
  results_list = self.model.roi_head.predict(
181
  feats, rpn_results_list, [data_sample], rescale=True
182
  )
183
  pred = results_list[0]
184
- inst = pred.pred_instances
 
185
  out = {
186
  "image_id": img_meta["image_id"],
187
  "bboxes": inst.bboxes.detach().cpu(),
@@ -195,9 +238,9 @@ class DetectionMetricRunner(TaskMetricRunner):
195
  # Fallback MMDet 2.x
196
  img_metas = [
197
  dict(
198
- img_shape=(H, W, 3),
199
- ori_shape=(H, W, 3),
200
- pad_shape=(H, W, 3),
201
  scale_factor=1.0,
202
  flip=False,
203
  )
 
85
  def swin_feats_from_h(backbone: nn.Module, h: torch.Tensor) -> Tuple[torch.Tensor, ...]:
86
  """Treat h as Swin F1 (stage-0 output) and run remaining stages.
87
 
88
+ Compatible with:
89
+ - MMDet 3.x SwinTransformer (token + hw_shape API, ``stages``)
90
+ - older Swin / MMSeg variants that expose ``stages`` / ``layers``
91
  """
92
  stages = None
93
  for name in ("stages", "layers"):
 
97
  if stages is None:
98
  raise RuntimeError("Backbone has no stages/layers; cannot inject h as F1")
99
 
100
+ # h is NCHW (B,C,H,W) == F1
101
+ if h.dim() != 4:
102
+ raise ValueError(f"expected NCHW h, got shape {tuple(h.shape)}")
103
+ B, C, H, W = h.shape
104
  outs = [h]
105
+
106
+ # Detect mmdet3-style SwinBlockSequence: forward(x, hw_shape)
107
+ import inspect
108
+
109
+ try:
110
+ needs_hw = "hw_shape" in inspect.signature(stages[0].forward).parameters
111
+ except (TypeError, ValueError):
112
+ needs_hw = False
113
+
114
+ if needs_hw:
115
+ # tokens: (B, H*W, C)
116
+ x = h.flatten(2).transpose(1, 2).contiguous()
117
+ hw_shape = (H, W)
118
+
119
+ # F1 is stage-0 block output (pre-downsample). Feed stage-0 downsample
120
+ # then run stages 1..N-1, mirroring SwinTransformer.forward.
121
+ if getattr(stages[0], "downsample", None) is not None:
122
+ x, hw_shape = stages[0].downsample(x, hw_shape)
123
+
124
+ for i in range(1, len(stages)):
125
+ x, hw_shape, out, out_hw_shape = stages[i](x, hw_shape)
126
+ norm_name = f"norm{i}"
127
+ if hasattr(backbone, norm_name):
128
+ out = getattr(backbone, norm_name)(out)
129
+ feat_dim = out.shape[-1]
130
+ out = (
131
+ out.view(B, out_hw_shape[0], out_hw_shape[1], feat_dim)
132
+ .permute(0, 3, 1, 2)
133
+ .contiguous()
134
+ )
135
+ outs.append(out)
136
+
137
+ # Optionally normalize F1 with norm0 for consistency with extract_feat
138
+ if hasattr(backbone, "norm0"):
139
+ f1 = h.flatten(2).transpose(1, 2).contiguous()
140
+ f1 = backbone.norm0(f1)
141
+ outs[0] = (
142
+ f1.view(B, H, W, C).permute(0, 3, 1, 2).contiguous()
143
+ )
144
+ return tuple(outs)
145
+
146
+ # Legacy path (timm / older mmdet): stage modules accept NCHW / plain tensors
147
  x = h
 
148
  for i in range(1, len(stages)):
149
  x = stages[i](x)
150
  if isinstance(x, (tuple, list)):
151
  x = x[0]
152
+ if x.dim() == 4 and x.shape[1] < x.shape[-1] and x.shape[-1] in (
153
+ 96, 128, 192, 256, 384, 512, 768, 1024
154
+ ):
155
  x = x.permute(0, 3, 1, 2).contiguous()
156
  outs.append(x)
157
 
 
158
  if hasattr(backbone, "num_features") or hasattr(backbone, "out_indices"):
159
  norm_outs = []
160
  for i, out in enumerate(outs):
161
  norm_name = f"norm{i}"
162
  if hasattr(backbone, norm_name):
163
  nchw = out
 
164
  norm = getattr(backbone, norm_name)
165
+ try:
166
+ y = nchw.permute(0, 2, 3, 1)
167
+ y = norm(y)
168
+ nchw = y.permute(0, 3, 1, 2).contiguous()
169
+ except Exception:
170
+ nchw = out
 
 
171
  norm_outs.append(nchw)
172
  else:
173
  norm_outs.append(out)
 
192
  @torch.no_grad()
193
  def predict_from_h(self, h: torch.Tensor, img_meta: Dict[str, Any]) -> Dict[str, Any]:
194
  assert self.model is not None
195
+ # h: 1xCx(H/4)x(W/4) — preferably on the padded codec grid
196
  backbone = self.model.backbone
197
  feats = swin_feats_from_h(backbone, h)
198
  if hasattr(self.model, "neck") and self.model.neck is not None:
199
  feats = self.model.neck(feats)
200
 
201
  # Build a minimal img_metas / data_samples for mmdet 3.x or 2.x
202
+ ori_h, ori_w = int(img_meta["height"]), int(img_meta["width"])
203
+ # If h comes from a padded codec input, prefer those spatial sizes so
204
+ # FPN strides line up; boxes are rescaled back to ori_shape.
205
+ pad_h = int(img_meta.get("pad_height", h.shape[-2] * 4))
206
+ pad_w = int(img_meta.get("pad_width", h.shape[-1] * 4))
207
  try:
208
  # MMDet 3.x style
209
  from mmdet.structures import DetDataSample
 
210
 
211
  data_sample = DetDataSample()
212
  data_sample.set_metainfo(
213
  dict(
214
+ img_shape=(pad_h, pad_w),
215
+ ori_shape=(ori_h, ori_w),
216
+ pad_shape=(pad_h, pad_w),
217
  scale_factor=(1.0, 1.0),
218
  img_id=img_meta.get("image_id"),
219
  )
220
  )
 
 
 
 
221
  rpn_results_list = self.model.rpn_head.predict(feats, [data_sample], rescale=False)
222
  results_list = self.model.roi_head.predict(
223
  feats, rpn_results_list, [data_sample], rescale=True
224
  )
225
  pred = results_list[0]
226
+ # mmdet 3.x roi_head.predict may return DetDataSample or InstanceData
227
+ inst = pred.pred_instances if hasattr(pred, "pred_instances") else pred
228
  out = {
229
  "image_id": img_meta["image_id"],
230
  "bboxes": inst.bboxes.detach().cpu(),
 
238
  # Fallback MMDet 2.x
239
  img_metas = [
240
  dict(
241
+ img_shape=(pad_h, pad_w, 3),
242
+ ori_shape=(ori_h, ori_w, 3),
243
+ pad_shape=(pad_h, pad_w, 3),
244
  scale_factor=1.0,
245
  flip=False,
246
  )
flexicm/tasks/official_teachers.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Teachers that load official task-network backbones (+ necks) for feature alignment.
2
+
3
+ Training Distortion D is computed against these frozen features so that codec
4
+ outputs match the same backbone used at metric evaluation time.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from typing import Dict, Optional, Tuple
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+ from flexicm.tasks.losses import freeze_module
17
+ from flexicm.tasks.metric_runners import swin_feats_from_h
18
+
19
+
20
+ def _resolve_path(path: Optional[str], repo_root: Optional[str] = None) -> Optional[str]:
21
+ if not path:
22
+ return None
23
+ if os.path.isabs(path):
24
+ return path
25
+ if repo_root is None:
26
+ repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
27
+ return os.path.join(repo_root, path)
28
+
29
+
30
+ def _imagenet_norm_rgb01(x: torch.Tensor) -> torch.Tensor:
31
+ """Normalize RGB float images in [0, 1] with ImageNet mean/std (float space)."""
32
+ mean = x.new_tensor([0.485, 0.456, 0.406])[None, :, None, None]
33
+ std = x.new_tensor([0.229, 0.224, 0.225])[None, :, None, None]
34
+ return (x - mean) / std
35
+
36
+
37
+ def _mmdet_preprocess_rgb01(x: torch.Tensor, model: nn.Module) -> torch.Tensor:
38
+ """Apply DetDataPreprocessor-equivalent norm: RGB [0,1] -> model input."""
39
+ pp = getattr(model, "data_preprocessor", None)
40
+ if pp is None:
41
+ return _imagenet_norm_rgb01(x)
42
+ # DetDataPreprocessor stores mean/std for 0-255 inputs
43
+ mean = getattr(pp, "mean", None)
44
+ std = getattr(pp, "std", None)
45
+ if mean is None or std is None:
46
+ return _imagenet_norm_rgb01(x)
47
+ mean_t = mean.view(1, -1, 1, 1).to(device=x.device, dtype=x.dtype)
48
+ std_t = std.view(1, -1, 1, 1).to(device=x.device, dtype=x.dtype)
49
+ # x in [0,1] RGB; preprocessor mean/std are for 0-255 RGB after bgr_to_rgb
50
+ return (x * 255.0 - mean_t) / std_t
51
+
52
+
53
+ class OfficialSwinTeacher(nn.Module):
54
+ """Frozen Swin teacher from an official MMDet / MMSeg checkpoint.
55
+
56
+ align_mode:
57
+ - ``fpn``: P2..P6 via backbone + FPN/neck (detection / instance / semantic)
58
+ - ``stages``: F1..F4 via backbone stages (panoptic)
59
+ """
60
+
61
+ def __init__(
62
+ self,
63
+ config_path: str,
64
+ checkpoint_path: str,
65
+ align_mode: str = "fpn",
66
+ framework: str = "mmdet",
67
+ device: str = "cpu",
68
+ ):
69
+ super().__init__()
70
+ assert align_mode in ("fpn", "stages")
71
+ self.align_mode = align_mode
72
+ self.framework = framework
73
+ self.config_path = _resolve_path(config_path)
74
+ self.checkpoint_path = _resolve_path(checkpoint_path)
75
+ if not self.config_path or not os.path.isfile(self.config_path):
76
+ raise FileNotFoundError(f"task_config not found: {config_path}")
77
+ if not self.checkpoint_path or not os.path.isfile(self.checkpoint_path):
78
+ raise FileNotFoundError(f"task_checkpoint not found: {checkpoint_path}")
79
+
80
+ self.model = self._load_model(device)
81
+ freeze_module(self.model)
82
+ self.out_channels = self._infer_f1_channels()
83
+ self._aux_fpn = None
84
+
85
+ def _load_model(self, device: str) -> nn.Module:
86
+ if self.framework == "mmdet":
87
+ from mmdet.apis import init_detector
88
+
89
+ return init_detector(self.config_path, self.checkpoint_path, device=device)
90
+ if self.framework == "mmseg":
91
+ from mmseg.apis import init_model
92
+
93
+ return init_model(self.config_path, self.checkpoint_path, device=device)
94
+ raise ValueError(f"Unknown framework={self.framework}")
95
+
96
+ def _infer_f1_channels(self) -> int:
97
+ bb = self.model.backbone
98
+ if hasattr(bb, "num_features"):
99
+ return int(bb.num_features[0])
100
+ if hasattr(bb, "embed_dims"):
101
+ return int(bb.embed_dims)
102
+ return 128
103
+
104
+ def _preprocess(self, images: torch.Tensor) -> torch.Tensor:
105
+ return _mmdet_preprocess_rgb01(images, self.model)
106
+
107
+ def _backbone_stages_from_image(self, x: torch.Tensor) -> Tuple[torch.Tensor, ...]:
108
+ """Return F1..F4 NCHW from Swin backbone (with per-stage norms)."""
109
+ bb = self.model.backbone
110
+ # Prefer official forward when possible (handles abs pos / dropout)
111
+ if hasattr(bb, "forward") and not hasattr(bb, "stages"):
112
+ feats = bb(x)
113
+ return tuple(feats[:4])
114
+
115
+ tokens, hw_shape = bb.patch_embed(x)
116
+ if getattr(bb, "use_abs_pos_embed", False):
117
+ tokens = tokens + bb.absolute_pos_embed
118
+ tokens = bb.drop_after_pos(tokens)
119
+ outs = []
120
+ for i, stage in enumerate(bb.stages):
121
+ tokens, hw_shape, out, out_hw = stage(tokens, hw_shape)
122
+ if i in getattr(bb, "out_indices", (0, 1, 2, 3)):
123
+ norm = getattr(bb, f"norm{i}")
124
+ out = norm(out)
125
+ feat = (
126
+ out.view(-1, *out_hw, bb.num_features[i])
127
+ .permute(0, 3, 1, 2)
128
+ .contiguous()
129
+ )
130
+ outs.append(feat)
131
+ return tuple(outs)
132
+
133
+ def _fpn_from_stages(self, stages: Tuple[torch.Tensor, ...]) -> Dict[str, torch.Tensor]:
134
+ neck = getattr(self.model, "neck", None)
135
+ if neck is None and self.framework == "mmseg":
136
+ # UPerNet has no separate FPN neck; reuse Cascade Mask R-CNN FPN
137
+ # (same Swin-B channel layout) so Eq.2 aligns P2..P6.
138
+ neck = self._get_or_build_aux_fpn(stages[0].device)
139
+ if neck is None:
140
+ p = list(stages[:4])
141
+ while len(p) < 4:
142
+ p.append(p[-1])
143
+ p2, p3, p4, p5 = p
144
+ p6 = F.avg_pool2d(p5, kernel_size=2, stride=2)
145
+ return {"p2": p2, "p3": p3, "p4": p4, "p5": p5, "p6": p6}
146
+
147
+ pyramid = neck(stages)
148
+ keys = ["p2", "p3", "p4", "p5", "p6"]
149
+ out = {}
150
+ for i, feat in enumerate(pyramid):
151
+ if i < len(keys):
152
+ out[keys[i]] = feat
153
+ return out
154
+
155
+ def _get_or_build_aux_fpn(self, device) -> nn.Module:
156
+ if hasattr(self, "_aux_fpn") and self._aux_fpn is not None:
157
+ return self._aux_fpn
158
+ from mmdet.models.necks import FPN
159
+
160
+ fpn = FPN(
161
+ in_channels=[128, 256, 512, 1024],
162
+ out_channels=256,
163
+ num_outs=5,
164
+ )
165
+ # Load official Cascade Mask R-CNN neck weights when available
166
+ det_ckpt = _resolve_path("checkpoints/task_networks/detection/model_mmdet3.pth")
167
+ if det_ckpt and os.path.isfile(det_ckpt):
168
+ raw = torch.load(det_ckpt, map_location="cpu")
169
+ state = raw["state_dict"] if isinstance(raw, dict) and "state_dict" in raw else raw
170
+ neck_state = {
171
+ k[len("neck.") :]: v for k, v in state.items() if k.startswith("neck.")
172
+ }
173
+ missing, unexpected = fpn.load_state_dict(neck_state, strict=False)
174
+ # missing/unexpected are fine to ignore for BN tracking buffers etc.
175
+ self._aux_fpn = freeze_module(fpn.to(device))
176
+ return self._aux_fpn
177
+
178
+ def gt_features(self, images: torch.Tensor) -> Dict[str, torch.Tensor]:
179
+ x = self._preprocess(images)
180
+ if (
181
+ self.align_mode == "fpn"
182
+ and hasattr(self.model, "extract_feat")
183
+ and getattr(self.model, "neck", None) is not None
184
+ ):
185
+ # CascadeRCNN.extract_feat = neck(backbone(x)) -> P2..P6
186
+ feats = self.model.extract_feat(x)
187
+ keys = ["p2", "p3", "p4", "p5", "p6"]
188
+ return {keys[i]: feats[i] for i in range(min(len(keys), len(feats)))}
189
+
190
+ if self.framework == "mmseg" and hasattr(self.model, "extract_feat"):
191
+ stages = tuple(self.model.extract_feat(x)[:4])
192
+ else:
193
+ stages = self._backbone_stages_from_image(x)
194
+ if self.align_mode == "stages":
195
+ return {f"f{i+1}": stages[i] for i in range(min(4, len(stages)))}
196
+ return self._fpn_from_stages(stages)
197
+
198
+ def pred_features(self, h: torch.Tensor) -> Dict[str, torch.Tensor]:
199
+ stages = swin_feats_from_h(self.model.backbone, h)
200
+ if self.align_mode == "stages":
201
+ return {f"f{i+1}": stages[i] for i in range(min(4, len(stages)))}
202
+ return self._fpn_from_stages(stages)
203
+
204
+
205
+ class OfficialHRNetTeacher(nn.Module):
206
+ """Frozen HRNet / HigherHRNet-style teacher from MMPose (stages F1..F4)."""
207
+
208
+ align_mode = "stages"
209
+ out_channels = 32
210
+
211
+ def __init__(
212
+ self,
213
+ config_path: str,
214
+ checkpoint_path: str,
215
+ device: str = "cpu",
216
+ width: int = 32,
217
+ ):
218
+ super().__init__()
219
+ self.config_path = _resolve_path(config_path)
220
+ self.checkpoint_path = _resolve_path(checkpoint_path)
221
+ if not self.config_path or not os.path.isfile(self.config_path):
222
+ raise FileNotFoundError(f"task_config not found: {config_path}")
223
+ if not self.checkpoint_path or not os.path.isfile(self.checkpoint_path):
224
+ raise FileNotFoundError(f"task_checkpoint not found: {checkpoint_path}")
225
+
226
+ from mmpose.apis import init_model
227
+
228
+ self.model = init_model(self.config_path, self.checkpoint_path, device=device)
229
+ freeze_module(self.model)
230
+ self.width = width
231
+ self.out_channels = width
232
+ # projection when codec h channels != stem width
233
+ self.h_proj = freeze_module(nn.Conv2d(128, width, 1))
234
+
235
+ def _preprocess(self, images: torch.Tensor) -> torch.Tensor:
236
+ return _imagenet_norm_rgb01(images)
237
+
238
+ def _stages_from_backbone(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:
239
+ bb = self.model.backbone if hasattr(self.model, "backbone") else self.model
240
+ # HRNet forward usually returns multi-resolution list / tensor
241
+ feats = bb(x)
242
+ if isinstance(feats, (list, tuple)):
243
+ # take highest-res stream as F1, then downsample proxies for F2..F4
244
+ f1 = feats[0] if feats[0].dim() == 4 else feats[0][-1]
245
+ outs = [f1]
246
+ cur = f1
247
+ for i in range(1, 4):
248
+ if i < len(feats) and isinstance(feats[i], torch.Tensor) and feats[i].dim() == 4:
249
+ outs.append(feats[i])
250
+ cur = feats[i]
251
+ else:
252
+ cur = F.avg_pool2d(cur, 2, 2)
253
+ outs.append(cur)
254
+ return {f"f{i+1}": outs[i] for i in range(4)}
255
+ # single tensor: synthesize pyramid
256
+ f1 = feats
257
+ outs = [f1]
258
+ cur = f1
259
+ for _ in range(3):
260
+ cur = F.avg_pool2d(cur, 2, 2)
261
+ outs.append(cur)
262
+ return {f"f{i+1}": outs[i] for i in range(4)}
263
+
264
+ def gt_features(self, images: torch.Tensor) -> Dict[str, torch.Tensor]:
265
+ return self._stages_from_backbone(self._preprocess(images))
266
+
267
+ def pred_features(self, h: torch.Tensor) -> Dict[str, torch.Tensor]:
268
+ if h.shape[1] != self.width:
269
+ if self.h_proj.in_channels != h.shape[1]:
270
+ self.h_proj = freeze_module(nn.Conv2d(h.shape[1], self.width, 1).to(h.device))
271
+ h = self.h_proj(h)
272
+ # Approximate remaining stages with stride-2 pools (HRNet full from-h
273
+ # needs model-specific stem hooks; pyramid still provides multi-scale D).
274
+ outs = [h]
275
+ cur = h
276
+ for _ in range(3):
277
+ cur = F.avg_pool2d(cur, 2, 2)
278
+ outs.append(cur)
279
+ return {f"f{i+1}": outs[i] for i in range(4)}
flexicm/tasks/swin_teacher.py CHANGED
@@ -55,12 +55,16 @@ def build_swin_backbone(pretrained: bool = True, swin_variant: str = "base"):
55
  if key not in _SWIN_TIMM_NAMES:
56
  raise ValueError(f"Unknown swin_variant={swin_variant!r}; expected one of {list(_SWIN_TIMM_NAMES)}")
57
 
 
 
58
  model = timm.create_model(
59
  _SWIN_TIMM_NAMES[key],
60
  pretrained=pretrained,
61
  features_only=True,
62
  out_indices=(0, 1, 2, 3),
63
- img_size=224,
 
 
64
  )
65
  return model
66
 
 
55
  if key not in _SWIN_TIMM_NAMES:
56
  raise ValueError(f"Unknown swin_variant={swin_variant!r}; expected one of {list(_SWIN_TIMM_NAMES)}")
57
 
58
+ # Training uses 256x256 crops; validation pads to multiples of 256.
59
+ # Allow variable spatial sizes (do not hard-lock PatchEmbed to 224).
60
  model = timm.create_model(
61
  _SWIN_TIMM_NAMES[key],
62
  pretrained=pretrained,
63
  features_only=True,
64
  out_indices=(0, 1, 2, 3),
65
+ img_size=256,
66
+ dynamic_img_size=True,
67
+ strict_img_size=False,
68
  )
69
  return model
70
 
flexicm/utils/codec_test.py CHANGED
@@ -93,13 +93,13 @@ def test_taic_loader(
93
  N, _, H, W = images.shape
94
  num_pixels = N * H * W
95
 
 
 
96
  x, _ = pad_for_codec(images, divisor=align_divisor, device=device)
97
  out = model(x)
98
- h = crop_feature_to_image(out["h"], (H, W))
99
- out["h"] = h
100
 
101
- gt = teacher.gt_features(images)
102
- pred = teacher.pred_features(h)
103
  stats = criterion(out, pred, gt, num_pixels=num_pixels)
104
 
105
  meters["loss"].update(stats["loss"].item(), n=N)
@@ -170,6 +170,7 @@ def test_ctaic_loader(
170
  N, _, H, W = images.shape
171
  num_pixels = N * H * W
172
 
 
173
  x, _ = pad_for_codec(images, divisor=align_divisor, device=device)
174
  y_b = None
175
  if use_condition:
@@ -177,11 +178,9 @@ def test_ctaic_loader(
177
  y_b = base_out["y_hat"]
178
 
179
  out = ext_model(x, y_b_hat=y_b, use_condition=use_condition and y_b is not None)
180
- h = crop_feature_to_image(out["h"], (H, W))
181
- out["h"] = h
182
 
183
- gt = teacher.gt_features(images)
184
- pred = teacher.pred_features(h)
185
  stats = criterion(out, pred, gt, num_pixels=num_pixels)
186
 
187
  meters["loss"].update(stats["loss"].item(), n=N)
 
93
  N, _, H, W = images.shape
94
  num_pixels = N * H * W
95
 
96
+ # Keep codec + teacher on the padded grid so Swin always sees a
97
+ # patch/window-divisible size. bpp still uses the original pixel count.
98
  x, _ = pad_for_codec(images, divisor=align_divisor, device=device)
99
  out = model(x)
 
 
100
 
101
+ gt = teacher.gt_features(x)
102
+ pred = teacher.pred_features(out["h"])
103
  stats = criterion(out, pred, gt, num_pixels=num_pixels)
104
 
105
  meters["loss"].update(stats["loss"].item(), n=N)
 
170
  N, _, H, W = images.shape
171
  num_pixels = N * H * W
172
 
173
+ # Keep codec + teacher on the padded grid (same rationale as TAIC test).
174
  x, _ = pad_for_codec(images, divisor=align_divisor, device=device)
175
  y_b = None
176
  if use_condition:
 
178
  y_b = base_out["y_hat"]
179
 
180
  out = ext_model(x, y_b_hat=y_b, use_condition=use_condition and y_b is not None)
 
 
181
 
182
+ gt = teacher.gt_features(x)
183
+ pred = teacher.pred_features(out["h"])
184
  stats = criterion(out, pred, gt, num_pixels=num_pixels)
185
 
186
  meters["loss"].update(stats["loss"].item(), n=N)
scripts/convert_swin_det_ckpt_to_mmdet3.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Convert official Swin-Det Cascade Mask R-CNN ckpt -> mmdet 3.x key layout.
3
+
4
+ Official source:
5
+ https://github.com/SwinTransformer/storage/releases/download/v1.0.2/cascade_mask_rcnn_swin_base_patch4_window7.pth
6
+
7
+ Only the Swin backbone keys need remapping (layers->stages, attn/mlp naming).
8
+ neck / rpn_head / roi_head keys already match mmdet 3 CascadeRCNN.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import os
15
+ import sys
16
+
17
+ import torch
18
+
19
+ REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
20
+ if REPO_ROOT not in sys.path:
21
+ sys.path.insert(0, REPO_ROOT)
22
+
23
+
24
+ def main():
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument(
27
+ "--src",
28
+ default=os.path.join(REPO_ROOT, "checkpoints/task_networks/detection/model.pth"),
29
+ )
30
+ parser.add_argument(
31
+ "--dst",
32
+ default=os.path.join(REPO_ROOT, "checkpoints/task_networks/detection/model_mmdet3.pth"),
33
+ )
34
+ args = parser.parse_args()
35
+
36
+ from mmdet.models.backbones.swin import swin_converter
37
+
38
+ raw = torch.load(args.src, map_location="cpu")
39
+ state = raw["state_dict"] if isinstance(raw, dict) and "state_dict" in raw else raw
40
+
41
+ backbone = {}
42
+ rest = {}
43
+ for k, v in state.items():
44
+ if k.startswith("backbone."):
45
+ backbone[k[len("backbone.") :]] = v
46
+ else:
47
+ rest[k] = v
48
+
49
+ converted_backbone = swin_converter(backbone) # adds 'backbone.' prefix
50
+ out_state = {}
51
+ out_state.update(converted_backbone)
52
+ out_state.update(rest)
53
+
54
+ os.makedirs(os.path.dirname(args.dst), exist_ok=True)
55
+ torch.save({"state_dict": out_state, "meta": {"converted_from": args.src}}, args.dst)
56
+ print(f"Wrote {args.dst}")
57
+ print(f" backbone keys: {sum(1 for k in out_state if k.startswith('backbone.'))}")
58
+ print(f" other keys: {sum(1 for k in out_state if not k.startswith('backbone.'))}")
59
+ print(f" sample backbone: {[k for k in out_state if k.startswith('backbone.')][:5]}")
60
+
61
+
62
+ if __name__ == "__main__":
63
+ main()
scripts/eval_ctaic.py CHANGED
@@ -49,7 +49,12 @@ def parse_args(argv):
49
  given, remaining = parser.parse_known_args(argv)
50
  cfg_path = given.config if os.path.isabs(given.config) else os.path.join(REPO_ROOT, given.config)
51
  cfg = load_yaml_config(cfg_path)
52
- parser.set_defaults(**cfg)
 
 
 
 
 
53
  parser.add_argument("--actual-bpp", action="store_true")
54
  parser.add_argument("--no-condition", action="store_true")
55
  parser.add_argument("--with-metrics", action="store_true")
@@ -139,7 +144,14 @@ def main(argv):
139
  net.load_state_dict(state, strict=False)
140
  net.eval()
141
 
142
- teacher = build_teacher(ext_task, pretrained_backbone=getattr(args, "pretrained_backbone", True))
 
 
 
 
 
 
 
143
  teacher = teacher.to(device).eval()
144
  criterion = TAICCriterion(lmbda=lmbda, align_mode=align_mode)
145
  codec_loader = build_codec_loader(args, ext_task, device)
 
49
  given, remaining = parser.parse_known_args(argv)
50
  cfg_path = given.config if os.path.isabs(given.config) else os.path.join(REPO_ROOT, given.config)
51
  cfg = load_yaml_config(cfg_path)
52
+ # -c already consumed by the first parse; keep it as a default for the second pass
53
+ parser.set_defaults(config=cfg_path, **cfg)
54
+ for action in parser._actions:
55
+ if "--config" in action.option_strings:
56
+ action.required = False
57
+ break
58
  parser.add_argument("--actual-bpp", action="store_true")
59
  parser.add_argument("--no-condition", action="store_true")
60
  parser.add_argument("--with-metrics", action="store_true")
 
144
  net.load_state_dict(state, strict=False)
145
  net.eval()
146
 
147
+ teacher = build_teacher(
148
+ ext_task,
149
+ pretrained_backbone=getattr(args, "pretrained_backbone", True),
150
+ use_official_teacher=getattr(args, "use_official_teacher", True),
151
+ task_config=getattr(args, "task_config", None),
152
+ task_checkpoint=getattr(args, "task_checkpoint", None),
153
+ device=device,
154
+ )
155
  teacher = teacher.to(device).eval()
156
  criterion = TAICCriterion(lmbda=lmbda, align_mode=align_mode)
157
  codec_loader = build_codec_loader(args, ext_task, device)
scripts/eval_taic.py CHANGED
@@ -55,7 +55,12 @@ def parse_args(argv):
55
  given, remaining = parser.parse_known_args(argv)
56
  cfg_path = given.config if os.path.isabs(given.config) else os.path.join(REPO_ROOT, given.config)
57
  cfg = load_yaml_config(cfg_path)
58
- parser.set_defaults(**cfg)
 
 
 
 
 
59
  parser.add_argument("--actual-bpp", action="store_true")
60
  parser.add_argument("--with-metrics", action="store_true", help="Run full task-network metrics")
61
  parser.add_argument("--max-batches", type=int, default=None)
@@ -136,7 +141,14 @@ def main(argv):
136
  net.eval()
137
 
138
  # ---- codec test ----
139
- teacher = build_teacher(task, pretrained_backbone=getattr(args, "pretrained_backbone", True))
 
 
 
 
 
 
 
140
  teacher = teacher.to(device).eval()
141
  criterion = TAICCriterion(lmbda=lmbda, align_mode=align_mode)
142
  codec_loader = build_codec_loader(args, device)
 
55
  given, remaining = parser.parse_known_args(argv)
56
  cfg_path = given.config if os.path.isabs(given.config) else os.path.join(REPO_ROOT, given.config)
57
  cfg = load_yaml_config(cfg_path)
58
+ # -c already consumed by the first parse; keep it as a default for the second pass
59
+ parser.set_defaults(config=cfg_path, **cfg)
60
+ for action in parser._actions:
61
+ if "--config" in action.option_strings:
62
+ action.required = False
63
+ break
64
  parser.add_argument("--actual-bpp", action="store_true")
65
  parser.add_argument("--with-metrics", action="store_true", help="Run full task-network metrics")
66
  parser.add_argument("--max-batches", type=int, default=None)
 
141
  net.eval()
142
 
143
  # ---- codec test ----
144
+ teacher = build_teacher(
145
+ task,
146
+ pretrained_backbone=getattr(args, "pretrained_backbone", True),
147
+ use_official_teacher=getattr(args, "use_official_teacher", True),
148
+ task_config=getattr(args, "task_config", None),
149
+ task_checkpoint=getattr(args, "task_checkpoint", None),
150
+ device=device,
151
+ )
152
  teacher = teacher.to(device).eval()
153
  criterion = TAICCriterion(lmbda=lmbda, align_mode=align_mode)
154
  codec_loader = build_codec_loader(args, device)
scripts/train_ctaic.py CHANGED
@@ -35,6 +35,7 @@ from flexicm.data import COCOImageDataset, COCOWholeBodyImageDataset, build_trai
35
  from flexicm.models import CTAIC, TAIC
36
  from flexicm.tasks import TASK_META, build_teacher
37
  from flexicm.tasks.losses import TAICCriterion
 
38
  from flexicm.utils.train_utils import (
39
  AverageMeter,
40
  CustomDataParallel,
@@ -61,7 +62,12 @@ def parse_args(argv):
61
  parser.add_argument("--name", default=datetime.now().strftime("%Y-%m-%d_%H_%M_%S"))
62
  given, remaining = parser.parse_known_args(argv)
63
  cfg = load_yaml_config(given.config)
64
- parser.set_defaults(**cfg)
 
 
 
 
 
65
  args = parser.parse_args(remaining)
66
  args.config = given.config
67
  args.stage = given.stage
@@ -121,17 +127,20 @@ def train_one_epoch(stage, ext_model, base_model, teacher, loader, optimizer, cr
121
 
122
 
123
  @torch.no_grad()
124
- def validate(stage, ext_model, base_model, teacher, loader, criterion, device):
125
  ext_model.eval()
126
  meters = {k: AverageMeter() for k in ("loss", "bpp", "distortion")}
127
  for images in loader:
128
  images = images.to(device)
 
 
 
129
  if stage == 1:
130
- out = ext_model(images, use_condition=False)
131
  else:
132
- y_b = encode_base_latent(base_model, images)
133
- out = ext_model(images, y_b_hat=y_b, use_condition=True)
134
- gt = teacher.gt_features(images)
135
  pred = teacher.pred_features(out["h"])
136
  N, _, H, W = images.shape
137
  stats = criterion(out, pred, gt, num_pixels=N * H * W)
@@ -198,7 +207,14 @@ def main(argv):
198
  f"Trainable params: {sum(p.numel() for p in net.parameters() if p.requires_grad)/1e6:.3f}M"
199
  )
200
 
201
- teacher = build_teacher(ext_task, pretrained_backbone=getattr(args, "pretrained_backbone", True))
 
 
 
 
 
 
 
202
  teacher = teacher.to(device).eval()
203
 
204
  if args.cuda and torch.cuda.device_count() > 1:
 
35
  from flexicm.models import CTAIC, TAIC
36
  from flexicm.tasks import TASK_META, build_teacher
37
  from flexicm.tasks.losses import TAICCriterion
38
+ from flexicm.utils.alignment import Alignment
39
  from flexicm.utils.train_utils import (
40
  AverageMeter,
41
  CustomDataParallel,
 
62
  parser.add_argument("--name", default=datetime.now().strftime("%Y-%m-%d_%H_%M_%S"))
63
  given, remaining = parser.parse_known_args(argv)
64
  cfg = load_yaml_config(given.config)
65
+ # -c/--stage already consumed by the first parse; keep them for the second pass
66
+ parser.set_defaults(config=given.config, stage=given.stage, **cfg)
67
+ for action in parser._actions:
68
+ if "--config" in action.option_strings:
69
+ action.required = False
70
+ break
71
  args = parser.parse_args(remaining)
72
  args.config = given.config
73
  args.stage = given.stage
 
127
 
128
 
129
  @torch.no_grad()
130
+ def validate(stage, ext_model, base_model, teacher, loader, criterion, device, align_divisor=256):
131
  ext_model.eval()
132
  meters = {k: AverageMeter() for k in ("loss", "bpp", "distortion")}
133
  for images in loader:
134
  images = images.to(device)
135
+ # Pad to codec/Swin-friendly size (same as train_taic.validate).
136
+ align = Alignment(divisor=align_divisor, mode="pad", padding_mode="constant").to(device)
137
+ x = align.align(images)
138
  if stage == 1:
139
+ out = ext_model(x, use_condition=False)
140
  else:
141
+ y_b = encode_base_latent(base_model, x)
142
+ out = ext_model(x, y_b_hat=y_b, use_condition=True)
143
+ gt = teacher.gt_features(x)
144
  pred = teacher.pred_features(out["h"])
145
  N, _, H, W = images.shape
146
  stats = criterion(out, pred, gt, num_pixels=N * H * W)
 
207
  f"Trainable params: {sum(p.numel() for p in net.parameters() if p.requires_grad)/1e6:.3f}M"
208
  )
209
 
210
+ teacher = build_teacher(
211
+ ext_task,
212
+ pretrained_backbone=getattr(args, "pretrained_backbone", True),
213
+ use_official_teacher=getattr(args, "use_official_teacher", True),
214
+ task_config=getattr(args, "task_config", None),
215
+ task_checkpoint=getattr(args, "task_checkpoint", None),
216
+ device=device,
217
+ )
218
  teacher = teacher.to(device).eval()
219
 
220
  if args.cuda and torch.cuda.device_count() > 1:
scripts/train_taic.py CHANGED
@@ -51,7 +51,12 @@ def parse_args(argv):
51
  parser.add_argument("--name", default=datetime.now().strftime("%Y-%m-%d_%H_%M_%S"))
52
  given, remaining = parser.parse_known_args(argv)
53
  cfg = load_yaml_config(given.config)
54
- parser.set_defaults(**cfg)
 
 
 
 
 
55
  parser.add_argument("-T", "--TEST", action="store_true")
56
  args = parser.parse_args(remaining)
57
  args.config = given.config
@@ -67,12 +72,12 @@ def validate(model, teacher, loader, criterion, device, align_divisor=256):
67
  align = Alignment(divisor=align_divisor, mode="pad", padding_mode="constant").to(device)
68
  x = align.align(images)
69
  out = model(x)
70
- # resume spatial pad on h
71
- h = align.resume(out["h"])
72
- out["h"] = h
73
  with torch.no_grad():
74
- gt = teacher.gt_features(images)
75
- pred = teacher.pred_features(h)
76
  N, _, H, W = images.shape
77
  stats = criterion(out, pred, gt, num_pixels=N * H * W)
78
  for k in meters:
@@ -126,9 +131,9 @@ def main(argv):
126
  # data
127
  train_tf = build_train_transform(args.patch_size)
128
  if task == "pose":
129
- train_set = COCOWholeBodyImageDataset(args.dataset_path, "train2017", train_tf)
130
  else:
131
- train_set = COCOImageDataset(args.dataset_path, "train2017", train_tf)
132
  val_split = getattr(args, "val_split", "val2017")
133
  val_root = os.path.join(args.dataset_path, val_split)
134
  if not os.path.isdir(val_root):
@@ -163,13 +168,26 @@ def main(argv):
163
  logging.info(f"Loading base TIC codec from {args.base_codec}")
164
  state, _ = load_checkpoint_dict(args.base_codec, map_location=device)
165
  net.load_base_codec(state, strict=False)
166
- net.freeze_base_codec()
 
 
 
 
 
 
167
  logging.info(
168
  f"Trainable params: {sum(p.numel() for p in net.parameters() if p.requires_grad)/1e6:.3f}M / "
169
  f"total {sum(p.numel() for p in net.parameters())/1e6:.3f}M"
170
  )
171
 
172
- teacher = build_teacher(task, pretrained_backbone=getattr(args, "pretrained_backbone", True))
 
 
 
 
 
 
 
173
  teacher = teacher.to(device).eval()
174
 
175
  if args.checkpoint:
@@ -192,22 +210,23 @@ def main(argv):
192
  for epoch in range(args.epochs):
193
  logging.info(f"===== Epoch {epoch}/{args.epochs} =====")
194
  train_stats = train_one_epoch(net, teacher, train_loader, optimizer, criterion, device)
195
- val_stats = validate(net, teacher, val_loader, criterion, device)
196
- logging.info(f"train={train_stats} val={val_stats}")
197
- is_best = val_stats["loss"] < best
198
- best = min(best, val_stats["loss"])
199
- if args.save:
200
- save_checkpoint(
201
- {
202
- "epoch": epoch,
203
- "state_dict": net.module.state_dict() if hasattr(net, "module") else net.state_dict(),
204
- "optimizer": optimizer.state_dict(),
205
- "loss": val_stats["loss"],
206
- "args": vars(args),
207
- },
208
- is_best,
209
- out_dir,
210
- )
 
211
 
212
 
213
  if __name__ == "__main__":
 
51
  parser.add_argument("--name", default=datetime.now().strftime("%Y-%m-%d_%H_%M_%S"))
52
  given, remaining = parser.parse_known_args(argv)
53
  cfg = load_yaml_config(given.config)
54
+ # -c already consumed by the first parse; keep it as a default for the second pass
55
+ parser.set_defaults(config=given.config, **cfg)
56
+ for action in parser._actions:
57
+ if "--config" in action.option_strings:
58
+ action.required = False
59
+ break
60
  parser.add_argument("-T", "--TEST", action="store_true")
61
  args = parser.parse_args(remaining)
62
  args.config = given.config
 
72
  align = Alignment(divisor=align_divisor, mode="pad", padding_mode="constant").to(device)
73
  x = align.align(images)
74
  out = model(x)
75
+ # Keep teacher + codec features on the aligned (padded) grid so the Swin
76
+ # backbone always sees a patch/window-divisible size. bpp still uses the
77
+ # original pixel count below.
78
  with torch.no_grad():
79
+ gt = teacher.gt_features(x)
80
+ pred = teacher.pred_features(out["h"])
81
  N, _, H, W = images.shape
82
  stats = criterion(out, pred, gt, num_pixels=N * H * W)
83
  for k in meters:
 
131
  # data
132
  train_tf = build_train_transform(args.patch_size)
133
  if task == "pose":
134
+ train_set = COCOWholeBodyImageDataset(args.dataset_path, "val2017", train_tf)
135
  else:
136
+ train_set = COCOImageDataset(args.dataset_path, "val2017", train_tf)
137
  val_split = getattr(args, "val_split", "val2017")
138
  val_root = os.path.join(args.dataset_path, val_split)
139
  if not os.path.isdir(val_root):
 
168
  logging.info(f"Loading base TIC codec from {args.base_codec}")
169
  state, _ = load_checkpoint_dict(args.base_codec, map_location=device)
170
  net.load_base_codec(state, strict=False)
171
+ if getattr(args, "freeze_base_codec", True):
172
+ net.freeze_base_codec()
173
+ logging.info("Base TIC codec frozen")
174
+ else:
175
+ for p in net.parameters():
176
+ p.requires_grad = True
177
+ logging.info("Base TIC codec unfrozen; training the entire TAIC model")
178
  logging.info(
179
  f"Trainable params: {sum(p.numel() for p in net.parameters() if p.requires_grad)/1e6:.3f}M / "
180
  f"total {sum(p.numel() for p in net.parameters())/1e6:.3f}M"
181
  )
182
 
183
+ teacher = build_teacher(
184
+ task,
185
+ pretrained_backbone=getattr(args, "pretrained_backbone", True),
186
+ use_official_teacher=getattr(args, "use_official_teacher", True),
187
+ task_config=getattr(args, "task_config", None),
188
+ task_checkpoint=getattr(args, "task_checkpoint", None),
189
+ device=device,
190
+ )
191
  teacher = teacher.to(device).eval()
192
 
193
  if args.checkpoint:
 
210
  for epoch in range(args.epochs):
211
  logging.info(f"===== Epoch {epoch}/{args.epochs} =====")
212
  train_stats = train_one_epoch(net, teacher, train_loader, optimizer, criterion, device)
213
+ if epoch % 10 == 0:
214
+ val_stats = validate(net, teacher, val_loader, criterion, device)
215
+ logging.info(f"train={train_stats} val={val_stats}")
216
+ is_best = val_stats["loss"] < best
217
+ best = min(best, val_stats["loss"])
218
+ if args.save:
219
+ save_checkpoint(
220
+ {
221
+ "epoch": epoch,
222
+ "state_dict": net.module.state_dict() if hasattr(net, "module") else net.state_dict(),
223
+ "optimizer": optimizer.state_dict(),
224
+ "loss": val_stats["loss"],
225
+ "args": vars(args),
226
+ },
227
+ is_best,
228
+ out_dir,
229
+ )
230
 
231
 
232
  if __name__ == "__main__":