code
stringlengths
17
6.64M
def run_cmd(cmd): os.system(cmd)
def opencv_write_jpeg(src_path, quality, tar_path): img = cv2.imread(src_path) encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality] (_, jpeg_data) = cv2.imencode('.jpg', img, encode_param) comp_img = cv2.imdecode(jpeg_data, cv2.IMREAD_COLOR) cv2.imwrite(tar_path, comp_img)
def parse_args(): parser = argparse.ArgumentParser(description='Compress image dataset.') parser.add_argument('--codec', type=str, required=True, choices=['bpg', 'jpeg']) parser.add_argument('--dataset', type=str, required=True, choices=['div2k', 'flickr2k']) parser.add_argument('--max-npro', type=int...
def write_planar(img, planar_path): 'Write planar.\n\n img: list of (h, w) array; each list item represents a channel.\n ' planar_file = open(planar_path, 'wb') for cha in img: (h, w) = cha.shape for ih in range(h): for iw in range(w): planar_file.write(ch...
def read_planar(planar_path, fmt=((1080, 1920), (1080, 1920), (1080, 1920))): 'Read planar.\n\n fmt: tuple of (h, w) tuple; each tuple item represents a channel.\n\n https://numpy.org/doc/stable/reference/generated/numpy.fromfile.html\n ' planar_file = np.fromfile(planar_path, dtype=np.uint8) img...
def write_ycbcr420(src_paths, tar_path, wdt, hgt): ycbcr420 = [] for src_path in src_paths: bgr = cv2.imread(src_path) (_hgt, _wdt) = bgr.shape[:2] assert ((_hgt == hgt) and (_wdt == wdt)) ycrcb = cv2.cvtColor(bgr, cv2.COLOR_BGR2YCrCb) cr_sub = cv2.resize(ycrcb[(..., 1)...
def read_ycbcr420(src_path, tar_paths, wdt, hgt, print_dir): ycbcr420_nfrms = read_planar(src_path, fmt=(((hgt, wdt), ((hgt // 2), (wdt // 2)), ((hgt // 2), (wdt // 2))) * nfrms)) for (idx, tar_path) in enumerate(tar_paths): ycrcb = np.empty((hgt, wdt, 3), np.uint8) ycrcb[(..., 0)] = ycbcr420_...
def run_cmd(cmd): os.system(cmd) return cmd
def img2planar(vids): "According to the HM manual, HM accepts videos in raw 4:2:0 planar format\n (Y'CbCr)." pool = mp.Pool(processes=args.max_nprocs) for vid in vids: pool.apply_async(func=write_ycbcr420, args=(vid['src_paths'], vid['planar_path'], vid['wdt'], vid['hgt']), callback=(lambda x: ...
def compress_planar(vids): pool = mp.Pool(processes=args.max_nprocs) for vid in vids: enc_cmd = f"{enc_path} -i {vid['planar_path']} -c {cfg_path} -b {vid['bit_path']} -o {vid['comp_planar_path']}" if (((vid['wdt'] % 8) != 0) or ((vid['hgt'] % 8) != 0)): enc_cmd += ' --ConformanceW...
def planar2img(vids): pool = mp.Pool(processes=args.max_nprocs) for vid in vids: _dir = osp.dirname(vid['tar_paths'][0]) os.makedirs(_dir) pool.apply_async(func=read_ycbcr420, args=(vid['comp_planar_path'], vid['tar_paths'], vid['wdt'], vid['hgt'], _dir), callback=(lambda x: print(x)),...
def planar2img_mfqev2(vids): pool = mp.Pool(processes=args.max_nprocs) for vid in vids: _dir = osp.dirname(vid['src_paths'][0]) os.makedirs(_dir) pool.apply_async(func=read_ycbcr420, args=(vid['planar_path'], vid['src_paths'], vid['wdt'], vid['hgt'], _dir), callback=(lambda x: print(x)...
def parse_args(): parser = argparse.ArgumentParser(description='Compress video dataset.') parser.add_argument('--max-nprocs', type=int, default=16) parser.add_argument('--dataset', type=str, required=True, choices=['vimeo-triplet', 'vimeo-septuplet', 'mfqev2']) parser.add_argument('--qp', type=int, de...
def parse_args(): parser = argparse.ArgumentParser(description='Eval PSNR.') parser.add_argument('--dataset', type=str, required=True, choices=['div2k', 'flickr2k', 'vimeo-triplet', 'vimeo-septuplet', 'mfqev2']) parser.add_argument('--out-dir', type=str, default=None) parser.add_argument('--crop-board...
def cal_imgdir_psnr(img_infos, silent=False, crop_boarder=0): '[{src:img path, tar:img path}]' results = [] if (not silent): img_infos = tqdm(img_infos, ncols=0) n_ignore = 0 for img_info in img_infos: src = cv2.imread(img_info['src']) tar = cv2.imread(img_info['tar']) ...
def cal_lq_out_psnr(gt_dir, lq_dir, img_names, args): if args.out_dir: img_infos = [dict(src=osp.join(gt_dir, img_name), tar=osp.join(args.out_dir, img_name)) for img_name in img_names] (ave_psnr, n_ignore) = cal_imgdir_psnr(img_infos=img_infos, crop_boarder=args.crop_boarder) print(f'Ave....
def cal_videos_psnr(gt_dir, lq_dir, sub_dirs, args): "sub_dirs (list): list of dict with keys 'dir_name' and 'img_names'." if args.out_dir: results = [] n_ignore_accm = 0 for sub_dir in tqdm(sub_dirs, ncols=0): img_infos = [dict(src=osp.join(gt_dir, sub_dir['dir_name'], img...
def parse_args(): parser = argparse.ArgumentParser(description='mmediting tester') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--seed', type=int, default=None, help='random seed') parser.add_argument('--...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.cfg_options is not None): cfg.merge_from_dict(args.cfg_options) setup_multi_processes(cfg) if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True cfg.model.pretrained = None if ...
def parse_args(): parser = argparse.ArgumentParser(description='Train an editor') parser.add_argument('config', help='train config file path') parser.add_argument('--work-dir', help='the dir to save logs and models') parser.add_argument('--resume-from', help='the checkpoint file to resume from') p...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.cfg_options is not None): cfg.merge_from_dict(args.cfg_options) setup_multi_processes(cfg) if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = True if (args.work_dir is not None): ...
def yuv_import(filename, dims, numfrm, startfrm): fp = open(filename, 'rb') blk_size = ((np.prod(dims) * 3) / 2) fp.seek(int((blk_size * startfrm)), 0) d00 = (dims[0] // 2) d01 = (dims[1] // 2) Y = np.zeros((numfrm, dims[0], dims[1]), np.uint8, 'C') U = np.zeros((numfrm, d00, d01), np.uint...
def yuv2rgb(Y, U, V, height, width): U = imresize(U, [height, width], 'bilinear', mode='F') V = imresize(V, [height, width], 'bilinear', mode='F') Y = (Y * 255.0) rf = (Y + (1.4075 * ((V * 255.0) - 128.0))) gf = ((Y - (0.3455 * ((U * 255.0) - 128.0))) - (0.7169 * ((V * 255.0) - 128.0))) bf = (...
def warp_img(batch_size, imga, imgb, reuse, scope='easyflow'): (n, h, w, c) = imga.get_shape().as_list() with tf.variable_scope(scope, reuse=reuse): with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biase...
def transformer(batch, chan, flow, U, out_size, name='SpatialTransformer', **kwargs): def _repeat(x, n_repeats): with tf.variable_scope('_repeat'): rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])), 1), [1, 0]) rep = tf.cast(rep, 'int32') x = tf.ma...
def network(frame1, frame2, frame3, reuse=False, scope='netflow'): with tf.variable_scope(scope, reuse=reuse): with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biases_initializer=tf.constant_initializer(0.0)...
def create_lmdb_for_mfqev2(): with open(yml_path, 'r') as fp: fp = yaml.load(fp, Loader=yaml.FullLoader) root_dir = fp['dataset']['train']['root'] gt_folder = fp['dataset']['train']['gt_folder'] lq_folder = fp['dataset']['train']['lq_folder'] gt_path = fp['dataset']['train'...
def create_lmdb_for_vimeo90k(): with open(yml_path, 'r') as fp: fp = yaml.load(fp, Loader=yaml.FullLoader) root_dir = fp['dataset']['root'] gt_folder = fp['dataset']['train']['gt_folder'] lq_folder = fp['dataset']['train']['lq_folder'] gt_path = fp['dataset']['train']['gt_p...
def _bytes2img(img_bytes): img_np = np.frombuffer(img_bytes, np.uint8) img = np.expand_dims(cv2.imdecode(img_np, cv2.IMREAD_GRAYSCALE), 2) img = (img.astype(np.float32) / 255.0) return img
class MFQEv2Dataset(data.Dataset): 'MFQEv2 dataset.\n\n For training data: LMDB is adopted. See create_lmdb for details.\n \n Return: A dict includes:\n img_lqs: (T, [RGB], H, W)\n img_gt: ([RGB], H, W)\n key: str\n ' def __init__(self, opts_dict, radius): super().__i...
class VideoTestMFQEv2Dataset(data.Dataset): '\n Video test dataset for MFQEv2 dataset recommended by ITU-T.\n\n For validation data: Disk IO is adopted.\n \n Test all frames. For the front and the last frames, they serve as their own\n neighboring frames.\n ' def __init__(self, opts_dict, r...
def _bytes2img(img_bytes): img_np = np.frombuffer(img_bytes, np.uint8) img = np.expand_dims(cv2.imdecode(img_np, cv2.IMREAD_GRAYSCALE), 2) img = (img.astype(np.float32) / 255.0) return img
class Vimeo90KDataset(data.Dataset): 'Vimeo-90K dataset.\n\n For training data: LMDB is adopted. See create_lmdb for details.\n \n Return: A dict includes:\n img_lqs: (T, [RGB], H, W)\n img_gt: ([RGB], H, W)\n key: str\n ' def __init__(self, opts_dict, radius): super(...
class VideoTestVimeo90KDataset(data.Dataset): '\n Video test dataset for Vimeo-90K.\n\n For validation data: Disk IO is adopted.\n \n Only test the center frame.\n ' def __init__(self, opts_dict, radius): super().__init__() assert (radius != 0), 'Not implemented!' self....
class DeformConvFunction(Function): @staticmethod def forward(ctx, input, offset, weight, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, im2col_step=64): if ((input is not None) and (input.dim() != 4)): raise ValueError('Expected 4D tensor as input, got {}D tensor instead...
class ModulatedDeformConvFunction(Function): @staticmethod def forward(ctx, input, offset, mask, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1): ctx.stride = stride ctx.padding = padding ctx.dilation = dilation ctx.groups = groups ct...
class DeformConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=False): super(DeformConv, self).__init__() assert (not bias) assert ((in_channels % groups) == 0), 'in_channels {} cannot be divisib...
class DeformConvPack(DeformConv): def __init__(self, *args, **kwargs): super(DeformConvPack, self).__init__(*args, **kwargs) self.conv_offset = nn.Conv2d(self.in_channels, (((self.deformable_groups * 2) * self.kernel_size[0]) * self.kernel_size[1]), kernel_size=self.kernel_size, stride=_pair(self...
class ModulatedDeformConv(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deformable_groups=1, bias=True): super(ModulatedDeformConv, self).__init__() self.in_channels = in_channels self.out_channels = out_channels ...
class ModulatedDeformConvPack(ModulatedDeformConv): def __init__(self, *args, **kwargs): super(ModulatedDeformConvPack, self).__init__(*args, **kwargs) self.conv_offset_mask = nn.Conv2d(self.in_channels, (((self.deformable_groups * 3) * self.kernel_size[0]) * self.kernel_size[1]), kernel_size=sel...
def main(): opts_dict = {'radius': 3, 'stdf': {'in_nc': 1, 'out_nc': 64, 'nf': 32, 'nb': 3, 'base_ks': 3, 'deform_ks': 3}, 'qenet': {'in_nc': 64, 'out_nc': 1, 'nf': 48, 'nb': 8, 'base_ks': 3}} model = MFVQE(opts_dict=opts_dict) msg = f'loading model {ckp_path}...' print(msg) checkpoint = torch.loa...
def set_random_seed(seed): 'Set random seeds.' random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def init_dist(local_rank=0, backend='nccl'): tmp.set_start_method('spawn') torch.cuda.set_device(local_rank) dist.init_process_group(backend=backend)
def get_dist_info(): if dist.is_available(): initialized = dist.is_initialized() else: initialized = False if initialized: rank = dist.get_rank() world_size = dist.get_world_size() else: rank = 0 world_size = 1 return (rank, world_size)
class DistSampler(Sampler): 'Sampler that restricts data loading to a subset of the dataset.\n \n Modified from torch.utils.data.distributed.DistributedSampler\n Support enlarging the dataset for iteration-based training, for saving\n time when restart the dataloader after each epoch.\n \n Args:...
def create_dataloader(dataset, opts_dict, sampler=None, phase='train', seed=None): 'Create dataloader.' if (phase == 'train'): dataloader_args = dict(dataset=dataset, batch_size=opts_dict['dataset']['train']['batch_size_per_gpu'], shuffle=False, num_workers=opts_dict['dataset']['train']['num_worker_pe...
def _worker_init_fn(worker_id, num_workers, rank, seed): worker_seed = (((num_workers * rank) + worker_id) + seed) np.random.seed(worker_seed) random.seed(worker_seed)
class CharbonnierLoss(torch.nn.Module): def __init__(self, eps=1e-06): super(CharbonnierLoss, self).__init__() self.eps = eps def forward(self, X, Y): diff = torch.add(X, (- Y)) error = torch.sqrt(((diff * diff) + self.eps)) loss = torch.mean(error) return los...
class PSNR(torch.nn.Module): def __init__(self, eps=1e-06): super(PSNR, self).__init__() self.mse_func = nn.MSELoss() def forward(self, X, Y): mse = self.mse_func(X, Y) psnr = (10 * math.log10((1 / mse.item()))) return psnr
class MultiStepRestartLR(_LRScheduler): ' MultiStep with restarts learning rate scheme.\n\n Args:\n optimizer (torch.nn.optimizer): Torch optimizer.\n milestones (list): Iterations that will decrease learning rate.\n gamma (float): Decrease ratio. Default: 0.1.\n restarts (list): Re...
def get_position_from_periods(iteration, cumulative_period): 'Get the position from a period list.\n\n It will return the index of the right-closest number in the period list.\n For example, the cumulative_period = [100, 200, 300, 400],\n if iteration == 50, return 0;\n if iteration == 210, return 2;\...
class CosineAnnealingRestartLR(_LRScheduler): ' Cosine annealing with restarts learning rate scheme.\n\n An example of config:\n periods = [10, 10, 10, 10]\n restart_weights = [1, 0.5, 0.5, 0.5]\n eta_min=1e-7\n\n It has four cycles, each has 10 iterations. At 10th, 20th, 30th, the\n scheduler w...
def import_yuv(seq_path, h, w, tot_frm, yuv_type='420p', start_frm=0, only_y=True): 'Load Y, U, and V channels separately from a 8bit yuv420p video.\n \n Args:\n seq_path (str): .yuv (imgs) path.\n h (int): Height.\n w (int): Width.\n tot_frm (int): Total frames to be imported.\n...
def write_ycbcr(y, cb, cr, vid_path): with open(vid_path, 'wb') as fp: for ite_frm in range(len(y)): fp.write(y[ite_frm].reshape(((y[0].shape[0] * y[0].shape[1]),))) fp.write(cb[ite_frm].reshape(((cb[0].shape[0] * cb[0].shape[1]),))) fp.write(cr[ite_frm].reshape(((cr[0]...
class _HardDiskBackend(): 'Raw hard disks storage backend.' def get(self, filepath): filepath = str(filepath) with open(filepath, 'rb') as f: value_buf = f.read() return value_buf
class _LmdbBackend(): 'Lmdb storage backend.\n\n Args:\n db_path (str): Lmdb database path.\n readonly (bool, optional): Lmdb environment parameter. If True,\n disallow any write operations. Default: True.\n lock (bool, optional): Lmdb environment parameter. If False, when\n ...
class FileClient(object): 'A file client to access LMDB files or general files on disk.\n \n Return a binary file.' _backends = {'disk': _HardDiskBackend, 'lmdb': _LmdbBackend} def __init__(self, backend='disk', **kwargs): if (backend == 'disk'): self.client = _HardDiskBackend()...
def dict2str(input_dict, indent=0): 'Dict to string for printing options.' msg = '' indent_msg = (' ' * indent) for (k, v) in input_dict.items(): if isinstance(v, dict): msg += ((indent_msg + k) + ':[\n') msg += dict2str(v, (indent + 2)) msg += (indent_msg +...
class PrefetchGenerator(threading.Thread): 'A general prefetch generator.\n\n Ref:\n https://stackoverflow.com/questions/7323664/python-generator-pre-fetch\n\n Args:\n generator: Python generator.\n num_prefetch_queue (int): Number of prefetch queue.\n ' def __init__(self, generator...
class PrefetchDataLoader(DataLoader): 'Prefetch version of dataloader.\n\n Ref:\n https://github.com/IgorSusmelj/pytorch-styleguide/issues/5#\n\n TODO:\n Need to test on single gpu and ddp (multi-gpu). There is a known issue in\n ddp.\n\n Args:\n num_prefetch_queue (int): Number of prefet...
class CPUPrefetcher(): 'CPU prefetcher.\n\n Args:\n loader: Dataloader.\n ' def __init__(self, loader): self.ori_loader = loader self.loader = iter(loader) def next(self): try: return next(self.loader) except StopIteration: return None...
class CUDAPrefetcher(): 'CUDA prefetcher.\n\n Ref:\n https://github.com/NVIDIA/apex/issues/304#\n\n It may consums more GPU memory.\n\n Args:\n loader: Dataloader.\n opt (dict): Options.\n ' def __init__(self, loader, opt): self.ori_loader = loader self.loader = i...
def make_lmdb_from_imgs(img_dir, lmdb_path, img_path_list, keys, batch=5000, compress_level=1, multiprocessing_read=False, map_size=None): 'Make lmdb from images.\n\n Args:\n img_dir (str): Image root dir.\n lmdb_path (str): LMDB save path.\n img_path_list (str): Image subpath under the im...
def _read_img_worker(path, key, compress_level): 'Read image worker.\n\n Args:\n path (str): Image path.\n key (str): Image key.\n compress_level (int): Compress level when encoding images.\n\n Returns:\n str: Image key.\n byte: Image byte.\n tuple[int]: Image shape...
def _read_y_from_yuv_worker(video_path, yuv_type, h, w, index_frame, key, compress_level): '不要把该函数放到主函数里,否则无法并行。' if (h == None): (w, h) = [int(k) for k in op.basename(video_path).split('_')[1].split('x')] img = import_yuv(seq_path=video_path, yuv_type=yuv_type, h=h, w=w, tot_frm=1, start_frm=inde...
def make_y_lmdb_from_yuv(video_path_list, index_frame_list, key_list, lmdb_path, yuv_type='420p', h=None, w=None, batch=7000, compress_level=1, multiprocessing_read=False, map_size=None): assert lmdb_path.endswith('.lmdb'), "lmdb_path must end with '.lmdb'." assert (not op.exists(lmdb_path)), f'Folder {lmdb_p...
def calculate_psnr(img0, img1, data_range=None): 'Calculate PSNR (Peak Signal-to-Noise Ratio).\n \n Args:\n img0 (ndarray)\n img1 (ndarray)\n data_range (int, optional): Distance between minimum and maximum \n possible values). By default, this is estimated from the image \n ...
def calculate_ssim(img0, img1, data_range=None): 'Calculate SSIM (Structural SIMilarity).\n\n Args:\n img0 (ndarray)\n img1 (ndarray)\n data_range (int, optional): Distance between minimum and maximum \n possible values). By default, this is estimated from the image \n ...
def calculate_mse(img0, img1): 'Calculate MSE (Mean Square Error).\n\n Args:\n img0 (ndarray)\n img1 (ndarray)\n\n Return:\n mse (float)\n ' mse = skm.mean_squared_error(img0, img1) return mse
def mkdir(dir_path): 'Create directory.\n \n Args:\n dir_path (str)\n ' assert (not op.exists(dir_path)), 'Dir already exists!' os.makedirs(dir_path)
def get_timestr(): 'Return current time str.' return time.strftime('%Y%m%d_%H%M%S', time.localtime())
class Timer(): def __init__(self): self.reset() def reset(self): self.start_time = time.time() self.accum_time = 0 def restart(self): self.start_time = time.time() def accum(self): self.accum_time += (time.time() - self.start_time) def get_time(self): ...
class Counter(): def __init__(self): self.reset() def reset(self): self.time = 0 self.accum_volume = 0 def accum(self, volume): self.time += 1 self.accum_volume += volume def get_ave(self): return (self.accum_volume / self.time)
def generate_k_iclause(n, k): vs = np.random.choice(n, size=min(n, k), replace=False) return [((v + 1) if (random.random() < 0.5) else (- (v + 1))) for v in vs]
def gen_iclause_pair(args, n): solver = minisolvers.MinisatSolver() for i in range(n): solver.new_var(dvar=True) iclauses = [] while True: k_base = (1 if (random.random() < args.p_k_2) else 2) k = (k_base + np.random.geometric(args.p_geo)) iclause = generate_k_iclause(n...
def generate(args): f = open(args.gen_log, 'w') n_cnt = ((args.max_n - args.min_n) + 1) problems_per_n = ((args.n_pairs * 1.0) / n_cnt) problems = [] batches = [] n_nodes_in_batch = 0 prev_n_vars = None for n_var in range(args.min_n, (args.max_n + 1)): lower_bound = int(((n_var...
def load_model(args, log_file=None): net = NeuroSAT(args) net = net.cuda() if args.restore: if (log_file is not None): print('restoring from', args.restore, file=log_file, flush=True) model = torch.load(args.restore) net.load_state_dict(model['state_dict']) return n...
def predict(net, data): net.eval() outputs = net(data) probs = net.vote preds = torch.where((outputs > 0.5), torch.ones(outputs.shape).cuda(), torch.zeros(outputs.shape).cuda()) return (preds.cpu().detach().numpy(), probs.cpu().detach().numpy())
class MLP(nn.Module): def __init__(self, in_dim, hidden_dim, out_dim): super(MLP, self).__init__() self.l1 = nn.Linear(in_dim, hidden_dim) self.l2 = nn.Linear(hidden_dim, hidden_dim) self.l3 = nn.Linear(hidden_dim, out_dim) def forward(self, x): x = self.l1(x) ...
def solve_sat(n_vars, iclauses): solver = minisolvers.MinisatSolver() for i in range(n_vars): solver.new_var(dvar=True) for iclause in iclauses: solver.add_clause(iclause) is_sat = solver.solve() stats = solver.get_stats() return (is_sat, stats)
@dataclass class AdversarialOptBase(): pass
@dataclass class FGSMOpt(AdversarialOptBase): eps: float = field(default=1e-05, metadata={'help': 'The noise coefficient to multiply the sign of gradient.Controls the extent of noise.'})
@dataclass class FGMOpt(AdversarialOptBase): eps: float = field(default=1e-05, metadata={'help': 'The noise coefficient to multiply the sign of gradient divided by its norm.Controls the extent of noise.'})
@dataclass class FreeLBOpt(AdversarialOptBase): adv_init_msg: float = field(default=0, metadata={'help': '\n TO DO.\n \n '}) norm_type: str = field(default='l2', metadata={'help': '\n The norm to use. \n Must be eit...
def is_torch_available(): return _torch_available
def is_tf_available(): return _tf_available
def is_torch_tpu_available(): return _torch_tpu_available
def is_psutil_available(): return _psutil_available
def is_py3nvml_available(): return _py3nvml_available
def is_apex_available(): return _has_apex
def add_start_docstrings(*docstr): def docstring_decorator(fn): fn.__doc__ = (''.join(docstr) + (fn.__doc__ if (fn.__doc__ is not None) else '')) return fn return docstring_decorator
def add_start_docstrings_to_callable(*docstr): def docstring_decorator(fn): class_name = ':class:`~transformers.{}`'.format(fn.__qualname__.split('.')[0]) intro = ' The {} forward method, overrides the :func:`__call__` special method.'.format(class_name) note = '\n .. note::\n ...
def add_end_docstrings(*docstr): def docstring_decorator(fn): fn.__doc__ = (fn.__doc__ + ''.join(docstr)) return fn return docstring_decorator
def _prepare_output_docstrings(output_type, config_class): '\n Prepares the return part of the docstring using `output_type`.\n ' docstrings = output_type.__doc__ lines = docstrings.split('\n') i = 0 while ((i < len(lines)) and (re.search('^\\s*(Args|Parameters):\\s*$', lines[i]) is None)): ...
def add_code_sample_docstrings(*docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None): def docstring_decorator(fn): model_class = fn.__qualname__.split('.')[0] is_tf_class = (model_class[:2] == 'TF') if ('SequenceClassification' in model_class): c...
def replace_return_docstrings(output_type=None, config_class=None): def docstring_decorator(fn): docstrings = fn.__doc__ lines = docstrings.split('\n') i = 0 while ((i < len(lines)) and (re.search('^\\s*Returns?:\\s*$', lines[i]) is None)): i += 1 if (i < len(l...
def is_remote_url(url_or_filename): parsed = urlparse(url_or_filename) return (parsed.scheme in ('http', 'https'))
def hf_bucket_url(model_id: str, filename: str, use_cdn=True) -> str: "\n Resolve a model identifier, and a file name, to a HF-hosted url\n on either S3 or Cloudfront (a Content Delivery Network, or CDN).\n Cloudfront is replicated over the globe so downloads are way faster\n for the end user (and it ...
def url_to_filename(url, etag=None): "\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 If the url ends with .h5 (Keras HDF5 weights) adds '.h5' to the name\n so that TF 2.0 can identify it as a HDF5 file\...
def filename_to_url(filename, cache_dir=None): '\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.\n ' if (cache_dir is None): cache_dir = TRANSFORMERS_CACHE if isinstance(cache_dir, Pat...