code
stringlengths
101
5.91M
def _require_without_generator(value, name): if (value is not None): return value else: raise ValueError(f"{name}: expected a value for 'n_samples', 'input_dim', and 'multiplicity' when 'generator' is not provided, found {name}=None.")
_utils.test(require=ti.extension.quant, debug=True) def test_1D_quant_array_negative(): N = 4 qi7 = ti.types.quant.int(7) x = ti.field(dtype=qi7) ti.root.quant_array(ti.i, N, max_num_bits=32).place(x) def assign(): for i in range(N): assert (x[i] == 0) x[i] = (- i) ...
def _model_to_graph(model, args, verbose=False, input_names=None, output_names=None, operator_export_type=OperatorExportTypes.ONNX, example_outputs=None, _retain_param_name=False, do_constant_folding=True, _disable_torch_constant_prop=False, fixed_batch_size=False, training=None, use_new_jit_passes=False, dynamic_axes=...
def __build_pyramid(models, features): return [__build_model_pyramid(n, m, features) for (n, m) in models]
.parametrize('dtype,device', product([torch.float], devices)) def test_knn_graph_large(dtype, device): x = torch.randn(1000, 3, dtype=dtype, device=device) edge_index = knn_graph(x, k=5, flow='target_to_source', loop=True) tree = scipy.spatial.cKDTree(x.cpu().numpy()) (_, col) = tree.query(x.cpu(), k=5)...
def calculate_bow_node_edge_feats(data_write_dir, rel2idx): print('[INFO] Starting BOW Feature Calculation For Node Edge Features...') scan_ids = os.listdir(osp.join(data_write_dir, 'data')) scan_ids = sorted([scan_id[:(- 4)] for scan_id in scan_ids]) idx_2_rel = {idx: relation_name for (relation_name, ...
def make_fullrank_matrices_with_distinct_singular_values(*shape, device, dtype): assert (shape[(- 1)] == shape[(- 2)]) t = make_tensor(shape, device=device, dtype=dtype) (u, _, vh) = torch.linalg.svd(t, full_matrices=False) real_dtype = (t.real.dtype if t.dtype.is_complex else t.dtype) s = torch.ara...
def parse_args(args=None): parser = argparse.ArgumentParser(description='Training and Testing Knowledge Graph Embedding Models', usage='train.py [<args>] [-h | --help]') parser.add_argument('--cuda', action='store_true', help='use GPU') parser.add_argument('--do_train', action='store_true') parser.add_a...
def degree_lowest_rational_function(r, x): from sage.rings.fraction_field import FractionField F = FractionField(r.parent()) r = F(r) f = r.numerator().polynomial(x) g = r.denominator().polynomial(x) return (f.valuation() - g.valuation())
def test_wrap_experiment_name_parameters_none(): _experiment(name_parameters='none') def test_exp(ctxt=None, seed=1): del ctxt del seed with pytest.raises(ValueError, match='wrap_experiment.name_parameters'): test_exp()
def _AllReduceBlobs(blob_names, devices, model, net, rendezvous, use_nccl, max_concurrent_distributed_ops): if ((rendezvous is None) or (rendezvous['num_shards'] <= 1)): _AllReduceBlobsSingleHost(blob_names, devices, model, net, use_nccl) else: _AllReduceBlobsDistributed(blob_names, devices, mod...
def test_unknown_language_tokenizer(unknown_language_name): base_pipe = stanza.Pipeline('en', dir=TEST_MODELS_DIR, processors='tokenize', download_method=None) tokenize_processor = base_pipe.processors['tokenize'] pipe = stanza.Pipeline(unknown_language_name, processors='tokenize', allow_unknown_language=Tr...
def unsqueeze_expand_flat_dim0(x, num): return x.unsqueeze(dim=0).expand(num, *(((- 1),) * x.ndim)).reshape((num * x.size(0)), *x.size()[1:])
class SingleThreadASGIRunner(SingleThreadRunner): def _execute_impl(self, results: TestResultSet) -> Generator[(events.ExecutionEvent, None, None)]: (yield from self._run_tests(maker=self.schema.get_all_tests, template=asgi_test, settings=self.hypothesis_settings, generation_config=self.generation_config, s...
class BPRLoss(ModelLayer): def __init__(self, model, input_record, name='bpr_loss', **kwargs): super(BPRLoss, self).__init__(model, name, input_record, **kwargs) assert schema.is_schema_subset(schema.Struct(('pos_prediction', schema.Scalar()), ('neg_prediction', schema.List(np.float32))), input_reco...
def load_grid(fname): with open(fname, 'r') as f: rows = f.readlines() outs = [] out = [] for row in rows: if ('#' in row): continue row = row.split() if (len(row) > 0): row = (row[:2] + [''.join(row[2:])]) ...
def get_args(): parser = argparse.ArgumentParser() home = os.path.expanduser('~') source_dir = os.path.join(home, 'data', 'squad') target_dir = os.path.join(home, 'data', 'squad-class') parser.add_argument('-s', '--source_dir', default=source_dir) parser.add_argument('-t', '--target_dir', defaul...
.skipif((not GPUs_available), reason='No GPU is available to test CUDA function') .parametrize(['no_of_packets', 'iterations'], [(200000, 5)]) def test_full_formal_integral(no_of_packets, iterations, config_verysimple, simulation_verysimple): sim = simulation_verysimple formal_integrator_numba = FormalIntegrato...
class MyContextManager(): def __init__(self, seed): self.rng = np.random.default_rng(seed) _blocker def __enter__(self): a = self.rng.integers(1, 10) b = self.rng.integers(1, 10) print(f'Computing LCM of {a} and {b}') return np.lcm(a, b) _blocker def __exit__(...
def plot_transition_matrix(transition_matrix): transition_matrix = validate_numpy_array(transition_matrix) fig = plt.figure(figsize=(20, 20)) ax = sns.heatmap(data=transition_matrix.T, annot=False, cbar=True) ax.set_ylabel('Hidden states') ax.set_xlabel('Time step') ax.set_title('Transition prob...
def get_transformations(mean, std, resize_size, crop_size, mode='train', jit_script=False): if (mode == 'train'): transform = [torchvision.transforms.Resize((resize_size, resize_size)), torchvision.transforms.RandomCrop((crop_size, crop_size)), torchvision.transforms.RandomHorizontalFlip(), torchvision.tran...
def _is_p_power_mod(a, p, N): for (q, e) in N.factor(): v = a.valuation(q) if (v >= e): continue if (v % p): return False aa = (a / (q ** v)) ee = (e - v) if (q != p): if ((q % p) == 1): if ((GF(q)(aa) ** ((q - 1) / ...
def cython_import_all(filename, globals, **kwds): m = cython_import(filename, **kwds) for (k, x) in m.__dict__.items(): if (k[0] != '_'): globals[k] = x
def convert_name(name): mapping = {'conv_3d': 'conv3d', 'batch_norm': 'bn', 'w:0': 'weight', 'b:0': 'bias', 'moving_mean:0': 'running_mean', 'moving_variance:0': 'running_var', 'beta:0': 'bias'} segs = name.split('/') new_segs = [] i = 0 while (i < len(segs)): seg = segs[i] if ('Mixe...
(reason='the class is not fully tested') class Neo4jDirectedBreadthFirstNeighbors(): def __init__(self, graph): if (not isinstance(graph, Neo4jStellarDiGraph)): raise TypeError('Graph must be a Neo4jStellarDiGraph.') self.graph = graph def run(self, nodes=None, n=1, in_size=None, out...
class SideObstacleSpaceInvadersWorld(SpaceInvadersWorld): def create_world(self, parent): super(SideObstacleSpaceInvadersWorld, self).create_world(parent) self.obstacle1 = SideObstacle(world=self, position=(10, (self._height / 2))) parent.add(self.obstacle1, z=1) self.obstacle2 = Sid...
def print_atoms(molname, forcepred, cgbeads, molecule, hbonda, hbondd, partitioning, ringatoms, ringatoms_flat, trial=False): logger.debug('Entering print_atoms()') atomnames = [] beadtypes = [] text = '' for bead in range(len(cgbeads)): try: (smi_frag, wc_log_p, charge) = substr...
_torch _pytesseract class LayoutLMv2FeatureExtractionTest(FeatureExtractionSavingTestMixin, unittest.TestCase): feature_extraction_class = (LayoutLMv2FeatureExtractor if is_pytesseract_available() else None) def setUp(self): self.feature_extract_tester = LayoutLMv2FeatureExtractionTester(self) def f...
def ComputeRHS(dU, rk): if (rk > 0): U[:] = TV.backward(U_hat, U) curl[:] = Curl(U_hat, curl) dU = Cross(U, curl, dU) P_hat[:] = np.sum((dU * K_over_K2), 0, out=P_hat) dU -= (P_hat * K) dU -= ((nu * K2) * U_hat) return dU
def parse_cpu_trace(thread_records): next_id = 0 start_record = None cuda_records = {} functions = [] record_stack = [] string_table = StringTable() def adjusted_time(cuda_record): assert (cuda_record.device() != (- 1)) cuda_time_0 = cuda_records[cuda_record.device()] ...
def graph_transform_dense_mpi(worker_id, meta_graph_def, op_library_path, config): with tf.Graph().as_default() as graph: tf.train.import_meta_graph(meta_graph_def) num_workers = hvd.size() op_to_control_consumer_ops = get_all_control_consumers(graph) trainable_variable_ops = [var.op...
.parametrize(['test_input', 'expected_result'], [(1, 'I'), (5, 'V'), (19, 'XIX'), (556, 'DLVI'), (1400, 'MCD'), (1999, 'MCMXCIX'), (3000, 'MMM')]) def test_int_to_roman(test_input, expected_result): assert (int_to_roman(test_input) == expected_result) with pytest.raises(TypeError): int_to_roman(1.5)
class _ASPP(nn.Module): def __init__(self, in_ch, out_ch, rates): super(_ASPP, self).__init__() for (i, rate) in enumerate(rates): self.add_module('c{}'.format(i), nn.Conv2d(in_ch, out_ch, 3, 1, padding=rate, dilation=rate, bias=True)) for m in self.children(): nn.ini...
def extract_meta_review(category='Video_Games'): processed_dir = f'files/{category}/processed' raw_dir = f'files/{category}/raw' path = f'{raw_dir}/meta_{category}.json.gz' g = gzip.open(path, 'r') asin2meta = {} for l in tqdm(g): line = json.loads(l) meta = {} meta['asin...
class TestRedisStoreHandlerOp(TestCase): def setUp(self): super(TestRedisStoreHandlerOp, self).setUp() self.uuid = (str(uuid.uuid4()) + '/') def tearDown(self): super(TestRedisStoreHandlerOp, self).tearDown() def create_store_handler(self): store_handler = 'store_handler' ...
(nopython=True, cache=True) def _label_switching_(A_indptr, A_indices, A_data, num_nodes, alpha=0.5, itnum_max=50): x = np.ones(num_nodes) deg = np.zeros(num_nodes) Nc = np.zeros(num_nodes) Np = np.zeros(num_nodes) cids = np.arange(num_nodes) for nid in range(num_nodes): deg[nid] = np.su...
class MDPEnvironment(Environment): def __init__(self, **configs): super().__init__(**configs) try: from blackhc import mdp from blackhc.mdp import example as mdp_examples except ImportError as e: Logger.error('please run `pip install -e .[dev]` before usin...
def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True): for node in node.find_all(nodes.Call): if ((not isinstance(node.node, nodes.Name)) or (node.node.name not in gettext_functions)): continue strings = [] for arg in node.args: if (isinsta...
def plot_point(res, marker='o', color=None): ax.plot((512 + res.x[0]), (512 + res.x[1]), marker=marker, color=color, ms=10)
def cal_recall(predicts, labels, user_ids, k): d = {'user': np.squeeze(user_ids), 'predict': np.squeeze(predicts), 'label': np.squeeze(labels)} df = pd.DataFrame(d) user_unique = df.user.unique() recall = [] for user_id in user_unique: user_sdf = df[(df['user'] == user_id)] if (user_...
def get_cursor_pos(window): xpos_value = ctypes.c_double(0.0) xpos = ctypes.pointer(xpos_value) ypos_value = ctypes.c_double(0.0) ypos = ctypes.pointer(ypos_value) _glfw.glfwGetCursorPos(window, xpos, ypos) return (xpos_value.value, ypos_value.value)
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, padding=(0, 1, 1), downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=(1, 1, 1), bias=False) self.bn1 = nn.BatchNorm3d(planes) self.con...
def adjust_learning_rate(optimizer, epoch, gammas, schedule, lr): assert (len(gammas) == len(schedule)), 'length of gammas and schedule should be equal' for (gamma, step) in zip(gammas, schedule): if (epoch >= step): lr = (lr * gamma) else: break for param_group in op...
def validate_cz_dic(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]: if isinstance(df, (pd.Series, dd.Series)): return df.apply(dic.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (column != ''): ...
_utils.test() def test_atomic_min_rvalue_as_frist_op(): def func(): y = ti.Vector([1, 2, 3]) z = ti.atomic_min([3, 2, 1], y) with pytest.raises(ti.TaichiSyntaxError) as e: func() assert ('atomic_min' in str(e.value)) assert ('cannot use a non-writable target as the first operand ...
def test_noconvert_args(msg): a = m.ArgInspector() assert (msg(a.f('hi')) == '\n loading ArgInspector1 argument WITH conversion allowed. Argument value = hi\n ') assert (msg(a.g('this is a', 'this is b')) == '\n loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = t...
def build_tiny_model_summary(results, organization=None, token=None): tiny_model_summary = {} for config_name in results: processors = [key for (key, value) in results[config_name]['processor'].items()] tokenizer_classes = sorted([x for x in processors if (x.endswith('TokenizerFast') or x.endswi...
def load_jsonl(fp: str) -> List[dict]: ret = [] with open(fp, 'r') as inf: for line in inf: content = json.loads(line) ret.append(content) return ret
def convert_to_score(s, binarize_thres=None): v = float(s) if (binarize_thres is not None): v = float((v >= binarize_thres)) return v
class TrainingSetup(): dataset_and_model: Tuple optimizer_with_config: Tuple[(TestOptimizer, Dict)] epochs: int batch_size: Optional[int] = None n_train_samples: Optional[int] = None def dataset(self): return self.dataset_and_model[0] def model(self): model = get_model(self.d...
def register_Ns3RrcDlDcchMessage_methods(root_module, cls): cls.add_constructor([param('ns3::RrcDlDcchMessage const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'bIterator')], is_virtual=True) cls.add_method('PreSerialize', 'void', [], i...
class BaseFileHandler(metaclass=ABCMeta): str_like = True def load_from_fileobj(self, file, **kwargs): pass def dump_to_fileobj(self, obj, file, **kwargs): pass def dump_to_str(self, obj, **kwargs): pass def load_from_path(self, filepath, mode='r', **kwargs): with ope...
class Unflatten(Module): NamedShape = Tuple[Tuple[(str, int)]] __constants__ = ['dim', 'unflattened_size'] dim: Union[(int, str)] unflattened_size: Union[(_size, NamedShape)] def __init__(self, dim: Union[(int, str)], unflattened_size: Union[(_size, NamedShape)]) -> None: super(Unflatten, se...
class TCManager(ABC): def __init__(self, tc, timeout): self._timeout = timeout errcodes = toml.load(pkg_resources.resource_filename(__name__, 'errcodes.toml'))[tc] self._all_errcodes = errcodes['all'] self._inc_errcodes = errcodes['included'] def _build_tc_cmd(self, fpath): ...
def get_padding_value(padding=None, kernel_size=7, stride=1, dilation=1) -> Tuple[(Tuple, bool)]: dynamic = False if (padding is None): padding = (((stride - 1) + (dilation * (kernel_size - 1))) // 2) return (padding, dynamic) if isinstance(padding, str): padding = padding.lower() ...
def _initialize_comm(comm: Optional[MPI.Comm]=None) -> MPI.Comm: if (comm is None): comm = fenics.MPI.comm_world return comm
class VideoDataset(data.Dataset): def __init__(self, root_path, list_file, num_segments=3, new_length=1, modality='RGB', image_tmpl='img_{:05d}.jpg', transform=None, force_grayscale=False, random_shift=True, test_mode=False, num_clips=1): self.root_path = root_path self.list_file = list_file ...
def compute_precision_at_k(targs, preds, k): check_inputs(targs, preds) classes_rel = np.flatnonzero((targs == 1)) if (len(classes_rel) == 0): return 0.0 top_k_pred = np.argsort(preds)[::(- 1)][:k] metric_value = (float(len(np.intersect1d(top_k_pred, classes_rel))) / k) return metric_val...
class HMRHead(BaseModule): def __init__(self, feat_dim, smpl_mean_params=None, npose=144, nbeta=10, ncam=3, hdim=1024, init_cfg=None): super(HMRHead, self).__init__(init_cfg=init_cfg) self.fc1 = nn.Linear((((feat_dim + npose) + nbeta) + ncam), hdim) self.drop1 = nn.Dropout() self.fc2...
def eval_vae(epoch, args, trainer, eval_data): tokenizer = BertTokenizer.from_pretrained(args.bert_model) RawResult = collections.namedtuple('RawResult', ['unique_id', 'start_logits', 'end_logits']) (eval_loader, eval_examples, eval_features) = eval_data all_results = [] qa_results = [] qg_resul...
class lora_sdr_lora_tx(gr.hier_block2): def __init__(self, bw=125000, cr=1, has_crc=True, impl_head=False, samp_rate=250000, sf=7, ldro_mode=2, frame_zero_padd=(2 ** 7)): gr.hier_block2.__init__(self, 'lora_sdr_lora_tx', gr.io_signature(0, 0, 0), gr.io_signature(1, 1, (gr.sizeof_gr_complex * 1))) se...
class Prior(ABC): def __init__(self, config): self.config = config self.device = config['device'] def add_expert(self): pass def record_usage(self, usage, index=None): pass def nl_prior(self, normalize=False): pass
def test_multiple_network(): module_creators = [ModuleCreator(TSTNetNormal(), [(4, 3, 32, 32), (4, 3, 32, 32)]), ModuleCreator(ResUnit(16), [(4, 3, 32, 32)]), ModuleCreator(NestedTestNet(), [(4, 3, 32, 32), (4, 3, 32, 32)])] with nn.graph_def.graph() as g: for module_creator in module_creators: ...
.parametrize('hint,expected', [(list, Instance(TypeInfo(list), (AnyType(),))), (list[int], Instance(TypeInfo(list), (Instance(TypeInfo(int)),))), (list[int], Instance(TypeInfo(list), (Instance(TypeInfo(int)),))), (set[int], Instance(TypeInfo(set), (Instance(TypeInfo(int)),))), (set, Instance(TypeInfo(set), (AnyType(),)...
def parse_win_mp_grid(f): for line in f.readlines(): if ('mp_grid' in line): return parse_line_list(line.split(':')[1], ' ', int)
class NoiseScheduleEDM(): def __init__(self, schedule='linear', betas=None, alphas_cumprod=None, continuous_beta_0=0.1, continuous_beta_1=20.0, dtype=torch.float32): if (schedule not in ['discrete', 'linear']): raise ValueError("Unsupported noise schedule {}. The schedule needs to be 'discrete' ...
class AutoModel(object): def __init__(self): raise EnvironmentError('AutoModel is designed to be instantiated using the `AutoModel.from_pretrained(pretrained_model_name_or_path)` or `AutoModel.from_config(config)` methods.') def from_config(cls, config): for (config_class, model_class) in MODEL_...
class OpenAssistantScenario(Scenario): name = 'open_assistant' description = "The conversation dataset released by LAION's Open Assistant project." tags = ['instructions'] def __init__(self, language: str): super().__init__() self.language: str = language def get_instances(self, outp...
class ConvTranspose3d(_ConvTransposeNd): __doc__ = ('Applies a 3D transposed convolution operator over an input image composed of several input\n planes.\n The transposed convolution operator multiplies each input value element-wise by a learnable kernel,\n and sums over the outputs from all input feature ...
def test_coerce_to_bytes_with_none(): _to_bytes_io def func(fh): assert (fh is None) func(None)
class Memory(object): def __init__(self, initial_feature, memory_net): self.h_state = initial_feature def update(self, new_feature, memory_net): self.h_state = memory_net(new_feature, self.h_state) def train_update(self, feature_sequence, memory_net): for (i, f) in enumerate(feature_...
class KRTToRCBijectionTypeDTwisted(KRTToRCBijectionTypeD, KRTToRCBijectionTypeA2Even): def run(self, verbose=False): if verbose: from sage.combinat.rigged_configurations.tensor_product_kr_tableaux_element import TensorProductOfKirillovReshetikhinTableauxElement for cur_crystal in reverse...
def saveScore(outPath, outValue, *args): flagPath = (outPath + '.flag') while os.path.isfile(flagPath): time.sleep(1) open(flagPath, 'a').close() if os.path.isfile(outPath): with open(outPath, 'rb') as file: outDict = json.load(file) if (not isinstance(outDict, dict))...
def accuracy(output, target, topk=(1,)): with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) (_, pred) = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, (- 1)).expand_as(pred)) res = [] for k in topk: ...
def test_bbsplus_and_range(): from zksk.primitives.rangeproof import RangeStmt from zksk.utils import make_generators mG = BilinearGroupPair() keypair = BBSPlusKeypair.generate(mG, 9) (pk, sk) = (keypair.pk, keypair.sk) (generators, h0) = (keypair.generators, keypair.h0) creator = BBSPlusSig...
def fpAbs(a, ctx=None): ctx = _get_ctx(ctx) [a] = _coerce_fp_expr_list([a], ctx) return FPRef(Z3_mk_fpa_abs(ctx.ref(), a.as_ast()), ctx)
def test_optimization_result_try_get_optimal_point_for_successful_optimization() -> None: data = {FOO: mk_dataset([[0.25, 0.25], [0.5, 0.4]], [[0.8], [0.7]])} result: OptimizationResult[None] = OptimizationResult(Ok(Record(data, {FOO: _PseudoTrainableQuadratic()}, None)), []) (x, y, idx) = result.try_get_op...
(nopython=True, fastmath=True, cache=True) def apply_bmask_1D(u, mask): for j in range(u.shape[1]): if (mask[j] == 0): for i in range(u.shape[0]): u[(i, j)] = 0 return u
class Player2Vec(Algorithm): def __init__(self, session, meta, nodes, class_size, gcn_output1, embedding, encoding): self.meta = meta self.nodes = nodes self.class_size = class_size self.gcn_output1 = gcn_output1 self.embedding = embedding self.encoding = encoding ...
def auto_str(cls): def __str__(self): return ('%s(%s)' % (type(self).__name__, ', '.join((('%s=%s' % item) for item in vars(self).items())))) cls.__str__ = __str__ return cls
def extractRelUIndexes(sequence, layers): layers.sort() index = 0 output = [] indexRef = 0 indexScale = 1 hasCaughtRelUOnLayer = False while ((indexRef < len(layers)) and (index < len(sequence))): if isinstance(sequence[index], torch.nn.ReLU): if ((not hasCaughtRelUOnLaye...
class ProgressMonitor(Plugin): stat_name = 'progress' def __init__(self): super(ProgressMonitor, self).__init__([(1, 'iteration'), (1, 'epoch')]) def register(self, trainer): self.trainer = trainer stats = self.trainer.stats.setdefault(self.stat_name, {}) stats['samples_used'...
def build_model_tabular(args, dims, regularization_fns=None): hidden_dims = tuple(map(int, args.dims.split('-'))) def build_cnf(): diffeq = layers.ODEnet(hidden_dims=hidden_dims, input_shape=(dims,), strides=None, conv=False, layer_type=args.layer_type, nonlinearity=args.nonlinearity) odefunc = ...
class CrossSelfTransformer(nn.Module): def __init__(self, latent_dim, input_dim, depth, heads, dim_head, ff_expansion=4, attn_dropout=0.0, ff_dropout=0.0): super().__init__() self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append(nn.ModuleList([PreNorm(latent_d...
class GraphAttentionEmbedding(torch.nn.Module): def __init__(self, in_channels, out_channels, msg_dim, time_enc): super().__init__() self.time_enc = time_enc edge_dim = (msg_dim + time_enc.out_channels) self.conv = TransformerConv(in_channels, (out_channels // 2), heads=2, dropout=0....
def count_nfe(model): class AccNumEvals(object): def __init__(self): self.num_evals = 0 def __call__(self, module): if isinstance(module, layers.ODEfunc): self.num_evals += module.num_evals() accumulator = AccNumEvals() model.apply(accumulator) ret...
def get_lbs_for_random_crop(crop_size, data_shape, margins): lbs = [] for i in range((len(data_shape) - 2)): if (((data_shape[(i + 2)] - crop_size[i]) - margins[i]) > margins[i]): lbs.append(np.random.randint(margins[i], ((data_shape[(i + 2)] - crop_size[i]) - margins[i]))) else: ...
def test_check_type_of_target() -> None: X = [0.5, 0.2, 0.4, 0.8, 3.8] y = [0.4, 0.2, 3.6, 3, 0.2] mapie_cal = MapieCalibrator() with pytest.raises(ValueError, match='.*Make sure to have one of the allowed targets:*'): mapie_cal.fit(X, y)
def lecun_normal_(tensor): variance_scaling_(tensor, mode='fan_in', distribution='truncated_normal')
class DenseNet(nn.Module): def __init__(self, depth=22, block=Bottleneck, dropRate=0, num_classes=10, growthRate=12, compressionRate=2): super(DenseNet, self).__init__() assert (((depth - 4) % 3) == 0), 'depth should be 3n+4' n = (((depth - 4) / 3) if (block == BasicBlock) else ((depth - 4) ...
def _load_word_clusters(path): clusters = dict() with path.open(encoding='utf8') as f: for line in f: split = line.rstrip().split('\t') if (not split): continue clusters[split[0]] = split[1] return clusters
def load(folder: Union[(str, Path)]): folder = Path(folder) if folder.is_absolute(): return load_from_numpy_bundle(folder, '/') else: return load_from_numpy_bundle(folder, '.')
def shard_params(params, params_spec, mesh): shard_fn = pjit((lambda x: x), in_shardings=(params_spec,), out_shardings=params_spec) with mesh: return shard_fn(params)
def novelty_local_competition(individual: IndividualLike, container: Sequence, k: int=1, dist: Union[(str, Callable)]='euclidean', ignore_first: bool=False, default_novelty: float=0.1, default_local_competition: float=1.0) -> Tuple[(float, float)]: if (len(container) == 0): return (default_novelty, default_...
def checkpoint(nets, history, args, epoch_num): print('Saving checkpoints...') (net_encoder, net_decoder, crit) = nets suffix_latest = 'epoch_{}.pth'.format(epoch_num) dict_encoder = net_encoder.state_dict() dict_decoder = net_decoder.state_dict() torch.save(history, '{}/history_{}'.format(args....
def _impl(array, highlevel, behavior, attrs): from awkward._connect.pyarrow import import_pyarrow_compute pc = import_pyarrow_compute('e') with HighLevelContext(behavior=behavior, attrs=attrs) as ctx: layout = ctx.unwrap(array) out = ak._do.recursively_apply(layout, ak.operations.str._get_ufunc_...
def remove_stopwords(sentence): return ' '.join((w for w in sentence.split() if (w not in STOPWORDS)))
def shell(args: List[str]): cmd = shlex.join(args) hlog(f'Executing: {cmd}') exit_code = subprocess.call(args) if (exit_code != 0): hlog(f'Failed with exit code {exit_code}: {cmd}')
class FlaxPreTrainedModel(ABC): config_class = None base_model_prefix = '' def __init__(self, config: PretrainedConfig, module: nn.Module, input_shape: Tuple=(1, 1), seed: int=0, dtype: jnp.dtype=jnp.float32): if (config is None): raise ValueError('config cannot be None') if (mod...
def operations_from_log(log_path: str) -> Generator[(tuple[(Operation, str, (str | None))], None, None)]: try: log = open(log_path, 'r', encoding='utf-8') except FileNotFoundError: return for line in log: line = line.replace('File Operation Logger', '').strip() if (not line):...