code
stringlengths
17
6.64M
def add_acc_diff_cols(dists_df, acc_dict, guid_set): for stress_test in guid_set: new_column = [] for pre_seed1 in range(1, 11): for fine_seed1 in range(1, 11): for pre_seed2 in range(pre_seed1, 11): for fine_seed2 in range(1, 11): ...
def get_full_df(scores_path, dists_path, full_df_path): dists_df = pd.read_csv(dists_path) dists_df = dists_df.rename(columns={'step1': 'fine_seed1', 'step2': 'fine_seed2', 'seed1': 'pre_seed1', 'seed2': 'pre_seed2'}) print('got dists_df') print('adding probing scores to get full_df') (guid_set, a...
def best_seed_pair(task): (_, acc_dict) = collect_scores(scores_path) acc_array = acc_dict[task].flatten() idxs = acc_array.argsort()[(- 1):][::(- 1)] ref_seeds = [] for idx in idxs: ref_seeds.append((int((idx / 10)), (idx % 10))) return ref_seeds[0]
def ftvft_sub_df(df, task, ref_depth): (best_pre_seed, best_fine_seed) = best_seed_pair(task) sub_df = df[(((df.layer1 == ref_depth) & (df.layer2 == ref_depth)) & (((df.pre_seed1 == best_pre_seed) & (df.fine_seed1 == best_fine_seed)) | ((df.pre_seed2 == best_pre_seed) & (df.fine_seed2 == best_fine_seed))))] ...
def best_seed_pair(task): (_, acc_dict) = collect_scores(scores_path) acc_array = acc_dict[task].flatten() idxs = acc_array.argsort()[(- 1):][::(- 1)] ref_seeds = [] for idx in idxs: ref_seeds.append((int((idx / 10)), (idx % 10))) return ref_seeds[0]
def ftvft_sub_df(df, task, ref_depth): (best_pre_seed, best_fine_seed) = best_seed_pair(task) sub_df = df[(((df.layer1 == ref_depth) & (df.layer2 == ref_depth)) & (((df.pre_seed1 == best_pre_seed) & (df.fine_seed1 == best_fine_seed)) | ((df.pre_seed2 == best_pre_seed) & (df.fine_seed2 == best_fine_seed))))] ...
def qs(xs): return np.array(list(map((lambda x: (pc(xs, x, 'rank') / 100)), xs)))
def plot_rank_corrs(rho, rho_p, tau, tau_p, METRICS, scatter=False, title=''): (fig, ax) = plt.subplots(2, 2, figsize=(10, 10)) fig.suptitle(title) if scatter: (x, y) = ([], []) for (i, metric) in enumerate(METRICS): x += (len(rho[metric]) * [i]) y += rho[metric] ...
def get_rank_corrs(sub_df, metric, task): plot_x = sub_df[metric] plot_y = sub_df[f'{task}_diff'] rho = spearmanr(plot_x, plot_y) rho_corr = rho.correlation rho_os_p = ((rho.pvalue / 2) if (rho_corr > 0) else (1 - (rho.pvalue / 2))) tau = kendalltau(plot_x, plot_y) tau_corr = tau.correlati...
def aggregate_rank_corrs(full_df, task, num_layers, METRICS, sub_df_fn, list_layers=None): if (list_layers == None): list_layers = list(range(num_layers)) rho = {metric: [] for metric in METRICS} rho_p = {metric: [] for metric in METRICS} tau = {metric: [] for metric in METRICS} tau_p = {m...
class FontDataLoader(): def __init__(self, dataset, sampler, batch_size): self.data_loader = torch.utils.data.DataLoader(dataset, sampler=sampler, batch_size=batch_size) def __iter__(self): self.data_loader_iterator = iter(self.data_loader) return self def __next__(self): ...
class FontData(): def __init__(self, font_name, font_path, image=None): self.font_name = font_name self.font_path = font_path self.image = None def load_data(self, loader): if (self.image == None): self.image = loader(self.font_path) return self.image ...
class FontDataset(Dataset): 'The Font Dataset.' def __init__(self, root_dir, glyph_size=(64, 64), glyphs_per_image=26): self.fonts = self.load_font_filenames(root_dir) self.root_dir = root_dir self.glyph_size = glyph_size self.glyphs_per_image = glyphs_per_image def __len...
def image_loader(path): return Image.open(path).convert('RGB')
def l1_and_adversarial_loss(D, G, real_data, generated_data, losses, options): l1_lamba = 10 return (min_max_loss(D, G, real_data, generated_data, losses, options) + (l1_lamba * l1_loss(D, G, real_data, generated_data, losses, options)))
def wasserstein_loss(D, G, real_data, generated_data, losses, options): real_loss = D(real_data) generated_loss = D(generated_data) (batch_size, data_type) = itemgetter('batch_size', 'data_type')(options) gradient_penalty_weight = 10 gradient_penalty = calculate_gradient_penalty(D, real_data, gene...
def min_max_loss(D, G, real_data, generated_data, losses, options): discriminator_loss = D(generated_data) loss = (- discriminator_loss.mean()) return loss
def l1_loss(D, G, real_data, generated_data, losses, options): '\n Performs the L1 loss between the generated data and the real data.\n\n It is expected that both `real_data` and `generated_data` are of the same shape.\n ' return torch.nn.L1Loss()(generated_data, real_data)
def calculate_gradient_penalty(D, real_data, generated_data, batch_size, gradient_penalty_weight, losses, data_type): alpha = torch.rand(batch_size, 1, 1, 1).expand_as(real_data).type(data_type) interpolated = ((alpha * real_data.data) + ((1 - alpha) * generated_data.data)).type(data_type) interpolated.re...
def build_font_shape_generator(glyph_size=(64, 64, 1), glyph_count=26, dimension=16): '\n Generator model for our GAN.\n\n Architecture is similar to DC-GAN with the exception of the input being an image.\n\n Inputs:\n - `image_size`: A triple (W, H, C) for the size of the images and number of channels. This ...
def simple_upscale_generator(dimension): '\n A generator that performs several ConvTranpsose2D Operations to upscale an image from `individual_image_size` to `final_image_size`. The dimensions of `final_image_size` must be an integer multiple of `individual_image_size.`\n\n Inputs:\n - `individual_image_size`:...
def intermediate_generator(glyph_size=(64, 64), glyph_count=26, dimension=16): linear_width = int((((((2 * dimension) * glyph_size[0]) / 4) * glyph_size[1]) / 4)) hidden_width = int((glyph_size[0] * glyph_size[1])) final_width = int(((((4 * dimension) * glyph_count) * 2) * 2)) return nn.Sequential(nn....
def intermediate_generator_alt(glyph_size=(16, 16), glyph_count=26, dimension=512): conv_dimensions = [dimension, int((dimension / 2)), int((dimension / 4))] fc_layer_widths = [int(((((conv_dimensions[2] * glyph_size[0]) / 8) * glyph_size[1]) / 8)), int((glyph_size[0] * glyph_size[1])), int(((((((glyph_size[0...
def build_font_shape_discriminator(image_size=(64, 1664), dimension=16): '\n PyTorch model implementing the GlyphGAN critic.\n\n Inputs:\n - `image_size`: The size of the entire alphabet (usually (H, W * 26))\n - `dimension`: The filter depth after each conv. Doubles per conv layer (1 - > 2 -> 4 -> 8)\n ' ...
def get_optimizer(model, learning_rate=0.0002, beta1=0.5, beta2=0.99): '\n Adam optimizer for model\n\n Input:\n - model: A PyTorch model that we want to optimize.\n\n Returns:\n - An Adam optimizer for the model with the desired hyperparameters.\n ' optimizer = optim.Adam(model.parameters()...
class Flatten(nn.Module): def forward(self, x): (N, _, _, _) = x.size() return x.view(N, (- 1))
class Unflatten(nn.Module): '\n An Unflatten module receives an input of shape (N, C*H*W) and reshapes it\n to produce an output of shape (N, C, H, W).\n ' def __init__(self, N=(- 1), C=128, H=7, W=7): super(Unflatten, self).__init__() self.N = N self.C = C self.H = H ...
def initialize_weights(m): if (isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose2d) or isinstance(m, nn.Conv2d)): nn.init.xavier_uniform_(m.weight.data)
class TestFontDatasets(unittest.TestCase): def test_cannot_create_invalid_font_dataset(self): with self.assertRaises(AssertionError): FontDataset('does_not_exist') def test_can_create_font_dataset(self): dataset = FontDataset(abspath(join(dirname(__file__), 'test_datasets/valid')...
def show_grayscale_image(image): plot.imshow(transforms.Compose([transforms.ToPILImage(), transforms.Grayscale(num_output_channels=3)])(image)) plot.axis('off') plot.show()
def perturb(V, word): print(model[word].predict(asarray(V).reshape(1, (- 1)))[0][1]) phonemes = ((len(V) - 1) // 4) pbs = [] for n in range(phonemes): Z = list(V) Z[((n * 4) + 1)] *= 1.5 Z[((n * 4) + 2)] *= 1.5 Z[((n * 4) + 3)] *= 1.5 p_i = model[word].predict(a...
def init_matrix(data): for i in range(len(data)): data[i][0] = float('inf') for i in range(len(data[0])): data[0][i] = float('inf') data[0][0] = 0 return data
def LpDist(time_pt_1, time_pt_2): if ((type(time_pt_1) == int) and (type(time_pt_2) == int)): return abs((time_pt_1 - time_pt_2)) else: return sum(abs((time_pt_1 - time_pt_2)))
def TWED(t1, t2, lam, nu): '"Requires: t1: multivariate time series in numpy matrix format. t2: multivariate time series in numpy matrix format. lam: penalty lambda parameter, nu: stiffness coefficient' 'Returns the TWED distance between the two time series. ' t1_data = t1 t2_data = t2 result = [(...
class HyperParams(): def __init__(self): pass def get_uniwarp_config(self, argv): config = {} config['optimizer:num_epochs'] = 1000000 config['model:num_batch_pairs'] = 100 config['uniwarp:length'] = 1024 config['uniwarp:rnn_encoder_layers'] = [256, 128, 64] ...
class Inference_Experiments(): def __init__(self, model_type, model_file, dataset_path): self.model_type = model_type self.model_file = model_file self.dataset_path = dataset_path hp = HyperParams() self.config = hp.get_uniwarp_config(None) self.ds = Dataset() ...
class Optimizer(): def __init__(self, config, dataset, sim_model): self.config = config self.dataset = dataset self.num_epochs = self.config['optimizer:num_epochs'] self.sim_model = sim_model self.saver = tf.train.Saver(max_to_keep=100) def optimize(self): wit...
class AbstractSimModel(): def __init__(self, config): self.config = config self.minus_one_constant = tf.constant((- 1.0), dtype=tf.float32) self.sequence_length = self.config['uniwarp:length'] self.X_batch = tf.placeholder(shape=((2 * self.config['model:num_batch_pairs']), self.co...
def kernel(r): return ((prior_std ** 2) * np.exp((- r)))
def forward_model(s, parallelization, ncores=None): model = ert.Model(forward_params) if parallelization: simul_obs = model.run(s, parallelization, ncores) else: simul_obs = model.run(s, parallelization) return simul_obs
def kernel(r): return ((prior_std ** 2) * np.exp((- r)))
def forward_model(s, parallelization, ncores=None): model = Model(forward_params) if parallelization: simul_obs = model.run(s, parallelization, ncores) else: simul_obs = model.run(s, parallelization) return simul_obs
def kernel(r): return ((prior_std ** 2) * np.exp((- (r ** 2))))
def forward_model(s, parallelization, ncores=None): params = {'nx': nx, 'ny': ny} model = mare2dem.Model(params) if parallelization: simul_obs = model.run(s, parallelization, ncores) else: simul_obs = model.run(s, parallelization) return simul_obs
def kernel(r): return ((prior_std ** 2) * np.exp((- (r ** 2))))
def forward_model(s, parallelization, ncores=None): params = {'nx': nx, 'ny': ny} model = mare2dem.Model(params) if parallelization: simul_obs = model.run(s, parallelization, ncores) else: simul_obs = model.run(s, parallelization) return simul_obs
def kernel(r): return ((prior_std ** 2) * np.exp((- r)))
def forward_model(s, parallelization, ncores=None): params = {} model = dd.Model(params) if parallelization: simul_obs = model.run(s, parallelization, ncores) else: simul_obs = model.run(s, parallelization) return simul_obs
def kernel(r): return ((prior_std ** 2) * np.exp((- r)))
def forward_model(s, parallelization, ncores=None): params = {'log': True} model = dd.Model(params) if parallelization: simul_obs = model.run(s, parallelization, ncores) else: simul_obs = model.run(s, parallelization) return simul_obs
class SepConvGRU(nn.Module): def __init__(self): super(SepConvGRU, self).__init__() hidden_dim = 128 catt = 256 self.convz1 = nn.Conv2d(catt, hidden_dim, (1, 3), padding=(0, 1)) self.convr1 = nn.Conv2d(catt, hidden_dim, (1, 3), padding=(0, 1)) self.convq1 = nn.Conv...
class R_MSFM3(nn.Module): def __init__(self, x): super(R_MSFM3, self).__init__() self.convX11 = torch.nn.Sequential(nn.ReflectionPad2d(1), torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=0, bias=True), torch.nn.LeakyReLU(inplace=True), nn.ReflectionPad2d(1), torc...
class R_MSFM6(nn.Module): def __init__(self, x): super(R_MSFM6, self).__init__() self.convX11 = torch.nn.Sequential(nn.ReflectionPad2d(1), torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=0, bias=True), torch.nn.LeakyReLU(inplace=True), nn.ReflectionPad2d(1), torc...
class ConvBlock(nn.Module): 'Layer to perform a convolution followed by LeakyReLU\n ' def __init__(self, in_channels, out_channels): super(ConvBlock, self).__init__() self.conv = Conv3x3(in_channels, out_channels) self.nonlin = nn.LeakyReLU(inplace=True) def forward(self, x): ...
class Conv3x3(nn.Module): 'Layer to pad and convolve input\n ' def __init__(self, in_channels, out_channels, use_refl=True): super(Conv3x3, self).__init__() if use_refl: self.pad = nn.ReflectionPad2d(1) else: self.pad = nn.ZeroPad2d(1) self.conv = nn...
class dispHead(nn.Module): def __init__(self): super(dispHead, self).__init__() outD = 1 self.covd1 = torch.nn.Sequential(nn.ReflectionPad2d(1), torch.nn.Conv2d(in_channels=192, out_channels=256, kernel_size=3, stride=1, padding=0, bias=True), torch.nn.LeakyReLU(inplace=True)) sel...
class BasicMotionEncoder(nn.Module): def __init__(self): super(BasicMotionEncoder, self).__init__() self.convc1 = ConvBlock(128, 160) self.convc2 = ConvBlock(160, 128) self.convf1 = torch.nn.Sequential(nn.ReflectionPad2d(3), torch.nn.Conv2d(in_channels=1, out_channels=64, kernel_s...
class BasicUpdateBlock(nn.Module): def __init__(self): super(BasicUpdateBlock, self).__init__() self.encoder = BasicMotionEncoder() self.flow_head = dispHead() self.mask = nn.Sequential(nn.ReflectionPad2d(1), nn.Conv2d(192, 324, 3), nn.LeakyReLU(inplace=True), nn.Conv2d(324, (64 *...
class ResNetMultiImageInput(models.ResNet): 'Constructs a resnet model with varying number of input images.\n Adapted from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\n ' def __init__(self, block, layers, num_classes=1000, num_input_images=1): super(ResNetMultiIma...
def resnet_multiimage_input(num_layers, pretrained=False, num_input_images=1): 'Constructs a ResNet model.\n Args:\n num_layers (int): Number of resnet layers. Must be 18 or 50\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n num_input_images (int): Number of frames ...
class ResnetEncoder(nn.Module): 'Pytorch module for a resnet encoder\n ' def __init__(self, num_layers, pretrained, num_input_images=1): super(ResnetEncoder, self).__init__() self.num_ch_enc = np.array([64, 64, 128, 256, 512]) resnets = {18: models.resnet18, 34: models.resnet34, 50...
class ResnetEncoder2(nn.Module): 'Pytorch module for a resnet encoder\n ' def __init__(self, num_layers, pretrained, num_input_images=1): super(ResnetEncoder2, self).__init__() self.num_ch_enc = np.array([64, 64, 128, 256, 512]) resnets = {18: models.resnet18, 34: models.resnet34, ...
def init_fourier_(tensor, norm='ortho'): 'Initialise convolution weight with Inverse Fourier Transform' with torch.no_grad(): (nc_out, nc_in, N, kernel_size) = tensor.shape for k in range(N): for n in range(N): tensor.data[(k, 0, n, (kernel_size // 2))] = np.cos((((...
def init_fourier_2d(N, M, inverse=True, norm='ortho', out_tensor=None, complex_type=np.complex64): "Initialise fully connected layer as 2D Fourier transform\n\n Parameters\n ----------\n\n N, M: a number of rows and columns\n\n inverse: bool (default: True) - if True, initialise with the weights for\n...
def init_noise_(tensor, init): with torch.no_grad(): return (getattr(torch.nn.init, init)(tensor) if init else tensor.zero_())
class GeneralisedIFT2Layer(nn.Module): def __init__(self, nrow, ncol, nch_in, nch_int=None, nch_out=None, kernel_size=1, nl=None, init_fourier=True, init=None, bias=False, batch_norm=False, share_tfxs=False, learnable=True): "Generalised domain transform layer\n\n The layer can be initialised as F...
def get_refinement_block(model='automap_scae', in_channel=1, out_channel=1): if (model == 'automap_scae'): return nn.Sequential(nn.Conv2d(in_channel, 64, 5, 1, 2), nn.ReLU(True), nn.Conv2d(64, 64, 5, 1, 2), nn.ReLU(True), nn.ConvTranspose2d(64, out_channel, 7, 1, 3)) elif (model == 'simple'): ...
class AUTOMAP(nn.Module): '\n Pytorch implementation of AUTOMAP [1].\n\n Reference:\n ----------\n [1] Zhu et al., AUTOMAP, Nature 2018. <url:https://www.nature.com/articles/nature25988.pdf>\n ' def __init__(self, input_shape, output_shape, init_fc2_fourier=False, init_fc3_fourier=False): ...
class dAUTOMAP(nn.Module): '\n Pytorch implementation of dAUTOMAP\n\n Decomposes the automap kernel into 2 Generalised "1D" transforms to make it scalable.\n ' def __init__(self, input_shape, output_shape, tfx_params, tfx_params2=None): super(dAUTOMAP, self).__init__() self.input_sha...
class dAUTOMAPExt(nn.Module): '\n Pytorch implementation of dAUTOMAP with adjustable depth and nonlinearity\n\n Decomposes the automap kernel into 2 Generalised "1D" transforms to make it scalable.\n\n Parameters\n ----------\n\n input_shape: tuple (n_channel, nx, ny)\n\n output_shape: tuple (n_...
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))))