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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!user/bin/env python
# -*- coding:utf-8 -*-
import argparse
import json
import os
import datetime
import pickle
import random
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from bisect import bisect
from math import fabs
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import LxmertTokenizer
from dist_train import get_world_size, get_rank, get_local_rank, barrier, reduce_sum

import numpy as np
from transformers.tokenization_utils_base import ENCODE_KWARGS_DOCSTRING
from config4LXMT5_DDP import args

from dataset4LXMT5 import KgDataset,my_collate,my_val_collate
from dataset_val4LXMT5 import KgDatasetVal

if args.visualBERT:
    from model_ViB2T5 import T5tokenizer, ViBT52T5, LXMtokenizer
else:
    from model_LXM2T5 import T5tokenizer, LXMT52T5, LXMtokenizer

from transformers import get_linear_schedule_with_warmup
from transformers import LxmertConfig, LxmertTokenizer, LxmertModel,BertTokenizer

dist.init_process_group(backend='nccl',timeout=datetime.timedelta(seconds=5400))
torch.cuda.set_device(args.local_rank)


# LR = 1e-5
LR = args.learning_rate
LR_LXM = args.learning_rate_LXM
# LR = 1e-4

torch.multiprocessing.set_sharing_strategy('file_system')

torch.cuda.set_device(get_local_rank())
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

def reduce_tensor(tensor: torch.Tensor):
    rt = tensor.clone().float()
    dist.all_reduce(rt,op=dist.ReduceOp.SUM)
    rt /= dist.get_world_size()#.float() 
    return rt

def set_seed(rank):
    random.seed(args.seed+rank) 
    np.random.seed(args.seed+rank)
    torch.manual_seed(args.seed+rank)
    torch.cuda.manual_seed(args.seed+rank)
    torch.cuda.manual_seed_all(args.seed+rank)
    torch.backends.cudnn.deterministic = True

set_seed(get_rank())





def cal_acc_multi(ground_truth, preds, return_id = False):
    all_num = len(ground_truth)
    acc_num = 0
    ids = []
    temp = []
    for i, answer_id in enumerate(ground_truth):
        pred = preds[i]
        # ids.append([i, int(pred)])
        cnt = 0
        for aid in answer_id:
            if pred == aid:
                cnt += 1
        if cnt ==1:
            acc_num += 1/3 
        elif cnt == 2:
            acc_num += 2/3 
        elif cnt > 2:
            acc_num += 1
    if return_id:
        return acc_num / all_num, ids
    else:
        return acc_num,  all_num
   
def cal_acc(ground_truth, preds, return_id = False):
    all_num = len(ground_truth)
    acc_num = 0
    ids = []
    temp = []
    for i, answer_id in enumerate(ground_truth):
        pred = preds[i]
        # ids.append([i, int(pred)])
        cnt = 0
        for aid in answer_id:
            if pred == aid:
                acc_num += 1
    if return_id:
        return acc_num / all_num, ids
    else:
        return acc_num, all_num


