code
stringlengths
101
5.91M
_numpy_output(check_dtype=True) def test_ufunc_expm1_c(A: dace.complex64[10]): return np.expm1(A)
class TestContainsNaNTest(): def test_policy(self): data = np.array([1, 2, 3, np.nan]) (contains_nan, nan_policy) = _contains_nan(data, nan_policy='propagate') assert contains_nan assert (nan_policy == 'propagate') (contains_nan, nan_policy) = _contains_nan(data, nan_policy='...
def create_batches(sampler, shuffle=True, cache_dir='cache'): batches_dict = defaultdict((lambda : [])) for (i, batch) in enumerate(tqdm(sampler, desc='Creating batches for training')): for (k, v) in batch.items(): batches_dict[k].append(v) batches = Dataset.from_dict(batches_dict) r...
class TestMediumLevelActionManagerSimple(unittest.TestCase): def test_simple_mdp_without_start_orientations(self): print('Simple - no start orientations (& shared motion goals)') mlam = ml_action_manager_simple self.simple_mpd_empty_hands(mlam) self.simple_mdp_deliver_soup(mlam) ...
def get_dataset_details(dataset): if (dataset == 'mnist'): (input_nc, input_width, input_height) = (1, 28, 28) classes = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) elif (dataset == 'cifar10'): (input_nc, input_width, input_height) = (3, 32, 32) classes = ('plane', 'car', 'bird', 'cat', 'deer...
def writetab(llargs, fout, kset): t = Texttable() t.set_max_width(500) info = ['dataset', 'al_type', 'knn', 'clustering'] restricted = ['knn', 'clustering'] header = [] format_row = [] for k in info: if (k not in ['exp_fd']): header.append(k) format_row.append...
def test_trigamma(): x = Symbol('x') assert (trigamma((- 2)) == zoo) assert (trigamma(x) == polygamma(1, x))
class GroupAll(nn.Module): def __init__(self, use_xyz: bool=True): super().__init__() self.use_xyz = use_xyz def forward(self, xyz: torch.Tensor, new_xyz: torch.Tensor, features: torch.Tensor=None): grouped_xyz = xyz.transpose(1, 2).unsqueeze(2) if (features is not None): ...
def verify_dir_exists(filename): if (not os.path.exists(os.path.dirname(filename))): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: if (exc.errno != errno.EEXIST): raise
def get_types(entity: str) -> List[str]: query = (('\n PREFIX rdf: < PREFIX rdfs: < PREFIX : < \n SELECT (?x0 AS ?value) WHERE {\n SELECT DISTINCT ?x0 WHERE {\n :' + entity) + ' :type.object.type ?x0 . \n }\n }\n ') sparql.setQuery(query) try: results = sparql.query().con...
def euler_xyz_to_R(euler): return ((_Rz(np.deg2rad(euler[2])) * _Ry(np.deg2rad(euler[1]))) * _Rx(np.deg2rad(euler[0])))
def test_Updater_GradientDescent(): with make_scope() as session: from returnn.tf.network import TFNetwork, ExternData from returnn.config import Config config = Config() network = TFNetwork(extern_data=ExternData(), train_flag=True) network.add_layer(name='output', layer_cla...
def plot_embedding_as_heatmap(embed, ax=None, title='', shape=None, color_range=(0, 0.3)): if (ax is None): ax = plt.gca() if (shape is None): height = int(np.sqrt(len(embed))) shape = (height, (- 1)) embed = embed.reshape(shape) cmap = cm.get_cmap() mappable = ax.imshow(embe...
def test_pytest_parametrize(testdir): testdir.make_test('\.parametrize("param", ("A", "B"))\()\ndef test_(request, param, case):\n request.config.HYPOTHESIS_CASES += 1\n assert case.full_path == "/v1/users"\n assert case.method in ("GET", "POST")\n', paths={'/users': {'get': {'responses': {'200': {'descrip...
def nonsaturating_hinge_gan_losses(discriminator_real_outputs, discriminator_fake_outputs): generator_loss = tf.losses.sigmoid_cross_entropy(tf.ones_like(discriminator_fake_outputs), discriminator_fake_outputs) discriminator_loss = (tf.reduce_mean(tf.nn.relu((1.0 - discriminator_real_outputs))) + tf.reduce_mean...
class ParameterNamer(object): def __call__(self, graph): for node in graph.nodes: if (node.data is None): continue if (node.kind in (NodeKind.Convolution, NodeKind.InnerProduct)): names = ('weights',) if node.parameters.bias_term: ...
def group_together(file_paths, num_samples): for i in range(1, len(num_samples)): num_samples[i] *= num_samples[(i - 1)] all_lines = [] for file_path in file_paths: lines = [] with open(file_path) as f: for line in f: lines.append(line.strip()) all...
class RefAdagrad(RefSolver): def __init__(self, lr, eps): super().__init__() self.lr = lr self.eps = eps self.G = {} def _set_state_impl(self, key, param): self.G[key] = np.zeros_like(param) def _update_impl(self, key, p, g): _update_adagrad(p, g, self.G[key],...
def test_test_case_equals_on_different_prim(simple_test_case: dtc.DefaultTestCase, constructor_mock): cloned = simple_test_case.clone() simple_test_case.add_statement(st.ConstructorStatement(simple_test_case, constructor_mock, {'y': simple_test_case.statements[0].ret_val})) cloned.add_statement(st.Construct...
def test_format_tags(): tags = ['tag_1', 'tag_2', 'tag_3'] assert (format_tags(tags) == '[tag_1,tag_2,tag_3]')
class ThresholdedImprovementScoringFunction(MoleculewiseScoringFunction): def __init__(self, objective, constraint, threshold, offset): super().__init__() self.objective = objective self.constraint = constraint self.threshold = threshold self.offset = offset def raw_score...
def test_for_one_epoch(model, loss, test_loader, epoch_number): model.eval() loss.eval() data_time_meter = utils.AverageMeter() batch_time_meter = utils.AverageMeter() loss_meter = utils.AverageMeter(recent=100) top1_meter = utils.AverageMeter(recent=100) top5_meter = utils.AverageMeter(rece...
class ContinualScaler(): state_dict_key = 'amp_scaler' def __init__(self, disable_amp): self._scaler = torch.cuda.amp.GradScaler(enabled=(not disable_amp)) def __call__(self, loss, optimizer, model_without_ddp, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False, hook=True): ...
def index_predicates(es, KB): file_name = ('%s_predicates' % KB) file_path = ('../data/%s.txt' % file_name) ns_filter = None index_name = ('%sp' % KB) start_indexing(es, index_name, file_path, ns_filter)
def run(*args, env=None): args = list(map(str, args)) if (env is None): return subprocess.Popen(args).wait() else: e = os.environ.copy() e.update(env) return subprocess.Popen(args, env=e).wait()
class Tanh_DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10): super(Tanh_DenseNet, self).__init__() self.growth_rate = growth_rate num_planes = (2 * growth_rate) self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, padding=1, bias=...
class Config(NamedTuple): name: str settings_train: str settings_eval: str rendering_mode: LoadedModel.EvaluationMode args: List[str]
class Dict(TokenConverter): def __init__(self, expr): super(Dict, self).__init__(expr) self.saveAsList = True def postParse(self, instring, loc, tokenlist): for (i, tok) in enumerate(tokenlist): if (len(tok) == 0): continue ikey = tok[0] ...
class ginn_autoencoder(nn.Module): def __init__(self, g, mask, in_feats, h_feats, activation, dropout): super(ginn_autoencoder, self).__init__() self.mask = mask self.masked_gcn = GCL(g, in_feats, h_feats, activation, dropout) self.output_gcn = GCL(g, h_feats, in_feats, torch.sigmoid...
def width_to_lifetime(Gamma): if (Gamma <= 0.0): raise ValueError('Input provided, %s <= 0!'.format(Gamma)) return (hbar / float((Gamma / MeV)))
def get_train_transformers(args): img_tr = [transforms.RandomResizedCrop(int(args.image_size), (args.min_scale, args.max_scale))] if (args.flip > 0.0): img_tr.append(transforms.RandomHorizontalFlip(args.flip)) if (args.jitter > 0.0): img_tr.append(transforms.ColorJitter(brightness=args.jitte...
class FunnelTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION slow_tokenizer_class = FunnelTokenizer max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDI...
def jamendo_resampler(track_id): audio_path = os.path.join(DATASET, 'mtg', 'raw30s', track_id) (src, _) = load_audio(path=audio_path, ch_format=STR_CH_FIRST, sample_rate=MUSIC_SAMPLE_RATE, downmix_to_mono=True) save_name = os.path.join(DATASET, 'mtg', 'npy', track_id.replace('.mp3', '.npy')) if (not os....
class TimeSplitter(Splitter): _init_arg_names = ['time_threshold', 'drop_cold_users', 'drop_cold_items', 'query_column', 'item_column', 'timestamp_column', 'session_id_column', 'session_id_processing_strategy', 'time_column_format'] def __init__(self, time_threshold: Union[(datetime, str, int, float)], query_co...
def get_image_ocrs_from_path(pdf_file_path: str, ocr_file_path: str, resize_scale=resize_scale): reader = PdfReader(pdf_file_path) img_list = [] for i in range(len(reader.pages)): page = reader.pages[i] for image_file_object in page.images: stream = io.BytesIO(image_file_object.d...
_torch _sigopt class TrainerHyperParameterSigOptIntegrationTest(unittest.TestCase): def setUp(self): args = TrainingArguments('..') self.n_epochs = args.num_train_epochs self.batch_size = args.train_batch_size def test_hyperparameter_search(self): class MyTrialShortNamer(TrialSho...
def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-08, epsrel=1.49e-08): def ranges0(*args): return [(qfun(args[1], args[0]) if callable(qfun) else qfun), (rfun(args[1], args[0]) if callable(rfun) else rfun)] def ranges1(*args): return [(gfun(args[0]) if callable(gfun) else gf...
class Renderer(object): MAX_FBO_WIDTH = 2000 MAX_FBO_HEIGHT = 2000 def __init__(self, models_cad_files, samples=1, vertex_tmp_store_folder='.', clamp=False, vertex_scale=1.0): self._samples = samples self._context = gu.OffscreenContext() (W, H) = (Renderer.MAX_FBO_WIDTH, Renderer.MAX...
def evaluate_mislabeling_patch(target_class, rois, detections_adv, detections_rand, iou_thresh=0.5): (score_adv, score_rand) = (0, 0) for (_, roi_obj_bbox, _, _) in rois: found = False for detection in detections_adv: det_obj_bbox = tuple(map(float, detection[(- 4):])) de...
def Train(model, x, adj, A, optimizer): max_epochs = 100 min_loss = 100 for epoch in range(max_epochs): Y = model(x, adj) loss = CutLoss.apply(Y, A) print('Epoch {}: Loss = {}'.format(epoch, loss.item())) if (loss < min_loss): min_loss = loss.item() ...
def rand_v_diffusion(shape, sigma_data=1.0, min_value=0.0, max_value=float('inf'), device='cpu', dtype=torch.float32): min_cdf = ((math.atan((min_value / sigma_data)) * 2) / math.pi) max_cdf = ((math.atan((max_value / sigma_data)) * 2) / math.pi) u = ((torch.rand(shape, device=device, dtype=dtype) * (max_cd...
class RepeatFactorTrainingSampler(Sampler): def __init__(self, dataset, config, num_replicas=None, rank=None, shuffle=True): self.shuffle = shuffle self.config = config if (num_replicas is None): if (not dist.is_available()): raise RuntimeError('Requires distribut...
class TrafficControlPredictTrafficCongestion(VirtualFunctionTool): name = 'TrafficControlPredictTrafficCongestion' summary = 'Predicts traffic congestion at a specific road or intersection in the future based on historical data and current conditions.' parameters: List[ArgParameter] = [{'name': 'location_id...
def get_activations(images, sess, batch_size=50, verbose=False): inception_layer = _get_inception_layer(sess) d0 = images.shape[0] if (batch_size > d0): print('warning: batch size is bigger than the data size. setting batch size to data size') batch_size = d0 n_batches = (d0 // batch_siz...
def test_evaluation(): table = pd.DataFrame({'id': [0, 1, 2, 3], 'col': [1, 2, 3, 4]}) slightly_different_table = pd.DataFrame({'id': [0, 1, 2, 3], 'col': [1, 2, 3, 3.5]}) data = {'table1': table, 'table2': table} samples = {'table1': table, 'table2': slightly_different_table} metadata = MultiTableM...
def late_import(): if ('GF2' in globals()): return global Cache_ntl_gf2e, GF, GF2 import sage.rings.finite_rings.element_ntl_gf2e Cache_ntl_gf2e = sage.rings.finite_rings.element_ntl_gf2e.Cache_ntl_gf2e import sage.rings.finite_rings.finite_field_constructor GF = sage.rings.finite_rings....
def first_bn_multiplier_weighting_fn(orig_bn_stats_holder: KerasOriginalBNStatsHolder, **kwargs) -> Dict[(str, float)]: num_bn_layers = orig_bn_stats_holder.get_num_bn_layers() layer_weighting_dict = {orig_bn_stats_holder.get_bn_layer_names()[0]: (10 / num_bn_layers)} layer_weighting_dict.update({bn_layer_n...
class _FilePersistence(_ConcretePersistence): def __init__(self, data_filename, data_store, configurator, ui): super(_FilePersistence, self).__init__(data_store, ui) if (not data_filename): raise ValueError(('DataPointPersistence expects a filename ' + ('for data_filename, but got: %s' %...
class Swish(nn.Module): def __init__(self, inplace: bool=False): super(Swish, self).__init__() self.inplace = inplace def forward(self, x): return swish(x, self.inplace)
def TupleSort(name, sorts, ctx=None): tuple = Datatype(name, ctx) projects = [(('project%d' % i), sorts[i]) for i in range(len(sorts))] tuple.declare(name, *projects) tuple = tuple.create() return (tuple, tuple.constructor(0), [tuple.accessor(0, i) for i in range(len(sorts))])
def magnet_loss(features, labels, margin=1.0, unique_labels=None): nil = tf.constant(0.0, tf.float32) one = tf.constant(1.0, tf.float32) minus_two = tf.constant((- 2.0), tf.float32) eps = tf.constant(0.0001, tf.float32) margin = tf.constant(margin, tf.float32) num_per_class = None if (unique...
def _has_only_empty_bbox(anno): return all((any(((o <= 1) for o in obj['bbox'][2:])) for obj in anno))
def model_parameters(model): return (sum([np.prod(p.size()) for p in model.parameters()]) / 1000000.0)
def gradients_speed(ys, xs, grad_ys=None, **kwargs): return gradients(ys, xs, grad_ys, checkpoints='speed', **kwargs)
def get_arg_parser(): from snips_nlu.cli.download import add_download_parser, add_download_all_languages_parser from snips_nlu.cli.download_entity import add_download_entity_parser, add_download_language_entities_parser from snips_nlu.cli.generate_dataset import add_generate_dataset_subparser from snips...
def get_args_EBM(): parser = argparse.ArgumentParser(description='Concept argparse.') parser.add_argument('--exp_id', type=str, help='Experiment id') parser.add_argument('--date_time', type=str, help='date and time') parser.add_argument('--exp_name', default='None', help='If not "None", will use asynchr...
def generate_png(all_iter, net, gt_hsi, Dataset, device, total_indices, path): pred_test = [] for (X, y) in all_iter: X = X.to(device) net.eval() pred_test.extend(net(X).cpu().argmax(axis=1).detach().numpy()) gt = gt_hsi.flatten() x_label = np.zeros(gt.shape) for i in range(l...
def parse_flags(line): d = {'include_dirs': [], 'library_dirs': [], 'libraries': [], 'macros': [], 'ignored': []} flags = (' ' + line).split(' -') for flag in flags: flag = ('-' + flag) if (len(flag) > 0): if flag.startswith('-I'): d['include_dirs'].append(flag[2:...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('dump_dir') parser.add_argument('start', type=int) parser.add_argument('end', type=int) return parser.parse_args()
def _apply_chi(dwg, g, meld, offset): tile = Meld.target(meld) if (Meld.action(meld) == Action.CHI_L): tile1 = tile tile2 = (tile + 1) tile3 = (tile + 2) elif (Meld.action(meld) == Action.CHI_M): tile1 = tile tile2 = (tile - 1) tile3 = (tile + 1) else: ...
def register_Ns3Icmpv6TimeExceeded_methods(root_module, cls): cls.add_constructor([param('ns3::Icmpv6TimeExceeded const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'uint32_t', [param('ns3::Buffer::Iterator', 'start')], is_virtual=True) cls.add_method('GetInstanceTypeId', 'ns3::Ty...
def is_external_stream(node: dace.sdfg.nodes.Node, subgraph: Union[(dace.sdfg.SDFGState, ScopeSubgraphView)]): external = False if (isinstance(node, dace.nodes.AccessNode) and isinstance(node.desc(subgraph), dt.Stream)): for nn in subgraph.nodes(): if ((nn != node) and isinstance(nn, dace.no...
class LinUCBVI(UCBVI): def __init__(self, mdp, n_episodes=1, init_state=0, reg_factor=1.0, confidence_scaling_factor=(- 1.0), bound_theta=1.0, throttle=int(100.0)): self.bound_theta = bound_theta super().__init__(mdp, n_episodes=n_episodes, init_state=init_state, reg_factor=reg_factor, confidence_sc...
.hypothesis_nested .operations('custom_format') def test_schema_query_hook(wsgi_app_schema, schema_url): _app_schema.hook def filter_query(context, query): return (query['id'].isdigit() and query['id'].isascii()) strategy = wsgi_app_schema['/custom_format']['GET'].as_strategy() (case=strategy) ...
_metric def fid50k_full(opts): opts.dataset_kwargs.update(max_size=None) opts.dataset_kwargs.cfg.update(mirror=False) fid = frechet_inception_distance.compute_fid(opts, max_real=None, num_gen=50000) return dict(fid50k_full=fid)
def get_command_args(): parser = argparse.ArgumentParser() parser.add_argument('--config', '-c', help='pattern config', type=str, default='meta_infos/configs/dataset_config.yaml') parser.add_argument('--out', '-o', help='folder to save generated patterns', type=str, default='test/outputs') args = parser...
class MobileInvertedResidualBlock(MyModule): def __init__(self, mobile_inverted_conv, shortcut): super(MobileInvertedResidualBlock, self).__init__() self.mobile_inverted_conv = mobile_inverted_conv self.shortcut = shortcut def forward(self, x): if ((self.mobile_inverted_conv is N...
def _update_command_info(): global _command_info_cache if (_command_info_cache is not None): return cache = {} with open(os.path.join(SAGE_LOCAL, 'share/qepcad', 'qepcad.help')) as help: assert (help.readline().strip() == '') while True: cmd_line = help.readline() ...
('/annotator', methods=['GET']) def annotator(): cad_type = request.args.get('cad', '') if (cad_type == '0'): condition = '' else: condition = f'and source = {cad_type}' keyword = request.args.get('keyword', '') img_info = get_cad_imgs(keyword, condition) print(f'{len(img_info)} ...
def _digit_span_to_special_tag(span): if ((span[0] == '0') and (len(span) > 2)): return '<NUM>' decimal_point_count = 0 for (idx, char) in enumerate(span): if ((char == '.') or (char == '.') or (char == '')): decimal_point_count += 1 if ((span[(- 1)] == '.') or (span[(- 1)] =...
def elog(x): if ((x <= 0.0) or (x >= 1.0)): return 0 else: return (x * log(x))
def build_input_fn(builder, is_training): def _input_fn(params): preprocess_fn_pretrain = get_preprocess_fn(is_training, is_pretrain=True) preprocess_fn_finetune = get_preprocess_fn(is_training, is_pretrain=False) num_classes = builder.info.features['label'].num_classes def map_fn(im...
def train(args, train_dataset, model: PreTrainedModel, tokenizer: PreTrainedTokenizer) -> Tuple[(int, float)]: if (args.local_rank in [(- 1), 0]): tb_writer = SummaryWriter() args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) def collate(examples: List[torch.Tensor]): ...
def is_valid_profile(profile, truncation_type, p=2, generic=None): from sage.rings.infinity import Infinity if (generic is None): generic = (p != 2) if (not generic): pro = (list(profile) + ([truncation_type] * len(profile))) r = 0 for pro_r in pro: r += 1 ...
class TomlEncoder(object): def __init__(self, _dict=dict, preserve=False): self._dict = _dict self.preserve = preserve self.dump_funcs = {str: _dump_str, unicode: _dump_str, list: self.dump_list, bool: (lambda v: unicode(v).lower()), int: (lambda v: v), float: _dump_float, Decimal: _dump_flo...
class PNW(BenchmarkDataset): def __init__(self, **kwargs): citation = 'Ni, Y., Hutko, A., Skene, F., Denolle, M., Malone, S., Bodin, P., Hartog, R., & Wright, A. (2023).Curated Pacific Northwest AI-ready Seismic Dataset. Seismica, 2(1). license = 'CC BY 4.0' super().__init__(citation=citati...
class Task(object): def __init__(self, config): self.config = config self.cli = Client(config) def exec_sql(self, code, output=sys.stdout, resultful=False): (task_id, status) = self.cli.create_sql_task(code) return self._tracking(task_id, status, output, resultful) def exec_p...
class blis_info(blas_info): section = 'blis' dir_env_var = 'BLIS' _lib_names = ['blis'] notfounderror = BlasNotFoundError def calc_info(self): lib_dirs = self.get_lib_dirs() opt = self.get_option_single('blis_libs', 'libraries') blis_libs = self.get_libs(opt, self._lib_names)...
class Brick(PhysicalObject): def __init__(self, *args, **kwargs): self.row = kwargs.pop('row') self.column = kwargs.pop('column') kwargs['color'] = self.get_color() super(Brick, self).__init__('brick.png', *args, **kwargs) def get_color(self): colors = {0: (255, 0, 0), 1:...
def create_model(cfg, device): cfg = copy.deepcopy(cfg) cfg.freeze() model = build_detection_model(cfg) model = model.to(device) return model
class Singular(Executable): def __init__(self): Executable.__init__(self, 'singular', SINGULAR_BIN, spkg='singular', type='standard')
class RandomIdentitySamplerAdv(Sampler): def __init__(self, data_source, batch_size, num_instances): self.data_source = data_source self.batch_size = batch_size self.num_instances = num_instances self.num_pids_per_batch = (self.batch_size // self.num_instances) self.index_dic...
class ChineseCLIPVisionConfig(PretrainedConfig): model_type = 'chinese_clip_vision_model' def __init__(self, hidden_size=768, intermediate_size=3072, projection_dim=512, num_hidden_layers=12, num_attention_heads=12, num_channels=3, image_size=224, patch_size=32, hidden_act='quick_gelu', layer_norm_eps=1e-05, at...
class FalseConditionElimination(transformation.MultiStateTransformation): state_a = transformation.PatternNode(sdfg.SDFGState) state_b = transformation.PatternNode(sdfg.SDFGState) def expressions(cls): return [sdutil.node_path_graph(cls.state_a, cls.state_b)] def can_be_applied(self, graph: SDFG...
def check_all_models_are_tested(): modules = get_model_modules() test_files = get_model_test_files() failures = [] for module in modules: test_file = [file for file in test_files if (f"test_{module.__name__.split('.')[(- 1)]}.py" in file)] if (len(test_file) == 0): failures.a...
def get_score(submission_folder): FLAGS(['eval.py']) if (FLAGS.hint_mode == 'encoded_decoded'): encode_hints = True decode_hints = True elif (FLAGS.hint_mode == 'decoded_only'): encode_hints = False decode_hints = True elif (FLAGS.hint_mode == 'none'): encode_hint...
def init_weights(net, init_type='normal', init_gain=0.02): def init_func(m): classname = m.__class__.__name__ if (hasattr(m, 'weight') and ((classname.find('Conv') != (- 1)) or (classname.find('Linear') != (- 1)))): if (init_type == 'normal'): init.normal_(m.weight.data, ...
class VoVNet(Backbone): def __init__(self, cfg, input_ch, out_features=None): super(VoVNet, self).__init__() global _NORM _NORM = cfg.MODEL.VOVNET.NORM stage_specs = _STAGE_SPECS[cfg.MODEL.VOVNET.CONV_BODY] stem_ch = stage_specs['stem'] config_stage_ch = stage_specs['...
def find_library_location(lib_name: str) -> Path: torch_root = Path(torch.__file__).resolve().parent path = ((torch_root / 'lib') / lib_name) if os.path.exists(path): return path torch_root = Path(__file__).resolve().parent.parent.parent return (((torch_root / 'build') / 'lib') / lib_name)
.parametrize('inspecs', inspecs_params()) .parametrize('op', ['logical_and_scalar', 'logical_or_scalar', 'logical_xor_scalar', 'greater_scalar', 'greater_equal_scalar', 'less_scalar', 'less_equal_scalar', 'equal_scalar', 'not_equal_scalar']) def test_scalar_logical(inspecs, op, nnabla_opts): func = getattr(F, op) ...
def main(): args = parse_args() cfg = Config.fromfile(args.config) timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) if (args.work_dir is not None): mmcv.mkdir_or_exist(osp.abspath(args.work_dir)) json_file = osp.join(args.work_dir, f'fps_{timestamp}.json') else: w...
class _ContextMethodMixin(object): def save_for_backward(self, *tensors): self.to_save = tensors def mark_dirty(self, *args): self.dirty_tensors = args def mark_shared_storage(self, *pairs): warnings.warn('mark_shared_storage is deprecated. Tensors with shared storages are automatica...
class BMProfileParserPerfAI(BMProfileParser): def __init__(self): super().__init__() self.gdma_cmd = [] self.bd_cmd = [] self.bd_monitor = [] self.gdma_monitor = [] self.in_dir = None self.out_dir = None def parse(self, in_dir): self.in_dir = in_di...
def add_dataset_arguments(parser): parser.add_argument('--train-examples-paths', nargs='*', default=[], help='Input training examples') parser.add_argument('--test-examples-paths', nargs='*', default=[], help='Input test examples') parser.add_argument('--train-max-examples', type=int, help='Maximum number o...
class WeightRing(CombinatorialFreeModule): def __classcall__(cls, parent, prefix=None): return super().__classcall__(cls, parent, prefix=prefix) def __init__(self, parent, prefix): self._parent = parent self._style = parent._style self._prefix = prefix self._space = paren...
class RegLog(nn.Module): def __init__(self, num_labels, arch='resnet50', global_avg=False, use_bn=True): super(RegLog, self).__init__() self.bn = None if global_avg: if (arch == 'resnet50'): s = 2048 elif (arch == 'resnet50w2'): s = 409...
def write_prediction_result(prediction_result: PredictionResult, output_dir) -> None: input_path = prediction_result.example representation = prediction_result.inference input_filename = os.path.basename(input_path.replace('gs://', '')) output_filename = input_filename.replace('.wav', '.npy') if out...
def _unique_python(values, *, return_inverse, return_counts): try: uniques_set = set(values) (uniques_set, missing_values) = _extract_missing(uniques_set) uniques = sorted(uniques_set) uniques.extend(missing_values.to_list()) uniques = np.array(uniques, dtype=values.dtype) ...
class Transformer_exp(FNN_exp): def __init__(self, data_path, param_dict, config): super().__init__(data_path, param_dict, config) def load_model(self): model = TransformerNet(hidden_size=self.param_dict['hidden_size'], num_layers=self.param_dict['num_layers'], dropout=self.param_dict['dropout']...
def job_fssdq_opt(p, data_source, tr, te, r, J, null_sim=None): if (null_sim is None): null_sim = gof.FSSDH0SimCovObs(n_simulate=2000, seed=r) Xtr = tr.data() with util.ContextTimer() as t: n_gwidth_cand = 5 gwidth_factors = (2.0 ** np.linspace((- 3), 3, n_gwidth_cand)) med2 ...