code
stringlengths
17
6.64M
class ML_ISTA(nn.Module): def __init__(self, T): super(ML_ISTA, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True) self.strd2 = 2 ...
class ML_FISTA(nn.Module): def __init__(self, T): super(ML_FISTA, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True) self.strd2 = 2 ...
class ML_LISTA_NET(nn.Module): def __init__(self, T): super(ML_LISTA_NET, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True) self.strd...
class LBP_NET(nn.Module): def __init__(self, T): super(LBP_NET, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True) self.strd2 = 2 ...
class All_Free(nn.Module): def __init__(self): super(All_Free, self).__init__() m1 = 32 m2 = 64 m3 = 128 self.W1_1 = nn.Parameter(((0.1 / np.sqrt((3 * 16))) * torch.randn(32, 3, 4, 4)), requires_grad=True) self.W1_2 = nn.Parameter(((0.1 / np.sqrt((3 * 16))) * torch...
class ML_ISTA_NET(nn.Module): def __init__(self, m1, m2, m3, T): super(ML_ISTA_NET, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True) ...
class ML_FISTA_NET(nn.Module): def __init__(self, m1, m2, m3, T): super(ML_FISTA_NET, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True) ...
class ML_LISTA_NET(nn.Module): def __init__(self, m1, m2, m3, T): super(ML_LISTA_NET, self).__init__() self.T = T self.B1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True) self.B2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True) self.B3 = nn.Paramet...
class LBP_NET(nn.Module): def __init__(self, m1, m2, m3, T): super(LBP_NET, self).__init__() self.T = T self.W1 = nn.Parameter(torch.randn(m1, 1, 6, 6), requires_grad=True) self.strd1 = 2 self.W2 = nn.Parameter(torch.randn(m2, m1, 6, 6), requires_grad=True) self.st...
class All_Free(nn.Module): def __init__(self, m1, m2, m3): super(All_Free, self).__init__() self.W1_1 = nn.Parameter(((0.1 / np.sqrt(36)) * torch.randn(m1, 1, 6, 6)), requires_grad=True) self.W1_2 = nn.Parameter(((0.1 / np.sqrt(36)) * torch.randn(m1, 1, 6, 6)), requires_grad=True) ...
def data_loader(data_name, miss_rate): 'Loads datasets and introduce missingness.\n \n Args:\n - data_name: letter, spam, or mnist\n - miss_rate: the probability of missing components\n \n Returns:\n data_x: original data\n miss_data_x: data with missing values\n data_m: indicator matrix for ...
def main(args): 'Main function for UCI letter and spam datasets.\n \n Args:\n - data_name: letter or spam\n - miss_rate: probability of missing components\n - batch:size: batch size\n - hint_rate: hint rate\n - alpha: hyperparameter\n - iterations: iterations\n \n Returns:\n - imputed_d...
class RawVideoExtractorCV2(): def __init__(self, centercrop=False, size=224, framerate=(- 1)): self.centercrop = centercrop self.size = size self.framerate = framerate self.transform = self._transform(self.size) def _transform(self, n_px): return Compose([Resize(n_px,...
def get_args(description='VQA Task'): parser = argparse.ArgumentParser(description=description) parser.add_argument('--do_pretrain', action='store_true', help='Whether to run training.') parser.add_argument('--do_train', action='store_true', help='Whether to run training.') parser.add_argument('--do_e...
def set_seed_logger(args): 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.benchmark = False torch....
def init_device(args, local_rank): 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 % args.n_gpu) != 0) or ((arg...
def init_model(args, device, n_gpu, local_rank): if args.init_model: model_state_dict = torch.load(args.init_model, map_location='cpu') else: model_state_dict = None cache_dir = (args.cache_dir if args.cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed')) mode...
def prep_optimizer(args, model, num_train_optimization_steps, device, n_gpu, local_rank, coef_lr=1.0): if hasattr(model, 'module'): model = model.module param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] decay_param_tp = [(n, p) for (n, p...
def dataloader_msrvtt_train(args, tokenizer): msrvtt_dataset = MSRVTT_TrainDataLoader(jsonl_path=args.train_csv, ans2label_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, unfold_sentences=ar...
def dataloader_msrvtt_test(args, tokenizer): msrvtt_testset = MSRVTT_DataLoader(jsonl_path=args.val_csv, train_jsonl=args.train_csv, ans2label_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,...
def save_model(epoch, args, model, type_name=''): model_to_save = (model.module if hasattr(model, 'module') else model) output_model_file = os.path.join(args.output_dir, 'pytorch_model.bin.{}{}'.format(('' if (type_name == '') else (type_name + '.')), epoch)) torch.save(model_to_save.state_dict(), output_...
def load_model(epoch, args, n_gpu, device, model_file=None): if ((model_file is None) or (len(model_file) == 0)): model_file = os.path.join(args.output_dir, 'pytorch_model.bin.{}'.format(epoch)) if os.path.exists(model_file): model_state_dict = torch.load(model_file, map_location='cpu') ...
def train_epoch(epoch, args, model, train_dataloader, device, n_gpu, optimizer, scheduler, global_step, local_rank=0, tokenizer=ClipTokenizer()): global logger torch.cuda.empty_cache() model.train() log_step = args.n_display start_time = time.time() total_loss = 0 for (step, batch) in enum...
def eval_epoch(args, model, test_dataloader, device, n_gpu): top1 = AverageMeter() top5 = AverageMeter() if hasattr(model, 'module'): model = model.module.to(device) else: model = model.to(device) model.eval() with torch.no_grad(): for (bid, batch) in enumerate(test_dat...
def main(): global logger args = get_args() args = set_seed_logger(args) (device, n_gpu) = init_device(args, args.local_rank) tokenizer = ClipTokenizer() assert (args.task_type == 'retrieval') args.num_labels = 1500 model = init_model(args, device, n_gpu, args.local_rank) assert ((...
class AverageMeter(object): 'Computes and stores the average and current value' def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (val...
def accuracy(output, target, topk=(1,)): 'Computes the precision@k for the specified values of k' with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expa...
def url_to_filename(url: str, etag: str=None) -> str: "\n Convert `url` into a hashed filename in a repeatable way.\n If `etag` is specified, append its hash to the url's, delimited\n by a period.\n " url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdiges...
def filename_to_url(filename: str, cache_dir: Union[(str, Path)]=None) -> Tuple[(str, str)]: '\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.\n ' if (cache_dir is None): cache_dir = PYTO...
def cached_path(url_or_filename: Union[(str, Path)], cache_dir: Union[(str, Path)]=None) -> str: "\n Given something that might be a URL (or might be a local path),\n determine which. If it's a URL, download the file and cache it, and\n return the path to the cached file. If it's already a local path,\n ...
def split_s3_path(url: str) -> Tuple[(str, str)]: 'Split a full s3 path into the bucket name and path.' parsed = urlparse(url) if ((not parsed.netloc) or (not parsed.path)): raise ValueError('bad s3 path {}'.format(url)) bucket_name = parsed.netloc s3_path = parsed.path if s3_path.star...
def s3_request(func: Callable): '\n Wrapper function for s3 requests in order to create more helpful error\n messages.\n ' @wraps(func) def wrapper(url: str, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if (int(exc.re...
@s3_request def s3_etag(url: str) -> Optional[str]: 'Check ETag on S3 object.' s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_object = s3_resource.Object(bucket_name, s3_path) return s3_object.e_tag
@s3_request def s3_get(url: str, temp_file: IO) -> None: 'Pull a file directly from S3.' s3_resource = boto3.resource('s3') (bucket_name, s3_path) = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
def http_get(url: str, temp_file: IO) -> None: req = requests.get(url, stream=True) content_length = req.headers.get('Content-Length') total = (int(content_length) if (content_length is not None) else None) progress = tqdm(unit='B', total=total) for chunk in req.iter_content(chunk_size=1024): ...
def get_from_cache(url: str, cache_dir: Union[(str, Path)]=None) -> str: "\n Given a URL, look for the corresponding dataset in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n " if (cache_dir is None): cache_dir = PYTORCH_PRETRAINED_BERT_CACHE ...
def read_set_from_file(filename: str) -> Set[str]: '\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n ' collection = set() with open(filename, 'r', encoding='utf-8') as file_: for line in file_: collection.add(line.rstri...
def get_file_extension(path: str, dot=True, lower: bool=True): ext = os.path.splitext(path)[1] ext = (ext if dot else ext[1:]) return (ext.lower() if lower else ext)
class CrossEn(nn.Module): def __init__(self, config=None): super(CrossEn, self).__init__() def forward(self, sim_matrix): logpt = F.log_softmax(sim_matrix, dim=(- 1)) logpt = th.diag(logpt) nce_loss = (- logpt) sim_loss = nce_loss.mean() return sim_loss
class InfoNceLoss(nn.Module): 'Implementation of the noise-constrastive estimation loss.' def __init__(self): super().__init__() self.loss = th.nn.CrossEntropyLoss(reduction='mean') def forward(self, x): n = x.size()[0] target = th.arange(n) if x.is_cuda: ...
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): ...
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)...
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)): ...