def train():
    if not args.describe:
        print('please set the description for the saved-model name! use --describe !')
        assert 1==0
    else:
        model_name=args.describe
    if not args.pretrain:
        train_dataset = KgDataset(val=False)
        train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
        train_dataloader = DataLoader(dataset=train_dataset, batch_size=args.batch_size, sampler=train_sampler,#shuffle=True,
                                      num_workers=0, collate_fn=my_collate)#, pin_memory=True)
        
        if args.validate:
            test_dataset = KgDatasetVal(val=False)
            test_dataloader = DataLoader(dataset=test_dataset, batch_size=args.batch_size, shuffle=False,
                                         num_workers=0, collate_fn=my_val_collate)
    else:
        train_dataset = KgDataset(val=False)
        
        train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
        train_dataloader = DataLoader(dataset=train_dataset, batch_size=args.batch_size,#pin_memory=True,
                                      num_workers=0, collate_fn=my_collate,  sampler=train_sampler)#shuffle=True,
                                    #   num_workers=0, collate_fn=my_collate_pretrain,  sampler=train_sampler)#shuffle=True,
        if args.validate:
            test_dataset = KgDatasetVal(val=False)
            test_dataloader = DataLoader(dataset=test_dataset, batch_size=args.batch_size,
                                         num_workers=0, collate_fn=my_val_collate, shuffle=False)#sampler=test_sampler)
    if args.pretrain:
        if get_rank() == 0: 
            print('pre-training!')
        if args.visualBERT:
            model=  ViBT52T5()
        else:
            model = LXMT52T5()
    else:
        if get_rank() == 0: 
            print('fine-tuning!')
        if args.visualBERT:
            model=  ViBT52T5()
        else:
            model = LXMT52T5()

    model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
    model = model.to(device)

    if get_world_size() > 1:
        if get_rank() == 0: 
            
            print("Let's use", get_world_size(), "GPUs!")
        
        model = nn.parallel.DistributedDataParallel(model, device_ids=[get_local_rank()], output_device=get_local_rank(),find_unused_parameters=True)

    print(model.named_modules)
    if get_world_size() > 1:
        if args.visualBERT:
            optimizer = optim.AdamW([
                {'params': model.module.T5model.parameters(), 'lr': LR},
                {'params': model.module.ViBmodel.parameters(), 'lr': LR_LXM},
                {'params': model.module.mapping.parameters(), 'lr': LR_LXM},
            ])
        else:
            optimizer = optim.AdamW([
                {'params': model.module.T5model.parameters(), 'lr': LR},
                {'params': model.module.LXMmodel.parameters(), 'lr': LR_LXM},
                {'params': model.module.mapping.parameters(), 'lr': LR_LXM},
    
            ])
    else:
        if args.visualBERT:
            optimizer = optim.AdamW([
                {'params': model.T5model.parameters(), 'lr': LR},
                {'params': model.ViBmodel.parameters(), 'lr': LR_LXM},
                {'params': model.mapping.parameters(), 'lr': LR_LXM},
            ])
        else:
            optimizer = optim.AdamW([
                {'params': model.T5model.parameters(), 'lr': LR},
                {'params': model.LXMmodel.parameters(), 'lr': LR_LXM},
                {'params': model.mapping.parameters(), 'lr': LR_LXM},
            ])
    


    if args.pretrain:
        steps_num = 100000
    else:
        steps_num = 20000




    args.num_epochs = steps_num // (len(train_dataset) / (args.batch_size * get_world_size())) \
        if len(train_dataset) % args.batch_size == 0 \
        else  (steps_num // (len(train_dataset) / (args.batch_size * get_world_size())) )+1 
        
    args.num_epochs = int(args.num_epochs)

    if get_rank() == 0: 
        print('total_epoch', args.num_epochs)
        print('total_steps', "we set steps=",steps_num)
        print('warmup_steps', int(steps_num/10)) #0.05*total_steps)
    scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=int(steps_num/10), #0.01 * total_steps,
                                                num_training_steps=steps_num)
    

    if args.load_pthpath == "":
        start_epoch = 0
    else:
        if get_rank() == 0: 
            print('load model')
        start_epoch = 0
        

        if get_world_size() > 1:
            model.module.load_state_dict(torch.load(args.load_pthpath))
        else:
            model.load_state_dict(torch.load(args.load_pthpath))



    best_acc = 0
    best_epoch = 0
    best_acc_t = 0
    best_epoch_t = 0
    best_acc_t3 = 0
    step_ind = 0

    for epoch in range(start_epoch, args.num_epochs):
        train_preds_trip = []
        train_sampler.set_epoch(epoch)
        train_answers_trip = []
        s=0
        for batch_data in tqdm(train_dataloader):
            step_ind+=1
            if get_rank()==0:
                print("step_ind",step_ind)
            s=s+1
            
            visual_faetures = torch.from_numpy(np.array(batch_data['img'], dtype=float)).float().to(device)
            spatial_features = torch.tensor(np.array(batch_data['spatial'])).float().to(device)
            
            if 1:
                
                T5_input_id = torch.stack(batch_data['T5_input_ids']).to(device)
                T5_input_mask = torch.stack(batch_data['T5_input_masks']).to(device)


            LXM_input_id = torch.stack(batch_data['LXM_input_ids']).to(device)
            LXM_input_mask = torch.stack(batch_data['LXM_input_masks']).to(device)
            LXM_token_type_ids = torch.stack(batch_data['LXM_token_type_ids']).to(device)


            T5_target_id = torch.stack(batch_data['T5_target_ids']).to(device)

            neg100 = torch.ones_like(T5_target_id)*(-100)
            T5_target_id = torch.where(T5_target_id==T5tokenizer.pad_token_id,neg100, T5_target_id)


            

            model.zero_grad()


            optimizer.zero_grad()
            if args.pretrain:
                outputs = model(train=True, LXM_source_ids=LXM_input_id, LXM_source_masks=LXM_input_mask,T5_source_ids=T5_input_id, T5_source_masks=T5_input_mask,token_type_ids=LXM_token_type_ids, visual_features=visual_faetures, spatial_features=spatial_features,T5_target_ids=T5_target_id)#,T5_target_masks=None
                

            else:
                outputs = model(train=True, LXM_source_ids=LXM_input_id, LXM_source_masks=LXM_input_mask,T5_source_ids=T5_input_id, T5_source_masks=T5_input_mask,token_type_ids=LXM_token_type_ids, visual_features=visual_faetures, spatial_features=spatial_features,T5_target_ids=T5_target_id)#,T5_target_masks=None
            loss = outputs.loss

            loss_stat = torch.mean(loss.detach()).item()

            if get_rank() == 0: 
                print("loss on GPU0", loss_stat)

            loss.sum().backward()
            optimizer.step()
            scheduler.step()

            with torch.no_grad():
                
                if args.pretrain:
                    eval_outputs = model(train=False, LXM_source_ids=LXM_input_id, LXM_source_masks=LXM_input_mask,T5_source_ids=T5_input_id, T5_source_masks=T5_input_mask,token_type_ids=LXM_token_type_ids, visual_features=visual_faetures, spatial_features=spatial_features,T5_target_ids=T5_target_id)#,T5_target_masks=None

                else:
                    eval_outputs = model(train=False, LXM_source_ids=LXM_input_id, LXM_source_masks=LXM_input_mask,T5_source_ids=T5_input_id, T5_source_masks=T5_input_mask,token_type_ids=LXM_token_type_ids, visual_features=visual_faetures, spatial_features=spatial_features,T5_target_ids=T5_target_id)#,T5_target_masks=None

                trip_predict = T5tokenizer.batch_decode(eval_outputs, skip_special_tokens=True)
                if get_rank() == 0: 
                    print('epoch', epoch, 'step', s, '>>>', '\tans:', batch_data['ans'][0], 'pred:', trip_predict[0])
                
                for i, pre in enumerate(batch_data['ans']):
                    train_answers_trip.append(batch_data['ans'][i])
                    train_preds_trip.append(trip_predict[i])

            barrier()
        barrier()

        
        if args.dataset == 'krvqa':
            train_acc_1_num, train_total_1_num = cal_acc(train_answers_trip, train_preds_trip)

            train_reduce_acc_num=reduce_tensor(torch.tensor(train_acc_1_num).cuda(args.local_rank)).item()
            train_reduce_total_num=reduce_tensor(torch.tensor(train_total_1_num).cuda(args.local_rank)).item()
            train_acc_1_trip = train_reduce_acc_num/train_reduce_total_num

            if get_rank() == 0: 
                # print("train_acc_1_trip all GPUs:", train_acc_1_trip)
                print('epoch %d train_loss = %.1f, acc_trip = %.4f' % (epoch, loss_stat,train_acc_1_trip))
        else:

            train_acc_1_num, train_total_1_num = cal_acc_multi(train_answers_trip, train_preds_trip)

            train_reduce_acc_num=reduce_tensor(torch.tensor(train_acc_1_num).cuda(args.local_rank)).item()
            train_reduce_total_num=reduce_tensor(torch.tensor(train_total_1_num).cuda(args.local_rank)).item()
            train_acc_1_trip = train_reduce_acc_num/train_reduce_total_num
            if get_rank() == 0:

                print('epoch %d train_loss of GPU0= %.1f, acc_trip on all GPUs= %.4f' % (epoch, loss_stat,
                                                                          train_acc_1_trip))

        barrier()
        if args.validate:
            model.eval()  
            answers = []  # [batch_answers,...]
            preds = []  # [batch_preds,...]
            preds_trip = []
            preds_trip_3 = []
            answers_trip = []
            id2pred_trip = {}
            print(f"\nValidation after epoch {epoch}:")
            for i, batch_data in enumerate(tqdm(test_dataloader)):
                with torch.no_grad():
                    val_T5_input_id = torch.stack(batch_data['T5_input_ids']).to(device)
                    val_T5_input_mask = torch.stack(batch_data['T5_input_masks']).to(device)


                    val_visual_faetures = torch.tensor(np.array(batch_data['img'])).float().to(device)

                    val_spatial_features = torch.tensor(np.array(batch_data['spatial'])).float().to(device)



                    val_LXM_input_id = torch.stack(batch_data['LXM_input_ids']).to(device)
                    val_LXM_input_mask = torch.stack(batch_data['LXM_input_masks']).to(device)
                    val_LXM_token_type_ids = torch.stack(batch_data['LXM_token_type_ids']).to(device)



                    if args.pretrain:
                        val_outputs = model(train=False, LXM_source_ids=val_LXM_input_id, LXM_source_masks=val_LXM_input_mask,T5_source_ids=val_T5_input_id, T5_source_masks=val_T5_input_mask,token_type_ids=val_LXM_token_type_ids, visual_features=val_visual_faetures, spatial_features=val_spatial_features,T5_target_ids=None)#,T5_target_masks=None
                       
                    else:
                        val_outputs = model(train=False, LXM_source_ids=val_LXM_input_id, LXM_source_masks=val_LXM_input_mask,T5_source_ids=val_T5_input_id, T5_source_masks=val_T5_input_mask,token_type_ids=val_LXM_token_type_ids, visual_features=val_visual_faetures, spatial_features=val_spatial_features,T5_target_ids=None)#,T5_target_masks=None



                    val_trip_predict = T5tokenizer.batch_decode(val_outputs, skip_special_tokens=True)


                    
                    
                    for i, pre in enumerate(batch_data['ans']):
                        preds_trip.append(val_trip_predict[i])
                        answers_trip.append(batch_data['ans'][i])

                        id2pred_trip[str(batch_data['id'][i])]=val_trip_predict[i]


            if args.dataset == 'krvqa':
                acc_1_num, total_1_num = cal_acc(answers_trip, preds_trip)
                reduce_acc_num=reduce_tensor(torch.tensor(acc_1_num).cuda(args.local_rank)).item()
                reduce_total_num=reduce_tensor(torch.tensor(total_1_num).cuda(args.local_rank)).item()
                acc_1_trip = reduce_acc_num/reduce_total_num
                if get_rank() == 0: 
                    print('epoch %d ,  acc_trip on all GPUs= %.4f' % (epoch, acc_1_trip))

            else:
                acc_1_num, total_1_num = cal_acc_multi(answers_trip, preds_trip)
                reduce_acc_num=reduce_tensor(torch.tensor(acc_1_num).cuda(args.local_rank)).item()
                reduce_total_num=reduce_tensor(torch.tensor(total_1_num).cuda(args.local_rank)).item()
                acc_1_trip = reduce_acc_num/reduce_total_num
                if get_rank() == 0: 
                    print('epoch %d ,  acc_trip on all GPUs= %.4f' % (epoch, acc_1_trip))

            if acc_1_trip > best_acc_t:
                
                best_acc_t = acc_1_trip
                best_epoch_t = epoch
                if not args.pretrain:
                    if get_rank() == 0:
                        f=open(args.model_dir+"/predictions.json", 'w')
                        json.dump(id2pred_trip, f)
                        f.close()
                        print('saving model at epoch', epoch, '!!')
                        
                        if get_world_size() > 1:
                            torch.save(model.module.state_dict(), args.model_dir+'/best_finetuned_model_'+model_name+'.pth')
                        else:
                            torch.save(model.state_dict(), args.model_dir+'/best_finetuned_model_'+model_name+'.pth')


  
            if get_rank() == 0: 
                print("best_acc@1t={:.2%}, epoch{}\n\n".format(best_acc_t, best_epoch_t))
            model.train()        
        if args.pretrain:
           
            if get_rank() == 0: #对于预训练,那么每个模型都保存一下,以便后面选取合适的,或者进行相应分析。
                if get_world_size() > 1:
                    torch.save(model.module.state_dict(), args.model_dir+ '/model_for_epoch_%d.pth' % epoch)
                else:
                    torch.save(model.state_dict(), args.model_dir+ '/model_for_epoch_%d.pth' % epoch)


        barrier()
        

    dist.destroy_process_group()
if __name__ == "__main__":
    train()