code
stringlengths
17
6.64M
def agent(agent_id, config, game, tm_subset, model_weights_queue, experience_queue): random_state = np.random.RandomState(seed=agent_id) network = Network(config, game.state_dims, game.action_dim, game.max_moves, master=False) model_weights = model_weights_queue.get() network.model.set_weights(model_weights) idx = 0 s_batch = [] a_batch = [] r_batch = [] if (config.method == 'pure_policy'): ad_batch = [] run_iteration_idx = 0 num_tms = len(tm_subset) random_state.shuffle(tm_subset) run_iterations = FLAGS.num_iter while True: tm_idx = tm_subset[idx] state = game.get_state(tm_idx) s_batch.append(state) if (config.method == 'actor_critic'): policy = network.actor_predict(np.expand_dims(state, 0)).numpy()[0] elif (config.method == 'pure_policy'): policy = network.policy_predict(np.expand_dims(state, 0)).numpy()[0] assert (np.count_nonzero(policy) >= game.max_moves), (policy, state) actions = random_state.choice(game.action_dim, game.max_moves, p=policy, replace=False) for a in actions: a_batch.append(a) reward = game.reward(tm_idx, actions) r_batch.append(reward) if (config.method == 'pure_policy'): if (config.baseline == 'avg'): ad_batch.append(game.advantage(tm_idx, reward)) game.update_baseline(tm_idx, reward) elif (config.baseline == 'best'): best_actions = policy.argsort()[(- game.max_moves):] best_reward = game.reward(tm_idx, best_actions) ad_batch.append((reward - best_reward)) run_iteration_idx += 1 if (run_iteration_idx >= run_iterations): if (config.method == 'actor_critic'): experience_queue.put([s_batch, a_batch, r_batch]) elif (config.method == 'pure_policy'): experience_queue.put([s_batch, a_batch, r_batch, ad_batch]) model_weights = model_weights_queue.get() network.model.set_weights(model_weights) del s_batch[:] del a_batch[:] del r_batch[:] if (config.method == 'pure_policy'): del ad_batch[:] run_iteration_idx = 0 idx += 1 if (idx == num_tms): random_state.shuffle(tm_subset) idx = 0
def main(_): tf.config.experimental.set_visible_devices([], 'GPU') tf.get_logger().setLevel('INFO') config = (get_config(FLAGS) or FLAGS) env = Environment(config, is_training=True) game = CFRRL_Game(config, env) model_weights_queues = [] experience_queues = [] if ((FLAGS.num_agents == 0) or (FLAGS.num_agents >= mp.cpu_count())): FLAGS.num_agents = (mp.cpu_count() - 1) print(('Agent num: %d, iter num: %d\n' % ((FLAGS.num_agents + 1), FLAGS.num_iter))) for _ in range(FLAGS.num_agents): model_weights_queues.append(mp.Queue(1)) experience_queues.append(mp.Queue(1)) tm_subsets = np.array_split(game.tm_indexes, FLAGS.num_agents) coordinator = mp.Process(target=central_agent, args=(config, game, model_weights_queues, experience_queues)) coordinator.start() agents = [] for i in range(FLAGS.num_agents): agents.append(mp.Process(target=agent, args=(i, config, game, tm_subsets[i], model_weights_queues[i], experience_queues[i]))) for i in range(FLAGS.num_agents): agents[i].start() coordinator.join()
class SiamRPN(nn.Module): def __init__(self, size=2, feature_out=512, anchor=5): configs = [3, 96, 256, 384, 384, 256] configs = list(map((lambda x: (3 if (x == 3) else (x * size))), configs)) feat_in = configs[(- 1)] super(SiamRPN, self).__init__() self.featureExtract = nn.Sequential(nn.Conv2d(configs[0], configs[1], kernel_size=11, stride=2), nn.BatchNorm2d(configs[1]), nn.MaxPool2d(kernel_size=3, stride=2), nn.ReLU(inplace=True), nn.Conv2d(configs[1], configs[2], kernel_size=5), nn.BatchNorm2d(configs[2]), nn.MaxPool2d(kernel_size=3, stride=2), nn.ReLU(inplace=True), nn.Conv2d(configs[2], configs[3], kernel_size=3), nn.BatchNorm2d(configs[3]), nn.ReLU(inplace=True), nn.Conv2d(configs[3], configs[4], kernel_size=3), nn.BatchNorm2d(configs[4]), nn.ReLU(inplace=True), nn.Conv2d(configs[4], configs[5], kernel_size=3), nn.BatchNorm2d(configs[5])) self.anchor = anchor self.feature_out = feature_out self.conv_r1 = nn.Conv2d(feat_in, ((feature_out * 4) * anchor), 3) self.conv_r2 = nn.Conv2d(feat_in, feature_out, 3) self.conv_cls1 = nn.Conv2d(feat_in, ((feature_out * 2) * anchor), 3) self.conv_cls2 = nn.Conv2d(feat_in, feature_out, 3) self.regress_adjust = nn.Conv2d((4 * anchor), (4 * anchor), 1) self.r1_kernel = [] self.cls1_kernel = [] self.cfg = {} def forward(self, x): x_f = self.featureExtract(x) temp = F.conv2d(self.conv_r2(x_f), self.r1_kernel) return (self.regress_adjust(temp), F.conv2d(self.conv_cls2(x_f), self.cls1_kernel)) def temple(self, z): z_f = self.featureExtract(z) r1_kernel_raw = self.conv_r1(z_f) cls1_kernel_raw = self.conv_cls1(z_f) kernel_size = r1_kernel_raw.data.size()[(- 1)] self.r1_kernel = r1_kernel_raw.view((self.anchor * 4), self.feature_out, kernel_size, kernel_size) self.cls1_kernel = cls1_kernel_raw.view((self.anchor * 2), self.feature_out, kernel_size, kernel_size)
class SiamRPNBIG(SiamRPN): def __init__(self): super(SiamRPNBIG, self).__init__(size=2) self.cfg = {'lr': 0.295, 'window_influence': 0.42, 'penalty_k': 0.055, 'instance_size': 271, 'adaptive': True}
class SiamRPNvot(SiamRPN): def __init__(self): super(SiamRPNvot, self).__init__(size=1, feature_out=256) self.cfg = {'lr': 0.45, 'window_influence': 0.44, 'penalty_k': 0.04, 'instance_size': 271, 'adaptive': False}
class SiamRPNotb(SiamRPN): def __init__(self): super(SiamRPNotb, self).__init__(size=1, feature_out=256) self.cfg = {'lr': 0.3, 'window_influence': 0.4, 'penalty_k': 0.22, 'instance_size': 271, 'adaptive': False}
def track_video(model, video): (toc, regions) = (0, []) (image_files, gt) = (video['image_files'], video['gt']) for (f, image_file) in enumerate(image_files): im = cv2.imread(image_file) tic = cv2.getTickCount() if (f == 0): (target_pos, target_sz) = rect_2_cxy_wh(gt[f]) state = SiamRPN_init(im, target_pos, target_sz, model) location = cxy_wh_2_rect(state['target_pos'], state['target_sz']) regions.append(gt[f]) elif (f > 0): state = SiamRPN_track(state, im) location = cxy_wh_2_rect((state['target_pos'] + 1), state['target_sz']) regions.append(location) toc += (cv2.getTickCount() - tic) if (args.visualization and (f >= 0)): if (f == 0): cv2.destroyAllWindows() if (len(gt[f]) == 8): cv2.polylines(im, [np.array(gt[f], np.int).reshape(((- 1), 1, 2))], True, (0, 255, 0), 3) else: cv2.rectangle(im, (gt[(f, 0)], gt[(f, 1)]), ((gt[(f, 0)] + gt[(f, 2)]), (gt[(f, 1)] + gt[(f, 3)])), (0, 255, 0), 3) if (len(location) == 8): cv2.polylines(im, [location.reshape(((- 1), 1, 2))], True, (0, 255, 255), 3) else: location = [int(l) for l in location] cv2.rectangle(im, (location[0], location[1]), ((location[0] + location[2]), (location[1] + location[3])), (0, 255, 255), 3) cv2.putText(im, str(f), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2) cv2.imshow(video['name'], im) cv2.waitKey(1) toc /= cv2.getTickFrequency() video_path = join('test', args.dataset, 'SiamRPN_AlexNet_OTB2015') if (not isdir(video_path)): makedirs(video_path) result_path = join(video_path, '{:s}.txt'.format(video['name'])) with open(result_path, 'w') as fin: for x in regions: fin.write((','.join([str(i) for i in x]) + '\n')) print('({:d}) Video: {:12s} Time: {:02.1f}s Speed: {:3.1f}fps'.format(v_id, video['name'], toc, (f / toc))) return (f / toc)
def load_dataset(dataset): base_path = join(realpath(dirname(__file__)), 'data', dataset) if (not exists(base_path)): print('Please download OTB dataset into `data` folder!') exit() json_path = join(realpath(dirname(__file__)), 'data', (dataset + '.json')) info = json.load(open(json_path, 'r')) for v in info.keys(): path_name = info[v]['name'] info[v]['image_files'] = [join(base_path, path_name, 'img', im_f) for im_f in info[v]['image_files']] info[v]['gt'] = (np.array(info[v]['gt_rect']) - [1, 1, 0, 0]) info[v]['name'] = v return info
def main(): global args, v_id args = parser.parse_args() net = SiamRPNotb() net.load_state_dict(torch.load(join(realpath(dirname(__file__)), 'SiamRPNOTB.model'))) net.eval().cuda() dataset = load_dataset(args.dataset) fps_list = [] for (v_id, video) in enumerate(dataset.keys()): fps_list.append(track_video(net, dataset[video])) print('Mean Running Speed {:.1f}fps'.format(np.mean(np.array(fps_list))))
def track_video(model, video): image_save = 0 (toc, regions) = (0, []) (image_files, gt) = (video['image_files'], video['gt']) for (f, image_file) in enumerate(image_files): im = cv2.imread(image_file) tic = cv2.getTickCount() if (f == 0): (target_pos, target_sz) = rect_2_cxy_wh(gt[f]) state = SiamRPN_init(im, target_pos, target_sz, model) location = cxy_wh_2_rect(state['target_pos'], state['target_sz']) regions.append(gt[f]) att_per = 0 def_per = 0 elif (f > 0): if ((f % 30) == 1): att_per = 0 def_per = 0 (state, att_per, def_per) = SiamRPN_track(state, im, f, regions[(f - 1)], att_per, def_per, image_save, iter=10) location = cxy_wh_2_rect((state['target_pos'] + 1), state['target_sz']) regions.append(location) else: (state, att_per, def_per) = SiamRPN_track(state, im, f, regions[(f - 1)], att_per, def_per, image_save, iter=5) location = cxy_wh_2_rect((state['target_pos'] + 1), state['target_sz']) regions.append(location) toc += (cv2.getTickCount() - tic) if (args.visualization and (f >= 0)): if (f == 0): cv2.destroyAllWindows() if (len(gt[f]) == 8): cv2.polylines(im, [np.array(gt[f], np.int).reshape(((- 1), 1, 2))], True, (0, 255, 0), 2) else: cv2.rectangle(im, (gt[(f, 0)], gt[(f, 1)]), ((gt[(f, 0)] + gt[(f, 2)]), (gt[(f, 1)] + gt[(f, 3)])), (0, 255, 0), 2) if (len(location) == 8): cv2.polylines(im, [location.reshape(((- 1), 1, 2))], True, (0, 255, 255), 2) else: location = [int(l) for l in location] cv2.rectangle(im, (location[0], location[1]), ((location[0] + location[2]), (location[1] + location[3])), (0, 255, 255), 2) cv2.putText(im, str(f), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2) cv2.imshow(video['name'], im) cv2.waitKey(1) toc /= cv2.getTickFrequency() video_path = join('test', args.dataset, 'DaSiamRPN_attack') if (not isdir(video_path)): makedirs(video_path) result_path = join(video_path, '{:s}.txt'.format(video['name'])) with open(result_path, 'w') as fin: for x in regions: fin.write((','.join([str(i) for i in x]) + '\n')) print('({:d}) Video: {:12s} Time: {:02.1f}s Speed: {:3.1f}fps'.format(v_id, video['name'], toc, (f / toc))) return (f / toc)
def load_dataset(dataset): base_path = join(realpath(dirname(__file__)), 'data', dataset) if (not exists(base_path)): print('Please download OTB dataset into `data` folder!') exit() json_path = join(realpath(dirname(__file__)), 'data', (dataset + '.json')) info = json.load(open(json_path, 'r')) for v in info.keys(): path_name = info[v]['name'] info[v]['image_files'] = [join(base_path, path_name, 'img', im_f) for im_f in info[v]['image_files']] info[v]['gt'] = (np.array(info[v]['gt_rect']) - [1, 1, 0, 0]) info[v]['name'] = v return info
def main(): global args, v_id args = parser.parse_args() net = SiamRPNotb() net.load_state_dict(torch.load(join(realpath(dirname(__file__)), 'SiamRPNOTB.model'))) net.eval().cuda() dataset = load_dataset(args.dataset) fps_list = [] for (v_id, video) in enumerate(dataset.keys()): if (v_id > (- 1)): fps_list.append(track_video(net, dataset[video])) print('Mean Running Speed {:.1f}fps'.format(np.mean(np.array(fps_list))))
def track_video(model, video): image_save = 0 (toc, regions) = (0, []) (image_files, gt) = (video['image_files'], video['gt']) for (f, image_file) in enumerate(image_files): im = cv2.imread(image_file) tic = cv2.getTickCount() if (f == 0): (target_pos, target_sz) = rect_2_cxy_wh(gt[f]) state = SiamRPN_init(im, target_pos, target_sz, model) location = cxy_wh_2_rect(state['target_pos'], state['target_sz']) regions.append(gt[f]) att_per = 0 def_per = 0 elif (f > 0): if ((f % 30) == 1): att_per = 0 def_per = 0 (state, att_per, def_per) = SiamRPN_track(state, im, f, regions[(f - 1)], att_per, def_per, image_save, iter=10) location = cxy_wh_2_rect((state['target_pos'] + 1), state['target_sz']) regions.append(location) else: (state, att_per, def_per) = SiamRPN_track(state, im, f, regions[(f - 1)], att_per, def_per, image_save, iter=5) location = cxy_wh_2_rect((state['target_pos'] + 1), state['target_sz']) regions.append(location) toc += (cv2.getTickCount() - tic) if (args.visualization and (f >= 0)): if (f == 0): cv2.destroyAllWindows() if (len(gt[f]) == 8): cv2.polylines(im, [np.array(gt[f], np.int).reshape(((- 1), 1, 2))], True, (0, 255, 0), 2) else: cv2.rectangle(im, (gt[(f, 0)], gt[(f, 1)]), ((gt[(f, 0)] + gt[(f, 2)]), (gt[(f, 1)] + gt[(f, 3)])), (0, 255, 0), 2) if (len(location) == 8): cv2.polylines(im, [location.reshape(((- 1), 1, 2))], True, (0, 255, 255), 2) else: location = [int(l) for l in location] cv2.rectangle(im, (location[0], location[1]), ((location[0] + location[2]), (location[1] + location[3])), (0, 255, 255), 2) cv2.putText(im, str(f), (40, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2) cv2.imshow(video['name'], im) cv2.waitKey(1) toc /= cv2.getTickFrequency() video_path = join('test', args.dataset, 'DaSiamRPN_defense') if (not isdir(video_path)): makedirs(video_path) result_path = join(video_path, '{:s}.txt'.format(video['name'])) with open(result_path, 'w') as fin: for x in regions: fin.write((','.join([str(i) for i in x]) + '\n')) print('({:d}) Video: {:12s} Time: {:02.1f}s Speed: {:3.1f}fps'.format(v_id, video['name'], toc, (f / toc))) return (f / toc)
def load_dataset(dataset): base_path = join(realpath(dirname(__file__)), 'data', dataset) if (not exists(base_path)): print('Please download OTB dataset into `data` folder!') exit() json_path = join(realpath(dirname(__file__)), 'data', (dataset + '.json')) info = json.load(open(json_path, 'r')) for v in info.keys(): path_name = info[v]['name'] info[v]['image_files'] = [join(base_path, path_name, 'img', im_f) for im_f in info[v]['image_files']] info[v]['gt'] = (np.array(info[v]['gt_rect']) - [1, 1, 0, 0]) info[v]['name'] = v return info
def main(): global args, v_id args = parser.parse_args() net = SiamRPNotb() net.load_state_dict(torch.load(join(realpath(dirname(__file__)), 'SiamRPNOTB.model'))) net.eval().cuda() dataset = load_dataset(args.dataset) fps_list = [] for (v_id, video) in enumerate(dataset.keys()): fps_list.append(track_video(net, dataset[video])) print('Mean Running Speed {:.1f}fps'.format(np.mean(np.array(fps_list))))
def recode_cc_data(frame): ' Recodes numeric categorical variables into categorical character variables\n with more transparent values. \n \n Args:\n frame: Pandas DataFrame version of UCI credit card default data.\n \n Returns: \n H2OFrame with recoded values.\n \n ' sex_dict = {1: 'male', 2: 'female'} education_dict = {0: 'other', 1: 'graduate school', 2: 'university', 3: 'high school', 4: 'other', 5: 'other', 6: 'other'} marriage_dict = {0: 'other', 1: 'married', 2: 'single', 3: 'divorced'} pay_dict = {(- 2): 'no consumption', (- 1): 'pay duly', 0: 'use of revolving credit', 1: '1 month delay', 2: '2 month delay', 3: '3 month delay', 4: '4 month delay', 5: '5 month delay', 6: '6 month delay', 7: '7 month delay', 8: '8 month delay', 9: '9+ month delay'} frame['SEX'] = frame['SEX'].apply((lambda i: sex_dict[i])) frame['EDUCATION'] = frame['EDUCATION'].apply((lambda i: education_dict[i])) frame['MARRIAGE'] = frame['MARRIAGE'].apply((lambda i: marriage_dict[i])) for name in frame.columns: if (name in ['PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']): frame[name] = frame[name].apply((lambda i: pay_dict[i])) return h2o.H2OFrame(frame)
def generate_local_sample(row, frame, X, N=1000): ' Generates a perturbed sample around a row of interest.\n \n Args:\n row: Row of H2OFrame to be explained.\n frame: H2OFrame in which row is stored.\n X: List of model input variables.\n N: Number of samples to generate.\n \n Returns:\n Pandas DataFrame containing perturbed sample.\n \n ' sample_frame = pd.DataFrame(data=np.zeros(shape=(N, len(X))), columns=X) for (key, val) in frame[X].types.items(): if (val == 'enum'): rs = np.random.RandomState(11111) draw = rs.choice(frame[key].levels()[0], size=(1, N))[0] else: rs = np.random.RandomState(11111) loc = row[key][(0, 0)] sd = frame[key].sd() draw = rs.normal(loc, sd, (N, 1)) draw[(draw < 0)] = loc sample_frame[key] = draw return sample_frame
def plot_local_contrib(row, model, X, g_pred=None, scale=False): ' Plots reason codes in a bar chart. \n \n Args:\n \n row: Row of H2OFrame to be explained.\n model: H2O linear model used for generating reason codes.\n X: List of model input variables.\n g_pred: Prediction of model to be explained, sometimes denoted g, used for scaling.\n scale: Whether to rescale contributions to sum to model predictions.\n \n ' local_contrib_frame = pd.DataFrame(columns=['Name', 'Local Contribution', 'Sign']) for (key, val) in sorted(row[X].types.items()): contrib = 0 name = '' if (val == 'enum'): level = row[key][(0, 0)] name = '.'.join([str(key), str(level)]) if (name in model.coef()): contrib = model.coef()[name] else: name = key if (name in model.coef()): contrib = (row[name][(0, 0)] * model.coef()[name]) if (contrib != 0.0): local_contrib_frame = local_contrib_frame.append({'Name': name, 'Local Contribution': contrib, 'Sign': (contrib > 0)}, ignore_index=True) if scale: scaler = ((g_pred - model.coef()['Intercept']) / local_contrib_frame['Local Contribution'].sum()) local_contrib_frame['Local Contribution'] *= scaler _ = local_contrib_frame.plot(x='Name', y='Local Contribution', kind='bar', title='Reason Codes', color=local_contrib_frame.Sign.map({True: 'b', False: 'g'}), legend=False)
def recode_cc_data(frame): ' Recodes numeric categorical variables into categorical character variables\n with more transparent values. \n \n Args:\n frame: Pandas DataFrame version of UCI credit card default data.\n \n Returns: \n H2OFrame with recoded values.\n \n ' sex_dict = {1: 'male', 2: 'female'} education_dict = {0: 'other', 1: 'graduate school', 2: 'university', 3: 'high school', 4: 'other', 5: 'other', 6: 'other'} marriage_dict = {0: 'other', 1: 'married', 2: 'single', 3: 'divorced'} pay_dict = {(- 2): 'no consumption', (- 1): 'pay duly', 0: 'use of revolving credit', 1: '1 month delay', 2: '2 month delay', 3: '3 month delay', 4: '4 month delay', 5: '5 month delay', 6: '6 month delay', 7: '7 month delay', 8: '8 month delay', 9: '9+ month delay'} frame['SEX'] = frame['SEX'].apply((lambda i: sex_dict[i])) frame['EDUCATION'] = frame['EDUCATION'].apply((lambda i: education_dict[i])) frame['MARRIAGE'] = frame['MARRIAGE'].apply((lambda i: marriage_dict[i])) for name in frame.columns: if (name in ['PAY_0', 'PAY_2', 'PAY_3', 'PAY_4', 'PAY_5', 'PAY_6']): frame[name] = frame[name].apply((lambda i: pay_dict[i])) return h2o.H2OFrame(frame)
def get_percentile_dict(yhat, id_, frame): ' Returns the minimum, the maximum, and the deciles of a column, yhat, \n as the indices based on another column id_.\n \n Args:\n yhat: Column in which to find percentiles.\n id_: Id column that stores indices for percentiles of yhat.\n frame: H2OFrame containing yhat and id_. \n \n Returns:\n Dictionary of percentile values and index column values.\n \n ' sort_df = frame.as_data_frame() sort_df.sort_values(yhat, inplace=True) sort_df.reset_index(inplace=True) percentiles_dict = {} percentiles_dict[0] = sort_df.loc[(0, id_)] percentiles_dict[99] = sort_df.loc[((sort_df.shape[0] - 1), id_)] inc = (sort_df.shape[0] // 10) for i in range(1, 10): percentiles_dict[(i * 10)] = sort_df.loc[((i * inc), id_)] return percentiles_dict
def dataloader_msrvtt_train(args, tokenizer): msrvtt_dataset = MSRVTTDataset(subset='train', anno_path=args.anno_path, video_path=args.video_path, max_words=args.max_words, tokenizer=tokenizer, max_frames=args.max_frames, video_framerate=args.video_framerate, config=args) try: train_sampler = torch.utils.data.distributed.DistributedSampler(msrvtt_dataset) except: train_sampler = None dataloader = DataLoader(msrvtt_dataset, batch_size=(args.batch_size // args.world_size), num_workers=args.workers, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True) return (dataloader, len(msrvtt_dataset), train_sampler)
def dataloader_msrvtt_test(args, tokenizer, subset='test'): msrvtt_testset = MSRVTTDataset(subset=subset, anno_path=args.anno_path, video_path=args.video_path, max_words=args.max_words, tokenizer=tokenizer, max_frames=args.max_frames, video_framerate=args.video_framerate, config=args) try: test_sampler = torch.utils.data.distributed.DistributedSampler(msrvtt_testset) except: test_sampler = None dataloader_msrvtt = DataLoader(msrvtt_testset, batch_size=(args.batch_size_val // args.world_size), num_workers=args.workers, shuffle=False, sampler=test_sampler, drop_last=False) return (dataloader_msrvtt, len(msrvtt_testset))
def dataloader_activity_train(args, tokenizer): activity_dataset = ActivityNetDataset(subset='train', data_path=args.anno_path, features_path=args.video_path, max_words=args.max_words, feature_framerate=args.video_framerate, tokenizer=tokenizer, max_frames=args.max_frames) train_sampler = torch.utils.data.distributed.DistributedSampler(activity_dataset) dataloader = DataLoader(activity_dataset, batch_size=(args.batch_size // args.world_size), num_workers=args.workers, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True) return (dataloader, len(activity_dataset), train_sampler)
def dataloader_activity_test(args, tokenizer, subset='test'): activity_testset = ActivityNetDataset(subset=subset, data_path=args.anno_path, features_path=args.video_path, max_words=args.max_words, feature_framerate=args.video_framerate, tokenizer=tokenizer, max_frames=args.max_frames) try: test_sampler = torch.utils.data.distributed.DistributedSampler(activity_testset) except: test_sampler = None dataloader_activity = DataLoader(activity_testset, batch_size=(args.batch_size_val // args.world_size), num_workers=args.workers, shuffle=False, sampler=test_sampler, drop_last=False) return (dataloader_activity, len(activity_testset))
def dataloader_didemo_train(args, tokenizer): didemo_dataset = DiDeMoDataset(subset='train', data_path=args.anno_path, features_path=args.video_path, max_words=args.max_words, feature_framerate=args.video_framerate, tokenizer=tokenizer, max_frames=args.max_frames) train_sampler = torch.utils.data.distributed.DistributedSampler(didemo_dataset) dataloader = DataLoader(didemo_dataset, batch_size=(args.batch_size // args.world_size), num_workers=args.workers, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True) return (dataloader, len(didemo_dataset), train_sampler)
def dataloader_didemo_test(args, tokenizer, subset='test'): didemo_testset = DiDeMoDataset(subset=subset, data_path=args.anno_path, features_path=args.video_path, max_words=args.max_words, feature_framerate=args.video_framerate, tokenizer=tokenizer, max_frames=args.max_frames) try: test_sampler = torch.utils.data.distributed.DistributedSampler(didemo_testset) except: test_sampler = None dataloader_didemo = DataLoader(didemo_testset, batch_size=(args.batch_size_val // args.world_size), num_workers=args.workers, shuffle=False, sampler=test_sampler, drop_last=False) return (dataloader_didemo, len(didemo_testset))
class MSRVTTDataset(RetrievalDataset): 'MSRVTT dataset.' def __init__(self, subset, anno_path, video_path, tokenizer, max_words=32, max_frames=12, video_framerate=1, image_resolution=224, mode='all', config=None): super(MSRVTTDataset, self).__init__(subset, anno_path, video_path, tokenizer, max_words, max_frames, video_framerate, image_resolution, mode, config=config) pass def _get_anns(self, subset='train'): '\n video_dict: dict: video_id -> video_path\n sentences_dict: list: [(video_id, caption)] , caption (list: [text:, start, end])\n ' csv_path = {'train': join(self.anno_path, 'MSRVTT_train.9k.csv'), 'val': join(self.anno_path, 'MSRVTT_JSFUSION_test.csv'), 'test': join(self.anno_path, 'MSRVTT_JSFUSION_test.csv')}[subset] if exists(csv_path): csv = pd.read_csv(csv_path) else: raise FileNotFoundError video_id_list = list(csv['video_id'].values) video_dict = OrderedDict() sentences_dict = OrderedDict() if (subset == 'train'): anno_path = join(self.anno_path, 'MSRVTT_data.json') data = json.load(open(anno_path, 'r')) for itm in data['sentences']: if (itm['video_id'] in video_id_list): sentences_dict[len(sentences_dict)] = (itm['video_id'], (itm['caption'], None, None)) video_dict[itm['video_id']] = join(self.video_path, '{}.mp4'.format(itm['video_id'])) else: for (_, itm) in csv.iterrows(): sentences_dict[len(sentences_dict)] = (itm['video_id'], (itm['sentence'], None, None)) video_dict[itm['video_id']] = join(self.video_path, '{}.mp4'.format(itm['video_id'])) unique_sentence = set([v[1][0] for v in sentences_dict.values()]) print('[{}] Unique sentence is {} , all num is {}'.format(subset, len(unique_sentence), len(sentences_dict))) return (video_dict, sentences_dict)
def _interpolation(kwargs): interpolation = kwargs.pop('resample', Image.BILINEAR) if isinstance(interpolation, (list, tuple)): return random.choice(interpolation) else: return interpolation
def _check_args_tf(kwargs): if (('fillcolor' in kwargs) and (_PIL_VER < (5, 0))): kwargs.pop('fillcolor') kwargs['resample'] = _interpolation(kwargs)
def shear_x(img, factor, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, factor, 0, 0, 1, 0), **kwargs)
def shear_y(img, factor, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, factor, 1, 0), **kwargs)
def translate_x_rel(img, pct, **kwargs): pixels = (pct * img.size[0]) _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
def translate_y_rel(img, pct, **kwargs): pixels = (pct * img.size[1]) _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
def translate_x_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, pixels, 0, 1, 0), **kwargs)
def translate_y_abs(img, pixels, **kwargs): _check_args_tf(kwargs) return img.transform(img.size, Image.AFFINE, (1, 0, 0, 0, 1, pixels), **kwargs)
def rotate(img, degrees, **kwargs): _check_args_tf(kwargs) if (_PIL_VER >= (5, 2)): return img.rotate(degrees, **kwargs) elif (_PIL_VER >= (5, 0)): (w, h) = img.size post_trans = (0, 0) rotn_center = ((w / 2.0), (h / 2.0)) angle = (- math.radians(degrees)) matrix = [round(math.cos(angle), 15), round(math.sin(angle), 15), 0.0, round((- math.sin(angle)), 15), round(math.cos(angle), 15), 0.0] def transform(x, y, matrix): (a, b, c, d, e, f) = matrix return ((((a * x) + (b * y)) + c), (((d * x) + (e * y)) + f)) (matrix[2], matrix[5]) = transform(((- rotn_center[0]) - post_trans[0]), ((- rotn_center[1]) - post_trans[1]), matrix) matrix[2] += rotn_center[0] matrix[5] += rotn_center[1] return img.transform(img.size, Image.AFFINE, matrix, **kwargs) else: return img.rotate(degrees, resample=kwargs['resample'])
def auto_contrast(img, **__): return ImageOps.autocontrast(img)
def invert(img, **__): return ImageOps.invert(img)
def equalize(img, **__): return ImageOps.equalize(img)
def solarize(img, thresh, **__): return ImageOps.solarize(img, thresh)
def solarize_add(img, add, thresh=128, **__): lut = [] for i in range(256): if (i < thresh): lut.append(min(255, (i + add))) else: lut.append(i) if (img.mode in ('L', 'RGB')): if ((img.mode == 'RGB') and (len(lut) == 256)): lut = ((lut + lut) + lut) return img.point(lut) else: return img
def posterize(img, bits_to_keep, **__): if (bits_to_keep >= 8): return img return ImageOps.posterize(img, bits_to_keep)
def contrast(img, factor, **__): return ImageEnhance.Contrast(img).enhance(factor)
def color(img, factor, **__): return ImageEnhance.Color(img).enhance(factor)
def brightness(img, factor, **__): return ImageEnhance.Brightness(img).enhance(factor)
def sharpness(img, factor, **__): return ImageEnhance.Sharpness(img).enhance(factor)
def _randomly_negate(v): 'With 50% prob, negate the value' return ((- v) if (random.random() > 0.5) else v)
def _rotate_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 30.0) level = _randomly_negate(level) return (level,)
def _enhance_level_to_arg(level, _hparams): return ((((level / _MAX_LEVEL) * 1.8) + 0.1),)
def _enhance_increasing_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 0.9) level = (1.0 + _randomly_negate(level)) return (level,)
def _shear_level_to_arg(level, _hparams): level = ((level / _MAX_LEVEL) * 0.3) level = _randomly_negate(level) return (level,)
def _translate_abs_level_to_arg(level, hparams): translate_const = hparams['translate_const'] level = ((level / _MAX_LEVEL) * float(translate_const)) level = _randomly_negate(level) return (level,)
def _translate_rel_level_to_arg(level, hparams): translate_pct = hparams.get('translate_pct', 0.45) level = ((level / _MAX_LEVEL) * translate_pct) level = _randomly_negate(level) return (level,)
def _posterize_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 4)),)
def _posterize_increasing_level_to_arg(level, hparams): return ((4 - _posterize_level_to_arg(level, hparams)[0]),)
def _posterize_original_level_to_arg(level, _hparams): return ((int(((level / _MAX_LEVEL) * 4)) + 4),)
def _solarize_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 256)),)
def _solarize_increasing_level_to_arg(level, _hparams): return ((256 - _solarize_level_to_arg(level, _hparams)[0]),)
def _solarize_add_level_to_arg(level, _hparams): return (int(((level / _MAX_LEVEL) * 110)),)
class AugmentOp(): '\n Apply for video.\n ' def __init__(self, name, prob=0.5, magnitude=10, hparams=None): hparams = (hparams or _HPARAMS_DEFAULT) self.aug_fn = NAME_TO_OP[name] self.level_fn = LEVEL_TO_ARG[name] self.prob = prob self.magnitude = magnitude self.hparams = hparams.copy() self.kwargs = {'fillcolor': (hparams['img_mean'] if ('img_mean' in hparams) else _FILL), 'resample': (hparams['interpolation'] if ('interpolation' in hparams) else _RANDOM_INTERPOLATION)} self.magnitude_std = self.hparams.get('magnitude_std', 0) def __call__(self, img_list): if ((self.prob < 1.0) and (random.random() > self.prob)): return img_list magnitude = self.magnitude if (self.magnitude_std and (self.magnitude_std > 0)): magnitude = random.gauss(magnitude, self.magnitude_std) magnitude = min(_MAX_LEVEL, max(0, magnitude)) level_args = (self.level_fn(magnitude, self.hparams) if (self.level_fn is not None) else ()) if isinstance(img_list, list): return [self.aug_fn(img, *level_args, **self.kwargs) for img in img_list] else: return self.aug_fn(img_list, *level_args, **self.kwargs)
def _select_rand_weights(weight_idx=0, transforms=None): transforms = (transforms or _RAND_TRANSFORMS) assert (weight_idx == 0) rand_weights = _RAND_CHOICE_WEIGHTS_0 probs = [rand_weights[k] for k in transforms] probs /= np.sum(probs) return probs
def rand_augment_ops(magnitude=10, hparams=None, transforms=None): hparams = (hparams or _HPARAMS_DEFAULT) transforms = (transforms or _RAND_TRANSFORMS) return [AugmentOp(name, prob=0.5, magnitude=magnitude, hparams=hparams) for name in transforms]
class RandAugment(): def __init__(self, ops, num_layers=2, choice_weights=None): self.ops = ops self.num_layers = num_layers self.choice_weights = choice_weights def __call__(self, img): ops = np.random.choice(self.ops, self.num_layers, replace=(self.choice_weights is None), p=self.choice_weights) for op in ops: img = op(img) return img
def rand_augment_transform(config_str, hparams): "\n RandAugment: Practical automated data augmentation... - https://arxiv.org/abs/1909.13719\n\n Create a RandAugment transform\n :param config_str: String defining configuration of random augmentation. Consists of multiple sections separated by\n dashes ('-'). The first section defines the specific variant of rand augment (currently only 'rand'). The remaining\n sections, not order sepecific determine\n 'm' - integer magnitude of rand augment\n 'n' - integer num layers (number of transform ops selected per image)\n 'w' - integer probabiliy weight index (index of a set of weights to influence choice of op)\n 'mstd' - float std deviation of magnitude noise applied\n 'inc' - integer (bool), use augmentations that increase in severity with magnitude (default: 0)\n Ex 'rand-m9-n3-mstd0.5' results in RandAugment with magnitude 9, num_layers 3, magnitude_std 0.5\n 'rand-mstd1-w0' results in magnitude_std 1.0, weights 0, default magnitude of 10 and num_layers 2\n :param hparams: Other hparams (kwargs) for the RandAugmentation scheme\n :return: A PyTorch compatible Transform\n " magnitude = _MAX_LEVEL num_layers = 2 weight_idx = None transforms = _RAND_TRANSFORMS config = config_str.split('-') assert (config[0] == 'rand') config = config[1:] for c in config: cs = re.split('(\\d.*)', c) if (len(cs) < 2): continue (key, val) = cs[:2] if (key == 'mstd'): hparams.setdefault('magnitude_std', float(val)) elif (key == 'inc'): if bool(val): transforms = _RAND_INCREASING_TRANSFORMS elif (key == 'm'): magnitude = int(val) elif (key == 'n'): num_layers = int(val) elif (key == 'w'): weight_idx = int(val) else: assert NotImplementedError ra_ops = rand_augment_ops(magnitude=magnitude, hparams=hparams, transforms=transforms) choice_weights = (None if (weight_idx is None) else _select_rand_weights(weight_idx)) return RandAugment(ra_ops, num_layers, choice_weights=choice_weights)
class RawVideoExtractorCV2(): def __init__(self, centercrop=False, size=224, framerate=(- 1), subset='test'): self.centercrop = centercrop self.size = size self.framerate = framerate self.transform = self._transform(self.size) self.subset = subset self.tsfm_dict = {'clip_test': Compose([Resize(size, interpolation=InterpolationMode.BICUBIC), CenterCrop(size), (lambda image: image.convert('RGB')), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))]), 'clip_train': Compose([RandomResizedCrop(size, scale=(0.5, 1.0)), RandomHorizontalFlip(), (lambda image: image.convert('RGB')), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))])} self.aug_transform = video_transforms.create_random_augment(input_size=(size, size), auto_augment='rand-m7-n4-mstd0.5-inc1', interpolation='bicubic') def _transform(self, n_px): return Compose([Resize(n_px, interpolation=InterpolationMode.BICUBIC), CenterCrop(n_px), (lambda image: image.convert('RGB')), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))]) def video_to_tensor(self, video_file, preprocess, sample_fp=0, start_time=None, end_time=None, _no_process=False): if ((start_time is not None) or (end_time is not None)): assert (isinstance(start_time, int) and isinstance(end_time, int) and (start_time > (- 1)) and (end_time > start_time)) assert (sample_fp > (- 1)) cap = cv2.VideoCapture(video_file) frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) if (fps == 0): print(((video_file + '\n') * 10)) total_duration = (((frameCount + fps) - 1) // fps) (start_sec, end_sec) = (0, total_duration) if (start_time is not None): (start_sec, end_sec) = (start_time, (end_time if (end_time <= total_duration) else total_duration)) cap.set(cv2.CAP_PROP_POS_FRAMES, int((start_time * fps))) interval = 1 if (sample_fp > 0): interval = (fps // sample_fp) else: sample_fp = fps if (interval == 0): interval = 1 inds = [ind for ind in np.arange(0, fps, interval)] assert (len(inds) >= sample_fp) inds = inds[:sample_fp] ret = True (images, included) = ([], []) for sec in np.arange(start_sec, (end_sec + 1)): if (not ret): break sec_base = int((sec * fps)) for ind in inds: cap.set(cv2.CAP_PROP_POS_FRAMES, (sec_base + ind)) (ret, frame) = cap.read() if (not ret): break frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if _no_process: images.append(Image.fromarray(frame_rgb).convert('RGB')) else: images.append(Image.fromarray(frame_rgb)) cap.release() if (len(images) > 0): if _no_process: video_data = images else: if (self.subset == 'train'): images = self.aug_transform(images) video_data = th.stack([preprocess(img) for img in images]) else: video_data = th.zeros(1) return {'video': video_data} def get_video_data(self, video_path, start_time=None, end_time=None, _no_process=False): image_input = self.video_to_tensor(video_path, self.transform, sample_fp=self.framerate, start_time=start_time, end_time=end_time, _no_process=_no_process) return image_input def process_raw_data(self, raw_video_data): tensor_size = raw_video_data.size() tensor = raw_video_data.view((- 1), 1, tensor_size[(- 3)], tensor_size[(- 2)], tensor_size[(- 1)]) return tensor def process_frame_order(self, raw_video_data, frame_order=0): if (frame_order == 0): pass elif (frame_order == 1): reverse_order = np.arange((raw_video_data.size(0) - 1), (- 1), (- 1)) raw_video_data = raw_video_data[(reverse_order, ...)] elif (frame_order == 2): random_order = np.arange(raw_video_data.size(0)) np.random.shuffle(random_order) raw_video_data = raw_video_data[(random_order, ...)] return raw_video_data
def url_to_filename(url: str, etag: str=None) -> str: "\n Convert `url` into a hashed filename in a repeatable way.\n If `etag` is specified, append its hash to the url's, delimited\n by a period.\n " url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdigest() if etag: etag_bytes = etag.encode('utf-8') etag_hash = sha256(etag_bytes) filename += ('.' + etag_hash.hexdigest()) return filename
def filename_to_url(filename: str, cache_dir: Union[(str, Path)]=None) -> Tuple[(str, str)]: '\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.\n ' if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if isinstance(cache_dir, Path): cache_dir = str(cache_dir) cache_path = os.path.join(cache_dir, filename) if (not os.path.exists(cache_path)): raise FileNotFoundError('file {} not found'.format(cache_path)) meta_path = (cache_path + '.json') if (not os.path.exists(meta_path)): raise FileNotFoundError('file {} not found'.format(meta_path)) with open(meta_path) as meta_file: metadata = json.load(meta_file) url = metadata['url'] etag = metadata['etag'] return (url, etag)
def cached_path(url_or_filename: Union[(str, Path)], cache_dir: Union[(str, Path)]=None) -> str: "\n Given something that might be a URL (or might be a local path),\n determine which. If it's a URL, download the file and cache it, and\n return the path to the cached file. If it's already a local path,\n make sure the file exists and then return the path.\n " if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if isinstance(url_or_filename, Path): url_or_filename = str(url_or_filename) if isinstance(cache_dir, Path): cache_dir = str(cache_dir) parsed = urlparse(url_or_filename) if (parsed.scheme in ('http', 'https', 's3')): return get_from_cache(url_or_filename, cache_dir) elif os.path.exists(url_or_filename): return url_or_filename elif (parsed.scheme == ''): raise FileNotFoundError('file {} not found'.format(url_or_filename)) else: raise ValueError('unable to parse {} as a URL or as a local path'.format(url_or_filename))
def split_s3_path(url: str) -> Tuple[(str, str)]: 'Split a full s3 path into the bucket name and path.' parsed = urlparse(url) if ((not parsed.netloc) or (not parsed.path)): raise ValueError('bad s3 path {}'.format(url)) bucket_name = parsed.netloc s3_path = parsed.path if s3_path.startswith('/'): s3_path = s3_path[1:] return (bucket_name, s3_path)
def s3_request(func: Callable): '\n Wrapper function for s3 requests in order to create more helpful error\n messages.\n ' @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if (int(exc.response['Error']['Code']) == 404): raise FileNotFoundError('file {} not found'.format(url)) else: raise return wrapper
@s3_request def s3_etag(url: str) -> Optional[str]: 'Check ETag on S3 object.' s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
@s3_request def s3_get(url: str, temp_file: IO) -> None: 'Pull a file directly from S3.' s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
def http_get(url: str, temp_file: IO) -> None: req = requests.get(url, stream=True) content_length = req.headers.get('Content-Length') total = (int(content_length) if (content_length is not None) else None) progress = tqdm(unit='B', total=total) for chunk in req.iter_content(chunk_size=1024): if chunk: progress.update(len(chunk)) temp_file.write(chunk) progress.close()
def get_from_cache(url: str, cache_dir: Union[(str, Path)]=None) -> str: "\n Given a URL, look for the corresponding dataset in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n " if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if isinstance(cache_dir, Path): cache_dir = str(cache_dir) os.makedirs(cache_dir, exist_ok=True) if url.startswith('s3://'): etag = s3_etag(url) else: response = requests.head(url, allow_redirects=True) if (response.status_code != 200): raise IOError('HEAD request failed for url {} with status code {}'.format(url, response.status_code)) etag = response.headers.get('ETag') filename = url_to_filename(url, etag) cache_path = os.path.join(cache_dir, filename) if (not os.path.exists(cache_path)): with tempfile.NamedTemporaryFile() as temp_file: logger.info('%s not found in cache, downloading to %s', url, temp_file.name) if url.startswith('s3://'): s3_get(url, temp_file) else: http_get(url, temp_file) temp_file.flush() temp_file.seek(0) logger.info('copying %s to cache at %s', temp_file.name, cache_path) with open(cache_path, 'wb') as cache_file: shutil.copyfileobj(temp_file, cache_file) logger.info('creating metadata file for %s', cache_path) meta = {'url': url, 'etag': etag} meta_path = (cache_path + '.json') with open(meta_path, 'w') as meta_file: json.dump(meta, meta_file) logger.info('removing temp file %s', temp_file.name) return cache_path
def read_set_from_file(filename: str) -> Set[str]: '\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n ' collection = set() with open(filename, 'r', encoding='utf-8') as file_: for line in file_: collection.add(line.rstrip()) return collection
def get_file_extension(path: str, dot=True, lower: bool=True): ext = os.path.splitext(path)[1] ext = (ext if dot else ext[1:]) return (ext.lower() if lower else ext)
class LayerNorm(nn.LayerNorm): "Subclass torch's LayerNorm to handle fp16." def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type)
class QuickGELU(nn.Module): def forward(self, x: torch.Tensor): return (x * torch.sigmoid((1.702 * x)))
class ResidualAttentionBlock(nn.Module): def __init__(self, d_model: int, n_head: int, attn_mask=None): super(ResidualAttentionBlock, self).__init__() self.attn = nn.MultiheadAttention(d_model, n_head) self.ln_1 = LayerNorm(d_model) self.mlp = nn.Sequential(OrderedDict([('c_fc', nn.Linear(d_model, (d_model * 4))), ('gelu', QuickGELU()), ('c_proj', nn.Linear((d_model * 4), d_model))])) self.ln_2 = LayerNorm(d_model) self.attn_mask = attn_mask self.n_head = n_head def attention(self, x: torch.Tensor, attn_mask_: torch.Tensor): attn_mask_ = attn_mask_.repeat_interleave(self.n_head, dim=0) attn_mask_ = (attn_mask_.to(dtype=x.dtype, device=x.device) if (attn_mask_ is not None) else None) return self.attn(x, x, x, need_weights=False, attn_mask=attn_mask_)[0] def forward(self, para_tuple: tuple): (x, attn_mask) = para_tuple x = (x + self.attention(self.ln_1(x), attn_mask)) x = (x + self.mlp(self.ln_2(x))) return (x, attn_mask)
class Transformer(nn.Module): def __init__(self, width: int, layers: int, heads: int, attn_mask=None): super(Transformer, self).__init__() self.width = width self.layers = layers self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads) for _ in range(layers)]) def forward(self, x: torch.Tensor, attn_mask: torch.Tensor): return self.resblocks((x, attn_mask))[0]
def warmup_cosine(x, warmup=0.002): if (x < warmup): return (x / warmup) return (0.5 * (1.0 + math.cos((math.pi * x))))
def warmup_constant(x, warmup=0.002): ' Linearly increases learning rate over `warmup`*`t_total` (as provided to BertAdam) training steps.\n Learning rate is 1. afterwards. ' if (x < warmup): return (x / warmup) return 1.0
def warmup_linear(x, warmup=0.002): ' Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step.\n After `t_total`-th training step, learning rate is zero. ' if (x < warmup): return (x / warmup) return max(((x - 1.0) / (warmup - 1.0)), 0)
class BertAdam(Optimizer): "Implements BERT version of Adam algorithm with weight decay fix.\n Params:\n lr: learning rate\n warmup: portion of t_total for the warmup, -1 means no warmup. Default: -1\n t_total: total number of training steps for the learning\n rate schedule, -1 means constant learning rate. Default: -1\n schedule: schedule to use for the warmup (see above). Default: 'warmup_linear'\n b1: Adams b1. Default: 0.9\n b2: Adams b2. Default: 0.999\n e: Adams epsilon. Default: 1e-6\n weight_decay: Weight decay. Default: 0.01\n max_grad_norm: Maximum norm for the gradients (-1 means no clipping). Default: 1.0\n " def __init__(self, params, lr=required, warmup=(- 1), t_total=(- 1), schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-06, weight_decay=0.01, max_grad_norm=1.0): if ((lr is not required) and (lr < 0.0)): raise ValueError('Invalid learning rate: {} - should be >= 0.0'.format(lr)) if (schedule not in SCHEDULES): raise ValueError('Invalid schedule parameter: {}'.format(schedule)) if ((not (0.0 <= warmup < 1.0)) and (not (warmup == (- 1)))): raise ValueError('Invalid warmup: {} - should be in [0.0, 1.0[ or -1'.format(warmup)) if (not (0.0 <= b1 < 1.0)): raise ValueError('Invalid b1 parameter: {} - should be in [0.0, 1.0['.format(b1)) if (not (0.0 <= b2 < 1.0)): raise ValueError('Invalid b2 parameter: {} - should be in [0.0, 1.0['.format(b2)) if (not (e >= 0.0)): raise ValueError('Invalid epsilon value: {} - should be >= 0.0'.format(e)) defaults = dict(lr=lr, schedule=schedule, warmup=warmup, t_total=t_total, b1=b1, b2=b2, e=e, weight_decay=weight_decay, max_grad_norm=max_grad_norm) super(BertAdam, self).__init__(params, defaults) def get_lr(self): lr = [] for group in self.param_groups: for p in group['params']: if (p.grad is None): continue state = self.state[p] if (len(state) == 0): return [0] if (group['t_total'] != (- 1)): schedule_fct = SCHEDULES[group['schedule']] lr_scheduled = (group['lr'] * schedule_fct((state['step'] / group['t_total']), group['warmup'])) else: lr_scheduled = group['lr'] lr.append(lr_scheduled) return lr def step(self, closure=None): 'Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n ' loss = None if (closure is not None): loss = closure() for group in self.param_groups: for p in group['params']: if (p.grad is None): continue grad = p.grad.data if grad.is_sparse: raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] if (len(state) == 0): state['step'] = 0 state['next_m'] = torch.zeros_like(p.data) state['next_v'] = torch.zeros_like(p.data) (next_m, next_v) = (state['next_m'], state['next_v']) (beta1, beta2) = (group['b1'], group['b2']) if (group['max_grad_norm'] > 0): clip_grad_norm_(p, group['max_grad_norm']) next_m.mul_(beta1).add_(grad, alpha=(1 - beta1)) next_v.mul_(beta2).addcmul_(grad, grad, value=(1 - beta2)) update = (next_m / (next_v.sqrt() + group['e'])) if (group['weight_decay'] > 0.0): update += (group['weight_decay'] * p.data) if (group['t_total'] != (- 1)): schedule_fct = SCHEDULES[group['schedule']] progress = (state['step'] / group['t_total']) lr_scheduled = (group['lr'] * schedule_fct(progress, group['warmup'])) else: lr_scheduled = group['lr'] update_with_lr = (lr_scheduled * update) p.data.add_((- update_with_lr)) state['step'] += 1 return loss
@lru_cache() def default_bpe(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bpe_simple_vocab_16e6.txt.gz')
@lru_cache() def bytes_to_unicode(): "\n Returns list of utf-8 byte and a corresponding list of unicode strings.\n The reversible bpe codes work on unicode strings.\n This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.\n When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.\n This is a signficant percentage of your normal, say, 32K bpe vocab.\n To avoid that, we want lookup tables between utf-8 bytes and unicode strings.\n And avoids mapping to whitespace/control characters the bpe code barfs on.\n " bs = ((list(range(ord('!'), (ord('~') + 1))) + list(range(ord('¡'), (ord('¬') + 1)))) + list(range(ord('®'), (ord('ÿ') + 1)))) cs = bs[:] n = 0 for b in range((2 ** 8)): if (b not in bs): bs.append(b) cs.append(((2 ** 8) + n)) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs))
def get_pairs(word): 'Return set of symbol pairs in a word.\n Word is represented as tuple of symbols (symbols being variable-length strings).\n ' pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs
def basic_clean(text): text = ftfy.fix_text(text) text = html.unescape(html.unescape(text)) return text.strip()
def whitespace_clean(text): text = re.sub('\\s+', ' ', text) text = text.strip() return text
class SimpleTokenizer(object): def __init__(self, bpe_path: str=default_bpe()): self.byte_encoder = bytes_to_unicode() self.byte_decoder = {v: k for (k, v) in self.byte_encoder.items()} merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') merges = merges[1:(((49152 - 256) - 2) + 1)] merges = [tuple(merge.split()) for merge in merges] vocab = list(bytes_to_unicode().values()) vocab = (vocab + [(v + '</w>') for v in vocab]) for merge in merges: vocab.append(''.join(merge)) vocab.extend(['<|startoftext|>', '<|endoftext|>']) self.encoder = dict(zip(vocab, range(len(vocab)))) self.decoder = {v: k for (k, v) in self.encoder.items()} self.bpe_ranks = dict(zip(merges, range(len(merges)))) self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} self.pat = re.compile("<\\|startoftext\\|>|<\\|endoftext\\|>|'s|'t|'re|'ve|'m|'ll|'d|[\\p{L}]+|[\\p{N}]|[^\\s\\p{L}\\p{N}]+", re.IGNORECASE) self.vocab = self.encoder def bpe(self, token): if (token in self.cache): return self.cache[token] word = (tuple(token[:(- 1)]) + ((token[(- 1)] + '</w>'),)) pairs = get_pairs(word) if (not pairs): return (token + '</w>') while True: bigram = min(pairs, key=(lambda pair: self.bpe_ranks.get(pair, float('inf')))) if (bigram not in self.bpe_ranks): break (first, second) = bigram new_word = [] i = 0 while (i < len(word)): try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break if ((word[i] == first) and (i < (len(word) - 1)) and (word[(i + 1)] == second)): new_word.append((first + second)) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if (len(word) == 1): break else: pairs = get_pairs(word) word = ' '.join(word) self.cache[token] = word return word def encode(self, text): bpe_tokens = [] text = whitespace_clean(basic_clean(text)).lower() for token in re.findall(self.pat, text): token = ''.join((self.byte_encoder[b] for b in token.encode('utf-8'))) bpe_tokens.extend((self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))) return bpe_tokens def decode(self, tokens): text = ''.join([self.decoder[token] for token in tokens]) text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors='replace').replace('</w>', ' ') return text def tokenize(self, text): tokens = [] text = whitespace_clean(basic_clean(text)).lower() for token in re.findall(self.pat, text): token = ''.join((self.byte_encoder[b] for b in token.encode('utf-8'))) tokens.extend((bpe_token for bpe_token in self.bpe(token).split(' '))) return tokens def convert_tokens_to_ids(self, tokens): return [self.encoder[bpe_token] for bpe_token in tokens]
class PretrainedConfig(object): pretrained_model_archive_map = {} config_name = '' weights_name = '' @classmethod def get_config(cls, pretrained_model_name, cache_dir, type_vocab_size, state_dict, task_config=None): archive_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), pretrained_model_name) if (os.path.exists(archive_file) is False): if (pretrained_model_name in cls.pretrained_model_archive_map): archive_file = cls.pretrained_model_archive_map[pretrained_model_name] else: archive_file = pretrained_model_name try: resolved_archive_file = cached_path(archive_file, cache_dir=cache_dir) except FileNotFoundError: if ((task_config is None) or (task_config.local_rank == 0)): logger.error("Model name '{}' was not found in model name list. We assumed '{}' was a path or url but couldn't find any file associated to this path or url.".format(pretrained_model_name, archive_file)) return None if (resolved_archive_file == archive_file): if ((task_config is None) or (task_config.local_rank == 0)): logger.info('loading archive file {}'.format(archive_file)) elif ((task_config is None) or (task_config.local_rank == 0)): logger.info('loading archive file {} from cache at {}'.format(archive_file, resolved_archive_file)) tempdir = None if os.path.isdir(resolved_archive_file): serialization_dir = resolved_archive_file else: tempdir = tempfile.mkdtemp() if ((task_config is None) or (task_config.local_rank == 0)): logger.info('extracting archive file {} to temp dir {}'.format(resolved_archive_file, tempdir)) with tarfile.open(resolved_archive_file, 'r:gz') as archive: archive.extractall(tempdir) serialization_dir = tempdir config_file = os.path.join(serialization_dir, cls.config_name) config = cls.from_json_file(config_file) config.type_vocab_size = type_vocab_size if ((task_config is None) or (task_config.local_rank == 0)): logger.info('Model config {}'.format(config)) if (state_dict is None): weights_path = os.path.join(serialization_dir, cls.weights_name) if os.path.exists(weights_path): state_dict = torch.load(weights_path, map_location='cpu') elif ((task_config is None) or (task_config.local_rank == 0)): logger.info("Weight doesn't exsits. {}".format(weights_path)) if tempdir: shutil.rmtree(tempdir) return (config, state_dict) @classmethod def from_dict(cls, json_object): 'Constructs a `BertConfig` from a Python dictionary of parameters.' config = cls(vocab_size_or_config_json_file=(- 1)) for (key, value) in json_object.items(): config.__dict__[key] = value return config @classmethod def from_json_file(cls, json_file): 'Constructs a `BertConfig` from a json file of parameters.' with open(json_file, 'r', encoding='utf-8') as reader: text = reader.read() return cls.from_dict(json.loads(text)) def __repr__(self): return str(self.to_json_string()) def to_dict(self): 'Serializes this instance to a Python dictionary.' output = copy.deepcopy(self.__dict__) return output def to_json_string(self): 'Serializes this instance to a JSON string.' return (json.dumps(self.to_dict(), indent=2, sort_keys=True) + '\n')
def get_world_size(): if (not dist.is_available()): return 1 if (not dist.is_initialized()): return 1 return dist.get_world_size()
def get_rank(): if (not dist.is_available()): return 0 if (not dist.is_initialized()): return 0 return dist.get_rank()
def is_main_process(): return (get_rank() == 0)
def synchronize(): '\n Helper function to synchronize (barrier) among all processes when\n using distributed training\n ' if (not dist.is_available()): return if (not dist.is_initialized()): return world_size = dist.get_world_size() if (world_size == 1): return dist.barrier()
def all_gather(data): '\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n ' world_size = get_world_size() if (world_size == 1): return [data] buffer = pickle.dumps(data) storage = torch.ByteStorage.from_buffer(buffer) tensor = torch.ByteTensor(storage).to('cuda') local_size = torch.LongTensor([tensor.numel()]).to('cuda') size_list = [torch.LongTensor([0]).to('cuda') for _ in range(world_size)] dist.all_gather(size_list, local_size) size_list = [int(size.item()) for size in size_list] max_size = max(size_list) tensor_list = [] for _ in size_list: tensor_list.append(torch.ByteTensor(size=(max_size,)).to('cuda')) if (local_size != max_size): padding = torch.ByteTensor(size=((max_size - local_size),)).to('cuda') tensor = torch.cat((tensor, padding), dim=0) dist.all_gather(tensor_list, tensor) data_list = [] for (size, tensor) in zip(size_list, tensor_list): buffer = tensor.cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list
def reduce_dict(input_dict, average=True): '\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the same fields as\n input_dict, after reduction.\n ' world_size = get_world_size() if (world_size < 2): return input_dict with torch.no_grad(): names = [] values = [] for k in sorted(input_dict.keys()): names.append(k) values.append(input_dict[k]) values = torch.stack(values, dim=0) dist.reduce(values, dst=0) if ((dist.get_rank() == 0) and average): values /= world_size reduced_dict = {k: v for (k, v) in zip(names, values)} return reduced_dict
def setup_logger(name, save_dir, dist_rank, filename='log.txt'): logger = logging.getLogger(name) logger.setLevel(logging.ERROR) if (dist_rank > 0): return logger logger.setLevel(logging.DEBUG) ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('[%(asctime)s %(name)s %(lineno)s %(levelname)s]: %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) logger.propagate = False if save_dir: fh = logging.FileHandler(os.path.join(save_dir, filename)) fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) return logger
class SmoothedValue(object): 'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n ' def __init__(self, window_size=20): self.deque = deque(maxlen=window_size) self.series = [] self.total = 0.0 self.count = 0 def update(self, value): self.deque.append(value) self.series.append(value) self.count += 1 self.total += value @property def median(self): d = torch.tensor(list(self.deque)) return d.median().item() @property def avg(self): d = torch.tensor(list(self.deque)) return d.mean().item() @property def global_avg(self): return (self.total / self.count)
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): if isinstance(v, torch.Tensor): v = v.item() assert isinstance(v, (float, int)) self.meters[k].update(v) def __getattr__(self, attr): if (attr in self.meters): return self.meters[attr] if (attr in self.__dict__): return self.__dict__[attr] raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr)) def __str__(self): loss_str = [] for (name, meter) in self.meters.items(): loss_str.append('{}: {:.4f} ({:.4f})'.format(name, meter.median, meter.global_avg)) return self.delimiter.join(loss_str)