File size: 9,913 Bytes
ea1014e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import os
import time
from tqdm import tqdm
import cv2
import numpy as np
import torch
import torch.cuda.amp as amp
import torch.distributed as dist
import torch.nn.functional as F
import wandb
from PIL import Image
from loguru import logger
from utils.misc import (AverageMeter, ProgressMeter, concat_all_gather, concat_all_gather_varsize, trainMetricGPU)


def train(train_loader, model, optimizer, scheduler, scaler, epoch, args):
    batch_time = AverageMeter('Batch', ':2.2f')
    data_time = AverageMeter('Data', ':2.2f')
    lr = AverageMeter('Lr', ':1.6f')
    loss_meter = AverageMeter('Loss', ':2.4f')
    iou_meter = AverageMeter('IoU', ':2.2f')
    pr_meter = AverageMeter('Prec@50', ':2.2f')
    progress = ProgressMeter(
        len(train_loader),
        [batch_time, data_time, lr, loss_meter, iou_meter, pr_meter],
        prefix="Training: Epoch=[{}/{}] ".format(epoch, args.epochs))

    model.train()
    time.sleep(2)
    end = time.time()

    # size_list = [320, 352, 384, 416, 448, 480, 512]

    for i, (image, text, target, l_mask, params) in enumerate(train_loader):
        data_time.update(time.time() - end)
        # data
        try:
            dist.barrier()
        except:
            logger.error(f"Barrier failed at iteration {i}, rank {dist.get_rank()}")
            continue
        
        image = image.cuda(non_blocking=True)
        text = text.cuda(non_blocking=True)
        target = target.cuda(non_blocking=True)
        l_mask = l_mask.cuda(non_blocking=True)
        hp_emb = params['hardpos_emb'].cuda(non_blocking=True)
        source_type = params['source_type']

        # for sanity check
        orig_sent = params['sent']
        orig_hardpos = params['hardpos']

        
        # # multi-scale training
        # image = F.interpolate(image, size=(new_size, new_size), mode='bilinear', align_corners=True)
        text = text.squeeze(1)
        l_mask = l_mask.squeeze(1)

        # forward
        with amp.autocast():
            pred, target, loss = \
            model(image, text, l_mask, mask=target, hp_bert_embs=hp_emb, source_type=source_type)
        dist.barrier()
        
        # metric
        iou, pr5 = trainMetricGPU(pred, target, 0.35)
        dist.all_reduce(loss.detach())
        dist.all_reduce(iou)
        dist.all_reduce(pr5)
        loss = loss / dist.get_world_size()
        iou = iou / dist.get_world_size()
        pr5 = pr5 / dist.get_world_size()

        del pred, target, text, l_mask, hp_emb

        #delete all opts and backptop
        optimizer.zero_grad()
        scaler.scale(loss).backward()
        scaler.step(optimizer)
        scaler.update()

        loss_meter.update(loss.item(), image.size(0))
        iou_meter.update(iou.item(), image.size(0))
        pr_meter.update(pr5.item(), image.size(0))
        lr.update(optimizer.param_groups[0]["lr"])
        batch_time.update(time.time() - end)
        end = time.time()

        if (i + 1) % args.print_freq == 0:
            progress.display(i + 1)
            if dist.get_rank() in [-1, 0]:
                wandb.log(
                    {
                        "time/batch": batch_time.val,
                        "time/data": data_time.val,
                        "training/lr": lr.val,
                        "training/loss": loss_meter.val,
                        "training/iou": iou_meter.val,
                        "training/prec@50": pr_meter.val,
                    },
                    step=epoch * len(train_loader) + (i + 1))

        # flush every 10 steps
        if i % 10 == 0:  
            torch.cuda.empty_cache()


