code
stringlengths
17
6.64M
def rmse_base(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, mask): depth_gt[mask] = 1 depth_prediction[mask] = 1 se = ((depth_prediction - depth_gt) ** 2) return torch.mean(torch.sqrt(mask_mean(se, mask, dim=[1, 2, 3])))
def rmse_log_base(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, mask): depth_gt[mask] = 1 depth_prediction[mask] = 1 sle = ((torch.log(depth_prediction) - torch.log(depth_gt)) ** 2) return torch.mean(torch.sqrt(mask_mean(sle, mask, dim=[1, 2, 3])))
def abs_rel_base(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, mask): return mask_mean((torch.abs((depth_prediction - depth_gt)) / depth_gt), mask)
def sq_rel_base(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, mask): return mask_mean((((depth_prediction - depth_gt) ** 2) / depth_gt), mask)
class ConfigParser(): def __init__(self, args, options='', timestamp=True): for opt in options: args.add_argument(*opt.flags, default=None, type=opt.type) args = args.parse_args() self.args = args if args.device: os.environ['CUDA_VISIBLE_DEVICES'] = args.de...
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 reduce(getitem, keys, tree)
def main(config, options=[]): seed_rng(0) logger = config.get_logger('train') data_loader = config.initialize('data_loader', module_data) if ('val_data_loader' in config.config): valid_data_loader = config.initialize('val_data_loader', module_data) else: valid_data_loader = data_lo...
class Trainer(BaseTrainer): def __init__(self, model, loss, metrics, optimizer, config, data_loader, valid_data_loader=None, lr_scheduler=None, options=[]): super().__init__(model, loss, metrics, optimizer, config) self.config = config self.data_loader = data_loader len_epoch = co...
def to(data, device): if isinstance(data, dict): return {k: to(data[k], device) for k in data.keys()} elif isinstance(data, list): return [to(v, device) for v in data] else: return data.to(device)
def infnan_to_zero(t: torch.Tensor()): t[torch.isinf(t)] = 0 t[torch.isnan(t)] = 0 return t
class ConfigParser(): def __init__(self, args, options='', timestamp=True): for opt in options: args.add_argument(*opt.flags, default=None, type=opt.type) args = args.parse_args() self.args = args if args.device: os.environ['CUDA_VISIBLE_DEVICES'] = args.de...
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 reduce(getitem, keys, tree)
def get_inception_model(): return tfhub.load(INCEPTION_TFHUB)
def create_inception_graph(pth): 'Creates a graph from saved GraphDef file.' with tf.gfile.FastGFile(pth, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def, name='FID_Inception_Net')
def _get_inception_layer(sess): 'Prepares inception net for batched usage and returns pool_3 layer. ' layername = 'FID_Inception_Net/pool_3:0' pool3 = sess.graph.get_tensor_by_name(layername) ops = pool3.graph.get_operations() for (op_idx, op) in enumerate(ops): for o in op.outputs: ...
def get_activations(images, sess, batch_size=50, verbose=False): 'Calculates the activations of the pool_3 layer for all images.\n\n Params:\n -- images : Numpy array of dimension (n_images, hi, wi, 3). The values\n must lie between 0 and 256.\n -- sess : current session\n...
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-06): "Numpy implementation of the Frechet Distance.\n The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)\n and X_2 ~ N(mu_2, C_2) is\n d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).\n\n Stable v...
def calculate_activation_statistics(images, sess, batch_size=50, verbose=False): 'Calculation of the statistics used by the FID.\n Params:\n -- images : Numpy array of dimension (n_images, hi, wi, 3). The values\n must lie between 0 and 255.\n -- sess : current session\n ...
def check_or_download_inception(inception_path): ' Checks if the path to the inception file is valid, or downloads\n the file if it is not present. ' INCEPTION_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz' if (inception_path is None): inception_path =...
def fid_score(create_session, data, samples, path='/tmp', cpu_only=False): with create_session() as sess: if cpu_only: with tf.device('cpu'): inception_path = check_or_download_inception(path) create_inception_graph(str(inception_path)) data = da...
def load_dataset_stats(config): 'Load the pre-computed dataset statistics.' filename = 'statistics/statistics_{}.npz'.format(config.problem) with tf2.io.gfile.GFile(filename, 'rb') as fin: stats = np.load(fin) return stats
def classifier_fn_from_tfhub(tfhub_module, output_fields, inception_model, return_tensor=False): 'Returns a function that can be as a classifier function.\n\n Copied from tfgan but avoid loading the model each time calling _classifier_fn\n\n Wrapping the TF-Hub module in another function defers loading the modu...
@tf2.function def run_inception_jit(inputs, inception_model, num_batches=1): 'Running the inception network. Assuming input is within [0, 255].' inputs = ((tf2.cast(inputs, tf2.float32) - 127.5) / 127.5) return tfgan.eval.run_classifier_fn(inputs, num_batches=num_batches, classifier_fn=classifier_fn_from_...
@tf2.function def run_inception_distributed(input_tensor, inception_model, num_batches=1): 'Distribute the inception network computation to all available TPUs.\n\n Assuming the input is within [0, 255].\n ' (num_tpus, device_type) = num_device() input_tensors = tf2.split(input_tensor, num_tpus, axis=0) ...
def compute_fid(x_data, x_samples): assert (type(x_data) == np.ndarray) assert (type(x_samples) == np.ndarray) assert (np.min(x_data) > (0.0 - 0.0001)) assert (np.max(x_data) < (255.0 + 0.0001)) assert (np.mean(x_data) > 10.0) assert (np.min(x_samples) > (0.0 - 0.0001)) assert (np.max(x_sa...
def main(argv): del argv LARGE_DATASETS = ['celebahq128', 'lsun_bedroom128', 'lsun_bedroom64', 'lsun_church128', 'lsun_church64', 'celeba'] exp_id = pygrid.get_exp_id(__file__) output_dir = pygrid.get_output_dir(exp_id, './') if (FLAGS.problem in LARGE_DATASETS): FLAGS.fid_n_samples = 2560...
def get_beta_schedule(*, beta_start, beta_end, num_diffusion_timesteps): betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64) betas = np.append(betas, 1.0) assert (betas.shape == ((num_diffusion_timesteps + 1),)) return betas
def get_sigma_schedule(*, beta_start, beta_end, num_diffusion_timesteps): '\n Get the noise level schedule\n :param beta_start: begin noise level\n :param beta_end: end noise level\n :param num_diffusion_timesteps: number of timesteps\n :return:\n -- sigmas: sigma_{t+1}, scaling parameter of epsilon_{t+1}\n...
class RecoveryLikelihood(tf.keras.Model): def __init__(self, hps): super(RecoveryLikelihood, self).__init__() self.hps = hps self.num_timesteps = FLAGS.num_diffusion_timesteps (self.sigmas, self.a_s) = get_sigma_schedule(beta_start=0.0001, beta_end=0.02, num_diffusion_timesteps=se...
def init_mp(tf2=True): if tf2: multiprocessing.set_start_method('spawn')
def copy_source(file, output_dir): with tf.io.gfile.GFile(os.path.join(output_dir, os.path.basename(file)), mode='wb') as f: with tf.io.gfile.GFile(file, mode='rb') as f0: shutil.copyfileobj(f0, f)
class FileHandler(StreamHandler): '\n A handler class which writes formatted logging records to disk files.\n ' def __init__(self, filename, mode='a', encoding=None, delay=False): '\n Open the specified file and use it as the stream for logging.\n ' self.baseFilename = os....
def setup_logging_file(name, f, console=True): log_format = logging.Formatter('%(asctime)s : %(message)s') logger = logging.getLogger(name) logger.handlers = [] file_handler = FileHandler(f) file_handler.setFormatter(log_format) logger.addHandler(file_handler) if console: console_h...
def setup_logging(name, output_dir, console=True): log_format = logging.Formatter('%(asctime)s : %(message)s') logger = logging.getLogger(name) logger.handlers = [] output_file = os.path.join(output_dir, 'output.log') file_handler = FileHandler(output_file) file_handler.setFormatter(log_format...
def get_argv(): argv = sys.argv for i in range(1, len(argv)): if (argv[i] == '--ckpt_load'): argv.pop(i) argv.pop(i) break for i in range(1, len(argv)): if argv[i].startswith('--ckpt_load='): argv.pop(i) break for i in range(1...
def get_output_filename(file): file_name = get_exp_id(file) if (len(sys.argv) > 1): file_name = (file_name + get_argv()) return file_name
def get_output_dir(exp_id, rootdir): t = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') output_dir = os.path.join(rootdir, ('output/' + exp_id), t) if (len(sys.argv) > 1): output_dir = (output_dir + get_argv()) if (not os.path.exists(output_dir)): os.makedirs(output_dir) ret...
def fill_queue(device_ids): [free_devices.put_nowait(device_id) for device_id in device_ids]
def allocate_device(): try: free_devices_lock.acquire() return free_devices.get() finally: free_devices_lock.release()
def free_device(device): try: free_devices_lock.acquire() return free_devices.put_nowait(device) finally: free_devices_lock.release()
def update_job_status(job_id, job_status, read_opts, write_opts): try: job_file_lock.acquire() opts = read_opts() opt = next((opt for opt in opts if (opt['job_id'] == job_id))) opt['status'] = job_status write_opts(opts) except Exception: logging.exception('exce...
def update_job_result_file(update_job_result, job_opt, job_stats, read_opts, write_opts): try: job_file_lock.acquire() opts = read_opts() target_opt = next((opt for opt in opts if (opt['job_id'] == job_opt['job_id']))) update_job_result(target_opt, job_stats) write_opts(opt...
def run_job(logger, opt, output_dir, output_dir_ckpt, train): device_id = allocate_device() opt_override = {'device': device_id} def merge(a, b): d = {} d.update(a) d.update(b) return d opt = merge(opt, opt_override) logger.info('new job: job_id={}, device_id={}'.f...
def run_jobs(logger, exp_id, output_dir, output_dir_ckpt, workers, train_job, read_opts, write_opts, update_job_result): opt_list = read_opts() opt_open = [opt for opt in opt_list if (opt['status'] == 'open')] logger.info('scheduling {} open of {} total jobs'.format(len(opt_open), len(opt_list))) logg...
def is_int(value): try: int(value) return True except ValueError: return False
def is_float(value): try: float(value) return (not is_int(value)) except ValueError: return False
def is_bool(value): return (value.upper() in ['TRUE', 'FALSE'])
def is_array(value): return ('[' in value)
def cast_str(value): if is_int(value): return int(value) if is_float(value): return float(value) if is_bool(value): return (value.upper() == 'TRUE') if is_array(value): return eval(value) return value
def get_exp_id(file): return os.path.splitext(os.path.basename(file))[0]
def overwrite_opt(opt, opt_override): for (k, v) in opt_override.items(): setattr(opt, k, v) return opt
def write_opts(opt_list, f): writer = csv.writer(f(), delimiter=',') header = [key for key in opt_list[0]] writer.writerow(header) for opt in opt_list: writer.writerow([opt[k] for k in header])
def read_opts(f): opt_list = [] reader = csv.reader(f(), delimiter=',') header = next(reader) for values in reader: opt = {} for (i, field) in enumerate(header): opt[field] = cast_str(values[i]) opt_list += [opt] return opt_list
def reset_job_status(opts_list): for opt in opts_list: if (opt['status'] == 'running'): opt['status'] = 'open' return opts_list
class AStar(): def __init__(self, neighbor_func, dist_func='euclidian', heuristic_func='euclidian', bias=0.0, silent=True): self.neighbor_func = neighbor_func self.heuristic_func = heuristic_func self.dist_func = dist_func if (heuristic_func == 'euclidian'): self.heuri...
class Pivots(): '\n Pivots is an ndarray of angular rotations\n\n This wrapper provides some functions for\n working with pivots.\n\n These are particularly useful as a number \n of atomic operations (such as adding or \n subtracting) cannot be achieved using\n the standard arithmatic and nee...
class DataAugmentationForVideoDistillation(object): def __init__(self, args, num_frames=None): self.input_mean = [0.485, 0.456, 0.406] self.input_std = [0.229, 0.224, 0.225] normalize = GroupNormalize(self.input_mean, self.input_std) self.train_augmentation = GroupMultiScaleTwoRes...
def build_distillation_dataset(args, num_frames=None): if (num_frames is None): num_frames = args.num_frames transform = DataAugmentationForVideoDistillation(args, num_frames=num_frames) dataset = VideoDistillation(root=args.data_root, setting=args.data_path, video_ext='mp4', is_color=True, modali...
def build_dataset(is_train, test_mode, args): if (args.data_set == 'Kinetics-400'): mode = None anno_path = None if (is_train is True): mode = 'train' anno_path = os.path.join(args.data_path, 'train.csv') elif (test_mode is True): mode = 'test' ...
def train_class_batch(model, samples, target, criterion): outputs = model(samples) loss = criterion(outputs, target) return (loss, outputs)
def get_loss_scale_for_deepspeed(model): optimizer = model.optimizer return (optimizer.loss_scale if hasattr(optimizer, 'loss_scale') else optimizer.cur_scale)
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, model_ema: Optional[ModelEma]=None, mixup_fn=None, log_writer=None, start_steps=None, lr_schedule_values=None, wd_schedule_...
@torch.no_grad() def validation_one_epoch(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = utils.MetricLogger(delimiter=' ') header = 'Val:' model.eval() for batch in metric_logger.log_every(data_loader, 10, header): videos = batch[0] target = b...
@torch.no_grad() def final_test(data_loader, model, device, file): criterion = torch.nn.CrossEntropyLoss() metric_logger = utils.MetricLogger(delimiter=' ') header = 'Test:' model.eval() final_result = [] for batch in metric_logger.log_every(data_loader, 10, header): videos = batch[0]...
def merge(eval_path, num_tasks): dict_feats = {} dict_label = {} dict_pos = {} print('Reading individual output files') for x in range(num_tasks): file = os.path.join(eval_path, (str(x) + '.txt')) lines = open(file, 'r').readlines()[1:] for line in lines: line =...
def compute_video(lst): (i, video_id, data, label) = lst feat = [x for x in data] feat = np.mean(feat, axis=0) pred = np.argmax(feat) top1 = ((int(pred) == int(label)) * 1.0) top5 = ((int(label) in np.argsort((- feat))[:5]) * 1.0) return [pred, top1, top5, int(label)]
class TubeMaskingGenerator(): def __init__(self, input_size, mask_ratio): (self.frames, self.height, self.width) = input_size self.num_patches_per_frame = (self.height * self.width) self.total_patches = (self.frames * self.num_patches_per_frame) self.num_masks_per_frame = int((mas...
class RandomMaskingGenerator(): def __init__(self, input_size, mask_ratio): (self.frames, self.height, self.width) = input_size self.total_patches = ((self.frames * self.height) * self.width) self.num_masks = int((mask_ratio * self.total_patches)) self.total_masks = self.num_masks...
def trunc_normal_(tensor, mean=0.0, std=1.0): __call_trunc_normal_(tensor, mean=mean, std=std, a=(- std), b=std)
class PretrainVisionTransformerEncoder(nn.Module): ' Vision Transformer with support for patch or hybrid CNN input stage\n ' def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=0, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop_rate=0.0, attn_d...
class PretrainVideoTransformerTeacher(nn.Module): ' Vision Transformer with support for patch or hybrid CNN input stage\n ' def __init__(self, img_size=224, patch_size=16, encoder_in_chans=3, encoder_num_classes=0, encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, mlp_ratio=4.0, qkv_bias=Fals...
@register_model def pretrain_videomae_teacher_base_patch16_224(pretrained=False, **kwargs): model = PretrainVideoTransformerTeacher(patch_size=16, encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_num_classes=0, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), **kwargs...
@register_model def pretrain_videomae_teacher_large_patch16_224(pretrained=False, **kwargs): model = PretrainVideoTransformerTeacher(patch_size=16, encoder_embed_dim=1024, encoder_depth=24, encoder_num_heads=16, encoder_num_classes=0, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), **kwar...
@register_model def pretrain_videomae_teacher_huge_patch16_224(pretrained=False, **kwargs): model = PretrainVideoTransformerTeacher(patch_size=16, encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_num_classes=0, mlp_ratio=4, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), **kwarg...
class LARS(torch.optim.Optimizer): '\n LARS optimizer, no rate scaling or weight decay for parameters <= 1D.\n ' def __init__(self, params, lr=0, weight_decay=0, momentum=0.9, trust_coefficient=0.001): defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, trust_coefficient=trust_...
def get_num_layer_for_vit(var_name, num_max_layer): if (var_name in ('cls_token', 'mask_token', 'pos_embed')): return 0 elif var_name.startswith('patch_embed'): return 0 elif var_name.startswith('rel_pos_bias'): return (num_max_layer - 1) elif var_name.startswith('blocks'): ...
class LayerDecayValueAssigner(object): def __init__(self, values): self.values = values def get_scale(self, layer_id): return self.values[layer_id] def get_layer_id(self, var_name): return get_num_layer_for_vit(var_name, len(self.values))
def get_parameter_groups(model, weight_decay=1e-05, skip_list=(), get_num_layer=None, get_layer_scale=None): parameter_group_names = {} parameter_group_vars = {} for (name, param) in model.named_parameters(): if (not param.requires_grad): continue if ((len(param.shape) == 1) or...
def create_optimizer(args, model, get_num_layer=None, get_layer_scale=None, filter_bias_and_bn=True, skip_list=None): opt_lower = args.opt.lower() weight_decay = args.weight_decay if filter_bias_and_bn: skip = {} if (skip_list is not None): skip = skip_list elif hasattr...
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)) m...
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) + l...
def posterize(img, bits_to_keep, **__): if (bits_to_keep >= 8): return img return ImageOps.posterize(img, bits_to_keep)