code
stringlengths
101
5.91M
def resolve_input_config(args, model_config=None, model=None): if (not isinstance(args, dict)): args = vars(args) input_config = {} if ((not model_config) and (model is not None) and hasattr(model, 'config')): model_config = model.config in_chans = 3 input_size = (in_chans, 512, 512)...
def local_errors(ignore=False): errors = [] error_stack.append(errors) try: (yield errors) finally: release_errors(ignore=ignore)
def main(top_block_cls=tx_rx_hier_functionality_check, options=None): tb = top_block_cls() def sig_handler(sig=None, frame=None): tb.stop() tb.wait() sys.exit(0) signal.signal(signal.SIGINT, sig_handler) signal.signal(signal.SIGTERM, sig_handler) tb.start() try: i...
class _AtrousSpatialPyramidPoolingModule(nn.Module): def __init__(self, in_dim, reduction_dim=256, output_stride=16, rates=(6, 12, 18)): super(_AtrousSpatialPyramidPoolingModule, self).__init__() print('output_stride = ', output_stride) if (output_stride == 8): rates = [(2 * r) f...
class ResNet50LatencyTable(LatencyTable): def query(self, **kwargs): raise NotImplementedError def predict_network_latency(self, net, image_size): raise NotImplementedError def predict_network_latency_given_config(self, net_config, image_size): raise NotImplementedError def count...
class TestEntity(unittest.TestCase): def setUp(self): self.entity1 = StringEntity(0.95, ExtractionMethod.NER, 'some string') self.entity2 = StringEntity(0.95, ExtractionMethod.NER, 'some string') self.entity3 = StringEntity(0.95, ExtractionMethod.SPELLING, 'some string') self.entity4...
class SamplerTestCase(unittest.TestCase): def test_training_sampler(self): sampler = TrainingSampler(5) for i in sampler: print(i)
class Normal(base.Prior): def __init__(self, mean, var): self.mean = mean self.var = var self.rho = (self.var + (self.mean ** 2)) def iter_v(self, a): return (1.0 / (a + (1.0 / self.var))) def eval_i(self, a): return ((0.5 * ((self.rho * a) + ((self.mean ** 2) / self....
def parse_argsV2(): parser = argparse.ArgumentParser(description='SaliencySegmentation') parser.add_argument('--config', '-c', required=True, type=str) parser.add_argument('--num_workers', dest='num_workers', help='num_workers', default=4, type=int) parser.add_argument('--local_rank', type=int, default=...
def calc_derv4gp(netD, conditional_strategy, real_data, fake_data, real_labels, device): (batch_size, c, h, w) = real_data.shape alpha = torch.rand(batch_size, 1) alpha = alpha.expand(batch_size, (real_data.nelement() // batch_size)).contiguous().view(batch_size, c, h, w) alpha = alpha.to(device) re...
class _REGISTRY_KEYS_NT(NamedTuple): X_KEY: str = 'X' BATCH_KEY: str = 'batch' LABELS_KEY: str = 'labels' PROTEIN_EXP_KEY: str = 'proteins' CAT_COVS_KEY: str = 'extra_categorical_covs' CONT_COVS_KEY: str = 'extra_continuous_covs' INDICES_KEY: str = 'ind_x' SIZE_FACTOR_KEY: str = 'size_fa...
def unpack_traced_args_and_kwargs(*traced_args, **traced_kwargs): args = [a._data for a in traced_args] kwargs = {k: v._data for (k, v) in traced_kwargs.items()} return (args, kwargs)
def test_compile_tf_graph_enc_dec_simple_recurrent_step(): tmp_dir = tempfile.mkdtemp() with open(os.path.join(tmp_dir, 'returnn.config'), 'wt') as config: config.write(rec_encoder_decoder_simple_config) args = ['tools/compile_tf_graph.py', '--output_file', os.path.join(tmp_dir, 'graph.metatxt'), '-...
class MockIntentClassifier(MockProcessingUnitMixin, IntentClassifier): def fit(self, dataset): self.fitted = True return self def get_intent(self, text, intents_filter): return None def get_intents(self, text): return []
def match_subj_with_event(verb_text, verb_index, subj_text, subj_index, sent, is_gold): event = match_event(verb_text, verb_index, sent, is_gold) if ((event is not None) and (event.arg0 is None)): entity = match_entity(subj_text, subj_index, sent, is_gold) if (entity is not None): if...
class XLMRobertaForCausalLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def profile(x, ops, n=100, device=None): device = (device or torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu'))) x = x.to(device) x.requires_grad = True print(torch.__version__, device.type, (torch.cuda.get_device_properties(0) if (device.type == 'cuda') else '')) print(f''' {'Params':...
class ETHZ(BenchmarkDataset): def __init__(self, **kwargs): citation = 'Each individual network has its own DOI. From publicly available data:\nCH: seisbench.logger.warning('Check available storage and memory before downloading and general use of ETHZ dataset. Dataset size: waveforms.hdf5 ~22G...
class Model(nn.Module): def __init__(self, mono=False, scale=2, odd_length=False, pad_type='zero', dropout=0.0, batchnorm=False): super(Model, self).__init__() assert (not (batchnorm and dropout)) self.scale = scale if mono: n_input_ch = 1 n_output_ch = 1 ...
def sudo(): if IS_WINDOWS: return with_options({'runas': True}) elif (os.geteuid() != 0): return prefix('sudo') else: return with_options({})
class deeplab_xception_transfer_basemodel_synBN(deeplab_xception_synBN.DeepLabv3_plus): def __init__(self, nInputChannels=3, n_classes=7, os=16, input_channels=256, hidden_layers=128, out_channels=256): super(deeplab_xception_transfer_basemodel_synBN, self).__init__(nInputChannels=nInputChannels, n_classes=...
def run(args): dataset = VOCSemanticSegmentationDataset(split=args.chainer_eval_set, data_dir=args.voc12_root) labels = [dataset.get_example_by_keys(i, (1,))[0] for i in range(len(dataset))] preds = [] for id in dataset.ids: cam_dict = np.load(os.path.join(args.cam_out_dir, (id + '.npy')), allow...
class Wide_ResNet(nn.Module): def __init__(self, depth, widen_factor, dropout_rate, num_classes): super(Wide_ResNet, self).__init__() self.in_planes = 16 assert (((depth - 4) % 6) == 0), 'Wide-resnet depth should be 6n+4' n = ((depth - 4) / 6) k = widen_factor print((...
def register_types(module): root_module = module.get_root() module.add_enum('EnvironmentType', ['UrbanEnvironment', 'SubUrbanEnvironment', 'OpenAreasEnvironment']) module.add_enum('CitySize', ['SmallCity', 'MediumCity', 'LargeCity']) module.add_class('AttributeConstructionList', import_from_module='ns.c...
def get_output_dir(module): outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', 'tracktor', module)) if (not os.path.exists(outdir)): os.makedirs(outdir) return outdir
.parametrize('clear_buffer, clear_no_need_grad', [(False, False), (True, False), (False, True)]) def test_intermediate_outputs(clear_buffer, clear_no_need_grad): rng = np.random.RandomState(311) nn.prefer_cached_array(False) x = nn.Variable.from_numpy_array(rng.randn(2, 10)) h1 = (x + 1) y1 = (h1 + ...
def main(argv): default_options = {} default_options['agent'] = 'mc_aixi_ctw' default_options['agent-horizon'] = 5 default_options['ct-depth'] = 30 default_options['environment'] = 'coin_flip' default_options['exploration'] = 0.0 default_options['explore-decay'] = 1.0 default_options['le...
def reduce_monos(lrtoks): i = 0 while (i < len(lrtoks)): if (lrtoks[i] == 'NOT'): args = [lrtoks[i], lrtoks[(i + 1)]] lrtoks[i] = eval_mon_op(args) del lrtoks[(i + 1)] i += 1
class title(html_tag): def _get_text(self): return u''.join(self.get(basestring)) def _set_text(self, text): self.clear() self.add(text) text = property(_get_text, _set_text)
class DeconvolutionDataGrad(LinearDataGrad): def __init__(self, ctx, base_axis=1, pad=None, stride=None, dilation=None, group=1, channel_last=False, output_padding=None): super(DeconvolutionDataGrad, self).__init__(ctx) self._linear = _F.Deconvolution(ctx, base_axis, pad, stride, dilation, group, ch...
.parametrize('clf', [SAGClassifier(loss='log', max_iter=20, verbose=0, random_state=0), SAGAClassifier(loss='log', max_iter=20, verbose=0, random_state=0), PySAGClassifier(loss='log', max_iter=20, random_state=0)]) def test_auto_stepsize(clf, bin_train_data): (X_bin, y_bin) = bin_train_data clf.fit(X_bin, y_bin...
def get_parents(phrases, p1_idx, p2_idx): parents1 = get_parent_trajectory(phrases, p1_idx) parents2 = get_parent_trajectory(phrases, p2_idx) for (i, p) in enumerate(parents1): if (p in parents2): closest_common_parent = p break common_parents = parents1[i:] return co...
def _get_clipfn(size, signed=True): maxval = _get_maxval(size, signed) minval = _get_minval(size, signed) return (lambda val: builtin_max(min(val, maxval), minval))
def add_economic_dynamics(model, config): def ygrosseq(model, time): return (model.YGROSS[time] == ((config.al(time) * ((config.L[time] / 1000) ** (1 - config.gama))) * (model.K[time] ** config.gama))) add_constraint(model, ygrosseq) def yneteq(model, time): return (model.YNET[time] == (mode...
def test_sdca_smooth_hinge_l1_only(bin_train_data): (X_bin, y_bin) = bin_train_data clf = SDCAClassifier(alpha=0.5, l1_ratio=1.0, loss='smooth_hinge', tol=0.01, max_iter=200, random_state=0) clf.fit(X_bin, y_bin) assert (clf.score(X_bin, y_bin) == 1.0)
def load_candidate_from_stream_with_score(f): qid_to_ranked_candidate_passages = {} for l in f: try: l = l.strip().split('\t') qid = int(l[0]) pid = int(l[1]) rank = int(l[2]) score = float(l[3]) if (qid not in qid_to_ranked_candida...
def _impl(array, axis, keepdims, mask_identity, highlevel, behavior, attrs): axis = regularize_axis(axis) with HighLevelContext(behavior=behavior, attrs=attrs) as ctx: layout = ctx.unwrap(array, allow_record=False, primitive_policy='error') reducer = ak._reducers.ArgMin() out = ak._do.reduce(lay...
class PMMNet(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.PMMNet_New() New = stati...
def build_resnext(): model = resnext.resnet101(num_classes=400, shortcut_type='B', cardinality=32, sample_size=112, sample_duration=16, last_fc=False) model = model.cuda() assert os.path.exists('pretrained/resnext-101-kinetics.pth') model_data = torch.load('pretrained/resnext-101-kinetics.pth', map_loca...
class StubRpcAgent(): def __init__(self, world_size): self.world_size = world_size def get_worker_infos(self): return {rpc.WorkerInfo(name=worker_name(rank), id=rank) for rank in range(self.world_size)}
class _MyCustomMapDatasetThrowingExceptionAtItem(MapDatasetBase): def __init__(self): super().__init__(data_types={'data': {'shape': (None, 3)}}) def __len__(self): return 2 def __getitem__(self, item): if (item == 0): return {'data': numpy.zeros((5, 3))} raise _M...
def pwdist_means_only(M1, M2=None, symmetric=False, device=None): if ((M2 is None) or symmetric): symmetric = True M2 = M1 D = torch.cdist(M1, M2) if device: D = D.to(device) return D
def compile_extension(temp_dir, install=False, verbose=True): env = {**os.environ, 'TUNING_SOURCE_DIR': str(temp_dir), 'TUNING_EXTENSION_NAME': str(temp_dir.stem)} output = subprocess.run([sys.executable, 'tuning_setup.py', ('build' if (not install) else 'develop')], cwd=temp_dir, env=env, capture_output=True) ...
class Partition1(nn.Module): LAYER_SCOPES = ['VisionTransformer/ModuleList[blocks]/Block[2]/Mlp[mlp]/Dropout[drop]', 'VisionTransformer/ModuleList[blocks]/Block[2]/Identity[drop_path]', 'VisionTransformer/ModuleList[blocks]/Block[3]/LayerNorm[norm1]', 'VisionTransformer/ModuleList[blocks]/Block[3]/Attention[attn]/L...
def ngrams_for_evaluation(sequence, max_n, predict_first=False): if (max_n <= 0): raise ValueError('Max N must be >=1') iterator = iter(sequence) history = [] if (not predict_first): history.append(next(iterator)) for token in iterator: if (len(history) == max_n): ...
def preemption_setup(config): if (config.tolerance.id is None): return config resume_dir = os.path.join(get_original_cwd(), config.tolerance.logdir, str(config.tolerance.id)) if os.path.exists(resume_dir): print(f'Resuming from {resume_dir}') with open(os.path.join(resume_dir, 'hydra...
def typeset_term_tables(fd, table): scattab = [('_st_', 2), ('_sd_', 0), ('_adj_', 0), ('_tl_', 1), ('_ul_', 1), ('_th', 2), ('_eth', 2), ('_of_', 2), ('de_', 3)] new_tabs = [[], [], [], []] for term_name in six.iterkeys(table): for (term_tag, tab_id) in scattab: if (term_tag in term_nam...
_class class VELoss(): def __init__(self, sigma_min=0.02, sigma_max=100): self.sigma_min = sigma_min self.sigma_max = sigma_max def __call__(self, net, images, labels, augment_pipe=None): rnd_uniform = torch.rand([images.shape[0], 1, 1, 1], device=images.device) sigma = (self.sig...
class mumps_struc_c_x(ctypes.Structure): _fields_ = [('sym', mumps_int), ('par', mumps_int), ('job', mumps_int), ('comm_fortran', mumps_int), ('icntl', (mumps_int * 40)), ('aux', (ctypes.c_uint8 * AUX_LENGTH))]
def test_sample_hiddens(): rng = np.random.RandomState(0) X = Xdigits[:100] rbm1 = BernoulliRBM(n_components=2, batch_size=5, n_iter=5, random_state=42) rbm1.fit(X) h = rbm1._mean_hiddens(X[0]) hs = np.mean([rbm1._sample_hiddens(X[0], rng) for i in range(100)], 0) assert_almost_equal(h, hs, ...
class KitModel(nn.Module): def __init__(self, weight_file): super(KitModel, self).__init__() global __weights_dict __weights_dict = load_weights(weight_file) self.res5a_branch1 = self.__conv(2, name='res5a_branch1', in_channels=1024, out_channels=2048, kernel_size=(1, 1), stride=(2, ...
def preprocess_all(): for (name, dataset) in datasets.items(): print(('Preprocessing ' + name)) dataset.preprocess(CACHE_LOCATION, OUTPUT_LOCATION)
def dtype_from_name(name): if (name == 'bit'): return core.TYPE_BIT elif (name == 'fp32'): return core.TYPE_FP32 elif (name == 'fp64'): return core.TYPE_FP64 elif (name == 'int8'): return core.TYPE_INT8 elif (name == 'int16'): return core.TYPE_INT16 elif (...
def get_reference_score(aligner, input_text, context, aligner_type, remove_stopwords): if isinstance(input_text, list): align_list = [] for ref in input_text: if (aligner_type == 'bleurt'): i = context c = ref else: i = ref ...
class NpDataset(Dataset): def _init_params_to_attrs(self, params): self._input_file = params.input_file self._output_file = params.output_file self._batch_size = params.batch_size self._horizon = params.horizon self._save_every_n_steps = params.save_every_n_steps self...
def braid_from_piecewise(strands): L = strands i = min((val[1][0] for val in L)) totalpoints = [[[a[0][1], a[0][2]]] for a in L] indices = [1 for a in range(len(L))] while (i < 1): for (j, val) in enumerate(L): if (val[indices[j]][0] > i): xauxr = val[(indices[j] ...
_utils.test(require=ti.extension.quant_basic, arch=[ti.cpu, ti.cuda, ti.vulkan], exclude=[vk_on_mac, cuda_on_windows], debug=True) def test_quant_store_fusion(capfd): x = ti.field(dtype=ti.types.quant.int(16, True)) y = ti.field(dtype=ti.types.quant.int(16, True)) v = ti.BitpackedFields(max_num_bits=32) ...
def test_nonlocal_failure(): import pybind11_cross_module_tests as cm with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal() assert (str(excinfo.value) == 'generic_type: type "NonLocalType" is already registered!')
class QueryOnTrilineGradQuery(PythonFunction): def __init__(self, ctx, min_, max_, boundary_check=False): super(QueryOnTrilineGradQuery, self).__init__(ctx) self._min = min_ self._max = max_ self._boundary_check = boundary_check def name(self): return self.__class__.__nam...
class ExprVisitor(GenericVisitor): _interp: Interpreter _in_values: List[Any] _out_value: Any _unary_dispatch_table: ClassVar[Dict[(UnaryOperator, Callable[([Any], Any)])]] = {UnaryOperator.NOT: (lambda x: (not x)), UnaryOperator.NEG: (lambda x: (- x))} _binary_dispatch_table: ClassVar[Dict[(BinaryO...
def test_multi_objective_gradients_losses_same(): with pytest.raises(ValueError): multi_cdv.get_descent_vector(losses, np.zeros(shape=(3, 1)))
def include_kernels_h(specification): print('Generating awkward-cpp/include/awkward/kernels.h...') with open(os.path.join(CURRENT_DIR, '..', 'awkward-cpp', 'include', 'awkward', 'kernels.h'), 'w') as header: header.write(f'''// AUTO GENERATED ON {reproducible_datetime()} // DO NOT EDIT BY HAND! // // To...
_task('bitod_nlg') class BiTODNLG(BiTOD): def __init__(self, name, args): super().__init__(name, args) self._metrics = ['casedbleu'] def get_splits(self, root, **kwargs): kwargs['train_target'] = 'rg' kwargs['e2e_evaluation'] = self.args.e2e_dialogue_evaluation return E2E...
class ConcatChannels(nn.Module): def __init__(self, channels): super(ConcatChannels, self).__init__() self.channels = int(channels) def forward(self, x): return torch.cat((x, Variable(torch.zeros(x.size()).type_as(x.data).repeat(1, self.channels, 1, 1))), dim=1)
def test_get_default_graph_def_by_name(): 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)])] network_names = ['network1', 'network2', 'network3'] for (module_creat...
def generate_scale_factor(rng): scale_factor = 1 r = rng.uniform(0, 1) if (0.7 <= r <= 0.8): scale_factor = 2 elif (0.8 <= r): scale_factor = 4 return scale_factor
def main(): parser = argparse.ArgumentParser(description='Caffe2: ImageNet Trainer') parser.add_argument('--train_data', type=str, default=None, required=True, help="Path to training data (or 'null' to simulate)") parser.add_argument('--num_layers', type=int, default=50, help='The number of layers in ResNe(...
def _format(message, category, filename, lineno, line=None): w = '{}: {}\n'.format(category.__name__, message) return w
class SetShuffleProduct(ShuffleProduct_abstract): def __init__(self, l1, l2, element_constructor=None): assert (isinstance(l1, Iterable) and isinstance(l2, Iterable)) assert all((isinstance(elem, Iterable) for elem in l1)) assert all((isinstance(elem, Iterable) for elem in l2)) if (e...
def collect_results_gpu(result_part, size): (rank, world_size) = get_dist_info() part_tensor = torch.tensor(bytearray(pickle.dumps(result_part)), dtype=torch.uint8, device='cuda') shape_tensor = torch.tensor(part_tensor.shape, device='cuda') shape_list = [shape_tensor.clone() for _ in range(world_size)]...
def run_simulation(model, loader, device): model.eval() with torch.no_grad(): predictions = eval_model(model, loader, device, return_predictions=True) return predictions
def load_mumps_libraries(): mumps_libs['dmumps'] = load_library('dmumps').dmumps_c mumps_libs['zmumps'] = load_library('zmumps').zmumps_c
def get_configs_from_args(args): config = {} args = args[1:].copy() if os.path.isfile(args[0]): config.update(read_config_from_file(args[0])) args = args[1:] elif os.path.isdir(args[0]): config_path = os.path.join(args[0], 'config_input.yaml') config.update(read_config_fr...
def fuse_conv_bn(module): last_conv = None last_conv_name = None for (name, child) in module.named_children(): if isinstance(child, (nn.modules.batchnorm._BatchNorm, nn.SyncBatchNorm)): if (last_conv is None): continue fused_conv = _fuse_conv_bn(last_conv, chi...
def standard_lane(offset=3.6, rm=STD_ROADMARK_BROKEN): lc = Lane(a=offset) lc.add_roadmark(rm) return lc
class NAG(Optimizer): def __init__(self, params, lr=required, momentum=0, weight_decay=0): defaults = dict(lr=lr, lr_old=lr, momentum=momentum, weight_decay=weight_decay) super(NAG, self).__init__(params, defaults) def step(self, closure=None): loss = None if (closure is not None...
class UNetDiscriminatorAesrgan(nn.Module): def __init__(self, num_in_ch, num_feat=64, skip_connection=True): super(UNetDiscriminatorAesrgan, self).__init__() norm = spectral_norm self.conv0 = nn.Conv2d(num_in_ch, num_feat, kernel_size=3, stride=1, padding=1) self.conv1 = norm(nn.Conv...
def runShardedTrainLoop(opts, myTrainFun): start_epoch = 0 pretrained_model = opts['model_param']['pretrained_model'] if ((pretrained_model != '') and os.path.exists(pretrained_model)): (start_epoch, prev_checkpointed_lr, best_metric) = checkpoint.initialize_params_from_file(model=None, weights_file...
def main(): n_generators = 5 dataset = 'mnist' path_teacher = f'../pretrained/{dataset}.pth.tar' path_out = f'../out/{dataset}' generators = [] for i in range(n_generators): path_gen = f'{path_out}/generator-{i}' path_model = train_generator(dataset, path_teacher, path_gen, i) ...
class ConvSN3D(Conv3D): def build(self, input_shape): if (self.data_format == 'channels_first'): channel_axis = 1 else: channel_axis = (- 1) if (input_shape[channel_axis] is None): raise ValueError('The channel dimension of the inputs should be defined. Fo...
def compare_commands_to_demonstrator(out_directory: str, parameters: Dict[(str, Union[(int, float, str, bool)])], loaded_policies: Iterable[policies.RvS], attribute_dicts: List[Dict[(str, Union[(int, float, str)])]], env: offline_env.OfflineEnv, goals: Union[(np.ndarray, List[np.ndarray])], goal_names: List[Union[(str,...
def main(): plot_collapse() plot_ETF() plot_WH_relation() plot_residual() plot_train_acc() plot_test_acc()
def val_generator(source_path, folder_list, batch_size): print('Source path = ', source_path, '; batch size =', batch_size) while True: t = np.random.permutation(folder_list) num_batches = (len(folder_list) // batch_size) for batch in range(num_batches): (yield val_load_batch...
def read_pfm(file): file = open(file, 'rb') color = None width = None height = None scale = None endian = None header = file.readline().rstrip() header = str(bytes.decode(header, encoding='utf-8')) if (header == 'PF'): color = True elif (header == 'Pf'): color = F...
def get_dataset_names(data_name): name_dt = {'image_pair_mnist': ['cifar10', 'mnist'], 'image_pair_rotation': ['cifar10', 'cifar10-rotated'], 'image_pair_flip': ['cifar10', 'cifar10-flipped'], 'image_pair_mnist_sound': ['mnist', 'fdss'], 'kinetics_sounds': ['kinetics-sounds-slowfast', 'kinetics-sounds-vggish']} ...
class ResultHandler(ScorerHandler): def get(self): r = json.dumps(self.scorer.score()) self.write(r)
class UnboundSymbols(EnvTransform, SkipDeclarations): def __init__(self): CythonTransform.__init__(self, None) self.unbound = set() def visit_NameNode(self, node): if (not self.current_env().lookup(node.name)): self.unbound.add(node.name) return node def __call__(...
class ConstantImportanceMetric(BaseImportanceMetric): first_num_oc = None second_num_oc = None simd = 1 def __init__(self, **kwargs): pass def get_entry_node_to_simd_score(self, entry_nodes: List[BaseNode]): grouped_indices = {entry_nodes[0]: [np.arange(i, min((i + ConstantImportance...
def make_graph_from_vectors(X, *, knn_edges, random_edges=0, virtual_vertices=0, deduplicate=True, directed=True, verbose=False, squared=True, **kwargs): (num_vectors, vector_dim) = X.shape X = np.require(check_numpy(X), dtype=np.float32, requirements=['C_CONTIGUOUS']) if (virtual_vertices != 0): if...
class RowStandardTableauTuples_all(RowStandardTableauTuples, DisjointUnionEnumeratedSets): def __init__(self): RowStandardTableauTuples.__init__(self) from sage.combinat.partition_tuple import PartitionTuples DisjointUnionEnumeratedSets.__init__(self, Family(PartitionTuples(), RowStandardTab...
def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, doc_stride, max_query_length, is_training, threads=1): features = [] threads = min(threads, cpu_count()) with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p: annotate_ = partial...
class TestDSWrapper(): def test_implicit_coco_initialization(self): ds_wrapper = DSWrapper(data_path=data_path) assert (ds_wrapper.parent_folder == base_ds) assert (ds_wrapper.data_path == data_path), 'root datset should be equal' assert (ds_wrapper.data_input == input_path), 'DSWrap...
class SimpleExperiment(): def __init__(self): self.data = {} def log_hparams(self, params: dict[(str, Any)]) -> None: def log_metrics(self, metrics: dict[(str, float)], step: Optional[int]=None) -> None: def _handle_value(value): if isinstance(value, torch.Tensor): ...
class TFMobileBertForSequenceClassification(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def word_normalise(words): ret = [] for word in words: if (word.lower() in months): word = months[word.lower()] if (word.lower() in replace_words): word = replace_words[word.lower()] for regex in replace_vocab: word = re.sub(regex, '', word) wo...
def create_RepVGG_B2g4(last_stride, norm_type): return RepVGG(last_stride, norm_type, num_blocks=[4, 6, 16, 1], width_multiplier=[2.5, 2.5, 2.5, 5], override_groups_map=g4_map)
.parametrize('data_dict, name, source, type, hint, result', [pytest.param('full_spark_dataset', 'gender', None, None, None, ['user_id', 'item_id', 'timestamp', 'rating', 'category_id', 'feature1'], marks=pytest.mark.spark), pytest.param('full_spark_dataset', 'feature1', FeatureSource.ITEM_FEATURES, FeatureType.NUMERICA...
def cla1_adv_ll_clamp(input, target, class_freq): target_freq = class_freq[target] limit = target_freq.clamp(min=1e-08).log() return torch.max(torch.gather(input, 1, target.unsqueeze(1)).squeeze(1), limit).mean()
class miniImageNetMultiCrop(miniImageNet): def __init__(self, root, mode, num_patch=9, image_sz=84): super().__init__(root, mode) self.num_patch = num_patch self.transform = transforms.Compose([transforms.RandomResizedCrop(image_sz), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ...
def test_validate_series(df_urls: pd.DataFrame) -> None: df_valid = validate_url(df_urls['messy_url']) df_check = pd.Series([False, True, True, False, False, False, True, False, False, False, False, True, True]) assert df_check.equals(df_valid)