code
stringlengths
17
6.64M
def create_tokenizer(tokenizer_type): 'Creates a tokenizer given a tokenizer type.' if tokenizer_type.endswith('frz'): freeze = True elif tokenizer_type.endswith('ftn'): freeze = False if tokenizer_type.startswith('bert'): model_name_or_path = 'bert-base-cased' do_lower_case = True cache_dir = 'data/cache_dir' tokenizer_class = BertTokenizer tokenizer = tokenizer_class.from_pretrained(model_name_or_path, do_lower_case=do_lower_case, cache_dir=cache_dir) elif tokenizer_type.startswith('wo2v'): we_filepath = 'data/word_embeddings/word2vec/GoogleNews-vectors-negative300.bin' tokenizer = WeTokenizer(we_filepath, freeze=freeze) elif tokenizer_type.startswith('grvl'): we_filepath = 'data/word_embeddings/GrOVLE/mt_grovle.txt' tokenizer = WeTokenizer(we_filepath, freeze=freeze) else: tokenizer = None return tokenizer
def update_perf_log(epoch_perf, perf_log_path): now = time.strftime('%c') line = 't: {}, '.format(now) for key in epoch_perf: line += '{}: {}, '.format(key, epoch_perf[key]) line += '\n' with open(perf_log_path, 'a') as file: file.write(line)
class Ranger(Optimizer): def __init__(self, params, lr=0.001, alpha=0.5, k=6, n_sma_threshhold=5, betas=(0.95, 0.999), eps=1e-05, weight_decay=0): if (not (0.0 <= alpha <= 1.0)): raise ValueError(f'Invalid slow update rate: {alpha}') if (not (1 <= k)): raise ValueError(f'Invalid lookahead steps: {k}') if (not (lr > 0)): raise ValueError(f'Invalid Learning Rate: {lr}') if (not (eps > 0)): raise ValueError(f'Invalid eps: {eps}') defaults = dict(lr=lr, alpha=alpha, k=k, step_counter=0, betas=betas, n_sma_threshhold=n_sma_threshhold, eps=eps, weight_decay=weight_decay) super().__init__(params, defaults) self.n_sma_threshhold = n_sma_threshhold self.alpha = alpha self.k = k self.radam_buffer = [[None, None, None] for ind in range(10)] def __setstate__(self, state): print('set state called') super(Ranger, self).__setstate__(state) def step(self, closure=None): loss = None for group in self.param_groups: for p in group['params']: if (p.grad is None): continue grad = p.grad.data.float() if grad.is_sparse: raise RuntimeError('Ranger optimizer does not support sparse gradients') p_data_fp32 = p.data.float() state = self.state[p] if (len(state) == 0): state['step'] = 0 state['exp_avg'] = torch.zeros_like(p_data_fp32) state['exp_avg_sq'] = torch.zeros_like(p_data_fp32) state['slow_buffer'] = torch.empty_like(p.data) state['slow_buffer'].copy_(p.data) else: state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32) state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32) (exp_avg, exp_avg_sq) = (state['exp_avg'], state['exp_avg_sq']) (beta1, beta2) = group['betas'] exp_avg_sq.mul_(beta2).addcmul_((1 - beta2), grad, grad) exp_avg.mul_(beta1).add_((1 - beta1), grad) state['step'] += 1 buffered = self.radam_buffer[int((state['step'] % 10))] if (state['step'] == buffered[0]): (n_sma, step_size) = (buffered[1], buffered[2]) else: buffered[0] = state['step'] beta2_t = (beta2 ** state['step']) n_sma_max = ((2 / (1 - beta2)) - 1) n_sma = (n_sma_max - (((2 * state['step']) * beta2_t) / (1 - beta2_t))) buffered[1] = n_sma if (n_sma > self.n_sma_threshhold): step_size = (math.sqrt((((((((1 - beta2_t) * (n_sma - 4)) / (n_sma_max - 4)) * (n_sma - 2)) / n_sma) * n_sma_max) / (n_sma_max - 2))) / (1 - (beta1 ** state['step']))) else: step_size = (1.0 / (1 - (beta1 ** state['step']))) buffered[2] = step_size if (group['weight_decay'] != 0): p_data_fp32.add_(((- group['weight_decay']) * group['lr']), p_data_fp32) if (n_sma > self.n_sma_threshhold): denom = exp_avg_sq.sqrt().add_(group['eps']) p_data_fp32.addcdiv_(((- step_size) * group['lr']), exp_avg, denom) else: p_data_fp32.add_(((- step_size) * group['lr']), exp_avg) p.data.copy_(p_data_fp32) if ((state['step'] % group['k']) == 0): slow_p = state['slow_buffer'] slow_p.add_(self.alpha, (p.data - slow_p)) p.data.copy_(slow_p) return loss
class AverageMeter(object): def __init__(self): self.dic = {} self.reset() def reset(self): for key in self.dic: for metric in self.dic[key]: self.dic[key][metric] = 0 def update(self, key, val, n=1): self.dic.setdefault(key, {'val': 0, 'sum': 0, 'count': 0, 'avg': 0}) self.dic[key]['val'] = val self.dic[key]['sum'] += (val * n) self.dic[key]['count'] += n self.dic[key]['avg'] = (self.dic[key]['sum'] / self.dic[key]['count'])
class RawFrameExtractor(): 'frame extractor for a given of directory with video\n\n Attributes:\n centercrop: center crop for pre-preprocess\n size: resolution of images\n framerate: frame rate for sampling\n transform: transform method for pre-process\n train: set train for random sampling in the uniform interval\n ' def __init__(self, centercrop=False, size=224, framerate=(- 1), train='subset'): self.centercrop = centercrop self.size = size self.framerate = framerate self.transform = self._transform(self.size) self.train = (True if (train == 'train') else False) def _transform(self, n_px): return Compose([Resize(n_px, interpolation=Image.BICUBIC), CenterCrop(n_px), ToTensor(), Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))]) def video_to_tensor(self, video_file, max_frame, preprocess, sample_fp=0): 'sample video into tensor\n Args:\n video_file: location of video file\n max_frame: max frame number\n preprocessL preprocess method\n sample_fp: sampling rate\n\n Returns:\n image_input: sample frames\n ' assert (sample_fp > (- 1)) video_name = os.listdir(video_file) video_name.sort() current_frame = (len(video_name) // sample_fp) current_sample_indx = np.linspace(0, (len(video_name) - 1), num=current_frame, dtype=int) if (max_frame >= current_sample_indx.shape[0]): frame_index = np.arange(0, current_sample_indx.shape[0]) else: frame_index = np.linspace(0, (current_sample_indx.shape[0] - 1), num=max_frame, dtype=int) if self.train: step_len = ((frame_index[1] - frame_index[0]) // 2) if (step_len > 2): random_index = np.random.randint(((- 1) * step_len), step_len, (frame_index.shape[0] - 2)) zero_index = np.zeros(1) index = np.concatenate((zero_index, random_index, zero_index)) frame_index = (frame_index + index) images = [] for index in frame_index: image_path = os.path.join(video_file, video_name[current_sample_indx[int(index)]]) images.append(preprocess(Image.open(image_path).convert('RGB'))) if (len(images) > 0): video_data = torch.tensor(np.stack(images)) else: video_data = torch.zeros(1) return {'video': video_data} def get_video_data(self, video_path, max_frame): 'get video data\n Args:\n video_path: id\n max_frame: max frame number\n\n Returns:\n image_input: sample frames\n ' image_input = self.video_to_tensor(video_path, max_frame, self.transform, sample_fp=self.framerate) return image_input def process_raw_data(self, raw_video_data): 'reshape the raw video\n Args:\n raw_video_data: sampled frames\n\n Returns:\n tensor: reshaped tensor\n ' 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 _run_on_single_gpu(model, batch_list_t, batch_list_v, batch_sequence_output_list, batch_visual_output_list): 'run similarity in one single gpu\n Args:\n model: CLIP2Video\n batch_list_t: id of text embedding\n batch_list_v: id of visual embedding\n batch_sequence_output_list: batch text embedding\n batch_visual_output_list: batch visual embedding\n Returns:\n sim_matrix: similarity\n\n ' sim_matrix = [] for (idx1, b1) in enumerate(batch_list_t): (input_mask, segment_ids, *_tmp) = b1 sequence_output = batch_sequence_output_list[idx1] each_row = [] for (idx2, b2) in enumerate(batch_list_v): (video_mask, *_tmp) = b2 visual_output = batch_visual_output_list[idx2] (b1b2_logits, *_tmp) = model.get_inference_logits(sequence_output, visual_output, input_mask, video_mask) b1b2_logits = b1b2_logits.cpu().detach().numpy() each_row.append(b1b2_logits) each_row = np.concatenate(tuple(each_row), axis=(- 1)) sim_matrix.append(each_row) return sim_matrix
def eval_epoch(model, test_dataloader, device, n_gpu, logger): 'run similarity in one single gpu\n Args:\n model: CLIP2Video\n test_dataloader: data loader for test\n device: device to run model\n n_gpu: GPU number\n batch_sequence_output_list: batch text embedding\n batch_visual_output_list: batch visual embedding\n Returns:\n R1: rank 1 of text-to-video retrieval\n\n ' if hasattr(model, 'module'): model = model.module.to(device) else: model = model.to(device) multi_sentence_ = False (cut_off_points_, sentence_num_, video_num_) = ([], (- 1), (- 1)) if (hasattr(test_dataloader.dataset, 'multi_sentence_per_video') and test_dataloader.dataset.multi_sentence_per_video): multi_sentence_ = True cut_off_points_ = test_dataloader.dataset.cut_off_points sentence_num_ = test_dataloader.dataset.sentence_num video_num_ = test_dataloader.dataset.video_num cut_off_points_ = [(itm - 1) for itm in cut_off_points_] if multi_sentence_: logger.warning('Eval under the multi-sentence per video clip setting.') logger.warning('sentence num: {}, video num: {}'.format(sentence_num_, video_num_)) model.eval() with torch.no_grad(): batch_list_t = [] batch_list_v = [] (batch_sequence_output_list, batch_visual_output_list) = ([], []) total_video_num = 0 for (bid, batch) in enumerate(test_dataloader): batch = tuple((t.to(device) for t in batch)) (input_ids, input_mask, segment_ids, video, video_mask) = batch if multi_sentence_: (b, *_t) = video.shape sequence_output = model.get_sequence_output(input_ids, segment_ids, input_mask) batch_sequence_output_list.append(sequence_output) batch_list_t.append((input_mask, segment_ids)) (s_, e_) = (total_video_num, (total_video_num + b)) filter_inds = [(itm - s_) for itm in cut_off_points_ if ((itm >= s_) and (itm < e_))] if (len(filter_inds) > 0): (video, video_mask) = (video[(filter_inds, ...)], video_mask[(filter_inds, ...)]) visual_output = model.get_visual_output(video, video_mask) batch_visual_output_list.append(visual_output) batch_list_v.append((video_mask,)) total_video_num += b else: (sequence_output, visual_output) = model.get_sequence_visual_output(input_ids, segment_ids, input_mask, video, video_mask) batch_sequence_output_list.append(sequence_output) batch_list_t.append((input_mask, segment_ids)) batch_visual_output_list.append(visual_output) batch_list_v.append((video_mask,)) print('{}/{}\r'.format(bid, len(test_dataloader)), end='') if (n_gpu > 1): device_ids = list(range(n_gpu)) batch_list_t_splits = [] batch_list_v_splits = [] batch_t_output_splits = [] batch_v_output_splits = [] bacth_len = len(batch_list_t) split_len = (((bacth_len + n_gpu) - 1) // n_gpu) for dev_id in device_ids: (s_, e_) = ((dev_id * split_len), ((dev_id + 1) * split_len)) if (dev_id == 0): batch_list_t_splits.append(batch_list_t[s_:e_]) batch_list_v_splits.append(batch_list_v) batch_t_output_splits.append(batch_sequence_output_list[s_:e_]) batch_v_output_splits.append(batch_visual_output_list) else: devc = torch.device('cuda:{}'.format(str(dev_id))) devc_batch_list = [tuple((t.to(devc) for t in b)) for b in batch_list_t[s_:e_]] batch_list_t_splits.append(devc_batch_list) devc_batch_list = [tuple((t.to(devc) for t in b)) for b in batch_list_v] batch_list_v_splits.append(devc_batch_list) if isinstance(batch_sequence_output_list[s_], tuple): devc_batch_list = [(b[0].to(devc), b[1].to(devc)) for b in batch_sequence_output_list[s_:e_]] else: devc_batch_list = [b.to(devc) for b in batch_sequence_output_list[s_:e_]] batch_t_output_splits.append(devc_batch_list) devc_batch_list = [b.to(devc) for b in batch_visual_output_list] batch_v_output_splits.append(devc_batch_list) parameters_tuple_list = [(batch_list_t_splits[dev_id], batch_list_v_splits[dev_id], batch_t_output_splits[dev_id], batch_v_output_splits[dev_id]) for dev_id in device_ids] parallel_outputs = parallel_apply(_run_on_single_gpu, model, parameters_tuple_list, device_ids) sim_matrix = [] for idx in range(len(parallel_outputs)): sim_matrix += parallel_outputs[idx] sim_matrix = np.concatenate(tuple(sim_matrix), axis=0) else: sim_matrix = _run_on_single_gpu(model, batch_list_t, batch_list_v, batch_sequence_output_list, batch_visual_output_list) sim_matrix = np.concatenate(tuple(sim_matrix), axis=0) R1 = logging_rank(sim_matrix, multi_sentence_, cut_off_points_, logger) return R1
def logging_rank(sim_matrix, multi_sentence_, cut_off_points_, logger): 'run similarity in one single gpu\n Args:\n sim_matrix: similarity matrix\n multi_sentence_: indicate whether the multi sentence retrieval\n cut_off_points_: tag the label when calculate the metric\n logger: logger for metric\n Returns:\n R1: rank 1 of text-to-video retrieval\n\n ' if multi_sentence_: logger.info('before reshape, sim matrix size: {} x {}'.format(sim_matrix.shape[0], sim_matrix.shape[1])) cut_off_points2len_ = [(itm + 1) for itm in cut_off_points_] max_length = max([(e_ - s_) for (s_, e_) in zip(([0] + cut_off_points2len_[:(- 1)]), cut_off_points2len_)]) sim_matrix_new = [] for (s_, e_) in zip(([0] + cut_off_points2len_[:(- 1)]), cut_off_points2len_): sim_matrix_new.append(np.concatenate((sim_matrix[s_:e_], np.full((((max_length - e_) + s_), sim_matrix.shape[1]), (- np.inf))), axis=0)) sim_matrix = np.stack(tuple(sim_matrix_new), axis=0) logger.info('after reshape, sim matrix size: {} x {} x {}'.format(sim_matrix.shape[0], sim_matrix.shape[1], sim_matrix.shape[2])) tv_metrics = tensor_text_to_video_metrics(sim_matrix) vt_metrics = compute_metrics(tensor_video_to_text_sim(sim_matrix)) else: logger.info('sim matrix size: {}, {}'.format(sim_matrix.shape[0], sim_matrix.shape[1])) tv_metrics = compute_metrics(sim_matrix) vt_metrics = compute_metrics(sim_matrix.T) logger.info('\t Length-T: {}, Length-V:{}'.format(len(sim_matrix), len(sim_matrix[0]))) logger.info('Text-to-Video:') logger.info('\t>>> R@1: {:.1f} - R@5: {:.1f} - R@10: {:.1f} - Median R: {:.1f} - Mean R: {:.1f}'.format(tv_metrics['R1'], tv_metrics['R5'], tv_metrics['R10'], tv_metrics['MR'], tv_metrics['MeanR'])) logger.info('Video-to-Text:') logger.info('\t>>> V2T$R@1: {:.1f} - V2T$R@5: {:.1f} - V2T$R@10: {:.1f} - V2T$Median R: {:.1f} - V2T$Mean R: {:.1f}'.format(vt_metrics['R1'], vt_metrics['R5'], vt_metrics['R10'], vt_metrics['MR'], vt_metrics['MeanR'])) R1 = tv_metrics['R1'] return R1
def set_seed_logger(args): 'Initialize the seed and environment variable\n\n Args:\n args: the hyper-parameters.\n\n Returns:\n args: the hyper-parameters modified by the random seed.\n\n ' global logger random.seed(args.seed) os.environ['PYTHONHASHSEED'] = str(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True logger = get_logger(os.path.join(args.output_dir)) return args
def init_device(args, local_rank): 'Initialize device to determine CPU or GPU\n\n Args:\n args: the hyper-parameters\n local_rank: GPU id\n\n Returns:\n devices: cuda\n n_gpu: number of gpu\n\n ' global logger device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'), local_rank) n_gpu = torch.cuda.device_count() logger.info('device: {} n_gpu: {}'.format(device, n_gpu)) args.n_gpu = n_gpu if ((args.batch_size_val % args.n_gpu) != 0): raise ValueError('Invalid batch_size/batch_size_val and n_gpu parameter: {}%{} and {}%{}, should be == 0'.format(args.batch_size, args.n_gpu, args.batch_size_val, args.n_gpu)) return (device, n_gpu)
def init_model(args, device): "Initialize model.\n\n if location of args.init_model exists, model will be initialized from the pretrained model.\n if no model exists, the training will be initialized from CLIP's parameters.\n\n Args:\n args: the hyper-parameters\n devices: cuda\n\n Returns:\n model: the initialized model\n\n " model_file = os.path.join(args.checkpoint, 'pytorch_model.bin.{}'.format(args.model_num)) if os.path.exists(model_file): model_state_dict = torch.load(model_file, map_location='cpu') if (args.local_rank == 0): logger.info('Model loaded from %s', model_file) else: model_state_dict = None if (args.local_rank == 0): logger.info('Model loaded fail %s', model_file) model = CLIP2Video.from_pretrained(args.cross_model, cache_dir=None, state_dict=model_state_dict, task_config=args) model.to(device) return model
def main(): global logger args = get_args() args = set_seed_logger(args) (device, n_gpu) = init_device(args, args.local_rank) tokenizer = ClipTokenizer() model = init_model(args, device) assert (args.datatype in DATALOADER_DICT) (test_dataloader, test_length) = DATALOADER_DICT[args.datatype]['test'](args, tokenizer) if (args.local_rank == 0): logger.info('***** Running test *****') logger.info(' Num examples = %d', test_length) logger.info(' Batch size = %d', args.batch_size_val) logger.info(' Num steps = %d', len(test_dataloader)) if (args.local_rank == 0): eval_epoch(model, test_dataloader, device, n_gpu, logger)
class CrossConfig(PretrainedConfig): 'Configuration class to store the configuration of a `CrossModel`.\n ' pretrained_model_archive_map = PRETRAINED_MODEL_ARCHIVE_MAP config_name = CONFIG_NAME weights_name = WEIGHTS_NAME def __init__(self, vocab_size_or_config_json_file, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initializer_range=0.02): 'Constructs CrossConfig.\n\n Args:\n vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `CrossModel`.\n hidden_size: Size of the encoder layers and the pooler layer.\n num_hidden_layers: Number of hidden layers in the Transformer encoder.\n num_attention_heads: Number of attention heads for each attention layer in\n the Transformer encoder.\n intermediate_size: The size of the "intermediate" (i.e., feed-forward)\n layer in the Transformer encoder.\n hidden_act: The non-linear activation function (function or string) in the\n encoder and pooler. If string, "gelu", "relu" and "swish" are supported.\n hidden_dropout_prob: The dropout probabilitiy for all fully connected\n layers in the embeddings, encoder, and pooler.\n attention_probs_dropout_prob: The dropout ratio for the attention\n probabilities.\n max_position_embeddings: The maximum sequence length that this model might\n ever be used with. Typically set this to something large just in case\n (e.g., 512 or 1024 or 2048).\n type_vocab_size: The vocabulary size of the `token_type_ids` passed into\n `CrossModel`.\n initializer_range: The sttdev of the truncated_normal_initializer for\n initializing all weight matrices.\n ' if isinstance(vocab_size_or_config_json_file, str): with open(vocab_size_or_config_json_file, 'r', encoding='utf-8') as reader: json_config = json.loads(reader.read()) for (key, value) in json_config.items(): self.__dict__[key] = value elif isinstance(vocab_size_or_config_json_file, int): self.vocab_size = vocab_size_or_config_json_file self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_act = hidden_act self.intermediate_size = intermediate_size self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.initializer_range = initializer_range else: raise ValueError('First argument must be either a vocabulary size (int)or the path to a pretrained model config file (str)')
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): super().__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.n_head = n_head def attention(self, x: torch.Tensor, attn_mask: torch.Tensor): attn_mask_ = attn_mask.repeat(self.n_head, 1, 1) 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): super().__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]
@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 resolved_archive_file = archive_file 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 gelu(x): "Implementation of the gelu activation function.\n For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):\n 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))\n " return ((x * 0.5) * (1.0 + torch.erf((x / math.sqrt(2.0)))))
def swish(x): return (x * torch.sigmoid(x))
class LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): 'Construct a layernorm module in the TF style (epsilon inside the square root).\n ' super(LayerNorm, self).__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) self.variance_epsilon = eps def forward(self, x): u = x.mean((- 1), keepdim=True) s = (x - u).pow(2).mean((- 1), keepdim=True) x = ((x - u) / torch.sqrt((s + self.variance_epsilon))) return ((self.weight * x) + self.bias)
class PreTrainedModel(nn.Module): ' An abstract class to handle weights initialization and\n a simple interface for dowloading and loading pretrained models.\n ' def __init__(self, config, *inputs, **kwargs): super(PreTrainedModel, self).__init__() if (not isinstance(config, PretrainedConfig)): raise ValueError('Parameter config in `{}(config)` should be an instance of class `PretrainedConfig`. To create a model from a Google pretrained model use `model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`'.format(self.__class__.__name__, self.__class__.__name__)) self.config = config def init_weights(self, module): ' Initialize the weights.\n ' if isinstance(module, (nn.Linear, nn.Embedding)): module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) elif isinstance(module, LayerNorm): if (('beta' in dir(module)) and ('gamma' in dir(module))): module.beta.data.zero_() module.gamma.data.fill_(1.0) else: module.bias.data.zero_() module.weight.data.fill_(1.0) if (isinstance(module, nn.Linear) and (module.bias is not None)): module.bias.data.zero_() def resize_token_embeddings(self, new_num_tokens=None): raise NotImplementedError @classmethod def init_preweight(cls, model, state_dict, prefix=None, task_config=None): old_keys = [] new_keys = [] for key in state_dict.keys(): new_key = None if ('gamma' in key): new_key = key.replace('gamma', 'weight') if ('beta' in key): new_key = key.replace('beta', 'bias') if new_key: old_keys.append(key) new_keys.append(new_key) for (old_key, new_key) in zip(old_keys, new_keys): state_dict[new_key] = state_dict.pop(old_key) if (prefix is not None): old_keys = [] new_keys = [] for key in state_dict.keys(): old_keys.append(key) new_keys.append((prefix + key)) for (old_key, new_key) in zip(old_keys, new_keys): state_dict[new_key] = state_dict.pop(old_key) missing_keys = [] unexpected_keys = [] error_msgs = [] metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.copy() if (metadata is not None): state_dict._metadata = metadata def load(module, prefix=''): local_metadata = ({} if (metadata is None) else metadata.get(prefix[:(- 1)], {})) module._load_from_state_dict(state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs) for (name, child) in module._modules.items(): if (child is not None): load(child, ((prefix + name) + '.')) load(model, prefix='') if ((prefix is None) and ((task_config is None) or (task_config.local_rank == 0))): logger.info(('-' * 20)) if (len(missing_keys) > 0): logger.info('Weights of {} not initialized from pretrained model: {}'.format(model.__class__.__name__, ('\n ' + '\n '.join(missing_keys)))) if (len(unexpected_keys) > 0): logger.info('Weights from pretrained model not used in {}: {}'.format(model.__class__.__name__, ('\n ' + '\n '.join(unexpected_keys)))) if (len(error_msgs) > 0): logger.error('Weights from pretrained model cause errors in {}: {}'.format(model.__class__.__name__, ('\n ' + '\n '.join(error_msgs)))) return model @property def dtype(self): '\n :obj:`torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).\n ' try: return next(self.parameters()).dtype except StopIteration: def find_tensor_attributes(module: nn.Module): tuples = [(k, v) for (k, v) in module.__dict__.items() if torch.is_tensor(v)] return tuples gen = self._named_members(get_members_fn=find_tensor_attributes) first_tuple = next(gen) return first_tuple[1].dtype @classmethod def from_pretrained(cls, config, state_dict=None, *inputs, **kwargs): '\n Instantiate a PreTrainedModel from a pre-trained model file or a pytorch state dict.\n Download and cache the pre-trained model file if needed.\n ' model = cls(config, *inputs, **kwargs) if (state_dict is None): return model model = cls.init_preweight(model, state_dict) return model
class CrossEn(nn.Module): 'cross entroy loss' def __init__(self): super(CrossEn, self).__init__() def forward(self, sim_matrix): logpt = F.log_softmax(sim_matrix, dim=(- 1)) logpt = torch.diag(logpt) nce_loss = (- logpt) sim_loss = nce_loss.mean() return sim_loss
def extract_frames(video_name, out_folder, fps=5): if os.path.exists(out_folder): os.system((('rm -rf ' + out_folder) + '/*')) os.system(('rm -rf ' + out_folder)) os.makedirs(out_folder) cmd = ('ffmpeg -v 0 -i %s -r %d -q 0 %s/%s.jpg' % (video_name, fps, out_folder, '%08d')) os.system(cmd)
def process(line): print(line) (mp4_name, folder_frame) = line extract_frames(mp4_name, folder_frame)
def get_args(description='CLIP2Video on Dideo-Text Retrieval Task'): parser = argparse.ArgumentParser(description=description) parser.add_argument('--do_eval', action='store_true', help='Whether to run eval on the dev set.') parser.add_argument('--val_csv', type=str, default='data/.val.csv', help='') parser.add_argument('--data_path', type=str, default='data/caption.pickle', help='data pickle file path') parser.add_argument('--features_path', type=str, default='data/videos_feature.pickle', help='feature path') parser.add_argument('--num_thread_reader', type=int, default=1, help='') parser.add_argument('--batch_size_val', type=int, default=3500, help='batch size eval') parser.add_argument('--seed', type=int, default=42, help='random seed') parser.add_argument('--max_words', type=int, default=32, help='') parser.add_argument('--max_frames', type=int, default=100, help='') parser.add_argument('--feature_framerate', type=int, default=1, help='frame rate for uniformly sampling the video') parser.add_argument('--output_dir', default=None, type=str, required=True, help='The output directory where the model predictions and checkpoints will be written.') parser.add_argument('--cross_model', default='cross-base', type=str, required=False, help='Cross module') parser.add_argument('--do_lower_case', action='store_true', help='Set this flag if you are using an uncased model.') parser.add_argument('--n_gpu', type=int, default=1, help='Changed in the execute process.') parser.add_argument('--cache_dir', default='', type=str, help='Where do you want to store the pre-trained models downloaded from s3') parser.add_argument('--fp16', action='store_true', help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit') parser.add_argument('--fp16_opt_level', type=str, default='O1', help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].See details at https://nvidia.github.io/apex/amp.html") parser.add_argument('--cross_num_hidden_layers', type=int, default=4, help='Layer NO. of cross.') parser.add_argument('--sim_type', type=str, default='meanP', choices=['meanP', 'seqTransf'], help='choice a similarity header.') parser.add_argument('--checkpoint', type=str, default='', help='checkpoint dir') parser.add_argument('--model_num', type=str, default='', help='model id') parser.add_argument('--local_rank', default=0, type=int, help='shard_id: node rank for distributed training') parser.add_argument('--datatype', default='msrvtt', type=str, help='msvd | msrvtt | vatexEnglish | msrvttfull') parser.add_argument('--vocab_size', type=int, default=49408, help='the number of vocab size') parser.add_argument('--temporal_type', type=str, default='', help='TDB type') parser.add_argument('--temporal_proj', type=str, default='', help='sigmoid_mlp | sigmoid_selfA') parser.add_argument('--center_type', type=str, default='', help='TAB') parser.add_argument('--centerK', type=int, default=5, help='center number for clustering.') parser.add_argument('--center_weight', type=float, default=0.5, help='the weight to adopt the main simiarility') parser.add_argument('--center_proj', type=str, default='', help='TAB | TAB_TDB') parser.add_argument('--clip_path', type=str, default='/data/ceph_11015/ssd/howiefang/videoCLIP/CLIP2Clip/ViT-B-32.pt', help='model path of CLIP') parser.add_argument('--EMCL', type=int, default=0) parser.add_argument('--K', type=int, default=16) parser.add_argument('--stage_num', type=int, default=5) parser.add_argument('--momentum', type=float, default=0.9) parser.add_argument('--lamd', type=float, default=1) parser.add_argument('--beta', type=float, default=1) args = parser.parse_args() return args
def dataloader_vatexEnglish_train(args, tokenizer): 'return dataloader for training VATEX with English annotations\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(vatexEnglish_dataset): length\n train_sampler: sampler for distributed training\n ' vatexEnglish_dataset = VATEXENGLISH_multi_sentence_dataLoader(subset='train', data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) train_sampler = torch.utils.data.distributed.DistributedSampler(vatexEnglish_dataset) dataloader = DataLoader(vatexEnglish_dataset, batch_size=(args.batch_size // args.n_gpu), num_workers=args.num_thread_reader, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True) return (dataloader, len(vatexEnglish_dataset), train_sampler)
def dataloader_vatexEnglish_test(args, tokenizer, subset='test'): 'return dataloader for testing VATEX with English annotations in multi-sentence captions\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(vatexEnglish_dataset): length\n ' vatexEnglish_dataset = VATEXENGLISH_multi_sentence_dataLoader(subset=subset, data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) dataloader = DataLoader(vatexEnglish_dataset, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False) return (dataloader, len(vatexEnglish_dataset))
def dataloader_msrvtt_train(args, tokenizer): 'return dataloader for training msrvtt-9k\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(msrvtt_train_set): length\n train_sampler: sampler for distributed training\n ' msrvtt_train_set = MSRVTT_multi_sentence_dataLoader(csv_path=args.train_csv, json_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) train_sampler = torch.utils.data.distributed.DistributedSampler(msrvtt_train_set) dataloader = DataLoader(msrvtt_train_set, batch_size=(args.batch_size // args.n_gpu), num_workers=args.num_thread_reader, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True) return (dataloader, len(msrvtt_train_set), train_sampler)
def dataloader_msrvtt_test(args, tokenizer): 'return dataloader for testing 1k-A protocol\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(msrvtt_test_set): length\n ' msrvtt_test_set = MSRVTT_single_sentence_dataLoader(csv_path=args.val_csv, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) dataloader = DataLoader(msrvtt_test_set, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False) return (dataloader, len(msrvtt_test_set))
def dataloader_msrvttfull_test(args, tokenizer): 'return dataloader for testing full protocol\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(msrvtt_test_set): length\n ' msrvtt_test_set = MSRVTTFULL_multi_sentence_dataLoader(subset='test', csv_path=args.val_csv, json_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) dataloader = DataLoader(msrvtt_test_set, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False) return (dataloader, len(msrvtt_test_set))
def dataloader_msvd_train(args, tokenizer): 'return dataloader for training msvd\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(msvd_dataset): length\n train_sampler: sampler for distributed training\n ' msvd_dataset = MSVD_multi_sentence_dataLoader(subset='train', data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) train_sampler = torch.utils.data.distributed.DistributedSampler(msvd_dataset) dataloader = DataLoader(msvd_dataset, batch_size=(args.batch_size // args.n_gpu), num_workers=args.num_thread_reader, pin_memory=False, shuffle=(train_sampler is None), sampler=train_sampler, drop_last=True) return (dataloader, len(msvd_dataset), train_sampler)
def dataloader_msvd_test(args, tokenizer, subset='test'): 'return dataloader for testing msvd in multi-sentence captions\n Args:\n args: hyper-parameters\n tokenizer: tokenizer\n Returns:\n dataloader: dataloader\n len(msvd_dataset): length\n ' msvd_test_set = MSVD_multi_sentence_dataLoader(subset=subset, data_path=args.data_path, features_path=args.features_path, max_words=args.max_words, feature_framerate=args.feature_framerate, tokenizer=tokenizer, max_frames=args.max_frames) dataloader = DataLoader(msvd_test_set, batch_size=args.batch_size_val, num_workers=args.num_thread_reader, shuffle=False, drop_last=False) return (dataloader, len(msvd_test_set))
def get_a_var(obj): if isinstance(obj, torch.Tensor): return obj if (isinstance(obj, list) or isinstance(obj, tuple)): for result in map(get_a_var, obj): if isinstance(result, torch.Tensor): return result if isinstance(obj, dict): for result in map(get_a_var, obj.items()): if isinstance(result, torch.Tensor): return result return None
def parallel_apply(fct, model, inputs, device_ids): modules = nn.parallel.replicate(model, device_ids) assert (len(modules) == len(inputs)) lock = threading.Lock() results = {} grad_enabled = torch.is_grad_enabled() def _worker(i, module, input): torch.set_grad_enabled(grad_enabled) device = get_a_var(input).get_device() try: with torch.cuda.device(device): if (not isinstance(input, (list, tuple))): input = (input,) output = fct(module, *input) with lock: results[i] = output except Exception: with lock: results[i] = ExceptionWrapper(where='in replica {} on device {}'.format(i, device)) if (len(modules) > 1): threads = [threading.Thread(target=_worker, args=(i, module, input)) for (i, (module, input)) in enumerate(zip(modules, inputs))] for thread in threads: thread.start() for thread in threads: thread.join() else: _worker(0, modules[0], inputs[0]) outputs = [] for i in range(len(inputs)): output = results[i] if isinstance(output, ExceptionWrapper): output.reraise() outputs.append(output) return outputs
def get_logger(filename=None): logger = logging.getLogger('logger') logger.setLevel(logging.DEBUG) logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) if (filename is not None): handler = logging.FileHandler(filename) handler.setLevel(logging.DEBUG) handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logging.getLogger().addHandler(handler) return logger
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_lsmdc_train(args, tokenizer): lsmdc_dataset = LsmdcDataset(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) train_sampler = torch.utils.data.distributed.DistributedSampler(lsmdc_dataset) dataloader = DataLoader(lsmdc_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(lsmdc_dataset), train_sampler)
def dataloader_lsmdc_test(args, tokenizer, subset='test'): lsmdc_testset = LsmdcDataset(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(lsmdc_testset) except: test_sampler = None dataloader_lsmdc = DataLoader(lsmdc_testset, batch_size=(args.batch_size_val // args.world_size), num_workers=args.workers, shuffle=False, sampler=test_sampler, drop_last=False) return (dataloader_lsmdc, len(lsmdc_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_msvd_train(args, tokenizer): msvd_dataset = MsvdDataset(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) train_sampler = torch.utils.data.distributed.DistributedSampler(msvd_dataset) dataloader = DataLoader(msvd_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(msvd_dataset), train_sampler)
def dataloader_msvd_test(args, tokenizer, subset='test'): msvd_testset = MsvdDataset(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) dataloader_msvd = DataLoader(msvd_testset, batch_size=args.batch_size_val, num_workers=args.workers, shuffle=False, drop_last=False) return (dataloader_msvd, len(msvd_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 LsmdcDataset(RetrievalDataset): 'LSMDC 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(LsmdcDataset, 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 ' video_json_path_dict = {} video_json_path_dict['train'] = os.path.join(self.anno_path, 'LSMDC16_annos_training.csv') video_json_path_dict['val'] = os.path.join(self.anno_path, 'LSMDC16_annos_val.csv') video_json_path_dict['test'] = os.path.join(self.anno_path, 'LSMDC16_challenge_1000_publictect.csv') video_id_list = [] caption_dict = {} with open(video_json_path_dict[self.subset], 'r') as fp: for line in fp: line = line.strip() line_split = line.split('\t') assert (len(line_split) == 6) (clip_id, start_aligned, end_aligned, start_extracted, end_extracted, sentence) = line_split if (clip_id not in ['0017_Pianist_00.23.28.872-00.23.34.843', '0017_Pianist_00.30.36.767-00.30.38.009', '3064_SPARKLE_2012_01.41.07.000-01.41.11.793']): caption_dict[len(caption_dict)] = (clip_id, (sentence, None, None)) if (clip_id not in video_id_list): video_id_list.append(clip_id) video_dict = OrderedDict() sentences_dict = OrderedDict() for (root, dub_dir, video_files) in os.walk(self.video_path): for video_file in video_files: video_id_ = '.'.join(video_file.split('.')[:(- 1)]) if (video_id_ not in video_id_list): continue file_path_ = os.path.join(root, video_file) video_dict[video_id_] = file_path_ for (clip_id, sentence) in caption_dict.values(): if (clip_id not in video_dict): continue sentences_dict[len(sentences_dict)] = (clip_id, sentence) 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)
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)
class MsvdDataset(RetrievalDataset): 'MSVD dataset loader.' 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(MsvdDataset, 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'): self.sample_len = 0 self.cut_off_points = [] self.multi_sentence_per_video = True video_id_path_dict = {} video_id_path_dict['train'] = os.path.join(self.anno_path, 'train_list.txt') video_id_path_dict['val'] = os.path.join(self.anno_path, 'val_list.txt') video_id_path_dict['test'] = os.path.join(self.anno_path, 'test_list.txt') caption_file = os.path.join(self.anno_path, 'raw-captions.pkl') with open(video_id_path_dict[subset], 'r') as fp: video_ids = [itm.strip() for itm in fp.readlines()] with open(caption_file, 'rb') as f: captions = pickle.load(f) video_dict = OrderedDict() sentences_dict = OrderedDict() for (root, dub_dir, video_files) in os.walk(self.video_path): for video_file in video_files: video_id_ = '.'.join(video_file.split('.')[:(- 1)]) if (video_id_ not in video_ids): continue file_path_ = os.path.join(root, video_file) video_dict[video_id_] = file_path_ for video_id in video_ids: assert (video_id in captions) for cap in captions[video_id]: cap_txt = ' '.join(cap) sentences_dict[len(sentences_dict)] = (video_id, (cap_txt, None, None)) self.cut_off_points.append((len(sentences_dict) - 1)) if ((subset == 'val') or (subset == 'test')): self.sentence_num = len(sentences_dict) self.video_num = len(video_ids) assert (len(self.cut_off_points) == self.video_num) print('For {}, sentence number: {}'.format(subset, self.sentence_num)) print('For {}, video number: {}'.format(subset, self.video_num)) print('Video number: {}'.format(len(video_dict))) print('Total Paire: {}'.format(len(sentences_dict))) self.sample_len = 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
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