code
stringlengths
101
5.91M
def sample_optional_tags(optional, sample_probs): sampled = [] if (len(optional) > 0): n_sample = np.random.choice([0, 1], 1, p=sample_probs[:2])[0] n_sample = min(n_sample, len(optional)) sampled = random.sample(optional, n_sample) return sampled
.parametrize('ctx, func_name', ctxs) .parametrize('inshape', [(5, 8, 16), (10, 16, 32)]) .parametrize('w0_init, w_init, b_init', [(None, None, None), (I.ConstantInitializer(), I.ConstantInitializer(), I.ConstantInitializer()), (True, True, True)]) .parametrize('num_layers, dropout, bidirectional, with_bias', [(1, 0.0, ...
def simple_log(spark): date = datetime(2019, 1, 1) return spark.createDataFrame(data=[[0, 0, date, 1.0], [1, 0, date, 1.0], [2, 1, date, 2.0], [1, 1, date, 2.0], [2, 2, date, 2.0], [0, 2, date, 2.0], [3, 0, date, 2.0]], schema=INTERACTIONS_SCHEMA)
(scope='module') def larger_control_flow_graph() -> CFG: graph = CFG(MagicMock()) entry = ProgramGraphNode(index=(- sys.maxsize)) n_1 = ProgramGraphNode(index=1) n_2 = ProgramGraphNode(index=2) n_3 = ProgramGraphNode(index=3) n_5 = ProgramGraphNode(index=5) n_100 = ProgramGraphNode(index=100...
def read_as_dict(filename, split=','): rows = [] with open(filename, 'r') as csvfile: for row in csv.DictReader(csvfile, delimiter=','): rows.append(row) return rows
def import_model(opt): model_name = ('SYE' + opt.model_task.upper()) if (opt.model_task == 'sr'): model_name += 'X{}'.format(opt.config['model']['scale']) kwargs = {'channels': opt.config['model']['channels']} if (opt.config['model']['type'] == 're-parameterized'): model_name += 'NetS' ...
def taylor_series_at_1(N): coeffs = [] with mpmath.workdps(100): coeffs.append((- mpmath.euler)) for n in range(2, (N + 1)): coeffs.append(((((- 1) ** n) * mpmath.zeta(n)) / n)) return coeffs
def build_val_dataset_for_pt(is_train, args): transform = build_transform(is_train, args) print('Transform = ') if isinstance(transform, tuple): for trans in transform: print(' - - - - - - - - - - ') for t in trans.transforms: print(t) else: for t ...
def test_expected_calibration_error(): pp = [0.1, 0.5, 0.8, 0.2] ac = [0.1, 0.3, 0.5, 0.8, 0.9] co = [0.15, 0.3, 0.55, 0.75, 0.92] with pytest.raises(ValueError): expected_calibration_error(prediction_probabilities=pp, accuracy=ac, confidence=co) with pytest.raises(ValueError): expec...
class Cylinder(): def __init__(self, center, axis, radius, texture): (x, y, z) = center self._center = (float(x), float(y), float(z)) (x, y, z) = axis self._axis = (float(x), float(y), float(z)) self._radius = float(radius) self._texture = texture def str(self): ...
def _initialize_control_variable(ocp: optimal_control.OptimalControlProblem, u: Optional[List[fenics.Function]]) -> List[fenics.Function]: if (u is None): u = [] for j in range(len(ocp.db.function_db.controls)): temp = fenics.Function(ocp.db.function_db.control_spaces[j]) tem...
class NewTypeMixin(DataDocumenterMixinBase): def should_suppress_directive_header(self) -> bool: return (inspect.isNewType(self.object) or super().should_suppress_directive_header()) def update_content(self, more_content: StringList) -> None: if inspect.isNewType(self.object): if (se...
(hookwrapper=True) def pytest_runtest_call(item): hooks = item.config.pluginmanager.hook settings = _get_item_settings(item) is_timeout = ((settings.timeout is not None) and (settings.timeout > 0)) if (is_timeout and (settings.func_only is True)): hooks.pytest_timeout_set_timer(item=item, settin...
def parse_assignment(alist): assert (len(alist) == 3) op = alist[0] head = parse_expression(alist[1]) exp = parse_expression(alist[2]) if (op == '='): return pddl.Assign(head, exp) elif (op == 'increase'): return pddl.Increase(head, exp) else: assert False, 'Assignmen...
def z_score_filter(z_threshold: float, bins: np.ndarray, counts: np.ndarray): bins = np.copy(bins) counts = np.copy(counts) bins = bins[:(- 1)] mu = (np.sum((bins * counts)) / np.sum(counts)) sigma = np.sqrt((np.sum((np.power((bins - mu), 2.0) * counts)) / np.sum(counts))) z_score = (np.abs((bin...
def frequencies(source, size_mb=None, sets=None): if (size_mb and (not bounter_is_installed)): size_mb = None source_is_generator = (isinstance(source, GeneratorType) or callable(source)) def get_indices(ids): if isinstance(ids, numbers.Integral): return ids if isinstance...
def get_free_gpus() -> Optional[List[int]]: try: free = [] proc = subprocess.Popen('nvidia-smi --query-compute-apps=gpu_uuid --format=csv,noheader,nounits'.split(' '), stdout=subprocess.PIPE) uuids = [s.strip() for s in proc.communicate()[0].decode().split('\n') if s] proc = subproce...
class DistOptimizerHook(OptimizerHook): def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=(- 1)): self.grad_clip = grad_clip self.coalesce = coalesce self.bucket_size_mb = bucket_size_mb def after_train_iter(self, runner): runner.optimizer.zero_grad() runne...
class TOMDataset(DatasetBase): def __getitem__(self, index): cloth_name = self.cloth_names[index] cloth_im = Image.open(os.path.join(self.data_path, 'warp-cloth', cloth_name)) cloth_tensor = self.transform(cloth_im) cloth_mask_im = Image.open(os.path.join(self.data_path, 'warp-cloth-...
def read_parsing_evaluation(evaluation_file_path): try: with open(evaluation_file_path, 'r') as f: lines = f.readlines() las = float(lines[0].split('=')[1].strip('% \n')) uas = float(lines[1].split('=')[1].strip('% \n')) acc = float(lines[2].split('=')[1].stri...
class PolicyNetwork(): def __init__(self, args): self.inputs = tf.placeholder(tf.float32, [args.batch_size, args.state_dim], name='inputs') self.targets = tf.placeholder(tf.float32, [args.batch_size, args.action_dim], name='targets') self.learning_rate = tf.Variable(0.0, trainable=False, nam...
class Partition8(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[encoder]/T5Block[21]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[22]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5Block[23]', 'T5ForConditionalGeneration/T5Stack[encoder]/T5LayerNorm[final_layer_norm]', 'T5ForConditional...
def fit_predict_balanced_model(X_train, y_train, X_test, y_test): model = make_model(X_train.shape[1]) training_generator = BalancedBatchGenerator(X_train, y_train, batch_size=1000, random_state=42) model.fit(training_generator, epochs=5, verbose=1) y_pred = model.predict(X_test, batch_size=1000) re...
class TestCrossProtoCalls(unittest.TestCase): def testSimple(self): net = caffe2_pb2.NetDef() meta = metanet_pb2.MetaNetDef() meta.nets.add(key='foo', value=net)
def get_beamline(): distance0 = 300.0 distance1 = 630.0 distance = (distance0 + distance1) f_hfm = 3.0 f_vfm = 1.9 distance_hfm_vfm = (f_hfm - f_vfm) distance_foc = (1.0 / ((1.0 / f_vfm) + (1.0 / (distance + distance_hfm_vfm)))) theta_om = 0.0035 theta_kb = 0.0035 om_mirror_lengt...
def configure(conf): cc = (conf.env['COMPILER_CC'] or None) cxx = (conf.env['COMPILER_CXX'] or None) if (not (cc or cxx)): raise Utils.WafError('neither COMPILER_CC nor COMPILER_CXX are defined; maybe the compiler_cc or compiler_cxx tool has not been configured yet?') try: compiler = com...
.parametrize('n_neighbors, idx_0, idx_1, expected, n_expected', [(1, [[0], [1], [2], [3]], [[4], [5], [6], [7]], {}, 0), (1, [[0], [1], [2], [3]], [[4], [1], [6], [7]], {1: {1}}, 1), (1, [[0], [1], [2], [3]], [[4], [1], [6], [7]], {1: {1}}, 1), (1, [[0], [1], [6], [3]], [[4], [1], [6], [7]], {1: {1}, 2: {6}}, 2), (1, [...
_args('v', 'v', 'v', 'is', 'is', 'is', 'i', 'is', 'i', 'i', 'i', 'i', 'i') def _convolution(g, input, weight, bias, stride, padding, dilation, transposed, output_padding, groups, benchmark, deterministic, cudnn_enabled, allow_tf32): weight_size = weight.type().sizes() args = [input, weight] if ((not sym_hel...
def interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None): if (input.numel() > 0): return torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners=align_corners) def _check_size_scale_factor(dim): if ((size is None) and (scale_factor is None))...
def load_saved_models(dir): file_paths = os.listdir(dir) records = {} for file_path in file_paths: if ('Java_Graph2Search' in file_path): with open(os.path.join(dir, file_path, 'config.json'), 'r') as f: config = json.load(f) set_random_seed(config['random_see...
def batch_logdet_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): dy = grad_inputs[0] x0 = inputs[0] raise NotImplementedError('batch_logdet_backward is not implemented.')
def train(writer, logger): model_cfg = get_config(args.model_cfg) train_dataset = DatasetEgobody(cfg=model_cfg, train=True, device=device, data_root=args.dataset_root, dataset_file=os.path.join(args.dataset_root, 'annotation_egocentric_smpl_npz/egocapture_train_smpl.npz'), add_scale=args.add_bbox_scale, do_augm...
def find_element_by_ref(ref, elements): for dom_element in elements: if (dom_element.ref == ref): return dom_element raise ValueError('Invalid ref: {}'.format(ref))
class FiniteJoinSemilattice(FinitePoset): Element = JoinSemilatticeElement _desc = 'Finite join-semilattice' def join_matrix(self): return self._hasse_diagram.join_matrix() def join(self, x, y=None): jn = self._hasse_diagram.join_matrix() if (y is not None): (i, j) = ...
class QueryOnTriplaneGradFeature(PythonFunction): def __init__(self, ctx, min_, max_, boundary_check=False, G=None): super(QueryOnTriplaneGradFeature, self).__init__(ctx) self._min = min_ self._max = max_ self._boundary_check = boundary_check self._G = G def name(self): ...
class DataSplitter(pl.LightningDataModule): data_loader_cls = AnnDataLoader def __init__(self, adata_manager: AnnDataManager, train_size: float=0.9, validation_size: Optional[float]=None, shuffle_set_split: bool=True, load_sparse_tensor: bool=False, pin_memory: bool=False, **kwargs): super().__init__() ...
def get_focused_table(table, ref_table, win_ratio): focused_table = copy.deepcopy(table) win_size = int((win_ratio * len(ref_table.data))) focused_table.data = focused_table.data.tail(win_size).reset_index(drop=True) focused_table.parse_columns() return focused_table
def test_lad_head_loss(): class mock_skm(): def GaussianMixture(self, *args, **kwargs): return self def fit(self, loss): pass def predict(self, loss): components = np.zeros_like(loss, dtype=np.long) return components.reshape((- 1)) def ...
class SecStr8(Alphabet): def __init__(self): chars = b'HBEGITS ' encoding = np.arange(len(chars)) super(SecStr8, self).__init__(chars, encoding, missing=255)
def _fix_real_abs_gt_1(x): x = asarray(x) if any((isreal(x) & (abs(x) > 1))): x = _tocomplex(x) return x
def getGPUbatchSize(num_gpus, batch_size): nf = int(noremDiv(batch_size, num_gpus)) nl = (batch_size - (nf * (num_gpus - 1))) return np.cumsum((([0] + ([nf] * (num_gpus - 1))) + [nl]))
def main_worker(gpu, argss): global args args = argss torch.cuda.set_device(gpu) rank = ((args.nr * args.gpus) + gpu) args.rank = rank exp_name = '/imagenet_pretrain' args.save_path = (args.save_path + exp_name) args.snapshot_root = (args.save_path + '/snapshot/') args.log_root = (ar...
def plot_heatmap(model_dir, name, features, labels, num_classes): (features_sort, _) = utils.sort_dataset(features, labels, classes=num_classes, stack=False) features_sort_ = np.vstack(features_sort) sim_mat = np.abs((features_sort_ features_sort_.T)) (fig, ax) = plt.subplots(figsize=(7, 5), sharey=Tru...
class PreBottleneckX(nn.Module): expansion = 4 bias = False def __init__(self, inplanes, planes, baseWidth, cardinality, stride=1, ptype='preact'): super(PreBottleneckX, self).__init__() D = math.floor(((planes * baseWidth) / 64.0)) if (ptype != 'no_preact'): self.preact ...
def compute_tensor_method(*, target: Target) -> Callable[([NativeFunction], Optional[str])]: _native_function def go(f: NativeFunction) -> Optional[str]: if (Variant.method not in f.variants): return None assert (not f.func.is_out_fn()) assert (len(f.func.arguments) > 0) ...
def get_root_logger(log_file=None, log_level=logging.INFO): logger = get_logger(__name__.split('.')[0], log_file, log_level) return logger
def plot_num_components_undirected(G_times, fname): max_time = len(G_times) t = list(range(0, max_time)) num_connected_components = [] for G in G_times: G = G.to_undirected() num_connected_components.append(nx.number_connected_components(G)) plt.rcParams.update({'figure.autolayout': ...
def make_command(params, unique_id): params['savedir'] = ('./log/%s/baselines-%s' % (datetime.date.today().strftime('%y-%m-%d'), unique_id)) params = itertools.chain(*[(('--%s' % k), str(v)) for (k, v) in params.items()]) return list(params)
def first_sunday_on_or_after(dt): days_to_go = (6 - dt.weekday()) if days_to_go: dt += timedelta(days_to_go) return dt
def warning(msg, warning_type=UserWarning, stacklevel=1, print_stack=True): if (not is_logging_effective('warn')): return if print_stack: msg += f''' {get_traceback(stacklevel)}''' warnings.warn((((Fore.YELLOW + Style.BRIGHT) + msg) + Style.RESET_ALL), warning_type)
class Extension(_Extension): def __init__(self, name, sources, *args, **kw): self.py_limited_api = kw.pop('py_limited_api', False) _Extension.__init__(self, name, sources, *args, **kw) def _convert_pyx_sources_to_lang(self): if _have_cython(): return lang = (self.lang...
def recall(pred, target, num_classes): tp = true_positive(pred, target, num_classes).to(torch.float) fn = false_negative(pred, target, num_classes).to(torch.float) out = (tp / (tp + fn)) out[torch.isnan(out)] = 0 return out
def max_pool3d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False) -> Tensor: return complex_fcaller(F.max_pool3d, input, kernel_size, stride, padding, dilation, ceil_mode, return_indices)
class Printable(object): def __init__(self): super().__init__() def print(self, indentation: int=0) -> str: raise NotImplementedError('print not implemented.') def __str__(self) -> str: return self.print(0)
class JBluesNormFactor(ProcessingPlasmaProperty): outputs = ('j_blues_norm_factor',) latex = '\\frac{c time_\\textrm{simulation}}}{4\\pitime_\\textrm{simulation} volume}' def calculate(time_explosion, time_simulation, volume): return ((const.c.cgs * time_explosion) / (((4 * np.pi) * time_simulation)...
def test_attn_agg_constructor_1(): agg = AttentionalAggregator(output_dim=4, bias=True, act=(lambda x: (x + 1))) assert (agg.output_dim == 4) assert agg.has_bias assert (agg.act(2) == 3)
class BR(nn.Module): def __init__(self, nOut): super().__init__() self.bn = nn.BatchNorm3d(nOut, momentum=0.95, eps=0.001) self.act = nn.ReLU(inplace=True) def forward(self, input): output = self.bn(input) output = self.act(output) return output
def check_list(rlms_list, rimgs_list, rmsks_list): (lms_list, imgs_list, msks_list) = ([], [], []) for i in range(len(rlms_list)): flag = 'false' lm_path = rlms_list[i] im_path = rimgs_list[i] msk_path = rmsks_list[i] if (os.path.isfile(lm_path) and os.path.isfile(im_path...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) def test_ceil_double_backward(seed, ctx, func_name): from nbla_test_utils import cap_ignore_region, backward_function_tester rng = np.random.RandomState(seed) inputs = [(rng.randn(2, 3, 4).astype(np.float32) * 2)] backward_function_tester(...
class History(Callback): def on_train_begin(self, logs=None): self.epoch = [] self.history = {} def on_epoch_end(self, epoch, logs=None): logs = (logs or {}) self.epoch.append(epoch) for (k, v) in logs.items(): self.history.setdefault(k, []).append(v)
def add_token(token_list, word, token): if ((token is None) and isinstance(word.id, int)): raise AssertionError("Only expected word w/o token for 'extra' words") query_token = token_list.add() query_token.word = word.text query_token.value = word.text if (word.lemma is not None): que...
def batch_mat_mul(model, blob_in, blob_out, enable_tensor_core=False, **kwargs): if enable_tensor_core: kwargs['engine'] = 'TENSORCORE' return model.net.BatchMatMul(blob_in, blob_out, **kwargs)
def test_yolov3_head_onnx_export(): yolo_model = yolo_config() s = 128 img_metas = [{'img_shape_for_onnx': torch.Tensor([s, s]), 'img_shape': (s, s, 3), 'scale_factor': np.ones(4), 'pad_shape': (s, s, 3)}] yolo_head_data = 'yolov3_head_get_bboxes.pkl' pred_maps = mmcv.load(osp.join(data_path, yolo_h...
class FileLoaderIterDataPipe(IterDataPipe[Tuple[(str, IOBase)]]): def __init__(self, datapipe: Iterable[str], mode: str='b', length: int=(- 1)): super().__init__() self.datapipe: Iterable = datapipe self.mode: str = mode if (self.mode not in ('b', 't', 'rb', 'rt', 'r')): ...
def FGCNN(linear_feature_columns, dnn_feature_columns, conv_kernel_width=(7, 7, 7, 7), conv_filters=(14, 16, 18, 20), new_maps=(3, 3, 3, 3), pooling_width=(2, 2, 2, 2), dnn_hidden_units=(256, 128, 64), l2_reg_linear=1e-05, l2_reg_embedding=1e-05, l2_reg_dnn=0, dnn_dropout=0, seed=1024, task='binary'): if (not (len(...
def _get_args_from_config(from_config_func, *args, **kwargs): signature = inspect.signature(from_config_func) if (list(signature.parameters.keys())[0] != 'cfg'): raise TypeError(f"{from_config_func.__self__}.from_config must take 'cfg' as the first argument!") support_var_arg = any(((param.kind in [...
def test_scar(): n_latent = 5 adata = synthetic_iid() adata.X = scipy.sparse.csr_matrix(adata.X) SCAR.setup_anndata(adata) _ = SCAR.get_ambient_profile(adata, adata, prob=0.0, iterations=1, sample=100) model = SCAR(adata, ambient_profile=None, n_latent=n_latent) model.train(1, check_val_ever...
def test(): x0s = [[2, 0.5], [8, 0.5], [2, 3.5], [8, 3.5]] wall_half_width = 0.05 A = np.array([[(- 1), 0], [1, 0], [0, (- 1)], [0, 1]]) walls = [] walls.append(np.array([0, 0, 0, 4], dtype=np.float64)) walls.append(np.array([10, 10, 0, 4], dtype=np.float64)) walls.append(np.array([0, 10, 0,...
def parse_args(): parser = argparse.ArgumentParser(description='Train a vanilla XGBoost GBDT model.') parser.add_argument('--train', '--train_data', type=str, help='train data file name.', required=True) parser.add_argument('--test', '--test_data', type=str, help='test data file name.', required=True) p...
def test_kwargs_with_default(): def kwarg(A: dace.float64[20], kw: dace.float64[20]=np.ones([20])): A[:] = (kw + 1) A = np.random.rand(20) kwarg(A) assert np.allclose(A, 2.0) kw = np.random.rand(20) kwarg(A, kw) assert np.allclose(A, (kw + 1))
def tr_interior_point(fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac, x0, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0, jac_eq0, stop_criteria, enforce_feasibility, xtol, state, initial_barrier_parameter, initial_tolerance, initial_penalty, initial_trust_radius, factorization_method): BOUNDARY_PARAMETE...
def add_code_sample_docstrings(*docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None, mask=None): def docstring_decorator(fn): model_class = fn.__qualname__.split('.')[0] is_tf_class = (model_class[:2] == 'TF') doc_kwargs = dict(model_class=model_class, tokenize...
class QuarterOfYear(TimeFeature): def __call__(self, idx: pd.DatetimeIndex) -> np.ndarray: return self.process((idx.quarter - 1)) def _max_val(self): return 3.0
def inputConversion(): try: user_input = input('Enter a number: ') user_input = int(user_input) except ValueError: logging.error('Invalid input') return user_input
_torch class CTRLModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): all_model_classes = ((CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()) all_generative_model_classes = ((CTRLLMHeadModel,) if is_torch_available() else ()) test_pruning = True ...
def is_FreeMonoid(x): if isinstance(x, FreeMonoid): return True from sage.monoids.indexed_free_monoid import IndexedFreeMonoid return isinstance(x, IndexedFreeMonoid)
def stp(s, ts: torch.Tensor): if isinstance(s, np.ndarray): s = torch.from_numpy(s).type_as(ts) extra_dims = ((1,) * (ts.dim() - 1)) return (s.view((- 1), *extra_dims) * ts)
_native_function def compute_registration_declarations(f: NativeFunction) -> str: name = dispatcher.name(f.func) returns_type = dispatcher.returns_type(f.func.returns) args = dispatcher.arguments(f.func) args_str = ', '.join(map(str, args)) dispatch = (f.dispatch is not None) math = (dispatch an...
def classification_eval(model, data_loader, limit=None): logging.info(f'Start classification evaluation') correct = 0 total = 0 device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu')) model.to(device) model.eval() with torch.no_grad(): for data in tqdm(data_loader, de...
class SlavePipe(_SlavePipeBase): def run_slave(self, msg): self.queue.put((self.identifier, msg)) ret = self.result.get() self.queue.put(True) return ret
def subscript_to_ast_slice(node, without_array=False): if isinstance(node, ast.Name): (result_arr, result_slice) = (node.id, None) return (result_slice if without_array else (result_arr, result_slice)) if (not isinstance(node, ast.Subscript)): raise TypeError('AST node is not a subscript...
def bool_flag(s): FALSY_STRINGS = {'off', 'false', '0'} TRUTHY_STRINGS = {'on', 'true', '1'} if (s.lower() in FALSY_STRINGS): return False elif (s.lower() in TRUTHY_STRINGS): return True else: raise argparse.ArgumentTypeError('invalid value for a boolean flag')
def register_bdd_context(name, dirname, split, class_names=BDD_SEM): DatasetCatalog.register(name, (lambda : load_bdd_instances(name, dirname, split, class_names))) MetadataCatalog.get(name).set(stuff_classes=class_names, dirname=dirname, split=split, ignore_label=[255], thing_dataset_id_to_contiguous_id={}, cl...
def deps_from_tsv(infile, limit=None): res = [] for (i, d) in enumerate(csv.DictReader(open(infile), delimiter='\t')): if ((limit is not None) and (i >= limit)): break res.append({x: (int(y) if y.isdigit() else y) for (x, y) in d.items()}) return res
class PathAlgebra(CombinatorialFreeModule): Element = PathAlgebraElement def __init__(self, k, P, order='negdegrevlex'): from sage.categories.graded_algebras_with_basis import GradedAlgebrasWithBasis self._quiver = P.quiver() self._semigroup = P self._ordstr = order super...
.gpu def test_relu(): _config() def halftest(A: dace.float16[N]): out = np.ndarray([N], dace.float16) for i in dace.map[0:N]: with dace.tasklet: (a << A[i]) (o >> out[i]) o = (a if (a > dace.float16(0)) else dace.float16(0)) ret...
def yaml_load(filename): with open(filename, 'r') as f: yaml_data = yaml.load(f) return yaml_data
def add_eval_lm_args(parser): group = parser.add_argument_group('LM Evaluation') add_common_eval_args(group) gen_parser_from_dataclass(group, EvalLMConfig())
def test_record_int32(): t = RecordType([NumpyType('int32')], None) assert (str(parser.parse(str(t))) == str(t))
def require_version_core(requirement): hint = "Try: pip install transformers -U or pip install -e '.[dev]' if you're working with git main" return require_version(requirement, hint)
def groupby_first_item(lst): groups = defaultdict(list) for (first, *rest) in lst: rest = (rest[0] if (len(rest) == 1) else rest) groups[first].append(rest) return groups
def test_example_config_file(): parser = ConfigParser() parser.read('orvara/tests/config.ini') assert (len(parser.items('data_paths')) == 8) assert (len(parser.items('mcmc_settings')) == 6) assert (parser.getint('mcmc_settings', 'nthreads') == 1) assert parser.getboolean('mcmc_settings', 'use_ep...
def get_all_epoch(): d = get_ckpt_dir() names = (os.listdir(d) if os.path.exists(d) else []) if (len(names) == 0): return [0] epochs = [int(name.split('.')[0]) for name in names] return epochs
def _get_samples(cp, size, signed=True): for i in range(_sample_count(cp, size)): (yield _get_sample(cp, size, i, signed))
class BertPlain(nn.Module): def __init__(self, num_tokens, num_labels, dropout): super().__init__() self.bert = BertModel.from_pretrained('bert-base-cased') self.bert.resize_token_embeddings(num_tokens) self.dropout = nn.Dropout(dropout) self.classifier = nn.Linear(self.bert....
def conv_bn(inp, oup, stride): return nn.Sequential(nn.Conv2d(inp, oup, 3, stride, 1, bias=False), SynchronizedBatchNorm2d(oup), nn.ReLU6(inplace=True))
def main(args): if (args.intfeat != None): infile = json.load(open(args.intfeat, 'r')) int_indices = infile['indices'] if (args.model_type == 'cln'): cln_model = torch.load(args.model_path) print('cln model loaded from', args.model_path) elif (args.model_type == 'xgboost'): ...
def locate_model(name): if os.path.exists(name): return name elif (('/' not in name) and ('.' not in name)): import nltk.data try: nltk_loc = nltk.data.find(f'models/{name}') return nltk_loc.path except LookupError as e: arg = e.args[0].replace...
class Sets(Category_singleton): def super_categories(self): return [SetsWithPartialMaps()] def _call_(self, X, enumerated_set=False): if (enumerated_set and (type(X) in (tuple, list, range))): from sage.categories.enumerated_sets import EnumeratedSets return EnumeratedSet...
def create_optimizer(opt, model): optimizer = find_optimizer_using_name(opt.optimizer) instance = optimizer(model) return instance