@torch.no_grad()
def validate(val_loader, model, epoch, args):
    iou_list = []
    I_sum = 0
    U_sum = 0
    mean_acc  = []
    
    model.eval()
    time.sleep(2)
    
    for idx, (imgs, text, masks, l_mask, source_type) in enumerate(val_loader):
        # data
        # imgs = torch.stack(imgs).cuda(non_blocking=True)
        # text = torch.stack(text).cuda(non_blocking=True)
        # l_mask = torch.stack(l_mask).cuda(non_blocking=True)
        imgs = imgs.cuda(non_blocking=True)
        text = text.cuda(non_blocking=True)
        l_mask = l_mask.cuda(non_blocking=True)
    
        text = text.squeeze(1)
        l_mask = l_mask.squeeze(1)

        # print(imgs.shape, text.shape, l_mask.shape)
        # print(source_type)
        
        # inference
        with amp.autocast(): # does inference need fp16?
            preds, maps = model(imgs, text, l_mask)
            preds = torch.sigmoid(preds)
        # process one batch
        for pred, mask, stype in zip(preds, masks, source_type):
            # iou
            pred = pred.cpu().numpy()
            mask = mask.cpu().numpy()
            pred = np.array(pred > 0.5)
            
            if stype == 'zero':  # Handle 'zero' source_type differently
                incorrect_num = np.sum(pred)
                acc = 1 if incorrect_num == 0 else 0
                mean_acc.append(acc)
            else :
                # IoU calculation                
                inter_sum = np.sum(np.logical_and(pred, mask))
                union_sum = np.sum(np.logical_or(pred, mask))

                iou = inter_sum / (union_sum + 1e-6)
                iou_list.append(iou)
                I_sum += inter_sum
                U_sum += union_sum


    iou_list = torch.tensor(iou_list, device=imgs.device)\

    I_sum = torch.tensor([I_sum], device=imgs.device)
    U_sum = torch.tensor([U_sum], device=imgs.device)

    # print("Before ioi list concat and gather ", iou_list.shape)
    # print("Before Isum, Usum concat and gather", I_sum.shape, U_sum.shape)


    gathered_iou = concat_all_gather_varsize(iou_list)
    gathered_I = concat_all_gather_varsize(I_sum)
    gathered_U = concat_all_gather_varsize(U_sum)

    # print("Before I and U concat and gather ", gathered_I.shape, gathered_U.shape)    
    # print("After ioi list concat and gather ", gathered_iou.shape)

    gathered_I_sum = gathered_I.sum().item()
    gathered_U_sum = gathered_U.sum().item()

    iou = gathered_iou.mean().item()
    oIoU = gathered_I_sum / (gathered_U_sum + 1e-6)
    
    # print("iou:", iou, "oIoU:", oIoU)
    torch.cuda.empty_cache()

    prec_list = []
    for thres in torch.arange(0.5, 1.0, 0.1):
        tmp = (gathered_iou > thres).float().mean()
        prec_list.append(tmp)
    
    prec = {}
    temp = '  '
    for i, thres in enumerate(range(5, 10)):
        key = 'Pr@{}'.format(thres * 10)
        value = prec_list[i].item()
        prec[key] = value
        temp += "{}: {:.2f}  ".format(key, 100. * value)
    
    dist.barrier()

    if dist.get_rank() == 0:
        head = 'Evaluation: Epoch=[{}/{}]  mIoU={:.2f}  oIoU={:.2f}'.format(
            epoch, args.epochs, 100. * iou, 100.*(oIoU))
        if mean_acc:
            mean_acc = np.mean(mean_acc)
            head += '  Acc={:.2f}'.format(100. * mean_acc)
        else:
            mean_acc = 0
        logger.info(head + temp)
        # print(head + temp)
        
    return iou, oIoU, prec, mean_acc


@torch.no_grad()
def inference(test_loader, model, args):
    iou_list = []
    I_sum = 0
    U_sum = 0
    mean_acc = []    

    tbar = tqdm(test_loader, desc='Inference:', ncols=100)
    model.eval()
    time.sleep(2)
    
    for ori_img, img, texts, mask, l_masks, seg_id, sents, source_type in tbar:
        img = img.cuda(non_blocking=True)
        mask = mask.cpu().numpy()
        
        # print(len(texts), source_type)
        # for all sentences for each referrals
        for text, l_mask, sent in zip(texts, l_masks, sents):
            text = text.cuda(non_blocking=True)
            l_mask = l_mask.cuda(non_blocking=True)

            text = text.squeeze(1)
            l_mask = l_mask.squeeze(1)

            with amp.autocast():
                pred, maps = model(img, text, l_mask)
                pred = torch.sigmoid(pred)
                if pred.shape[-2:] != ori_img.shape[:-1]:
                    #print(f"before** {pred.shape}, {ori_img.shape}, {mask.shape}")
                    pred = F.interpolate(pred, size=ori_img.shape[1:-1], mode='bicubic', align_corners=True)
                    
            # # process one sentence
            pred = pred.cpu().numpy()
            pred = np.array(pred > 0.35)

            if source_type == 'zero':
                incorrect_num = np.sum(pred)
                acc = 1 if incorrect_num == 0 else 0
                mean_acc.append(acc)
            else:
                inter_sum = np.sum(np.logical_and(pred, mask))  # sum of intersection
                union_sum = np.sum(np.logical_or(pred, mask))  # sum of union
                
                if union_sum == 0 :
                    iou = 0.0
                else :            
                    iou = inter_sum*1.0 / union_sum 

                iou_list.append(iou)
                I_sum += inter_sum  
                U_sum += union_sum  
    
    logger.info('=> Metric Calculation <=')

    iou_list = np.stack(iou_list)
    iou_list = torch.from_numpy(iou_list).to(img.device)
    # print(iou_list.shape)
    overall_IoU = I_sum / U_sum 

    prec_list = []
    for thres in torch.arange(0.5, 1.0, 0.1):
        tmp = (iou_list > thres).float().mean()
        prec_list.append(tmp)
    iou = iou_list.mean()
    prec = {}
    for i, thres in enumerate(range(5, 10)):
        key = 'Pr@{}'.format(thres*10)
        value = prec_list[i].item()
        prec[key] = value
    logger.info('oIoU={:.2f}'.format(100.*(I_sum/U_sum)))
    logger.info('mIoU={:.2f}'.format(100.*iou.item()))
    
    if mean_acc:
        # Calculate accuracy for 'zero' cases
        mean_acc = np.mean(mean_acc)
        logger.info('Acc={:.2f}'.format(100. * mean_acc))
    else:
        mean_acc = 0

    for k, v in prec.items():
        logger.info('{}: {:.2f}.'.format(k, 100.*v))

    return iou.item(), overall_IoU, prec, mean_acc