code stringlengths 17 6.64M |
|---|
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)... |
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... |
@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 toke... |
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 - 25... |
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__)), p... |
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 ... |
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.z... |
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, Pretrai... |
class CrossEn(nn.Module):
def __init__(self):
super(CrossEn, self).__init__()
def forward(self, sim_matrix, target):
logpt = F.log_softmax(sim_matrix, dim=(- 1))
logpt = torch.index_select(logpt, (- 1), target)
loss = (- logpt)
sim_loss = loss.mean()
return si... |
class MILNCELoss(nn.Module):
def __init__(self, batch_size=1, n_pair=1):
super(MILNCELoss, self).__init__()
self.batch_size = batch_size
self.n_pair = n_pair
torch_v = float('.'.join(torch.__version__.split('.')[:2]))
self.bool_dtype = (torch.bool if (torch_v >= 1.3) else ... |
class MaxMarginRankingLoss(nn.Module):
def __init__(self, margin=1.0, negative_weighting=False, batch_size=1, n_pair=1, hard_negative_rate=0.5):
super(MaxMarginRankingLoss, self).__init__()
self.margin = margin
self.n_pair = n_pair
self.batch_size = batch_size
easy_negativ... |
class Emcl(object):
def __init__(self, k=32, stage_num=9, momentum=0.9, lamd=1, beta=3):
self.k = k
self.lamd = lamd
self.stage_num = stage_num
self.beta = beta
self.momentum = momentum
self.mu = torch.Tensor(1, self.k)
self.mu.normal_(0, math.sqrt((2.0 / s... |
class AllGather(torch.autograd.Function):
'An autograd function that performs allgather on a tensor.'
@staticmethod
def forward(ctx, tensor, args):
output = [torch.empty_like(tensor) for _ in range(args.world_size)]
torch.distributed.all_gather(output, tensor)
ctx.rank = args.rank... |
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... |
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)
... |
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)
... |
def compress(paras):
(input_video_path, output_video_path) = paras
try:
command = ['ffmpeg', '-y', '-i', input_video_path, '-filter:v', "scale='if(gt(a,1),trunc(oh*a/2)*2,224)':'if(gt(a,1),224,trunc(ow*a/2)*2)'", '-map', '0:v', '-r', '3', output_video_path]
ffmpeg = subprocess.Popen(command, s... |
def prepare_input_output_pairs(input_root, output_root):
input_video_path_list = []
output_video_path_list = []
for (root, dirs, files) in os.walk(input_root):
for file_name in files:
input_video_path = os.path.join(root, file_name)
output_video_path = os.path.join(output_r... |
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... |
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)
... |
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)
... |
class BaseDataLoader(DataLoader):
'Base class for all data loaders.'
def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate):
self.validation_split = validation_split
self.shuffle = shuffle
self.batch_idx = 0
self.n_samples =... |
class BaseModel(nn.Module):
'Base class for all models.'
@abc.abstractmethod
def forward(self, *inputs):
'Forward pass logic.'
raise NotImplementedError
def __str__(self):
'Model prints with number of trainable parameters.'
model_parameters = filter((lambda p: p.requi... |
class BaseTrainer():
'Base class for all trainers.'
def __init__(self, model, loss, metrics, optimizer, lr_scheduler, config):
self.config = config
self.hparams = get_hparams_from_config(self.config)
(self.device, device_ids) = self._prepare_device(config['n_gpu'])
self.model ... |
class ActivityNet(BaseDataset):
'ActivityNet captions dataset.'
def configure_train_test_splits(self, cut_name, split_name):
if (cut_name in ['val1']):
train_list_path = 'train_list.txt'
test_list_path = 'val_1_list.txt'
test_list_path = os.path.join(self.data_dir,... |
class ExpertDataLoader():
'Data loading of a dataset.'
def __init__(self, mix, num_workers, batch_size, raw_input_dims, until_epoch=float('inf'), pin_memory=False, n_pairs=1, training=False, tokenizer=None, loaded_data=None, cross_seed=0):
self.batch_size = batch_size
self.until_epoch = until... |
class DiDeMo(BaseDataset):
'DiDeMo dataset.'
def configure_train_test_splits(self, cut_name, split_name):
if (cut_name in ['full']):
if (split_name in ['train', 'trn']):
list_path = 'train_list.txt'
elif (split_name in ['val']):
list_path = 'val... |
class HowTo100M(BaseDataset):
'HowTo100M dataset.'
def configure_train_test_splits(self, cut_name, split_name):
self.restrict_test_captions = None
list_path = None
if (cut_name in ['full']):
if (split_name in ['train']):
list_path = 'train_list_full.txt'
... |
class LSMDC(BaseDataset):
'LSMDC dataset.'
def configure_train_test_splits(self, cut_name, split_name):
if (cut_name in ['full']):
train_list_path = 'LSMDC16_annos_training.csv'
test_list_path = 'LSMDC16_challenge_1000_publictect.csv'
test_list_path = os.path.join(... |
class MixDataset(Dataset):
'Dataset composed of a mix of different datasets.'
@abc.abstractmethod
def configure_train_test_splits(self, split_name):
'Partition the datset into train/val/test splits.'
raise NotImplementedError
@abc.abstractmethod
def sanity_checks(self):
'... |
class MSRVTT(BaseDataset):
'MSR-VTT dataset.'
def configure_train_test_splits(self, cut_name, split_name):
self.restrict_test_captions = None
if (cut_name in ['miech', 'jsfusion']):
if (cut_name in ['miech']):
train_list_path = 'train_list_miech.txt'
... |
class MSVD(BaseDataset):
'MSVD dataset.'
def configure_train_test_splits(self, cut_name, split_name):
if (cut_name in ['full']):
if (split_name in ['train', 'trn']):
list_path = 'train_list.txt'
elif (split_name in ['val']):
list_path = 'val_lis... |
class YouCook2(BaseDataset):
'YouCook2 dataset.'
def configure_train_test_splits(self, cut_name, split_name):
if (cut_name in ['full']):
if (split_name in ['train', 'trn']):
list_path = 'train_list.txt'
elif (split_name in ['val']):
list_path = ... |
class MaxMarginRankingLoss(nn.Module):
'Implementation of the Max-margin ranking loss.'
def __init__(self, margin=1, fix_norm=True):
super().__init__()
self.fix_norm = fix_norm
self.loss = th.nn.MarginRankingLoss(margin)
self.margin = margin
def forward(self, x):
... |
class TripletLoss(object):
def __init__(self, margin=None, mining_type='hard', topk=1):
self.margin = margin
if ((self.margin is not None) and (self.margin > 0)):
self.ranking_loss = nn.MarginRankingLoss(margin=margin)
else:
self.ranking_loss = nn.SoftMarginLoss()
... |
def hard_example_mining(dist_mat):
assert (len(dist_mat.size()) == 2)
assert (dist_mat.size(0) == dist_mat.size(1))
N = dist_mat.size(0)
is_pos = th.eye(N)
is_neg = (th.ones(dist_mat.shape) - th.eye(N))
is_pos = is_pos.cuda()
is_neg = is_neg.cuda()
dist_ap = th.mul(dist_mat, is_pos)
... |
def topk_example_mining(dist_mat, topk):
assert (len(dist_mat.size()) == 2)
assert (dist_mat.size(0) == dist_mat.size(1))
N = dist_mat.size(0)
is_pos = th.eye(N)
is_neg = (th.ones(dist_mat.shape) - th.eye(N))
is_pos = is_pos.cuda()
is_neg = is_neg.cuda()
dist_ap = th.mul(dist_mat, is_p... |
def topk_example_mining2(dist_mat, topk):
assert (len(dist_mat.size()) == 2)
assert (dist_mat.size(0) == dist_mat.size(1))
N = dist_mat.size(0)
is_pos = th.eye(N)
is_neg = (th.ones(dist_mat.shape) - th.eye(N))
_dist_mat = (F.softmax(dist_mat, dim=1) * dist_mat)
_dist_mat_t = (F.softmax(dis... |
def batch_all(dist_mat):
assert (len(dist_mat.size()) == 2)
assert (dist_mat.size(0) == dist_mat.size(1))
N = dist_mat.size(0)
is_pos = th.eye(N)
is_neg = (th.ones(dist_mat.shape) - th.eye(N))
is_pos = is_pos.cuda()
is_neg = is_neg.cuda()
dist_ap = th.mul(dist_mat, is_pos)
dist_an ... |
def batch_weight(dist_mat):
assert (len(dist_mat.size()) == 2)
assert (dist_mat.size(0) == dist_mat.size(1))
N = dist_mat.size(0)
is_pos = th.eye(N)
is_neg = (th.ones(dist_mat.shape) - th.eye(N))
is_pos = is_pos.cuda()
is_neg = is_neg.cuda()
dist_ap = th.mul(dist_mat, is_pos)
dist_... |
class LSTMModel(nn.Module):
'Long Short-Term memory network.'
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
super(LSTMModel, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = layer_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, batch... |
class NetVLAD(nn.Module):
'Net Vlad module.'
def __init__(self, cluster_size, feature_size, add_batch_norm=True):
super().__init__()
self.feature_size = feature_size
self.cluster_size = cluster_size
init_sc = (1 / math.sqrt(feature_size))
self.clusters = nn.Parameter((... |
class TxtEmbeddings(nn.Module):
'Construct the embeddings from word, position and token_type embeddings.'
def __init__(self, vocab_size=None, emb_dim=None, ckpt=None, freeze=False):
super(TxtEmbeddings, self).__init__()
if (ckpt is not None):
if isinstance(ckpt, str):
... |
class WeTokenizer():
'Word embeddings tokenizer.'
def __init__(self, we_filepath, freeze=False):
if we_filepath.endswith('.bin'):
binary = True
self.we = KeyedVectors.load_word2vec_format(we_filepath, binary=binary)
elif we_filepath.endswith('.txt'):
w2v_fo... |
class ConfigParser():
'Config parser.'
def __init__(self, args, options=''):
if args.resume:
msg_cfg = 'If resuming experiment then no config should be provided'
assert (args.config is None), msg_cfg
msg_cfg = 'If resuming experiment then no checkpoint should be pr... |
def _update_config(config, options, args):
for opt in options:
value = getattr(args, _get_opt_name(opt.flags))
if (value is not None):
_set_by_path(config, opt.target, value)
return config
|
def _get_opt_name(flags):
for flg in flags:
if flg.startswith('--'):
return flg.replace('--', '')
return flags[0].replace('--', '')
|
def _set_by_path(tree, keys, value):
'Set a value in a nested object in tree by sequence of keys.'
_get_by_path(tree, keys[:(- 1)])[keys[(- 1)]] = value
|
def _get_by_path(tree, keys):
'Access a nested object in tree by sequence of keys.'
return functools.reduce(operator.getitem, keys, tree)
|
def train(config):
expert_dims = compute_dims(config)
raw_input_dims = {}
for (expert, expert_dic) in expert_dims.items():
raw_input_dims[expert] = expert_dic['dim']
tic = time.time()
seed = config['seed']
cross_seed = config.get('cross_seed', seed)
logger.debug('Setting experiment... |
def main_train(raw_args=None):
parser = argparse.ArgumentParser(description='PyTorch Template')
parser.add_argument('--config', default=None, type=str, help='config file path (default: None)')
parser.add_argument('--resume', default=None, type=str, help='path to the experiment dir to resume (default: None... |
class HTML():
def __init__(self, web_dir, title, refresh=0):
self.title = title
self.web_dir = web_dir
self.img_dir = os.path.join(self.web_dir, 'images')
if (not os.path.exists(self.web_dir)):
os.makedirs(self.web_dir)
if (not os.path.exists(self.img_dir)):
... |
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... |
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'I... |
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':... |
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 ... |
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: ba... |
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 b... |
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: lo... |
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... |
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_avail... |
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 Retur... |
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.dat... |
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_... |
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', ... |
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, ... |
@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 toke... |
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 - 25... |
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__)), p... |
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 ... |
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.z... |
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, Pretrai... |
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 s... |
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(... |
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='')
... |
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 d... |
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): leng... |
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 '
... |
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_... |
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_dataLoad... |
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_datase... |
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_s... |
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... |
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)
... |
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)
... |
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.ut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.