code
stringlengths
101
5.91M
def test_train_learning_rate_sinescheduler(train_data_fx, model_fx): h = model_fx.train(train_data_fx[0], train_data_fx[1], epochs=10, learning_rate={'scheduler': 'sineexponentialdecay', 'initial_learning_rate': 0.001, 'final_learning_rate': 0.0001, 'decay_epochs': 100, 'sine_freq': 2, 'sine_decay_rate': 0.5})
_dataset(NAME) class KITTIMaskedDiosDataset(KITTIMturkersInstanceDataset): def __init__(self, config, subset, name=NAME): super().__init__(config, subset, name) def get_extraction_keys(self): return self.pascal_masked_dataset.get_extraction_keys() def postproc_example_before_assembly(self, t...
class FeatureExtractor(object): def __init__(self, model_name='', model_path='', image_size=(256, 128), pixel_mean=[0.485, 0.456, 0.406], pixel_std=[0.229, 0.224, 0.225], pixel_norm=True, device='cuda', verbose=True): model = build_model(model_name, num_classes=1, pretrained=True, use_gpu=device.startswith(...
def test_validate_parameters_invalid_language(): with pytest.raises(ValueError): loader.validate_parameters('assin', 'invalid_language', 'full')
class PackagePickler(_Pickler): dispatch = _Pickler.dispatch.copy() def __init__(self, importer: Importer, *args, **kwargs): self.importer = importer super().__init__(*args, **kwargs) def save_global(self, obj, name=None): write = self.write memo = self.memo try: ...
def linalg_solve(A: dace.float64[(100, 100)], B: dace.float64[(100, 10)]): return np.linalg.solve(A, B)
def test3d_8n_ub(): query_pts = np.array([[787014.438, (- 340616.906), 6313018.0], [751763.125, (- 59925.969), 6326205.5], [769957.188, (- 202418.125), 6321069.5]]) kdtree = KDTree(data_pts_real) (dist, idx) = kdtree.query(query_pts, k=8, distance_upper_bound=10000.0, sqr_dists=False) exp_dist = np.arra...
def update_args(doc: str, beg: int, prefix: str=' ') -> str: prefix += ' ' for i in range(10): if ((res := re_blank_line.match(doc, beg)) is not None): (beg, end) = res.span(0) break if ((res := re_arg.search(doc, beg)) is None): return doc prefi...
class Mixed_3c(nn.Module): def __init__(self): super(Mixed_3c, self).__init__() self.branch0 = nn.Sequential(BasicConv3d(256, 128, kernel_size=1, stride=1)) self.branch1 = nn.Sequential(BasicConv3d(256, 128, kernel_size=1, stride=1), SepConv3d(128, 192, kernel_size=3, stride=1, padding=1)) ...
_dispatch def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None): return (Dispatchable(x, np.ndarray),)
_module class NonLinearNeckSimCLRDense(nn.Module): def __init__(self, in_channels, hid_channels, out_channels, num_layers=2, sync_bn=True, with_bias=False, with_last_bn=True, with_avg_pool=True, with_attn=False): super(NonLinearNeckSimCLRDense, self).__init__() self.sync_bn = sync_bn self.wi...
def main(): paths = get_default_paths() ner_input_path = paths['NERBASE'] conll_path = os.path.join(ner_input_path, 'english', 'en_conll03') ner_output_path = paths['NER_DATA_DIR'] process_dataset('en_conll03', conll_path, ner_output_path)
def _assert_valid_lists(groundtruth_list, predicted_list): assert (len(groundtruth_list) == len(predicted_list)) for unique_element in np.unique(groundtruth_list).tolist(): assert (unique_element in [0, 1])
class MOTDataReader(): def __init__(self, image_folder, detection_file_name, min_confidence=None): self.image_folder = image_folder self.detection_file_name = detection_file_name self.image_format = os.path.join(self.image_folder, '{0:06d}.jpg') self.detection = pd.read_csv(self.dete...
def model_creator(data, name, dtypes): if (name in _model_creator_list): return _model_creator_list[name](data) return (data, None)
class Vocab(): def __init__(self, list_of_tokens: List[str]=None, padding_token: str='<pad>', unknown_token: str='<unk>', bos_token: str='<bos>', eos_token: str='<eos>', reserved_tokens: List[str]=None, token_to_idx: Dict[(str, int)]=None): self._unknown_token = unknown_token self._padding_token = p...
def test_ufunc_add_out(): A = np.random.randint(10, size=(10,), dtype=np.int32) B = np.random.randint(10, size=(10,), dtype=np.int32) C = np.empty((10,), dtype=np.int32) ufunc_add_out(A, B, C) assert np.array_equal((A + B), C)
def test_model(test_dl, model, scaler): x_input = [] truth = [] predicted = [] with torch.no_grad(): model.eval() step = 0 for (x, y, mask) in test_dl: x = x.to('cuda') y = y.to('cuda') output = model(x).float() x = x.to('cpu') ...
class VideoLDMUpBlock(CrossAttnUpBlock2D): def __init__(self, *args, n_frames=8, n_temp_heads=8, **kwargs): super().__init__(*args, **kwargs) out_channels = kwargs['out_channels'] num_layers = kwargs['num_layers'] cross_attn_dim = kwargs.get('cross_attention_dim') conv3ds = [...
def download_protein_folder(bucket_name, local_dir=None): s3 = boto3.resource('s3') bucket = s3.Bucket(bucket_name) for obj in bucket.objects.filter(Prefix='protein'): target = (obj.key if (local_dir is None) else os.path.join(local_dir, os.path.relpath(obj.key, 'protein'))) if (not os.path....
def _qz(A, B, output='real', lwork=None, sort=None, overwrite_a=False, overwrite_b=False, check_finite=True): if (sort is not None): raise ValueError("The 'sort' input of qz() has to be None and will be removed in a future release. Use ordqz instead.") if (output not in ['real', 'complex', 'r', 'c']): ...
_decorator(False) def is_404(html): soup = BeautifulSoup(html, 'lxml') try: if (' in html): return True elif (soup.title.text == '404'): return True elif (html == ''): return True elif (',' in html): return True else: ...
class ImageAugmentation(Layer): def call(self, x): one = tf.fill([tf.shape(x[0])[0], 1], 1.0) zero = tf.fill([tf.shape(x[0])[0], 1], 0.0) transforms = tf.concat([one, zero, zero, zero, one, zero, zero, zero], axis=1) rands = tf.concat([tf.truncated_normal([tf.shape(x[0])[0], 6], stdd...
def gpu_mem_usage(): if torch.cuda.is_available(): mem_usage_bytes = torch.cuda.max_memory_allocated() else: mem_usage_bytes = 0 return (mem_usage_bytes / (1024 ** 3))
class GPT2Tokenizer(object): def __init__(self, vocab_file=None, special_tokens=None): self.pad_token = '[PAD]' self.sep_token = '[SEP]' self.unk_token = '[UNK]' self.cls_token = '[CLS]' self.symbols = [] self.count = [] self.indices = {} self.pad_toke...
def register_Ns3ChannelParams_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::ChannelParams const &', 'arg0')]) cls.add_instance_attribute('m_delaySpread', 'ns3::doubleVector_t', is_const=False) cls.add_instance_attribute('m_doppler', 'ns3::doubleVector_t', is_const=F...
class _EnvironWrapper(_Environ): def __setitem__(self, name: str, value: str) -> None: orig = self.get(name, None) _Environ.__setitem__(self, name, value) new = self[name] self._print_diff(name, orig, new) def __delitem__(self, name: str) -> None: orig = self.get(name, No...
class DCGANTest(tf.test.TestCase): def test_generator_run(self): tf.set_random_seed(1234) noise = tf.random_normal([100, 64]) (image, _) = dcgan.generator(noise) with self.test_session() as sess: sess.run(tf.global_variables_initializer()) image.eval() def...
def print_csv(fname): with open(fname, 'r') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') ctr = 0 for row in csv_reader: ctr += 1 print('there are ', ctr, ' rows in the csv file')
class DataLoader(torch.utils.data.DataLoader): def __init__(self, input_dir, fn, bert_name, ent2id, rel2id, batch_size, training=False): print('Reading questions from {}'.format(fn)) self.tokenizer = AutoTokenizer.from_pretrained(bert_name) self.ent2id = ent2id self.rel2id = rel2id ...
def cost(factor, goldfactors): if (options.cost == 'hamming'): return hamming_cost(factor, goldfactors) elif (options.cost == 'recall'): return recall_oriented_cost(factor, goldfactors) else: raise Exception('undefined cost type', options.cost)
.filterwarnings('ignore::sklearn.exceptions.FitFailedWarning') .filterwarnings('ignore:Scoring failed:UserWarning') .filterwarnings('ignore:One or more of the:UserWarning') .parametrize('HalvingSearch', (HalvingGridSearchCV, HalvingRandomSearchCV)) .parametrize('fail_at', ('fit', 'predict')) def test_nan_handling(Halvi...
def generate_alignment(sequences, ep=0.0, op=1.53): with tempfile.TemporaryDirectory() as tmp: tmp_fasta_path = (tmp + '/tmp.fasta') write_partitioned_fasta(tmp_fasta_path, sequences) align_out = subprocess.run(['mafft', '--thread', '8', '--maxiterate', '1000', '--globalpair', '--ep', str(ep...
def test0(): N = 1500 (X, Y) = np.meshgrid(np.linspace((- 1), 1, N), np.linspace((- 1), 1, N)) r = 0.5 dx = [(2.0 / (N - 1)), (2.0 / (N - 1))] phi = (((X ** 2) + (Y ** 2)) - (r ** 2)) phi = np.ones_like(phi) phi[0][0] = (- 1) t0 = time.time() d = distance(phi, dx) t1 = time.time(...
_scheduler('multi_step') class MultiStepScheduler(PythiaScheduler): def __init__(self, optimizer, *args, **kwargs): self.use_warmup = kwargs['use_warmup'] self.lr_steps = kwargs['lr_steps'] self.lr_ratio = kwargs['lr_ratio'] self.warmup_iterations = (kwargs['warmup_iterations'] if se...
def sensitive_topics_classifier(batch_size, data): from .sensitive_checker import sensitive_scorer (scores, meta_data) = sensitive_scorer(batch_size, data) return (scores, meta_data)
(scope='module') def test_data_xy(): x = np.linspace((- 1), 1, 11) y = np.linspace(0, 2, 11) return list(np.meshgrid(x, y))
class HGFilter(nn.Module): def __init__(self, opt): super(HGFilter, self).__init__() self.num_modules = opt.num_stack self.opt = opt self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3) if (self.opt.norm == 'batch'): self.bn1 = nn.BatchNorm2d(64) ...
_dispatch def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None): return (Dispatchable(x, np.ndarray),)
def get_evaluation_extra_data_key(evaluation_id): return 'evaluations/{}_data.bytes'.format(evaluation_id)
def point_from(arr): x = int((arr[0] * WIDTH)) y = int((arr[1] * HEIGHT)) return gr.Point(x, y)
def test_estimator_getstate_using_slots_error_message(): class WithSlots(): __slots__ = ('x',) class Estimator(BaseEstimator, WithSlots): pass msg = 'You cannot use `__slots__` in objects inheriting from `sklearn.base.BaseEstimator`' with pytest.raises(TypeError, match=msg): Esti...
def keyword_ifelse(A: dace.float32[N], B: dace.float32[N], C: dace.int32): if (C == 0): B[:] = (- A[:]) elif (C == 1): B[:] = (A[:] * A[:]) else: B[:] = A
class TestSuiteAssertionCheckedCoverageFunction(TestSuiteCoverageFunction): def compute_coverage(self, individual) -> float: results = self._run_test_suite_chromosome(individual) merged_trace = analyze_results(results) tracer = self._executor.tracer return compute_assertion_checked_c...
class BaseModelOutputWithPastAndCrossAttentions(ModelOutput): last_hidden_state: torch.FloatTensor past_key_values: Optional[List[torch.FloatTensor]] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None cross_attentions: Optional[Tuple...
.pure def test_cast_float_to_long(sdfg_name): sdfg = dace.SDFG(sdfg_name) sdfg.add_array('X', [2, 4], dace.float32) sdfg.add_array('__return', [2, 4], dace.int64) state = sdfg.add_state() access_X = state.add_access('X') access_result = state.add_access('__return') op_node = donnx.ONNXCast('...
def load(path: PathLike) -> dict[(str, Any)]: try: with open(path, 'rb') as fd: return tomli.load(fd) except FileNotFoundError: _try_make_config_directory(path) return {} except tomli.TOMLDecodeError: return {}
def conv3(in_planes, out_planes, stride=2): return nn.Sequential(nn.Conv2d(in_planes, out_planes, 3, stride, 1), nn.PReLU(out_planes), nn.Conv2d(out_planes, out_planes, 3, 1, 1), nn.PReLU(out_planes), nn.Conv2d(out_planes, out_planes, 3, 1, 1), nn.PReLU(out_planes))
def make_and_restore_model(*_, arch, dataset, resume_path=None, parallel=True, pytorch_pretrained=False): classifier_model = (dataset.get_model(arch, pytorch_pretrained) if isinstance(arch, str) else arch) model = AttackerModel(classifier_model, dataset) checkpoint = None if resume_path: if os.p...
def run_demo(model='inpainting', data='mnist', category=0, p_rem=1, type_rem='uniform', Delta=0.001, seed=0, max_iter=1000, save_fig=False, block=False): if (model == 'inpainting'): model_params = {'name': 'inpainting', 'N': 784, 'p_rem': p_rem, 'type': type_rem} elif (model == 'denoising'): mod...
def _len(L): try: return L.cardinality() except AttributeError: return len(L)
def show_test_anomaly_results(base: Path): idxs = [] for p in base.glob(f'* - test_anomaly_results.png'): (idx, _) = p.stem.split(' - ') idxs.append(int(idx)) idxs = sorted(idxs) idx = st.slider(label=' ', min_value=min(idxs), max_value=max(idxs), value=min(idxs), step=(idxs[1] - idxs[0]...
def create_model_7(input_shape): inputs = Input(shape=input_shape, name='input1') x_bn = BatchNormalization(gamma_initializer='random_normal', beta_initializer='random_normal', name='bn1')(inputs) x_bn2 = BatchNormalization(gamma_initializer='random_normal', beta_initializer='random_normal', name='bn2')(inp...
def check_yaml_vs_script(hparam_file, script_file): print(('Checking %s...' % hparam_file)) if (not os.path.exists(hparam_file)): print(('File %s not found!' % (hparam_file,))) return False if (not os.path.exists(script_file)): print(('File %s not found!' % (script_file,))) r...
def build_optimizer(params, train_steps, precision): _params = dict(deepcopy(params)) lr_params = _params.pop('lr_params', None) use_moving_average = _params.pop('use_moving_average', None) moving_average_decay = _params.pop('moving_average_decay', None) _ = _params.pop('global_clipnorm', None) ...
def test_depthwise_separable_conv(): with pytest.raises(AssertionError): DepthwiseSeparableConvModule(4, 8, 2, groups=2) conv = DepthwiseSeparableConvModule(3, 8, 2) assert (conv.depthwise_conv.conv.groups == 3) assert (conv.pointwise_conv.conv.kernel_size == (1, 1)) assert (not conv.depthwi...
def check_pdf_logpdf_at_endpoints(distfn, args, msg): points = np.array([0, 1]) vals = distfn.ppf(points, *args) vals = vals[np.isfinite(vals)] with suppress_warnings() as sup: suppress_messsages = ['divide by zero encountered in true_divide', 'divide by zero encountered in log', 'divide by zero...
def _random_linkability_attack(n_synthetic: int, n_attacks: int, n_neighbors: int) -> LinkabilityIndexes: idx_0 = _random_links(n_synthetic=n_synthetic, n_attacks=n_attacks, n_neighbors=n_neighbors) idx_1 = _random_links(n_synthetic=n_synthetic, n_attacks=n_attacks, n_neighbors=n_neighbors) return Linkabili...
class GaussianLatentVAE(VAEBase): def __init__(self, representation_size): super().__init__(representation_size) self.dist_mu = np.zeros(self.representation_size) self.dist_std = np.ones(self.representation_size) def rsample(self, latent_distribution_params): (mu, logvar) = laten...
.expansion class ExpandCholeskyOpenBLAS(ExpandTransformation): environments = [blas_environments.openblas.OpenBLAS] def expansion(node, parent_state, parent_sdfg, **kwargs): return _make_sdfg(node, parent_state, parent_sdfg, 'OpenBLAS')
class KerasModelBuilder(ModelBuilder): def __init__(self, inputs_op, output_op, model_compile_dict, model_space=None, gpus=None, **kwargs): self.model_compile_dict = model_compile_dict self.input_node = inputs_op self.output_node = output_op self.model_space = model_space sel...
def criteria_3_is_valid(index_date, start_date, baseline): return ((index_date - start_date).days >= baseline)
def get_trainable_quantizer_weights_config(n: BaseNode, weights_quantization_candidates: List[TrainableQuantizerCandidateConfig]=None) -> TrainableQuantizerWeightsConfig: if (n.final_weights_quantization_cfg is None): Logger.error(f'Node must have final_weights_quantization_cfg in order to build quantizer c...
def subtokenizer(identifier): splitter_regex = re.compile('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)') identifiers = re.split('[._\\-]', identifier) subtoken_list = [] for identifier in identifiers: matches = splitter_regex.finditer(identifier) for subtoken in [m.group(0) for...
def _extract_return_annotation(sigstr, has_return_anno): if (not has_return_anno): return '' return sigstr.split(')')[1]
class TrainOptions(BaseOptions): def __init__(self): super().__init__() self.isTrain = True def initialize(self, parser): super().initialize(parser) parser.add_argument('--continue_train', type=util.str2bool, default=False, help='resume training from last checkpoint') par...
def TietzeGraph(): g = Graph([(0, 9), (3, 10), (6, 11), (1, 5), (2, 7), (4, 8)], name='Tietze Graph') g.add_cycle(list(range(9))) g.add_cycle([9, 10, 11]) g._circle_embedding(list(range(9))) g._circle_embedding([9, 10, 11], radius=0.5) return g
def replace_params(hf_params, tf_params, key_mapping): list(hf_params.keys()) for (key, value) in tf_params.items(): if (key not in key_mapping): continue hf_key = key_mapping[key] if (('_conv' in key) and ('kernel' in key)): new_hf_value = torch.from_numpy(value)...
class ObjectOnNode(NodeEnumerator): def __init__(self, node: Node): self.surface_node = node def enumerate(self, state: EnvironmentState, **kwargs): for n in state.get_nodes(): if state.evaluate(ExistsRelation(NodeInstance(n), Relation.ON, NodeInstanceFilter(self.surface_node))): ...
def save_np_arrays(arrays, directory, filename): save_metadata(arrays, directory, filename=filename, default=numpy_serialize)
def densenet161(pretrained=False, progress=True, device='cpu', **kwargs): return _densenet('densenet161', 48, (6, 12, 36, 24), 96, pretrained, progress, device, **kwargs)
class BaseResolver(): DEFAULT_SCALAR_TAG = 'tag:yaml.org,2002:str' DEFAULT_SEQUENCE_TAG = 'tag:yaml.org,2002:seq' DEFAULT_MAPPING_TAG = 'tag:yaml.org,2002:map' yaml_implicit_resolvers = {} yaml_path_resolvers = {} def __init__(self): self.resolver_exact_paths = [] self.resolver_p...
_reader(nn.GradientReversal) def GradientReversal_reader(reader, version, obj): if (version < 2): setattr(obj, 'lambda', 1)
def test_IndexedArray_getitem(): content = ak.from_iter([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9], highlevel=False) index = ak.index.Index64(np.array([3, 2, 2, 5, 0, 7], dtype=np.int64)) array = ak.highlevel.Array(ak.contents.IndexedArray(index, content)) def f1(x, i): return x[i] a...
def windows_nvToolsExt_path(): WINDOWS_HOME = 'C:/Program Files/NVIDIA Corporation/NvToolsExt' NVTOOLEXT_HOME = os.getenv('NVTOOLSEXT_PATH', WINDOWS_HOME) if os.path.exists(NVTOOLEXT_HOME): lib_paths = glob.glob((NVTOOLEXT_HOME + '/bin/x64/nvToolsExt*.dll')) if (len(lib_paths) > 0): ...
class Partition0(nn.Module): LAYER_SCOPES = ['VisionTransformer/PatchEmbed[patch_embed]/Conv2d[proj]', 'VisionTransformer/Dropout[pos_drop]', 'VisionTransformer/ModuleList[blocks]/Block[0]/LayerNorm[norm1]', 'VisionTransformer/ModuleList[blocks]/Block[0]/Attention[attn]/Linear[qkv]', 'VisionTransformer/ModuleList[b...
class ResnetGenerator_UpsampleBilinear(nn.Module): def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'): assert (n_blocks >= 0) super(ResnetGenerator_UpsampleBilinear, self).__init__() self.input_nc = input_nc ...
.parametrize('hidden_units,use_bn', [(hidden_units, use_bn) for hidden_units in [(), (10,)] for use_bn in [True, False]]) def test_DNN(hidden_units, use_bn): with CustomObjectScope({'DNN': layers.DNN}): layer_test(layers.DNN, kwargs={'hidden_units': hidden_units, 'use_bn': use_bn, 'dropout_rate': 0.5}, inpu...
class TrainOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--display_freq', type=int, default=100, help='frequency of showing training results on screen') self.parser.add_argument('--print_freq', type=int, default=100, help='frequency of sho...
_model def metaformer_pppf_s12_224(pretrained=False, **kwargs): layers = [2, 2, 6, 2] embed_dims = [64, 128, 320, 512] token_mixers = [Pooling, Pooling, Pooling, partial(SpatialFc, spatial_shape=[7, 7])] mlp_ratios = [4, 4, 4, 4] downsamples = [True, True, True, True] model = MetaFormer(layers, ...
def levelPlot(data, var=None, time=None, levels=(3, 5), target=None, colors=None, **kwargs): if (var is not None): try: usearr = data[var] except KeyError: raise KeyError('Key "{1}" not present in data'.format(var)) elif (not isinstance(data, Mapping)): usearr = n...
class QDQBertForTokenClassification(metaclass=DummyObject): _backends = ['pytorch_quantization', 'torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['pytorch_quantization', 'torch'])
def _build_events_df(events): events = pd.DataFrame(list(events), columns=['start', 'end', 'score']) events['start'] = events['start'].astype('int64') events['end'] = events['end'].astype('int64') return events
def test(): A = dace.ndarray((2,), dace.uint32) B = dace.ndarray((1,), dace.uint32) A[:] = 5 B[:] = 0 cpp_tasklet(A, B) assert (B[0] == 5)
class MCPEvent(Structure): _fields_ = [('size', c_uint32), ('event_type', c_int32), ('timestamp', c_double), ('event_data', MCPEventData)]
def simSetExplicitHandling(generalObjectHandle, explicitFlags): ret = lib.simSetExplicitHandling(generalObjectHandle, explicitFlags) _check_return(ret)
def main(args): saver = Saver() utils.import_user_module(args) assert ((args.max_tokens is not None) or (args.batch_size is not None)), 'Must specify batch size either with --max-tokens or --batch-size' metrics.reset() np.random.seed(args.seed) utils.set_torch_seed(args.seed) if distributed_...
def register_Ns3AmpduTag_methods(root_module, cls): cls.add_constructor([param('ns3::AmpduTag const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) cls.add_method('GetInstanceTypeId', 'ns3::TypeId', [], is_const=True, is_virtua...
def LoadCrossNet(Graph, Table, SrcCol, DstCol, EdgeAttrV): return _snap.LoadCrossNet(Graph, Table, SrcCol, DstCol, EdgeAttrV)
def wrap_objective(objective, data, pdf, stitch_pars, do_grad=False, jit_pieces=None): (tensorlib, _) = get_backend() if do_grad: raise exceptions.Unsupported('Numpy does not support autodifferentiation.') def func(pars): pars = tensorlib.astensor(pars) constrained_pars = stitch_pars...
def _sweep_poly_phase(t, poly): intpoly = polyint(poly) phase = ((2 * pi) * polyval(intpoly, t)) return phase
class PNGraph(object): thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag') def __init__(self, *args, **kwargs): raise AttributeError('No constructor defined') __repr__ = _swig_repr def New(): return _snap.PNGraph_New() New = sta...
def _evaluate_hparams(text_embeddings, text_labels, label_embeddings, folds, loss_type, hparams): predictions = [] references = [] for (fold_index, test_indexes) in enumerate(folds): train_indexes = _get_complement(folds, test_indexes) assert ((len(train_indexes) + len(test_indexes)) == len(...
class MinTotalDurationPolicyWithPerf(Policy): def __init__(self, solver, num_threads=None): self._num_threads = num_threads Policy.__init__(self, solver) self._name = 'MinTotalDuration_Perf' def get_allocation_helper(self, throughputs, scale_factors_array): x = cp.Variable(throug...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--root', type=str, help='Root of Common Voice 7.0 directory.') parser.add_argument('--lang', type=str, help='Language abbreviation.') parser.add_argument('--out', type=str, help='Path to output directory.') parser.add_argument('--ac...
('name,rbf_class', list(rbf_class_mapping.items())) def test_num_rbf(name, rbf_class, num_rbf=20): rbf = rbf_class(num_rbf=num_rbf) y = rbf(torch.linspace(0, 10, 100)) assert (y.ndim == 2), 'Failed to expand the dimension.' assert (y.size(1) == num_rbf), f'Found {y.size(1)} values but expected {num_rbf}...
class ExactTermMonoid(TermWithCoefficientMonoid): Element = ExactTerm def _convert_construction_(self, kwds_construction): if (('parent' in kwds_construction) and isinstance(kwds_construction['parent'], BTermMonoid)): try: del kwds_construction['valid_from'] excep...
class BLDLDmat(SpectralMatrix): def assemble(self, method): (test, trial) = (self.testfunction, self.trialfunction) assert isinstance(test[0], LD) assert isinstance(trial[0], LD) d0 = get_norm_sq(test[0], trial[0], method) d = {0: (d0[:(- 1)] + d0[1:]), (- 1): d0[1:(- 1)]} ...
class BigBirdPegasusForSequenceClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class MetaLearnerStage(): name: str params: Dict[(str, Any)] = field(default_factory=dict) prev_stage: Optional['MetaLearnerStage'] = None def full_name(self) -> MLStageFullName: fn: MLStageFullName if (self.prev_stage is None): fn = (self.name,) else: fn ...