code
stringlengths
101
5.91M
def parse_args(): parser = argparse.ArgumentParser(description='Video Classification') parser.add_argument('--mode', type=str, default='test', help='train/test') parser.add_argument('--model', type=str, default='r3d', help='c3d/r3d/r21d') parser.add_argument('--dataset', type=str, default='ucf101', help...
_model def ig_resnext101_32x48d(pretrained=True, **kwargs): model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=32, base_width=48, **kwargs) return _create_resnet('ig_resnext101_32x48d', pretrained, **model_args)
def generate_data_ratio(rows): x_array = [] y_array = [] while (len(x_array) < rows): x = [np.random.uniform(0, 1), np.random.uniform(0.01, 1)] try: y = (x[0] / x[1]) x_array.append(x) y_array.append(y) except (ValueError, ZeroDivisionError): ...
def create_reverse_dependency_tree(): modules = [str(f.relative_to(PATH_TO_TRANFORMERS)) for f in (Path(PATH_TO_TRANFORMERS) / 'src/transformers').glob('**/*.py')] module_edges = [(d, m) for m in modules for d in get_module_dependencies(m)] tests = [str(f.relative_to(PATH_TO_TRANFORMERS)) for f in (Path(PAT...
def _no_grad_trunc_normal_(tensor, mean, std, a, b): def norm_cdf(x): return ((1.0 + math.erf((x / math.sqrt(2.0)))) / 2.0) if ((mean < (a - (2 * std))) or (mean > (b + (2 * std)))): warnings.warn('mean is more than 2 std from [a, b] in nn.init.trunc_normal_. The distribution of values may be in...
class ROIAlign(nn.Module): def __init__(self, output_size, spatial_scale, sampling_ratio): super(ROIAlign, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale self.sampling_ratio = sampling_ratio _function def forward(self, input, rois): ...
class TripletNet(nn.Module): def __init__(self, embedding_net): super(TripletNet, self).__init__() self.embedding_net = embedding_net def forward(self, x1, x2, x3): output1 = self.embedding_net(x1) output2 = self.embedding_net(x2) output3 = self.embedding_net(x3) ...
def get_parser(): parser = argparse.ArgumentParser(description='Cumulative Reasoning') parser.add_argument('--temperature', type=float, default=0.1, help='temperature') parser.add_argument('--propnum', type=int, choices=range(0, 21), default=2, help='numbers of props') parser.add_argument('--reasoningnu...
def read_labeled_image_list(image_list_file, isSkip=True): f = open(image_list_file, 'r') content = f.readlines() glen1 = len(content) pair1 = [] pair2 = [] labels = [] st = 2 it = 25 if (not isSkip): st = 0 it = 1 for i in range(st, glen1, it): line = con...
def modularize(f): class Transform(nn.Module): def __init__(self, f): super(Transform, self).__init__() self.f = f def forward(self, x): return self.f(x) return Transform(f)
def bbox_ious(boxes1, boxes2, x1y1x2y2=True): if x1y1x2y2: mx = torch.min(boxes1[0], boxes2[0]) Mx = torch.max(boxes1[2], boxes2[2]) my = torch.min(boxes1[1], boxes2[1]) My = torch.max(boxes1[3], boxes2[3]) w1 = (boxes1[2] - boxes1[0]) h1 = (boxes1[3] - boxes1[1]) ...
def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.array: ar = f'{sampling_rate}' ac = '1' format_for_conversion = 'f32le' ffmpeg_command = ['ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1'] try: with subproce...
def test_fpn(): s = 64 in_channels = [8, 16, 32, 64] feat_sizes = [(s // (2 ** i)) for i in range(4)] out_channels = 8 with pytest.raises(AssertionError): FPN(in_channels=in_channels, out_channels=out_channels, start_level=1, num_outs=2) with pytest.raises(AssertionError): FPN(in...
class InceptionV4(nn.Module): def __init__(self, num_classes=1001): super(InceptionV4, self).__init__() self.input_space = None self.input_size = (299, 299, 3) self.mean = None self.std = None self.features = nn.Sequential(BasicConv2d(3, 32, kernel_size=3, stride=2), ...
def session_indexed(s): action_to_idx = {'start': 0, 'end': 1, 'add': 2, 'remove': 3, 'purchase': 4, 'detail': 5, 'view': 6} return (([action_to_idx['start']] + [action_to_idx[e] for e in s]) + [action_to_idx['end']])
def is_number(s): try: float(s) return True except ValueError: pass return False
def test_register_new_sensors_and_measures(): if (not PointNavDatasetV1.check_config_paths_exist(config=habitat.get_config().DATASET)): pytest.skip('Please download Habitat test data to data folder.') register_new_sensors_and_measures.main()
class VisualNavigationModel(nn.Module): def init_weights(self, module): if (type(module) in [nn.GRU, nn.LSTM, nn.RNN]): for (name, param) in module.named_parameters(): if ('weight_ih' in name): nn.init.xavier_uniform_(param.data) elif ('weight_...
class TFBertForMaskedLM(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def get_bs_per_stream(batch_size, stream_number): result = [] batch_per_instance = (batch_size // stream_number) if (batch_per_instance >= 1): used_num_streams = stream_number instance_need_extra_input = (batch_size % stream_number) else: batch_per_instance = 1 used_num_s...
def init_weights(m): if (isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear)): m.weight.data.normal_(0, 0.001) if (m.bias is not None): m.bias.data.zero_() elif isinstance(m, nn.ConvTranspose2d): m.weight.data.normal_(0, 0.001) if (m.bias is not None): m....
.parametrize('size', list_tensor_sizes()) .parametrize('dtype', list_non_bool_dtypes()) .parametrize('op', list_binary_ops()) def test_binary_ew_ops(benchmark, size, dtype, op): np_a = np.array(np.random.uniform(1, 127, size), dtype=to_numpy_dtype(dtype)) np_b = np.array(np.random.uniform(1, 127, size), dtype=t...
_vision class CLIPProcessorTest(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endof...
class Abstractor(object): def __init__(self, abs_dir, max_len=30, cuda=True): abs_meta = json.load(open(os.path.join(abs_dir, 'meta.json'))) assert (abs_meta['net'] == 'base_abstractor') abs_args = abs_meta['net_args'] abs_ckpt = load_best_ckpt(abs_dir) word2id = pkl.load(ope...
class BNMomentumScheduler(object): def __init__(self, model, bn_lambda, last_epoch=(- 1), setter=set_bn_momentum_default): if (not isinstance(model, nn.Module)): raise RuntimeError("Class '{}' is not a PyTorch nn Module".format(type(model).__name__)) self.model = model self.sette...
def lossfun(x, alpha, scale, approximate=False, epsilon=1e-06): assert torch.is_tensor(x) assert torch.is_tensor(scale) assert torch.is_tensor(alpha) assert (alpha.dtype == x.dtype) assert (scale.dtype == x.dtype) assert (scale > 0).all() if approximate: assert (epsilon > np.finfo(np...
def one_of_k_encoding_unk(x, allowable_set): if (x not in allowable_set): return None return list(map((lambda s: int((x == s))), allowable_set))
(others=sampled_from([{'box': TFBoxTensor(tf.Variable([[[1, 1], [3, 5]], [[2, 0], [6, 2]]], dtype=tf.float32)), 'weights': None, 'mask': None, 'keepdim': True, 'dim': 0, 'expected': TFBoxTensor(tf.Variable([[(3.0 / 2.0), (1.0 / 2.0)], [(9.0 / 2.0), (7.0 / 2.0)]]))}, {'box': TFBoxTensor(tf.Variable([[[1, 1], [3, 5]], [[...
def merge_new_config(config, new_config): for (key, val) in new_config.items(): if (not isinstance(val, dict)): if (key == '_base_'): with open(new_config['_base_'], 'r') as f: try: val = yaml.load(f, Loader=yaml.FullLoader) ...
class TransNorm2d(_TransNorm): def _check_input(self, x): if (x.dim() != 4): raise ValueError('Expected the input to be 4-D, but got {}-D'.format(x.dim()))
def dc_state_dict(dc_vars, *name_list): return {(name + '_state_dict'): dc_vars[name].state_dict() for name in name_list if hasattr(dc_vars[name], 'state_dict')}
def eval(args, val_loader, model, criterion): model.eval() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() device = args.device if args.cuda: torch.cuda.empty_cache() for (data, y) in val_loader: data = data.to(device, non_blocking=True) y = y.to(d...
def convert_coco_poly_to_mask(segmentations, height, width): masks = [] for polygons in segmentations: rles = coco_mask.frPyObjects(polygons, height, width) mask = coco_mask.decode(rles) if (len(mask.shape) < 3): mask = mask[(..., None)] mask = torch.as_tensor(mask, d...
def weights_to_cpu(state_dict): state_dict_cpu = OrderedDict() for (key, val) in state_dict.items(): state_dict_cpu[key] = val.cpu() return state_dict_cpu
class CmsPfSinglePi(tfds.core.GeneratorBasedBuilder): VERSION = tfds.core.Version('1.6.0') RELEASE_NOTES = {'1.0.0': 'Initial release.', '1.1.0': 'Add muon type, fix electron GSF association', '1.2.0': '12_1_0_pre3 generation, add corrected energy, cluster flags, 20k events', '1.4.0': 'Add genjet information', ...
def connect_nodes(n1, n2): if (n2['node'].name not in n1['outputs']): n1['outputs'].append(n2['node'].name) n2['inputs'].append(n1['node'].name) else: print('{} -> {} already connected'.format(n1['node'].name, n2['node'].name))
def load_actor(checkpointpath): import json with open(checkpointpath.replace('model.tar', 'meta.json'), 'r') as file: args = json.load(file)['args'] if ('breath' not in args): args['breath'] = 2 env = create_gymenv(AttributeDict(args)) return (env, create_model(AttributeDict(...
class Res16UNetSN14(Res16UNet14): NORM_TYPE = NormType.SPARSE_SWITCH_NORM BLOCK = BasicBlockSN
class MyMetric_keras(MyMetric): def __init__(self, *args): super(MyMetric_keras, self).__init__(*args)
class BasePose(nn.Module): __metaclass__ = ABCMeta def forward_train(self, img, img_metas, **kwargs): def forward_test(self, img, img_metas, **kwargs): def forward(self, img, img_metas, return_loss=True, **kwargs): def _parse_losses(losses): log_vars = OrderedDict() for (loss_name, l...
def symlink_force(target, link_name): try: os.symlink(target, link_name) except OSError as e: if (e.errno == errno.EEXIST): os.remove(link_name) os.symlink(target, link_name) else: raise e
class Trainer(): _pipeline: Union[(BaseNRHintPipeline, DDP)] def __init__(self, config: SystemConfig, shm_info: NRDataSHMInfo): self.config = config self.rank = local_rank() self.world_size = 1 if torch.cuda.is_available(): self.device = torch.device('cuda') ...
class ConvVAE(nn.Module): def __init__(self, latent_size): super(ConvVAE, self).__init__() self.latent_size = latent_size self.encoder = nn.Sequential(nn.Conv2d(3, 64, kernel_size=4, stride=2, padding=1), nn.ReLU(), nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1), nn.ReLU(), Flatten()...
def get_sorted_wordlist(path): freqs = defaultdict((lambda : 0)) with codecs.open(path, 'r', encoding='utf-8') as fin: for line in fin: words = line.strip().split() for word in words: freqs[word] += 1 sorted_words = sorted(freqs, key=freqs.get, reverse=True) ...
def make_layers(cfg, batch_norm=False): layers = [] in_channels = 3 for (i, v) in enumerate(cfg): if (v == 'M'): layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: padding = (v[1] if isinstance(v, tuple) else 1) out_channels = (v[0] if isinstance(v, t...
class Conv2dIndepBeta(_DeepIndepBeta): def __init__(self, backbone: nn.Module, hidden_channels: int=1, out_channels: int=1): super().__init__(backbone=backbone, alpha_head=nn.Conv2d(hidden_channels, out_channels=out_channels, kernel_size=1), beta_head=nn.Conv2d(hidden_channels, out_channels=out_channels, ke...
def prune(model, amount=0.3): import torch.nn.utils.prune as prune print('Pruning model... ', end='') for (name, m) in model.named_modules(): if isinstance(m, nn.Conv2d): prune.l1_unstructured(m, name='weight', amount=amount) prune.remove(m, 'weight') print((' %.3g global...
class MelFilterBank(): def __init__(self, specSize, numCoefficients, sampleRate): numBands = int(numCoefficients) minMel = 0 maxMel = self.freqToMel((sampleRate / 2.0)) melStep = ((maxMel - minMel) / (numBands + 1)) melFilterEdges = (np.arange(0, (numBands + 2)) * melStep) ...
class Softmax(Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, input): return input.softmax(self.dim) def from_onnx(parameters=None, attributes=None): if (attributes is None): attributes = {} return Softmax(attributes['...
def tf2th(conv_weights): if (conv_weights.ndim == 4): conv_weights = conv_weights.transpose([3, 2, 0, 1]) return torch.from_numpy(conv_weights)
def add_args(parser): parser.add_argument('--num_steps', type=int, default=(10 ** 6), help='number of steps in training') parser.add_argument('--transitions_per_step', type=int, default=1, help='env transitions per training step. Defaults to 1, but will need to be set higher for repaly ratios < 1') ...
def read_reco2vol(volumes_file): volumes = {} with open(volumes_file) as volume_reader: for line in volume_reader.readlines(): if (len(line.strip()) == 0): continue parts = line.strip().split() if (len(parts) != 2): raise RuntimeError('...
def gelu(x): x = tf.convert_to_tensor(x) cdf = (0.5 * (1.0 + tf.math.erf((x / tf.math.sqrt(2.0))))) return (x * cdf)
_registry(operator_type='LayerNorm') class LayerNorm(Operator): def __init__(self): super().__init__() def set_attr(self, framework, node): if (framework == 'torch'): if (node.inputsSize() > 4): self._attr['epsilon'] = node.inputsAt(4).toIValue() self....
def get_train_type(train_type, checkpoint): exist_status = (checkpoint and os.path.exists(checkpoint)) if (train_type == 'NORMAL'): return train_type if ((train_type == 'FPD') and exist_status): return 'FPD' if ((train_type == 'FPD') and (not exist_status)): exit('ERROR: teacher ...
class Indexer(): def __init__(self, symbols=['<pad>', '<unk>', '<s>', '</s>']): self.vocab = defaultdict(int) self.PAD = symbols[0] self.UNK = symbols[1] self.BOS = symbols[2] self.EOS = symbols[3] self.d = {self.PAD: 0, self.UNK: 1, self.BOS: 2, self.EOS: 3} ...
_module() class Sharpness(object): def __init__(self, magnitude, prob=0.5, random_negative_prob=0.5): assert isinstance(magnitude, (int, float)), f'The magnitude type must be int or float, but got {type(magnitude)} instead.' assert (0 <= prob <= 1.0), f'The prob should be in range [0,1], got {prob} ...
def parse_args(): parser = argparse.ArgumentParser(description='Create periodicity threshold figure') parser.add_argument('--names', required=True, nargs='+', help='Corresponding labels for each evaluation') parser.add_argument('--evaluations', type=Path, required=True, nargs='+', help='The evaluations to p...
def get_messages_tokens(messages): cnt = 0 for message in messages: cnt += count_tokens(message['content']) return cnt
def D_logistic(G, D, opt, training_set, minibatch_size, reals, labels): _ = (opt, training_set) latents = tf.random_normal(([minibatch_size] + G.input_shapes[0][1:])) fake_images_out = G.get_output_for(latents, labels, is_training=True) real_scores_out = D.get_output_for(reals, labels, is_training=True)...
def run(api_key, api_url, index): es = Elasticsearch(hosts=[ELASTICSEARCH_HOST]) arxivdigest_connector = ArxivdigestConnector(api_key, api_url) if (not es.indices.exists(index=index)): logger.info('Creating index') init_index(es, index) logger.info('Indexing articles from arXivDigest API...
class nnUNetTrainerV2_lReLU_biasInSegOutput(nnUNetTrainerV2): def initialize_network(self): if self.threeD: conv_op = nn.Conv3d dropout_op = nn.Dropout3d norm_op = nn.InstanceNorm3d else: conv_op = nn.Conv2d dropout_op = nn.Dropout2d ...
def iso_recal(exp_props, obs_props): exp_props = exp_props.flatten() obs_props = obs_props.flatten() min_obs = torch.min(obs_props) max_obs = torch.max(obs_props) iso_model = IsotonicRegression(increasing=True, out_of_bounds='clip') try: assert (torch.min(obs_props) == 0.0) asser...
class AdapterResnetBlock(nn.Module): def __init__(self, channels: int): super().__init__() self.block1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1) self.act = nn.ReLU() self.block2 = nn.Conv2d(channels, channels, kernel_size=1) def forward(self, x: torch.Tensor) -> t...
class CrossEntropyLoss(nn.CrossEntropyLoss): def __init__(self, weight=None, ignore_index=(- 100), reduction='mean', smooth_eps=None, smooth_dist=None): super(CrossEntropyLoss, self).__init__(weight=weight, ignore_index=ignore_index, reduction=reduction) self.smooth_eps = smooth_eps self.smo...
def getModelFiles(): return [dict(name=os.path.basename(p), mtime=int(os.path.getmtime(p))) for p in glob.glob(os.path.join(models_dir, '*.tflite'))]
def test_poisson_time_generator(): gen = PoissonTimeGenerator(lambda_time=2, random_generator=np.random.RandomState(seed=1)) for _ in range(10): print(gen.next())
def test_capsule(capture): pytest.gc_collect() with capture: a = m.return_capsule_with_destructor() del a pytest.gc_collect() assert (capture.unordered == '\n creating capsule\n destructing capsule\n ') with capture: a = m.return_capsule_with_destructor_2...
_model('s2spect2_conformer') class S2SpecT2ConformerModel(S2SpecTConformerModel): def add_args(parser): S2SpecTConformerModel.add_args(parser) parser.add_argument('--translation-decoder-layers', type=int, default=4, metavar='N', help='num decoder layers in the first-pass translation module') ...
def resnet18(pretrained=False, filter_size=1, pool_only=True, **kwargs): model = ResNet(BasicBlock, [2, 2, 2, 2], filter_size=filter_size, pool_only=pool_only, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
def test_digits_corr_two_stage_init(): model = SaturatedCoverageSelection(100, 'corr', optimizer='two-stage', initial_subset=digits_corr_ranking[:5]) model.fit(X_digits) assert_array_equal(model.ranking[:(- 5)], digits_corr_ranking[5:]) assert_array_almost_equal(model.gains[:(- 5)], digits_corr_gains[5:...
.parametrize('as_frame', [True, False]) def test_load_movielens100k(as_frame): (df_data, df_users, df_items) = load_movielens100k(as_frame=as_frame) if as_frame: assert ((df_data.shape, df_users.shape, df_items.shape, type(df_data), type(df_users), type(df_items)) == ((100000, 4), (943, 5), (1682, 24), ...
def objective(trial): param = {'min_samples_leaf': trial.suggest_int('min_samples_leaf', 2, 20), 'min_samples_split': trial.suggest_int('min_samples_split', 2, 20), 'max_depth': trial.suggest_int('max_depth', 2, 32), 'n_estimators': trial.suggest_int('n_estimators', 100, 1000, step=100)} clf = RandomForestRegre...
class MyDataloader(data.Dataset): modality_names = ['rgb', 'rgbd', 'd'] color_jitter = transforms.ColorJitter(0.4, 0.4, 0.4) def __init__(self, root, type, sparsifier=None, modality='rgb', loader=h5_loader): (classes, class_to_idx) = find_classes(root) imgs = make_dataset(root, class_to_idx)...
class Config(): def __init__(self): self.det_head = 'pip' self.net_stride = 32 self.batch_size = 16 self.init_lr = 0.0001 self.num_epochs = 60 self.decay_steps = [30, 50] self.input_size = 256 self.backbone = 'resnet18' self.pretrained = True ...
def static_baseline(num, probas): logits = [np.log((p + 1e-19)) for p in probas] return torch.tensor(([logits] * num)).float()
def build_optim(model, optim_opt): optim = nmt.Optim(optim_opt.optim_method, optim_opt.learning_rate, optim_opt.max_grad_norm, optim_opt.learning_rate_decay, optim_opt.weight_decay, optim_opt.start_decay_at) optim.set_parameters(model.parameters()) return optim
def DPT_Hybrid(pretrained=True, **kwargs): model = DPTDepthModel(path=None, backbone='vitb_rn50_384', non_negative=True) if pretrained: checkpoint = ' state_dict = torch.hub.load_state_dict_from_url(checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True) model.load_...
def identify_and_tag_authors(line, authors_kb): (re_auth, re_auth_near_miss) = get_author_regexps() for (pattern, repl) in authors_kb: line = line.replace(pattern, repl) output_line = line line = strip_tags(output_line) matched_authors = list(re_auth.finditer(line)) unidecoded_line = str...
def build_feature_extractor(cfg): (model_name, backbone_name) = cfg.MODEL.NAME.split('_') if backbone_name.startswith('resnetv2'): backbone = resnet_feature_extractor_v2(backbone_name.replace('v2', ''), pretrained_weights=cfg.MODEL.WEIGHTS, aux=False, pretrained_backbone=True, eval_bn=cfg.MODEL.EVAL_BN)...
def GetPlanToJointStateService(): return GetService('/costar/PlanToJointState', ServoToJointState)
class LengthGroupedSampler(Sampler): def __init__(self, batch_size: int, world_size: int, lengths: Optional[List[int]]=None, generator=None, group_by_modality: bool=False): if (lengths is None): raise ValueError('Lengths must be provided.') self.batch_size = batch_size self.world...
def get_split_time(num_domain=2, mode='pre_process', data_file=None, station=None, dis_type='coral'): spilt_time = {'2': [('2013-3-6 0:0', '2015-5-31 23:0'), ('2015-6-2 0:0', '2016-6-30 23:0')]} if (mode == 'pre_process'): return spilt_time[str(num_domain)] if (mode == 'tdc'): return TDC(num...
(scope='session') def t2(dummy: ep.Tensor) -> ep.Tensor: return ep.arange(dummy, 7, 17, 2).float32()
def fake_output_machine(t, beam_size): assert (beam_size >= 2) if (t >= 0): values = ([0.5, 0.3] + [0.001 for _ in range((beam_size - 2))]) indices = (random.sample([1, 2, 3, 4], k=2) + [0 for _ in range((beam_size - 2))]) return (values, indices)
def partition_data(datadir, partition, n_nets, alpha, logger): logger.info('partition data') (X_train, y_train, X_test, y_test) = load_tiny_data(datadir) n_train = X_train.shape[0] if (partition == 'homo'): total_num = n_train idxs = np.random.permutation(total_num) batch_idxs = ...
_module() class BaseConvBboxHead(nn.Module): def __init__(self, in_channels=0, shared_conv_channels=(), cls_conv_channels=(), num_cls_out_channels=0, reg_conv_channels=(), num_reg_out_channels=0, conv_cfg=dict(type='Conv1d'), norm_cfg=dict(type='BN1d'), act_cfg=dict(type='ReLU'), bias='auto', *args, **kwargs): ...
class Scale(object): def __init__(self, size): self.size = size def __call__(self, sample): (image, depth) = (sample['image'], sample['depth']) image = self.changeScale(image, self.size) depth = self.changeScale(depth, self.size, Image.NEAREST) return {'image': image, 'de...
class HierarchicalDecoder(nn.Module): def __init__(self, num_convolutions=3, filters=(256, 128, 64, 32, 16), latent_dim=100, output_size=(1, 128, 128), upconv=False, use_weight_norm=False, use_spectral_norm=False, hierarchical_layers=(1, 3, 5), context_dim=4, div_factor=8): super().__init__() self.n...
def fit_to_block_size(sequence, block_size, pad_token_id): if (len(sequence) > block_size): return sequence[:block_size] else: sequence.extend(([pad_token_id] * (block_size - len(sequence)))) return sequence
class SparseMaxPool2d(SparseMaxPool): def __init__(self, kernel_size, stride=1, padding=0, dilation=1): super(SparseMaxPool2d, self).__init__(2, kernel_size, stride, padding, dilation)
class GCKNet(nn.Module): def __init__(self, nclass, input_size, hidden_sizes, path_sizes, kernel_funcs=None, kernel_args_list=None, pooling='mean', global_pooling='sum', heads=1, out_size=3, max_iter=100, eps=0.1, aggregation=False, weight_decay=0.0, batch_norm=False, **kwargs): super().__init__() s...
class Epanechnikov(torch.nn.Module): def __init__(self): super().__init__() self.support = ((- 1.0), 1.0) def forward(self, u): return (((((- 1.0) <= u) * (u <= 1.0)) * (1.0 - (u ** 2))) * 0.75)
def get_mask_paths(metadata): mask_paths = {} ignore_paths = {} with open(metadata.localization) as f: for line in f.readlines(): (image_id, mask_path, ignore_path) = line.strip('\n').split(',') if (image_id in mask_paths): mask_paths[image_id].append(mask_pat...
def new_func(*args, **kwds): default_in_kw = kwds.get('default', None) default_in_args = (args[2] if (len(args) > 2) else None) default = (default_in_kw or default_in_args) try: return config_tree_get_ori(*args, **kwds) except ConfigMissingException: logger.info(f'key {args[1]}, def ...
def parse_args(): parser = argparse.ArgumentParser(description='Finetune a transformers model on a text classification task') parser.add_argument('--task_name', type=str, default=None, help='The name of the glue task to train on.', choices=list(task_to_keys.keys())) parser.add_argument('--train_file', type=...
def _find_stack(stacks, item): for (stack_id, stack) in enumerate(stacks): if (stack[0] == item): return (stack, stack_id) return (None, None)
class FlaxElectraForMaskedLM(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def loadmat(file): f = h5py.File(file) arr = {k: np.array(v) for (k, v) in f.items()} return arr
_model_architecture('transformer_lm', 'transformer_lm_gpt3_2_7') def transformer_lm_gpt3_2_7(args): args.decoder_layers = getattr(args, 'decoder_layers', 32) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 2560) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 32) base...