code
stringlengths
101
5.91M
def validate_ext(args, device_id): timestep = 0 if args.test_all: cp_files = sorted(glob.glob(os.path.join(args.model_path, 'model_step_*.pt'))) cp_files.sort(key=os.path.getmtime) xent_lst = [] for (i, cp) in enumerate(cp_files): step = int(cp.split('.')[(- 2)].split...
def prepare_data(args): if (args.dataset == 'CamCAN'): CamCANHandler(args) elif (args.dataset == 'BraTS'): BraTSHandler(args) elif (args.dataset == 'ATLAS'): ATLASHandler(args) elif (args.dataset == 'DDR'): DDRHandler(args) else: raise NotImplementedError
def closest_holder(exp_scope, holder_scopes): exp_off1 = int(exp_scope.split(':')[0]) h = np.array([i[0] for i in holder_scopes]) idx = np.argmin(np.abs((h - exp_off1))) return holder_scopes[idx]
class BaseWarmUpLR(lr_scheduler._LRScheduler): def __init__(self, optimizer, warmup_type='NO', warmup_iters=0, warmup_factor=0.1): self._warmup_type = warmup_type.upper() assert (self.warmup_type in ['NO', 'CONST', 'LINEAR', 'EXP']) self._warmup_iters = warmup_iters self._warmup_fact...
def plot_single_task_curve(aggregated_data: Dict[(str, Any)], algorithms: list, colors: Optional[Dict]=None, color_palette: str='colorblind', figsize: tuple=(7, 5), xlabel: str='Number of Frames (in millions)', ylabel: str='Aggregate Human Normalized Score', ax: Optional[Axes]=None, labelsize: str='xx-large', ticklabel...
class Fold(torch.nn.Module): def __init__(self, img_size, fold_size): super().__init__() self.n_locs = ((2 * (img_size // fold_size)) - 1) def forward(self, x): (dim_c, dim_x, dim_y) = x.size()[1:] x = x.reshape((- 1), (self.n_locs * self.n_locs), dim_c, (dim_x * dim_y)) ...
.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_points_in_boxes_part(): boxes = torch.tensor([[[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 0.3]], [[(- 10.0), 23.0, 16.0, 10, 20, 20, 0.5]]], dtype=torch.float32).cuda() pts = torch.tensor([[[1, 2, 3.3], [1.2, 2.5, 3.0], [0.8, 2.1, 3.5], [1.6,...
class ImageClient(): def __init__(self, top_only=False, port1=6000, port2=6001, scale_factor=1.0): if top_only: self.cameras = [CameraClientWrapper(CAMERA_SERIALS[0], port1, scale_factor=scale_factor)] else: self.cameras = [CameraClientWrapper(CAMERA_SERIALS[0], port1, scale_...
_tokenizers class AutoTokenizerCustomTest(unittest.TestCase): def test_tokenizer_bert_japanese(self): EXAMPLE_BERT_JAPANESE_ID = 'cl-tohoku/bert-base-japanese' tokenizer = AutoTokenizer.from_pretrained(EXAMPLE_BERT_JAPANESE_ID) self.assertIsInstance(tokenizer, BertJapaneseTokenizer)
class SSIMMetric(BaseDistanceMetric): def __init__(self, data_range=None, mode='default', **kwargs): super(SSIMMetric, self).__init__(name='ssim', **kwargs) self.data_range = data_range self.mode = mode def add(self, es, ta, ma=None): if (es.shape != ta.shape): raise ...
def plot_models(data_path, figsize=(12, 4), max_params=128000.0, max_maccs=4500000.0): df = logmel_models(data_path) (fig, ax) = plt.subplots(1, figsize=figsize) check_missing(df, 'accuracy') check_missing(df, 'kparams') check_missing(df, 'mmacc') df.plot.scatter(x='params', y='macc_s', logx=Tru...
def main(): parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', default='settings/pretrain.yaml', type=str, help='Setting files') parser.add_argument('-n', '--exp_name', default='exp_name', type=str, help='name of this experiment.') parser.add_argument('-l', '--lr', default=1e-05, t...
def zhong_selfatt(U, dim, mask=None, seq_len=None, transform=None, scope=None, reuse=None): if (mask is None): assert (seq_len is not None) mask = tf.expand_dims(tf.sequence_mask(seq_len, tf.shape(U)[1]), axis=1) with tf.variable_scope((scope or 'zhong_selfAttention'), reuse=reuse): W1 =...
def startOutputFile(): if (options.outputFileName is not None): output = open(options.outputFileName, 'w') else: output = sys.stdout output.write('/* Generated file, do not edit */\n\n') return output
def build_cnn(): l2_reg = keras.regularizers.l2(L2_LAMBDA) inpt = keras.layers.Input(shape=IMG_SHAPE) conv1 = keras.layers.Convolution2D(32, (5, 5), padding='same', activation='relu')(inpt) drop1 = keras.layers.Dropout(rate=0.1)(conv1) conv2 = keras.layers.Convolution2D(32, (5, 5), padding='same', a...
def GenIdx(train_color_label, train_thermal_label): color_pos = [] unique_label_color = np.unique(train_color_label) for i in range(len(unique_label_color)): tmp_pos = [k for (k, v) in enumerate(train_color_label) if (v == unique_label_color[i])] color_pos.append(tmp_pos) thermal_pos = [...
def get_data_provider_by_name(name, train_params): if (name == 'C10'): return Cifar10DataProvider(**train_params) if (name == 'C10+'): return Cifar10AugmentedDataProvider(**train_params) if (name == 'C100'): return Cifar100DataProvider(**train_params) if (name == 'C100+'): ...
(events=subsets(_ALL_EVENTS_WITH_HANDLERS)) _events_with_registered_handlers_to_subset def test_for_loop(events): assert (_RECORDED_EVENTS == []) run_cell('\n for i in range(10):\n pass\n ') throw_and_print_diff_if_recorded_not_equal_to(filter_events_to_subset((([TraceEvent.init_mod...
class DampedRotarySpring(Constraint): def __init__(self, a, b, rest_angle, stiffness, damping): self._constraint = cp.cpDampedRotarySpringNew(a._body, b._body, rest_angle, stiffness, damping) self._ccontents = self._constraint.contents self._dsc = cp.cast(self._constraint, ct.POINTER(cp.cpDa...
def neg_squad(args): with open(args.source_path, 'r') as fp: squad = json.load(fp) with open(args.source_path, 'r') as fp: ref_squad = json.load(fp) for (ai, article) in enumerate(ref_squad['data']): for (pi, para) in enumerate(article['paragraphs']): cands = (list(range(...
class TFCTRLForSequenceClassification(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def get_mnms_data(data_root): files_raw = [] files_gt = [] for (r, dirs, files) in os.walk(data_root): for f in files: if f.endswith('nii.gz'): file_path = os.path.join(r, f) if ('_gt' in f): files_gt.append(file_path) e...
class Adam(torch.optim.Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False): defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(Adam, self).__init__(params, defaults) def supports_memory_efficie...
class DummyObject(type): def __getattribute__(cls, key): if (key.startswith('_') and (key != '_from_config')): return super().__getattribute__(key) requires_backends(cls, cls._backends)
def _tower_loss(network_fn, images, labels, input_seqs, input_masks): (image_features, _) = build_image_features(network_fn, images) (text_features, _) = build_text_features(input_seqs, input_masks) image_embeddings = build_joint_embeddings(image_features, scope='image_joint_embedding') text_embeddings ...
class BAT(nn.Module): def __init__(self, num_classes, num_layers, point_pred, decoder=False, transformer_type_index=0, hidden_features=128, number_of_query_positions=1, segmentation_attention_heads=8): super(BAT, self).__init__() self.num_classes = num_classes self.point_pred = point_pred ...
class PredictionTransform(): def __init__(self, size, mean=0.0, std=1.0): self.transform = Compose([Resize(size), SubtractMeans(mean), (lambda img, boxes=None, labels=None: ((img / std), boxes, labels)), ToTensor()]) def __call__(self, image): (image, _, _) = self.transform(image) return...
class HasOptimMethod(): def __init__(self): super(HasOptimMethod, self).__init__() self.optimMethod = SGD() def setOptimMethod(self, val): pythonBigDL_method_name = 'setOptimMethod' callZooFunc(self.bigdl_type, pythonBigDL_method_name, self.value, val) self.optimMethod = ...
class XLMConfig(PretrainedConfig): pretrained_config_archive_map = XLM_PRETRAINED_CONFIG_ARCHIVE_MAP model_type = 'xlm' def __init__(self, vocab_size=30145, emb_dim=2048, n_layers=12, n_heads=16, dropout=0.1, attention_dropout=0.1, gelu_activation=True, sinusoidal_embeddings=False, causal=False, asm=False, ...
class CheckpointMergerPipeline(DiffusionPipeline): def __init__(self): self.register_to_config() super().__init__() def _compare_model_configs(self, dict0, dict1): if (dict0 == dict1): return True else: (config0, meta_keys0) = self._remove_meta_keys(dict0)...
def load_model(args, model_without_ddp, optimizer, loss_scaler): checkpoint = torch.load(args.resume, map_location='cpu') model_without_ddp.load_state_dict(checkpoint['model']) print(('Resume checkpoint %s' % args.resume)) if (('optimizer' in checkpoint) and ('epoch' in checkpoint)): optimizer.l...
class CustomFormatter(logging.Formatter): grey = '\x1b[38;20m' green = '\x1b[32;20m' yellow = '\x1b[33;20m' red = '\x1b[31;20m' bold_red = '\x1b[31;1m' reset = '\x1b[0m' format = '[%(name)s] - %(levelname)s - %(message)s' FORMATS = {logging.DEBUG: (((grey + '[%(levelname)s]') + reset) + ...
def get_new_model_dir(root: str, model_name: str) -> str: (prev_run_ids, prev_run_dirs) = get_valid_model_dir(root) cur_id = (max(prev_run_ids, default=(- 1)) + 1) model_dir = os.path.join(root, f'{cur_id:05d}-{model_name}') assert (not os.path.exists(model_dir)) os.makedirs(model_dir) return mo...
_tf _retrieval class TFRagModelSaveLoadTests(unittest.TestCase): def get_rag_config(self): question_encoder_config = AutoConfig.from_pretrained('facebook/dpr-question_encoder-single-nq-base') generator_config = AutoConfig.from_pretrained('facebook/bart-large-cnn') return RagConfig.from_quest...
def Timer(func): (func) def wrapper(*args, **kwargs): start_time = datetime.now() construct_print(f'a new epoch start: {start_time}') func(*args, **kwargs) construct_print(f'the time of the epoch: {(datetime.now() - start_time)}') return wrapper
class SIMCLRGenerator(): def __call__(self, partition_list: List[str], **kwargs): return list(range(len(partition_list)))
def md_parse_line_break(comment): comment = comment.replace(' ', '\n\n') return comment.replace(' - ', '\n\n- ')
class NoStoppingCondition(StoppingCondition): def should_stop_this_iter(self, latest_trainer_result: dict, *args, **kwargs) -> bool: return False
def test_shufflenet_v2(): cfg.merge_from_file('configs/benchmarks/ghostnet/ghostnet_x1_0_zcls_imagenet_224.yaml') print(cfg) model = GhostNet(cfg) print(model) test_data(model)
def infer(): with tf.Graph().as_default() as graph: print('In Graph') (ops, tuple_shape) = build_inference_model() sess = restore_weights() num_loader_threads = 6 for i in range(num_loader_threads): worker = Thread(target=cpu_thread) worker.setDaemon(T...
_on_pypy def test_pointer_to_member_fn(): for cls in [m.Buffer, m.ConstBuffer, m.DerivedBuffer]: buf = cls() buf.value = value = struct.unpack('i', bytearray(buf))[0] assert (value == )
class RobertaTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] slow_tokenizer_class = RobertaTokenize...
def set_seed_code(data_size, batch_size): backend = ('nccl' if torch.cuda.is_available() else 'gloo') res = atorch.init_distributed(backend, set_cuda_device_using_local_rank=True) if (not res): raise Exception('init failed') seed = 13 model_context = create_model_context(data_size=data_size,...
class TFBaseModelOutputWithCLSToken(ModelOutput): last_hidden_state: tf.Tensor = None cls_token_value: tf.Tensor = None hidden_states: Optional[Tuple[tf.Tensor]] = None
class RetrievedOptions(SystemResponse): def __init__(self, session_token: str=None, retrieved_results: list=None): super().__init__(session_token) self.retrieved_results = retrieved_results self.type = 'RETRIEVED_OPTIONS' def update(self, retrieved_results: list=None): self.retri...
class TFAlbertForMultipleChoice(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class StdConv2d(nn.Conv2d): def forward(self, x): w = self.weight (v, m) = torch.var_mean(w, dim=[1, 2, 3], keepdim=True, unbiased=False) w = ((w - m) / torch.sqrt((v + 1e-05))) return F.conv2d(x, w, self.bias, self.stride, self.padding, self.dilation, self.groups)
def identity_transform(img_shape): data_transforms = transforms.Compose([transforms.ToTensor()]) return data_transforms
class DataInputTest(): def __init__(self, data, batch_size): self.batch_size = batch_size self.data = data self.epoch_size = (len(self.data) // self.batch_size) if ((self.epoch_size * self.batch_size) < len(self.data)): self.epoch_size += 1 self.i = 0 def __it...
_sentencepiece _tokenizers class TestMarian_MT_EN(MarianIntegrationTest): src = 'mt' tgt = 'en' src_text = ["Billi messu b'mod gentili, Gesu fejjaq ragel li kien milqut bil - marda kerha tal - gdiem."] expected_text = ['Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.'...
class Text2ImageDataset(): def __init__(self, train_shards_path_or_url: Union[(str, List[str])], num_train_examples: int, per_gpu_batch_size: int, global_batch_size: int, num_workers: int, resolution: int=1024, shuffle_buffer_size: int=1000, pin_memory: bool=False, persistent_workers: bool=False, use_fix_crop_and_s...
def make_random_policy_bin_pack(bin_pack: BinPack) -> RandomPolicy: action_spec_num_values = bin_pack.action_spec().num_values return make_masked_categorical_random_ndim(action_spec_num_values=action_spec_num_values)
def get_score(occurences): if (occurences == 0): return 0 elif (occurences == 1): return 0.3 elif (occurences == 2): return 0.6 elif (occurences == 3): return 0.9 else: return 1
def readIntentPredTxt(intent_pred_txt, userIntent2id, sample_nb, userIntent_vocab_size): checkExistence(intent_pred_txt) indicator = np.zeros((sample_nb, userIntent_vocab_size)) with open(intent_pred_txt, 'rb') as f: for (idx, line) in enumerate(f): for intent in line.strip().split(';'):...
class RepLKBlock(nn.Module): def __init__(self, in_channels, dw_channels, block_lk_size, small_kernel, drop_path, small_kernel_merged=False): super().__init__() self.pw1 = conv_bn_relu(in_channels, dw_channels, 1, 1, 0, groups=1) self.pw2 = conv_bn(dw_channels, in_channels, 1, 1, 0, groups=1...
def test_can_move_left(board: Board, another_board: Board) -> None: assert can_move_left(board) assert can_move_left(another_board) board = jnp.array([[1, 2, 3, 4], [1, 2, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]]) assert (~ can_move_left(board))
class TestDummyGenerator(): def dummy_generator(self) -> DummyGenerator: return DummyGenerator() def test_dummy_generator__properties(self, dummy_generator: DummyGenerator) -> None: assert (dummy_generator.num_jobs == 3) assert (dummy_generator.num_machines == 3) assert (dummy_ge...
def get_egs_info(egs_dir): ipf = open(os.path.join(egs_dir, 'info', 'num_archives')) num_archives = int(ipf.readline().strip()) ipf.close() return num_archives
def load_model_ensemble_and_task(filenames, arg_overrides: Optional[Dict[(str, Any)]]=None, task=None, strict=True, suffix='', num_shards=1, state=None): assert ((state is None) or (len(filenames) == 1)) from fairseq import tasks assert (not (strict and (num_shards > 1))), 'Cannot load state dict with stric...
def bias(shape, name='bias', value=0.0, dtype=None, trainable=True): if (dtype is None): dtype = tf.float32 b = tf.get_variable(name=name, shape=shape, initializer=tf.constant_initializer(value), dtype=dtype, trainable=trainable) return b
def tile(x, count, dim=0): perm = list(range(len(x.size()))) if (dim != 0): (perm[0], perm[dim]) = (perm[dim], perm[0]) x = x.permute(perm).contiguous() out_size = list(x.size()) out_size[0] *= count batch = x.size(0) x = x.view(batch, (- 1)).transpose(0, 1).repeat(count, 1).tran...
def write_results_to_file(filename, data): with open(filename, 'wb') as handle: pickle.dump(data, handle, protocol=2)
class gradient_difference_loss(nn.Module): def __init__(self, gdl_weight=0.01): super().__init__() self.gdl_weight = float(gdl_weight) self.mse = nn.MSELoss() self.abs_loss = (lambda x, y: F.l1_loss(x, y).mean()) def forward(self, pred: torch.Tensor, gt: torch.Tensor): as...
def projection(p, grad, perturb, delta: float, wd_ratio: float, eps: float): wd = 1.0 expand_size = (((- 1),) + ((1,) * (len(p.shape) - 1))) for view_func in [_channel_view, _layer_view]: param_view = view_func(p) grad_view = view_func(grad) cosine_sim = F.cosine_similarity(grad_view...
class DreamBoothDataset(Dataset): def __init__(self, instance_data_root, instance_prompt, class_prompt, class_data_root=None, class_num=None, size=1024, repeats=1, center_crop=False): self.size = size self.center_crop = center_crop self.instance_prompt = instance_prompt self.custom_i...
class TFDebertaV2ForMaskedLM(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def set_template(args): if (args.template.find('jpeg') >= 0): args.data_train = 'DIV2K_jpeg' args.data_test = 'DIV2K_jpeg' args.epochs = 200 args.decay = '100' if (args.template.find('EDSR_paper') >= 0): args.model = 'EDSR' args.n_resblocks = 32 args.n_fea...
def test_pretty_text(): cfg_file = osp.join(data_path, 'config/l.py') cfg = Config.fromfile(cfg_file) with tempfile.TemporaryDirectory() as temp_config_dir: text_cfg_filename = osp.join(temp_config_dir, '_text_config.py') with open(text_cfg_filename, 'w') as f: f.write(cfg.pretty...
class LSegModuleZS(LSegmentationModuleZS): def __init__(self, data_path, dataset, batch_size, base_lr, max_epochs, **kwargs): super(LSegModuleZS, self).__init__(data_path, dataset, batch_size, base_lr, max_epochs, **kwargs) label_list = self.get_labels(dataset) self.len_dataloader = len(labe...
class ArgumentParser(): def __init__(self, mode='train'): self.parser = argparse.ArgumentParser(description='CNNGeometric PyTorch implementation') self.add_cnn_model_parameters() if (mode == 'train'): self.add_train_parameters() self.add_synth_dataset_parameters() ...
def _gen_fbnetc(variant, channel_multiplier=1.0, pretrained=False, **kwargs): arch_def = [['ir_r1_k3_s1_e1_c16'], ['ir_r1_k3_s2_e6_c24', 'ir_r2_k3_s1_e1_c24'], ['ir_r1_k5_s2_e6_c32', 'ir_r1_k5_s1_e3_c32', 'ir_r1_k5_s1_e6_c32', 'ir_r1_k3_s1_e6_c32'], ['ir_r1_k5_s2_e6_c64', 'ir_r1_k5_s1_e3_c64', 'ir_r2_k5_s1_e6_c64']...
def Data_func(): ((X_train, y_train), (X_test, y_test)) = datasets.boston_housing.load_data() scaler = preprocessing.MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) return ((X_train, y_train), (X_test, y_test))
class MemoryType(Enum): CPU_BUFFER = 0 GPU_BUFFER = 1 GPU_IMAGE = 2 MEMORY_NONE = 10000
def compute_similarity_transform_batch(S1, S2): S1_hat = np.zeros_like(S1) for i in range(S1.shape[0]): S1_hat[i] = compute_similarity_transform(S1[i], S2[i]) return S1_hat
def get_local_batch_size_in_trainer(global_batch_size: int, trainer: Trainer) -> int: strategy = get_trainer_strategy(trainer) devices = trainer.num_devices num_nodes = trainer.num_nodes if (not any([isinstance(strategy, supported_strategy) for supported_strategy in supported_strategies])): rais...
def evaluate_json(gold: List, pred: List): for test_set in TEST_SETS: print(test_set) for language in LANGUAGES: instance_indices = [i for (i, instance) in enumerate(gold) if ((instance['test_set'] == test_set) and (instance['language'] == language))] gold_labels = [gold[i]['...
class ScipyWrapperODESolver(metaclass=abc.ABCMeta): def __init__(self, func, y0, rtol, atol, min_step=0, max_step=float('inf'), solver='LSODA', **unused_kwargs): unused_kwargs.pop('norm', None) unused_kwargs.pop('grid_points', None) unused_kwargs.pop('eps', None) _handle_unused_kwarg...
def initialize_scheduler(optimizer, config, last_step=(- 1)): if (config.scheduler == 'StepLR'): return StepLR(optimizer, step_size=config.step_size, gamma=config.step_gamma, last_epoch=last_step) elif (config.scheduler == 'PolyLR'): return PolyLR(optimizer, max_iter=config.max_iter, power=confi...
_staging_test class SchedulerPushToHubTester(unittest.TestCase): identifier = uuid.uuid4() repo_id = f'test-scheduler-{identifier}' org_repo_id = f'valid_org/{repo_id}-org' def test_push_to_hub(self): scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule='scaled_linear', cl...
class TransformerEncoderLayer(nn.Module): def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='relu', normalize_before=False): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) self.linear1 = nn.Linear(d_model, dim_feedfor...
class TestNoIntegration(unittest.TestCase): def test_odeint(self): for reverse in (False, True): for dtype in DTYPES: for device in DEVICES: for method in METHODS: for ode in PROBLEMS: with self.subTest(rever...
class IndexRanker(): def __init__(self, tensor, doclens, device): self.tensor = tensor self.doclens = doclens self.maxsim_dtype = torch.float32 self.doclens_pfxsum = ([0] + list(accumulate(self.doclens))) self.doclens = torch.tensor(self.doclens) self.doclens_pfxsum =...
def _encoded_image_string_tensor_input_placeholder(): batch_image_str_placeholder = tf.placeholder(dtype=tf.string, shape=[None], name='encoded_image_string_tensor') def decode(encoded_image_string_tensor): image_tensor = tf.image.decode_image(encoded_image_string_tensor, channels=3) image_tenso...
class OutGate(object): def __init__(self, W_in=init.Normal(0.1), W_hid=init.Normal(0.1), W_cell=init.Normal(0.1), W_to=init.Normal(0.1), b=init.Constant(0.0), nonlinearity=nonlinearities.sigmoid): self.W_in = W_in self.W_hid = W_hid self.W_to = W_to if (W_cell is not None): ...
def find_deletable_span_rule_based_updated(tree: TreeNode, root_len: int, parent=None, grand_parent=None): next_parent = tree next_grandparent = parent deletable_bag = [] deletable_bag += det_JJ(tree) deletable_bag += det_PRN(tree) deletable_bag += det_ccs(tree, root_len) deletable_bag += de...
class ImageProjModel(torch.nn.Module): def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4): super().__init__() self.cross_attention_dim = cross_attention_dim self.clip_extra_context_tokens = clip_extra_context_tokens self.proj = torch.n...
class PrioritizedReplayBuffer(ReplayBuffer): def __init__(self, size, alpha): super(PrioritizedReplayBuffer, self).__init__(size) assert (alpha >= 0) self._alpha = alpha it_capacity = 1 while (it_capacity < size): it_capacity *= 2 self._it_sum = SumSegment...
class ClipAdapter(nn.Module): def __init__(self, clip_model_name: str, prompt_learner: PromptExtractor): super().__init__() self.clip_model = build_clip_model(clip_model_name) self.prompt_learner = prompt_learner self.prompt_learner.init_buffer(self.clip_model) self.text_feat...
_start_docstrings('XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer\n on top of the pooled output) e.g. for GLUE tasks. ', XLM_ROBERTA_START_DOCSTRING) class TFXLMRobertaForSequenceClassification(TFRobertaForSequenceClassification): config_class = XLMRobertaConf...
def save(opt): opt_path = opt['opt_path'] opt_path_copy = opt['path']['options'] (dirname, filename_ext) = os.path.split(opt_path) (filename, ext) = os.path.splitext(filename_ext) dump_path = os.path.join(opt_path_copy, ((filename + get_timestamp()) + ext)) with open(dump_path, 'w') as dump_file...
class Loss_Saver(): def __init__(self): (self.loss_list, self.last_loss) = ([], 0.0) return def updata(self, value): if (not self.loss_list): self.loss_list += [value] self.last_loss = value else: update_val = ((self.last_loss * 0.9) + (value *...
class HRSCDDataModule(BaseDataModule): def __init__(self, root: str='.data/HRSCD', transform: Compose=Compose([ToTensor()]), *args, **kwargs): super().__init__(*args, **kwargs) self.root = root self.transform = transform def setup(self, stage: Optional[str]=None): dataset = HRSCD...
class DataPointFactory(): def get_datapoint(config): if (config.task_type == TaskType.Classification): if (config.model_type in [ModelType.NaiveBayes, ModelType.XGBoost, ModelType.SVM]): return TFIDFDataPoint elif (config.model_type in [ModelType.LSTM, ModelType.BiLST...
class TestPrune(unittest.TestCase): SPARSITY_TARGET = 0.8 def setUp(self) -> None: set_seed(8888) def _test_model(self, mask_type): model = Model(mask_type) with self.subTest(f'{mask_type} : Initial sparsity check'): self.assertEqual(model.get_sparsity(active=False), 0, '...
def register_all_lvis(root='datasets'): for (dataset_name, splits_per_dataset) in _PREDEFINED_SPLITS_LVIS.items(): for (key, (image_root, json_file)) in splits_per_dataset.items(): register_lvis_instances(key, get_lvis_instances_meta(dataset_name), (os.path.join(root, json_file) if ('://' not in...
_module() class TridentFasterRCNN(FasterRCNN): 'Implementation of `TridentNet < def __init__(self, backbone, rpn_head, roi_head, train_cfg, test_cfg, neck=None, pretrained=None): super(TridentFasterRCNN, self).__init__(backbone=backbone, neck=neck, rpn_head=rpn_head, roi_head=roi_head, train_cfg=train_c...
class Annotation(object): def __init__(self): self.gender = None self.name_a_coref = None self.name_b_coref = None
_start_docstrings('The bare SegFormer encoder (Mix-Transformer) outputting raw hidden-states without any specific head on top.', SEGFORMER_START_DOCSTRING) class TFSegformerModel(TFSegformerPreTrainedModel): def __init__(self, config: SegformerConfig, *inputs, **kwargs): super().__init__(config, *inputs, **...
class CometCallback(TrainerCallback): def __init__(self): if (not _has_comet): raise RuntimeError('CometCallback requires comet-ml to be installed. Run `pip install comet-ml`.') self._initialized = False self._log_assets = False def setup(self, args, state, model): se...
class CUHK01(ImageDataset): dataset_dir = 'cuhk01' dataset_url = None def __init__(self, root='', split_id=0, **kwargs): self.root = osp.abspath(osp.expanduser(root)) self.dataset_dir = osp.join(self.root, self.dataset_dir) self.download_dataset(self.dataset_dir, self.dataset_url) ...