code
stringlengths
101
5.91M
_name('slim_eval') def test_slim_eval_nonuniform(benchmark): slim_eval_runner(benchmark, uniform=False)
def test_revelation(): d = DogmaticDict({'a': 7, 'b': 12}) d['b'] = 23 assert ('a' not in d) m = d.revelation() assert (set(m) == {'a'}) assert ('a' in d)
class KLDivergence(PytorchMetric): def __init__(self): self.total = torch.tensor(0) self.divergence = torch.tensor(0) def __call__(self, preds, targets): epsilon = 1e-07 _check_same_shape(preds, targets) output_size = targets.size(0) div = (targets / preds) ...
def filter_file(infile, filt, exclude): vocab = set() with codecs.open(filt, 'r', encoding='utf-8') as vocabfile: for line in vocabfile: vocab.add(line.strip()) sys.stdout = codecs.getwriter('utf-8')((sys.stdout if is_python2 else sys.stdout.buffer)) with codecs.open(infile, 'r', enc...
def test_cpp_iterators(): assert (m.tuple_iterator() == 12) assert (m.dict_iterator() == (305 + 711)) assert (m.passed_iterator(iter(((- 7), 3))) == (- 4))
class SPADEGenerator(BaseNetwork): def modify_commandline_options(parser, is_train): parser.set_defaults(norm_G='spectralspadesyncbatch3x3') parser.add_argument('--num_upsampling_layers', choices=('normal', 'more', 'most'), default='normal', help="If 'more', adds upsampling layer between the two mid...
def _stack(in_ch: int, out_ch: int, kernel_size: int, stride: int, exp_factor: int, repeats: int, bn_momentum: float) -> nn.Sequential: assert (repeats >= 1) first = _InvertedResidual(in_ch, out_ch, kernel_size, stride, exp_factor, bn_momentum=bn_momentum) remaining = [] for _ in range(1, repeats): ...
def ignore_undocumented(name): if name.isupper(): return True if (name.endswith('ModelMixin') or name.endswith('Decoder') or name.endswith('Encoder') or name.endswith('Layer') or name.endswith('Embeddings') or name.endswith('Attention')): return True if (os.path.isdir(os.path.join(PATH_TO_DI...
def test_divergence_bound(): np.random.seed(846) var1 = 4 var2 = 16 p1 = norm(scale=np.sqrt(var1)) p2 = norm(scale=np.sqrt(var2)) samples = p2.rvs(MC_SAMPLES) log_weights = (p1.logpdf(samples) - p2.logpdf(samples)) for alpha in [1.5, 2, 3]: print('alpha =', alpha) for elb...
class Trainer(object): def __init__(self, env, sampler, sample_processor, policy, dynamics_model, n_itr, start_itr=0, initial_random_samples=True, dynamics_model_max_epochs=200, sess=None): self.env = env self.sampler = sampler self.sample_processor = sample_processor self.dynamics_m...
def test_masked_ones_summarize(model, X, w): X = torch.tensor(numpy.array(X)) mask = torch.ones_like(X).type(torch.bool) X_ = torch.masked.MaskedTensor(X, mask=mask) d1 = model.distributions[0] d2 = model.distributions[1] model.summarize(X_, sample_weight=w) assert_array_almost_equal(model._...
class Program(): def __init__(self, ir: GraphIR) -> None: self.inputs: Dict[(str, torch.Tensor)] = {} code_forward: List[str] = [] for input_var_name in ir.input_var(): abs_tensor: AbsTensor = ir.vars[input_var_name] assert abs_tensor.is_concrete(), f'Input {input_var...
def get_activation(act_fn): if (act_fn in ['swish', 'silu']): return nn.SiLU() elif (act_fn == 'mish'): return nn.Mish() elif (act_fn == 'gelu'): return nn.GELU() elif (act_fn == 'relu'): return nn.ReLU() else: raise ValueError(f'Unsupported activation functio...
def auprOut(X1, Y1): auprBase = 0.0 recallTemp = 1.0 for delta in diff[::(- 1)]: fp = (np.sum(np.sum((X1 < delta))) / np.float(len(X1))) tp = (np.sum(np.sum((Y1 < delta))) / np.float(len(Y1))) if ((tp + fp) == 0): continue precision = (tp / (tp + fp)) reca...
def prepare(config): (train_examples, train_eval) = process_file(config.train_para_file, config.train_question_file, para_limit=config.para_limit) (dev_examples, dev_eval) = process_file(config.dev_para_file, config.dev_question_file, para_limit=config.para_limit) (test_examples, test_eval) = process_file(c...
class MSE(PytorchMetric): def __init__(self): self.total = torch.tensor(0) self.sum_squared_error = torch.tensor(0.0) def __call__(self, preds, targets): _check_same_shape(preds, targets) self.sum_squared_error += torch.sum(torch.square(torch.sub(preds, targets))) self.to...
def is_int_tensor(tensor): return _is_type_tensor(tensor, [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64])
class SamplingStrategy(): Random = 'random' Genetic = 'genetic' KdTree = 'kdtree' Gradient = 'gradient'
def sample_many(inner_func, get_cost_func, input, batch_rep=1, iter_rep=1): input = do_batch_rep(input, batch_rep) costs = [] pis = [] for i in range(iter_rep): (_log_p, pi) = inner_func(input) (cost, mask) = get_cost_func(input, pi) costs.append(cost.view(batch_rep, (- 1)).t()) ...
class Receiver(metaclass=abc.ABCMeta): def receive_notify(self, obj: object, message: Dict): raise NotImplementedError('Method receive_notify() not implemented!')
_arg_scope def customized_slim_fully_connected(inputs, num_outputs, activation_fn=nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializer(), weights_regularizer=None, biases_initializer=init_ops.zeros_initializer(), biases_regularizer=None, reuse=None, variables_collecti...
def gradient_penalty(y, x): weight = torch.ones(y.size()).cuda() dydx = torch.autograd.grad(outputs=y, inputs=x, grad_outputs=weight, retain_graph=True, create_graph=True, only_inputs=True)[0] dydx = dydx.view(dydx.size(0), (- 1)) dydx_l2norm = torch.sqrt(torch.sum((dydx ** 2), dim=1)) return torch....
def setup_logger(logging_level_console=logging.DEBUG, log_file=None, logging_level_file=logging.DEBUG): if isinstance(logging_level_console, str): if (logging_level_console.upper() == 'PROGRESS'): logging_level_console = PROGRESS_LEVEL_NUM else: logging_level_console = getatt...
def evaluate(dataset, predictions, output_folder, **kwargs): args = dict(dataset=dataset, predictions=predictions, output_folder=output_folder, **kwargs) if isinstance(dataset, datasets.WordDataset): return word_evaluation(**args) else: dataset_name = dataset.__class__.__name__ raise...
class NullTransformer(BaseEstimator, TransformerMixin): def fit(self, X, y=None): return self def transform(self, X): return X
class Layer(object): def __init__(self, nonlin=tf.identity, N=1, name=None, logging=False): self.N = N if (name is None): layer = self.__class__.__name__.lower() name = ((layer + '_') + str(get_layer_uid(layer))) self.name = name self.logging = logging ...
('/app/initCustomProvider', methods=['POST']) def initCustomProvider(): data = request.get_json() if ('code' not in data): return jsonify({'error': 'POST data is improper format.'}) if ('' not in data['code']): return jsonify({'error': 'Did not detect a decorator. Custom provider scripts sh...
def cheater(mdim, pdim, qdeg, start, startsols): dim = ((mdim * pdim) + (qdeg * (mdim + pdim))) planes = [random_complex_matrix((mdim + pdim), mdim) for _ in range(0, dim)] pols = make_pieri_system(mdim, pdim, qdeg, planes) from phcpy.trackers import track print(('cheater homotopy with %d paths' % l...
def random_tensor(tensor_shape, tensor_dtype, library='torch'): if (library == 'torch'): import torch if (tensor_dtype == torch.bool): return torch.randint(0, 2, tensor_shape, dtype=tensor_dtype) elif (tensor_dtype.is_floating_point or tensor_dtype.is_complex): return...
class LatentVariableModel(nn.Module): def __init__(self, model_config): super(LatentVariableModel, self).__init__() self.model_config = model_config self.output_interval = None def _construct(self, model_config): raise NotImplementedError def infer(self, observation): ...
class ResidualBlock(nn.Module): def __init__(self, h_dim, norm_layer=None, nl_layer=None, use_dropout=False): super(ResidualBlock, self).__init__() block = [conv3x3(h_dim, h_dim, norm_layer=norm_layer, nl_layer=nl_layer), conv3x3(h_dim, h_dim, norm_layer=norm_layer)] if use_dropout: ...
def _has_soft_sentence_predictions(results: List[dict]) -> bool: return (('rationales' in results[0]) and (len(results[0]['rationales']) > 0) and ('soft_sentence_predictions' in results[0]['rationales'][0]) and (results[0]['rationales'][0]['soft_sentence_predictions'] is not None))
class RandomResizedCrop(DualTransform): def __init__(self, shape, scale_limit=(0.8, 1.2), interpolation=3, always_apply=False, p=1.0): super().__init__(always_apply, p) self.shape = shape self.scale_limit = scale_limit self.interpolation = interpolation def apply(self, img, scale...
def spect_diff(u_spect, signal_ndim, order, mesh_bound=None): size0 = u_spect.shape s = ([1] * u_spect.dim()) freq0 = np.ones(s) assert (len(order) == signal_ndim) b = ((u_spect.dim() - signal_ndim) - 1) for i in range(signal_ndim): if (order[i] == 0): continue freq =...
class TextDataset(Dataset): def __init__(self, tokenizer: PreTrainedTokenizer, file_path: str, block_size: int, overwrite_cache=False, cache_dir: Optional[str]=None): assert os.path.isfile(file_path), f'Input file path {file_path} not found' block_size = (block_size - tokenizer.num_special_tokens_to...
class COCO(data.Dataset): num_classes = 80 default_resolution = [512, 512] mean = np.array([0., 0., 0.], dtype=np.float32).reshape(1, 1, 3) std = np.array([0., 0., 0.], dtype=np.float32).reshape(1, 1, 3) def __init__(self, opt, split): super(COCO, self).__init__() self.data_dir = ('/...
def whether_move(masks, frames): if (len(frames) == 4): c_x_list = ([None] * 4) c_y_list = ([None] * 4) diff_c_x = ([None] * 3) diff_c_y = ([None] * 3) for k in range(4): cnt_mask = frames[k] (c_x, c_y) = mask2bbox(cnt_mask) c_x_list[k] = c...
def test_aggregated_agent_metric_3(): env = MockEnv() metric = ph.metrics.AggregatedAgentMetric(agent_ids=['agent1', 'agent2'], agent_property='test_property', group_reduce_action='mean', train_reduce_action='last') values = [] for _ in range(5): env.step() values.append(metric.extract(e...
def fasttext_predict(corpus: Union[(List[str], List[List[str]])]): url = ' filepath = get_cached_file_path('fasttext', 'lid.176.ftz', url) fasttext.FastText.eprint = (lambda x: None) classifier = fasttext.load_model(str(filepath)) prediction: Tuple[(List[List[str]], List)] = None if all([isinsta...
.parametrize('cv1, cv2, expected', [(GroupKFold(2), KFold(3), False), (GroupKFold(2), GroupKFold(3), False), (GroupKFold(3), GroupKFold(3), True), (GroupShuffleSplit(2), GroupShuffleSplit(3), 'non-reproducible'), (GroupShuffleSplit(2, random_state=32), GroupShuffleSplit(3, random_state=32), False), (GroupShuffleSplit(3...
class Cell(nn.Module): def __init__(self, steps, block_multiplier, prev_prev_fmultiplier, prev_fmultiplier_down, prev_fmultiplier_same, prev_fmultiplier_up, filter_multiplier): super(Cell, self).__init__() self.C_in = (block_multiplier * filter_multiplier) self.C_out = filter_multiplier ...
class WnBReportBest(Callback): def __init__(self, wb: object, monitor: str='val_loss', mode: str='auto'): super(WnBReportBest, self).__init__() self.monitor = monitor self.mode = mode self.wb = wb if (self.mode not in ['auto', 'min', 'max']): warnings.warn(('WnBRe...
class ExploitabilityP2SROManagerLogger(SimpleP2SROManagerLogger): def __init__(self, p2sro_manger, log_dir: str, scenario: PSROScenario): super(ExploitabilityP2SROManagerLogger, self).__init__(p2sro_manger=p2sro_manger, log_dir=log_dir) self._scenario = scenario if (not issubclass(scenario.e...
def make_lr_cdb_scheduler(cfg, optimizer): return WarmupMultiStepLR(optimizer, cfg.SOLVER_CDB.STEPS, cfg.SOLVER_CDB.GAMMA, warmup_factor=cfg.SOLVER_CDB.WARMUP_FACTOR, warmup_iters=cfg.SOLVER_CDB.WARMUP_ITERS, warmup_method=cfg.SOLVER_CDB.WARMUP_METHOD)
class TestHeatSphere(unittest.TestCase): def test_sphere_heat_kernel(self): grid_size = 4 nb_samples = 10 n = 5 space = Sphere(n=n, order=_TRUNCATION_LEVEL) ts = torch.linspace(0.1, 1, grid_size, requires_grad=True) xs = space.rand(nb_samples).requires_grad_(True) ...
class RandomDirectionEmitter(EmitterBase): def __init__(self, archive, x0, sigma0, selection_rule='filter', restart_rule='no_improvement', weight_rule='truncation', bounds=None, batch_size=None, seed=None): self._rng = np.random.default_rng(seed) self._batch_size = batch_size self._x0 = np.a...
def log_scaffold_stats(data: MoleculeDataset, index_sets: List[Set[int]], num_scaffolds: int=10, num_labels: int=20, logger: logging.Logger=None) -> List[Tuple[(List[float], List[int])]]: target_avgs = [] counts = [] for index_set in index_sets: data_set = [data[i] for i in index_set] target...
def test_initial_solutions_shape(archive_fixture): (archive, _) = archive_fixture initial_solutions = [[0, 0, 0], [1, 1, 1]] with pytest.raises(ValueError): GaussianEmitter(archive, sigma=1.0, initial_solutions=initial_solutions)
def try_wrapper(func): def inner(*args, **kwargs): try_cnt = 0 while (try_cnt < TRY_CNT): try: return func(*args, **kwargs) except Exception as e: print(f'func() failed, try again... (No. {(try_cnt + 1)}). Error: {e}') try_cnt +...
def main(exp, args, num_gpu): if (args.seed is not None): random.seed(args.seed) torch.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed testing. This will turn on the CUDNN deterministic setting, ') is_distributed = (num_gpu > 1) cudnn....
def D_loss(G, D, reals, labels, minibatch_size, loss_type, reg_type, gamma=10.0, wgan_epsilon=0.001, wgan_target=1.0, **kwargs): latents = tf.random_normal(([minibatch_size] + G.input_shapes[0][1:])) fake_imgs_out = G.get_output_for(latents, labels, is_training=True)[0] real_scores_out = D.get_output_for(re...
def rectangular_coordinates(size: tuple) -> Tensor: def linspace_func(nx): return torch.linspace(0.0, 1.0, nx) linspaces = map(linspace_func, size) coordinates = torch.meshgrid(*linspaces, indexing='ij') return torch.stack(coordinates, dim=(- 1))
def main(): args = parse_args() dist_world_size = (args.nproc_per_node * args.nnodes) current_env = os.environ.copy() current_env['MASTER_ADDR'] = args.master_addr current_env['MASTER_PORT'] = str(args.master_port) current_env['WORLD_SIZE'] = str(dist_world_size) processes = [] for local...
def cal_gcmvn_stats(features_list): features = np.concatenate(features_list) square_sums = (features ** 2).sum(axis=0) mean = features.mean(axis=0) features = np.subtract(features, mean) var = ((square_sums / features.shape[0]) - (mean ** 2)) std = np.sqrt(np.maximum(var, 1e-08)) return {'me...
def crps_loss(model, y, x, q_list, device, args): num_pts = y.size(0) q_list = (torch.arange(101) / 100.0) num_q = q_list.size(0) q_rep = q_list.view((- 1), 1).repeat(1, num_pts).view((- 1), 1).to(device) y_stacked = y.repeat(num_q, 1) y_mat = y_stacked.reshape(num_q, num_pts) if (x is None)...
def get_git_sha(repo=None): process = subprocess.Popen(['git', 'rev-parse', 'HEAD'], stdout=subprocess.PIPE, cwd=repo) (out, _err) = process.communicate() return out.decode('UTF-8').strip()
def get_initial_model(params, train_seed): model = model_dict[params['model_name']](seed=train_seed, **params['model_kwargs']) model.randomize_params(params['randomize_kernel_weight']['high'], params['randomize_kernel_weight']['low'], except_for=['bias']) model.randomize_params(params['randomize_bias']['hig...
def _get_right_parentheses_index_(s): left_paren_count = 0 for (index, x) in enumerate(s): if (x == '('): left_paren_count += 1 elif (x == ')'): left_paren_count -= 1 if (left_paren_count == 0): return index else: pass r...
class ActualIndexDataset(): def get_collate_fn(self): def collate_fn(batch): collated = {**super(ActualIndexDataset, self).get_collate_fn()(batch), 'index': [s['index'] for s in batch]} return collated return collate_fn def __getitem__(self, index): return {**supe...
class MEInitBlock(nn.Module): def __init__(self, in_channels, out_channels): super(MEInitBlock, self).__init__() self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=2, padding=1, bias=False) self.bn = nn.BatchNorm2d(num_features=out_channels) ...
class UNet(nn.Module): def __init__(self, in_channels, n_classes, base_n_filter=8): super(UNet, self).__init__() self.in_channels = in_channels self.n_classes = n_classes self.base_n_filter = base_n_filter self.lrelu = nn.LeakyReLU() self.dropout3d = nn.Dropout3d(p=0....
class TestMXNetGluonMultipleInput(TestCase): def test_gluon_multiple_input(self): config = create_config(log_interval=2, optimizer='adagrad', seed=1128, optimizer_params={'learning_rate': 0.02}) estimator = Estimator.from_mxnet(config=config, model_creator=get_model, loss_creator=get_loss, eval_metr...
def get_dataloaders(dataset, val_dataset=None, batch_size=None, val_batch_size=None, drop_last=True, val_drop_last=False, shuffle_train=False, pin_memory=True, num_workers=0, persistent_workers=True): if (num_workers == 0): persistent_workers = False if (batch_size is None): batch_size = len(dat...
def test_dataset_wrapper(): CustomDataset.load_annotations = MagicMock() CustomDataset.__getitem__ = MagicMock(side_effect=(lambda idx: idx)) dataset_a = CustomDataset(ann_file=MagicMock(), pipeline=[], test_mode=True, img_prefix='') len_a = 10 cat_ids_list_a = [np.random.randint(0, 80, num).tolist(...
def test_pickle_simple_callable(): assert (m.simple_callable() == ) if env.PYPY: serialized = pickle.dumps(m.simple_callable) deserialized = pickle.loads(serialized) assert (deserialized() == ) else: with pytest.raises(TypeError) as excinfo: pickle.dumps(m.simple_...
def _prepare_args(kwargs, create_keys, run_keys, fit_keys, backend): create_kwargs = _filter_tuner_args(kwargs, create_keys) run_kwargs = _filter_tuner_args(kwargs, run_keys) fit_kwargs = _filter_tuner_args(kwargs, fit_keys) sampler_type = create_kwargs.get('sampler', None) if sampler_type: ...
def trigger_nets() -> None: with Timer(as_ms=True) as t: from src import networks logger.debug(f'Triggered registry networks in {t.elapsed}ms...')
_grad() def LPIPS(rgb, rgb_gt): rgb = torch.moveaxis(rgb, (- 1), 0)[(None, ...)] rgb_gt = torch.moveaxis(rgb_gt, (- 1), 0)[(None, ...)] with warnings.catch_warnings(): warnings.simplefilter('ignore') lpips = _LPIPS(net='alex', verbose=False).cpu() return float(lpips(rgb, rgb_gt, normaliz...
def get_dynamic_gnn_methods(): gnn_list = ['GCRN', 'EvolveGCN', 'VGRNN', 'CTGCN-C', 'CTGCN-S'] return dict(zip(gnn_list, np.ones(len(gnn_list), dtype=np.int)))
def basic_bn_stem(): return nn.Sequential(OrderedDict([('conv1', nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)), ('bn1', mynn.AffineChannel2d(64)), ('relu', nn.ReLU(inplace=True)), ('maxpool', nn.MaxPool2d(kernel_size=3, stride=2, padding=1))]))
def test_add_batch_none_inserted(data): add_info = data.archive_with_elite.add(solution=([[1, 2, 3]] * 4), objective=[(data.objective - 1) for _ in range(4)], measures=[data.measures for _ in range(4)]) assert (add_info['status'] == 0).all() assert np.isclose(add_info['value'], (- 1.0)).all() assert_arc...
class DirDecoder(nn.Module): def __init__(self): super(DirDecoder, self).__init__() self.conv_inputs = utils.GraphConv1x1(3, 128, batch_norm=None) self.conv_noise = utils.GraphConv1x1(100, 128, batch_norm=None) self.num_layers = 5 for i in range(self.num_layers): ...
def make_cseg_image_name(id: int, extension: str='.png') -> str: return (('image.%06d.cseg' % id) + extension)
def compute_sim_matrix(model, data_loader, **kwargs): k_test = kwargs.pop('k_test') metric_logger = MetricLogger(delimiter=' ') header = 'Evaluation:' logging.info('Computing features for evaluation...') start_time = time.time() texts = data_loader.dataset.text num_text = len(texts) tex...
def is_uncovered_api(api): covered_api_list = load_data(join(root_dir, 'logs', 'covered_api.txt'), multiline=True) covered_api_list = [a.strip() for a in covered_api_list] return (api.strip() not in covered_api_list)
def test_digits_sqrt_stochastic_sparse(): model = FeatureBasedSelection(100, 'sqrt', optimizer='stochastic', random_state=0) model.fit(X_digits_sparse) assert_array_equal(model.ranking, digits_sqrt_stochastic_ranking) assert_array_almost_equal(model.gains, digits_sqrt_stochastic_gains, 4) assert_arr...
class RandomResizedCrop(transforms.RandomResizedCrop): def __init__(self, size: Union[(int, Iterable[int])], scale: Iterable[float]=[0.08, 1.0], ratio: Iterable[float]=[(3 / 4), (4 / 3)], interpolation: Union[(str, InterpolationMode)]='bilinear', antialias: bool=True, **kwargs) -> None: if (type(interpolati...
def check_syntax(sandbox_dir): models = Path('../benchmarks').rglob('*.[iI][mM][iI]') count = 0 error_models = [] for model in models: print((model.name + ' - check syntax')) print('') result = subprocess.run(['imitator', '-mode', 'checksyntax', model.absolute()], cwd=sandbox_dir...
('/evaluation/systems/', methods=['GET']) def system_list(): return jsonify({'success': True, 'systems': general_db.get_systems(g.user)})
def preprocess_date_understanding(path, shuffle_choices_seed=None): if (shuffle_choices_seed is not None): return preprocess_bigbench_choice(path, n=369, name='date_understanding', shuffle_choices=True, shuffle_choices_seed=shuffle_choices_seed) else: return preprocess_bigbench_choice(path, n=36...
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): assert (not bias) super(DeformConv, self).__init__() self.with_bias = bias assert ((in_channels % groups) == 0), 'in_ch...
class TFLayoutLMv3Model(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class DebertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = DebertaTokenizer test_rust_tokenizer = True rust_tokenizer_class = DebertaTokenizerFast def setUp(self): super().setUp() vocab = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'G', 'Gl', 'Gn', '...
def batch_it(seq, num=1): out = [] for item in seq: if (len(out) == num): (yield out) out = [] out.append(item) if len(out): (yield out)
def _make_scratch_csm(scratch, in_channels, cout, expand): scratch.layer3_csm = FeatureFusionBlock(in_channels[3], nn.ReLU(False), expand=expand, lowest=True) scratch.layer2_csm = FeatureFusionBlock(in_channels[2], nn.ReLU(False), expand=expand) scratch.layer1_csm = FeatureFusionBlock(in_channels[1], nn.ReL...
def get_sparsity_ratio(pruners, model): pattern_sparsity_cnt = 0 element_sparsity_cnt = 0 if hasattr(model, 'model'): model = model.model for pruner in pruners: if ('MultiheadAttentionPruner' in type(pruner).__name__): logger.info('Calculate multihead-attention sparsity') ...
def patch_llama_for_dynamic_yarn_rotary_embeddings(model, original_max_position_embeddings, finetuned): from .LlamaDynamicYaRNScaledRotaryEmbedding import LlamaDynamicYaRNScaledRotaryEmbedding for each in model.model.layers: each.self_attn.rotary_emb = LlamaDynamicYaRNScaledRotaryEmbedding(each.self_att...
.slow def test_vmc_loop_logging(caplog): nburn = 4 nepochs = 13 nsteps_per_param_update = 10 fixed_metrics = {'energy': 1.0, 'energy_noclip': 2.5, 'variance': 3.0, 'variance_noclip': np.pi} def update_param_fn(params, data, optimizer_state, key): return (params, data, optimizer_state, fixed_...
_REGISTRY.register() def resnet101(norm_layer=nn.BatchNorm2d): num_block = [3, 4, 23, 3] return ResNetV1(BottleneckV1b, num_block, norm_layer=norm_layer)
def main(): parser = argparse.ArgumentParser(description='Neural Solution') parser.add_argument('action', choices=['start', 'stop', 'cluster'], help='start/stop/management service') parser.add_argument('--hostfile', default=None, help='start backend serve host file which contains all available nodes') p...
class PNASNetTest(tf.test.TestCase): def testBuildLogitsLargeModel(self): batch_size = 5 (height, width) = (331, 331) num_classes = 1000 inputs = tf.random_uniform((batch_size, height, width, 3)) tf.train.create_global_step() with slim.arg_scope(pnasnet.pnasnet_large_...
class MultimodalDecoder(nn.Module): def __init__(self, embed_dim, future_steps) -> None: super().__init__() self.embed_dim = embed_dim self.future_steps = future_steps self.multimodal_proj = nn.Linear(embed_dim, (6 * embed_dim)) self.loc = nn.Sequential(nn.Linear(embed_dim, 2...
def primaldual(y, OpA, OpW, c0, eta, y0=None, iter=20, sigma=0.5, tau=0.5, theta=1.0, silent=False, report_pd_gap=False): if (y0 is None): y0 = torch.zeros_like(y) def F(_y): return (((_y - y).norm(p=2, dim=(- 1)) > (eta + 0.01)) * 10000.0) def Fstar(_y): return ((eta * _y.norm(p=2, ...
_name('slim_eval') def test_slim_eval_large_inputdim(benchmark): slim_eval_runner(benchmark, input_dim=100)
def scan_imageid_and_annoid(sequence_dirs): image_start_end_ids = [] anno_start_end_ids = [] (start_image_id, start_anno_id) = (0, 0) for sequence_dir in sequence_dirs: sequence_gt_info_path = osp.join(sequence_dir, 'scene_gt_info.json') with open(sequence_gt_info_path, 'r') as f: ...
class PFRNN_Policy(Policy): def __init__(self, action_space, nr_inputs, observation_type, action_encoding, cnn_channels, h_dim, encoder_batch_norm, policy_batch_norm, batch_size, resample, dropout=0.1, num_particles=10, num_features=256, particle_aggregation='mgf'): super().__init__(action_space, encoding_d...
class TestAverageCheckpoints(unittest.TestCase): def test_average_checkpoints(self): params_0 = collections.OrderedDict([('a', torch.DoubleTensor([100.0])), ('b', torch.FloatTensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])), ('c', torch.IntTensor([7, 8, 9]))]) params_1 = collections.OrderedDict([('a', tor...
class Net(nn.Module): def __init__(self, bias=True): super(Net, self).__init__() self.linear = nn.Linear(30, 50, bias=bias) self.linear2 = nn.Linear(50, 10, bias=bias) def forward(self, x): x = self.linear(x) x = self.linear2(x) return x
def make_figure1_data(): D = util.read_data_single(('%s/choices/%s.csv' % (util.data_path, 'g-1.00-0.50-u-00'))) step = 0.01 scores_uniform = np.array((1.0 / D.groupby('choice_id')['y'].aggregate(len))) with open('../results/fig1_data.csv', 'w') as f: writer = csv.writer(f) writer.writer...
() ('--src', help='Source directory with JPEG images.', metavar='PATH') ('--dest', help='Directory in which to write modified images.', metavar='PATH') ('--mpp', help='Microns per pixel.', metavar=float, required=True) def main(src, dest, mpp): source_jpgs = [f for f in os.listdir(src) if (sf.util.path_to_ext(f).lo...