code
stringlengths
101
5.91M
def _get_broker_actor(cache_dir, input_shards, processor, rows_per_chunk=DEFAULT_ROWS_PER_CHUNK): return ChunkCacheBroker.options(name=('lev_cache_manager::' + cache_dir), get_if_exists=True).remote(cache_dir, input_shards, processor, rows_per_chunk)
def untargeted_detection(model, img, dataset, lr, u_radius, cap=1000, margin=20, use_margin=False): model.eval() x_var = torch.autograd.Variable(img.clone().cuda(), requires_grad=True) true_label = model(transform(x_var.clone(), dataset=dataset)).data.max(1, keepdim=True)[1][0].item() optimizer_s = opti...
class _BaseMetric(ABC): def __init__(self): self.plottable = False self.integer_fields = [] self.float_fields = [] self.array_labels = [] self.integer_array_fields = [] self.float_array_fields = [] self.fields = [] self.summary_fields = [] self...
def run_info(tool, findings): fnames = {finding['name'] for finding in findings} return {'tool': tool_info(tool, fnames), 'results': [result_info(tool['id'], finding) for finding in findings]}
def process_alias_tokenization(tokens): processed_tokens = [] i = 0 while (i < len(tokens)): token = tokens[i] if (token.endswith('alias ') and ((i < (len(tokens) - 1)) and re.fullmatch(alias_id_revtok_pattern, tokens[(i + 1)])) and token[:(- 6)].isupper()): processed_tokens.appe...
def main(): t0 = time() print(__doc__) pwd = os.path.dirname(__file__) eps = (np.finfo(float).eps * 100) a_range = np.array([eps, (0.0001 * (1 - eps)), 0.0001, (0.0001 * (1 + eps)), (0.001 * (1 - eps)), 0.001, (0.001 * (1 + eps)), 0.1, 0.5, (1 * (1 - eps)), 1, (1 * (1 + eps)), 1.5, 2, 4.999, 5, 10])...
def test_compare_chromosome_2_none(comparator): assert (comparator.compare(MagicMock(chrom.Chromosome), None) == (- 1))
def _get_bytes(in_path: str, out_path: str): with open(in_path) as f, open(out_path, 'w') as f_o: for s in f: f_o.write((Bytes.encode(s.strip()) + '\n'))
def GetWeightedPageRankMP(Graph, PRankH, Attr, C=0.85, Eps=0.0001, MaxIter=100): return _snap.GetWeightedPageRankMP(Graph, PRankH, Attr, C, Eps, MaxIter)
() def run_pure_state(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): physics = Physics.from_xml_string(*get_model_and_assets()) task = Humanoid(move_speed=_RUN_SPEED, pure_state=True, random=random) environment_kwargs = (environment_kwargs or {}) return control.Environment(physic...
class alias(option_base): description = 'define a shortcut to invoke one or more commands' command_consumes_arguments = True user_options = ([('remove', 'r', 'remove (unset) the alias')] + option_base.user_options) boolean_options = (option_base.boolean_options + ['remove']) def initialize_options(s...
class MobileNetV2(nn.Module): def __init__(self, num_classes=1000, output_stride=8, width_mult=1.0, inverted_residual_setting=None, round_nearest=8): super(MobileNetV2, self).__init__() block = InvertedResidual input_channel = 32 last_channel = 1280 self.output_stride = outpu...
_test(run_synthesis=False) def test_nd_split(): (csdfg, sdfg) = _exec_hbmtransform((lambda : create_nd_sdfg('nd_split')), [('x', 'HBM', '0:10'), ('y', 'HBM', '10:20'), ('z', 'HBM', '20:30')]) validate_nd_sdfg(csdfg, 10, 10, divide_n=10) return sdfg
class Constellation_class(Element): def __init__(self, parent, g, connected, mutable, check): Element.__init__(self, parent) self._connected = connected self._mutable = mutable self._g = g if check: self._check() def __hash__(self): if self._mutable: ...
def _fit_single_estimator(estimator, X, y, sample_weight=None, message_clsname=None, message=None): if (sample_weight is not None): try: with _print_elapsed_time(message_clsname, message): estimator.fit(X, y, sample_weight=sample_weight) except TypeError as exc: ...
class BitBottleneckLayer(nn.Module): def __init__(self, config, in_channels, out_channels=None, bottle_ratio=0.25, stride=1, dilation=1, first_dilation=None, groups=1, drop_path_rate=0.0, is_first_layer=False): super().__init__() first_dilation = (first_dilation or dilation) out_channels = (...
def main(): args = parse_args() mmcv.check_file_exist(args.prediction_path) cfg = Config.fromfile(args.config) update_data_root(cfg) if (args.cfg_options is not None): cfg.merge_from_dict(args.cfg_options) cfg.data.test.test_mode = True cfg.data.test.pop('samples_per_gpu', 0) cfg...
class TestNorms(unittest.TestCase): def test_norm(self): def f(t, x): return x t = torch.tensor([0.0, 1.0]) is_called = False def norm(state): nonlocal is_called is_called = True self.assertIsInstance(state, torch.Tensor) se...
.parametrize('factory_type', (' 'requests')) .parametrize('response_schema, payload, schema_path, instance, instance_path', (({'type': 'object'}, [], ['type'], [], []), ({'$ref': '#/components/schemas/Foo'}, [], ['type'], [], []), ({'type': 'object', 'properties': {'foo': {'type': 'object'}}}, {'foo': 42}, ['properties...
class IntQuantizer(Function): def __init__(self, size, params): self.num_bits = size self.stochastic = False self.int_exp = False self.enforce_true_zero = True self.clipping = params['threshold'] self.alpha_gaus = {2: 1.71, 3: 2.15, 4: 2.55, 5: 2.93, 6: 3.28, 7: 3.61,...
def initialize(NI, NJ, NK, datatype=np.float64): alpha = datatype(1.5) beta = datatype(1.2) C = np.fromfunction((lambda i, j: ((((i * j) + 1) % NI) / NI)), (NI, NJ), dtype=datatype) A = np.fromfunction((lambda i, k: (((i * (k + 1)) % NK) / NK)), (NI, NK), dtype=datatype) B = np.fromfunction((lambda ...
def retrieve_step_blobs(net, prefix='rnn'): count = 1 output_list = [] for op in net.Proto().op: if (op.type == 'RecurrentNetwork'): blob_name = ((prefix + '_') + str(count)) count = (count + 1) scratch_workspaces_blob_name = op.output[(- 1)] workspace...
def all_generator_source(): r = [] for (directory, _, filenames) in os.walk('tools'): for f in filenames: if (os.path.splitext(f)[1] in source_files): full = os.path.join(directory, f) r.append(full) return sorted(r)
def list_sum(x): if (len(x) == 1): return x[0] else: return (x[0] + list_sum(x[1:]))
_utils.test(require=ti.extension.sparse) def test_complex_pointer(): a = ti.field(ti.i32, shape=(4, 4)) b = ti.field(ti.i32, shape=(16, 16)) c = ti.field(ti.i32, shape=(16, 4)) d = ti.field(ti.i32, shape=(4, 4, 4)) w = ti.field(ti.i32) x = ti.field(ti.i32) y = ti.field(ti.i32) z = ti.fie...
def softmax_predictive_accuracy(logits_list, y, criterion, ret_loss=False): probs_list = [logits for logits in logits_list] probs_tensor = torch.stack(probs_list, dim=2) probs = torch.mean(probs_tensor, dim=2) if ret_loss: loss = criterion(probs, y).item() (_, pred_class) = torch.max(probs, ...
def load_json(fname, subdict=None): try: with open(fname) as json_file: params = json.load(json_file) except ValueError as e: raise Exception(f'Unable to load file {fname}') from e if (subdict is None): return params else: return params[subdict]
def is_parallel(model): return (type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))
def load_results(align_fine='none'): addregated_dir = Path(to_absolute_path('results/aggregated/')) figure_dir = Path(to_absolute_path('figures/')) if align_fine.startswith('icp'): addregated_dir = (addregated_dir.parent / (addregated_dir.name + f'_align{align_fine}')) figure_dir = (figure_d...
class BufferBinding(): def __init__(self, binding: int, iarg: int, buffer_bind_ty: BufferBindingType): self.binding: int = binding self.iarg: int = iarg self.buffer_bind_ty: BufferBindingType = buffer_bind_ty
def get_path(u: ExtNode, v: ExtNode, ancestor: ExtNode, leaf_token, up_symbol=UP, down_symbol=DOWN): path = [] (start, end) = (leaf_token(u), leaf_token(v)) while (u != ancestor): path.append(u.bn) path.append(up_symbol) u = u.log_parents[0] path.append(ancestor.bn) aux_path ...
def vgg19(): return VGG(make_layers([64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M']))
def modify_results(result_lines, duplicate_files): if (not duplicate_files): return result_lines else: mod_result_lines = [] for i in range(len(result_lines)): res_hid = json.loads(result_lines[i])['hole_identity'] if is_valid_hole(res_hid, duplicate_files): ...
def _create_entry(img, data, answer): if (None != answer): answer.pop('image_name') answer.pop('qid') entry = {'qid': data['qid'], 'image_name': data['image_name'], 'image': img, 'question': data['question'], 'answer': answer, 'answer_text': data['answer'], 'answer_type': data['answer_type'], 'q...
def compute_vw_kohel_even_deg3(b2, b4, s1, s2, s3): temp1 = ((s1 ** 2) - (2 * s2)) v = ((3 * temp1) + (((b2 * s1) + (3 * b4)) / 2)) w = ((3 * (((s1 ** 3) - ((3 * s1) * s2)) + (3 * s3))) + (((b2 * temp1) + (b4 * s1)) / 2)) return (v, w)
('/start_session', methods=['GET', 'POST']) def start_session(): json_data = request.get_json() return api.start_session(**json_data)
class SawyerDrawerCloseEnv(SawyerXYZEnv): def __init__(self): hand_low = ((- 0.5), 0.4, 0.05) hand_high = (0.5, 1, 0.5) obj_low = ((- 0.1), 0.9, 0.04) obj_high = (0.1, 0.9, 0.04) goal_low = ((- 0.1), 0.699, 0.04) goal_high = (0.1, 0.701, 0.04) super().__init__...
def minimum(c): install_minimum(c) c.run('python -m pip check') c.run('python -m pytest')
def init_hf_bert_tenzorizer(args, **kwargs): if (importlib.util.find_spec('transformers') is None): raise RuntimeError('Please install transformers lib') from .hf_models import get_bert_tensorizer return get_bert_tensorizer(args)
class StochasticBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, survival_rate=1): super().__init__() self.survival_rate = survival_rate self.conv1 = nn.Conv2d(inplanes, planes, 3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(plane...
def test_0459_types(): plain_plain = ak.highlevel.Array([[0.0, 1.1, 2.2, 3.3, 4.4]]) array_plain = ak.operations.with_parameter(plain_plain, '__list__', 'zoinks') plain_isdoc = ak.operations.with_parameter(plain_plain, '__doc__', 'This is a zoink.') array_isdoc = ak.operations.with_parameter(array_plain...
_optimizer('adam') class FairseqAdam(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) fused_adam_cls = get_fused_adam_class() use_fused_adam = ((not getattr(args, 'use_old_adam', False)) and (fused_adam_cls is not None) and torch.cuda.is_available()) if get...
def synchronize(): global _USE_HVD if _USE_HVD: hvd.broadcast_object(0) return return comm.synchronize()
def load_errors(path): with open(path, 'r') as f: errors = yaml.load(f, Loader=yaml.CLoader) return errors
def dump_label(feat_dir, split, km_path, nshard, rank, lab_dir): apply_kmeans = ApplyKmeans(km_path) (generator, num) = get_feat_iterator(feat_dir, split, nshard, rank) iterator = generator() lab_path = f'{lab_dir}/{split}_{rank}_{nshard}.km' os.makedirs(lab_dir, exist_ok=True) with open(lab_pat...
class YolosConfig(PretrainedConfig): model_type = 'yolos' def __init__(self, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, initializer_range=0.02, layer_norm_eps=1e-12, image_size=[512, 864], p...
def MathonPseudocyclicStronglyRegularGraph(t, G=None, L=None): from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF from sage.rings.integer_ring import ZZ from sage.matrix.constructor import matrix, block_matrix, ones_matrix, identity_matrix from sage.arith.misc import two_squa...
def make_data_loader_view(cfg, is_train=False): batch_size = cfg.SOLVER.IMS_PER_BATCH transforms = build_transforms(cfg, is_train) datasets = build_dataset_view(cfg.DATASETS.TRAIN, transforms, use_mask=cfg.DATASETS.USE_MASK, num_frame=cfg.DATASETS.NUM_FRAME) num_workers = cfg.DATALOADER.NUM_WORKERS ...
def enhance_contrast(image, footprint, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False): np_image = np.asanyarray(image) if (np_image.ndim == 2): return _apply_scalar_per_pixel(generic_cy._enhance_contrast, image, footprint, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y) elif...
def get_config(): config = ml_collections.ConfigDict() config.actor_lr = 0.0003 config.value_lr = 0.0003 config.critic_lr = 0.0003 config.hidden_dims = (256, 256) config.discount = 0.99 config.dropout_rate = 0 config.layernorm = True config.tau = 0.005 return config
def _GetAutoCorr(ps): AC = {} AC.update(GetAutoCorrMoreauBroto(ps)) AC.update(GetAutoCorrMoran(ps)) AC.update(GetAutoCorrGeary(ps)) return AC
.spark def test_diff_feedback_type(log, model): dataset = create_dataset(log) pred_exp = model.fit_predict(dataset, k=1) model.implicit_prefs = True pred_imp = model.fit_predict(dataset, k=1) assert (not np.allclose(pred_exp.toPandas().sort_values('user_idx')['relevance'].values, pred_imp.toPandas()...
class Attackmodel(nn.Module): def __init__(self, out_channel=3): super(Attackmodel, self).__init__() self.dconv_down1 = double_conv(3, 64) self.dconv_down2 = double_conv(64, 128) self.dconv_down3 = double_conv(128, 256) self.dconv_down4 = double_conv(256, 512) self.dc...
.parametrize('split,num_sample', [('train', 37951), ('test', 9488), ('competition', 31626)]) def test_california_house_price(split, num_sample): df = create_dataset('california_house_price', split).data assert (len(df) == num_sample)
def is_integral(dtype: torch.dtype) -> bool: dtypes = [x for x in get_all_dtypes() if (x not in get_all_complex_dtypes())] return ((dtype in dtypes) and (not dtype.is_floating_point))
def test_add(): def _run_test(values): stat = OnlineStatistics() for i in values: stat.add(i) _assert_correct_stats(stat, values) _run_test(range(51)) _run_test(range(10, 10000, 3)) _run_test(range((- 400), (- 300))) _run_test((list(range(4, 900, 2)) + list(range(...
def enable_dropout(model): for module in model.modules(): if module.__class__.__name__.startswith('Dropout'): module.train() return model
def deepnn(l, x, final_dim=1): with tf.name_scope('reshape'): x_image = tf.reshape(x, [(- 1), (l * 28), 28, 1]) with tf.name_scope('conv1'): W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu((conv2d(x_image, W_conv1) + b_conv1)) with ...
def NN_Regression(x, y, x_test, y_test): print('SGD Training Begins!') x = x.flatten() X = Var(x) X = torch.unsqueeze(X, 1) y = y.flatten() Y = Var(y) Y = torch.unsqueeze(Y, 1) X_test = Var(x_test) X_test = torch.unsqueeze(X_test, 1) class Net(torch.nn.Module): def __init...
.no_cover .mujoco .timeout(100) def test_te_ppo_metaworld_ml1_push(): assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'tf/te_ppo_metaworld_ml1_push.py')), '--n_epochs', '1', '--batch_size_per_task', '100'], check=False).returncode == 0)
_torch class AutoModelTest(unittest.TestCase): def test_model_from_pretrained(self): logging.basicConfig(level=logging.INFO) for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: config = AutoConfig.from_pretrained(model_name) self.assertIsNotNone(config) ...
def find_missing_tags(known_tags, test_tags): if (isinstance(known_tags, list) and isinstance(known_tags[0], list)): known_tags = set((x for y in known_tags for x in y)) if (isinstance(test_tags, list) and isinstance(test_tags[0], list)): test_tags = sorted(set((x for y in test_tags for x in y))...
def _init_beta_gamma(shape, fix_parameters, param_init, no_bias, no_scale): from nnabla.parameter import get_parameter_or_create from nnabla.initializer import ConstantInitializer if no_bias: beta = None else: beta_init = param_init.get('beta', ConstantInitializer(0)) beta = get_...
def register_Ns3Ipv6RawSocketFactory_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Ipv6RawSocketFactory const &', 'arg0')]) cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) return
def load_state_dict(model, state_dict): try: model.load_state_dict(state_dict) except RuntimeError: new_state_dict = {i[len('module.'):]: j for (i, j) in state_dict.items()} model.load_state_dict(new_state_dict)
def buzzard_tpslopes(p, N, kmax): v = gp().eval(('tpslopes(%s, %s, %s)' % (p, N, kmax))) v = sage_eval(v) v.insert(0, []) return v
class AttentionalAggregator(GraphSAGEAggregator): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.hidden_dim = self.output_dim self.attn_act = LeakyReLU(0.2) def _build_group_weights(self, in_shape, out_size, group_idx=0): if (group_idx == 0): ...
def clean_dict(content): new_content = {} new_sent = '' new_sent_id = '' for (sent_id, sent_) in content.items(): try: sent = sent_['sentence'].rstrip() sent = sent.replace('\n', ' ').replace('\t', ' ') sent = re.sub(' +', ' ', sent) if ((new_sent ...
def all_networks(): import os nns_dir = os.path.dirname(os.path.abspath(__file__)) nns = [f[:(- len('.py'))] for f in os.listdir(nns_dir) if (f.endswith('.py') and (not f.startswith('__')))] return list(sorted(nns))
_module() class MSELoss(nn.Module): def __init__(self, reduction='mean', loss_weight=1.0): super().__init__() self.reduction = reduction self.loss_weight = loss_weight def forward(self, pred, target, weight=None, avg_factor=None, reduction_override=None): assert (reduction_overri...
class TestJointMotionPlanner(unittest.TestCase): def test_same_start_and_end_pos_with_no_start_orientations(self): jm_planner = ml_action_manager_simple.joint_motion_planner start = (((1, 1), w), ((1, 2), s)) goal = (((1, 1), n), ((2, 1), n)) (joint_action_plan, end_jm_state, finshin...
_BOX_PREDICTOR.register('FastRCNNPredictor') class FastRCNNPredictor(nn.Module): def __init__(self, config, in_channels): super(FastRCNNPredictor, self).__init__() assert (in_channels is not None) num_inputs = in_channels num_classes = config.MODEL.ROI_BOX_HEAD.NUM_CLASSES se...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) .parametrize('val', [0.5, 1, 2]) def test_add_scalar_forward_backward(seed, val, ctx, func_name): from nbla_test_utils import function_tester rng = np.random.RandomState(seed) inputs = [(rng.randn(2, 3, 4).astype(np.float32) * 2)] function...
def deleteImage(request): file = request.FILES.get('file') if file: filename = file.name file.delete() return HttpResponse('ok')
def evaluate_factual_consistency(args): scorer = FactualConsistencyScorer(align=args.align) scores = [] for (grounding, hypo) in tqdm(zip(open(args.grounding).readlines(), open(args.hypo).readlines())): (grounding, hypo) = (grounding.strip(), hypo.strip()) if ((grounding == '') and (hypo == ...
def inception_v4_ra(cnn, k, l, m, n): cols = [[('mpool', 3, 3, 2, 2, 'VALID')], [('conv', n, 3, 3, 2, 2, 'VALID')], [('conv', k, 1, 1), ('conv', l, 3, 3), ('conv', m, 3, 3, 2, 2, 'VALID')]] cnn.inception_module('incept_v4_ra', cols)
def save_best_model(path, model, word_encoder, word_pos_encoder, time_delay_encoder, optimizer, type_, file): path_model = os.path.join(path, 'best_model', (((('best_model_' + type_) + '_') + file) + '.pt')) path_word_encoder = os.path.join(path, 'best_model', (((('best_model_word_encoder_' + type_) + '_') + fi...
def namedtuple_fieldnames(declaration): returns = declaration['returns'] if ((len(returns) <= 1) or all([('field_name' not in x) for x in returns])): return [] else: def get_field_name(x): if ('field_name' not in x): raise ValueError('Unnamed field is not supporte...
def compute_pose(image_dir, annotations_file, savePath): annotations_file = pd.read_csv(annotations_file, sep=':') annotations_file = annotations_file.set_index('name') image_size = (128, 64) cnt = len(annotations_file) for i in range(cnt): print(('processing %d / %d ...' % (i, cnt))) ...
def _has_4gram_match(ref, pred): if ((len(ref) < 4) or (len(pred) < 4)): return False for i in range((len(ref) - 3)): for j in range((len(pred) - 3)): if (ref[i:(i + 4)] == pred[j:(j + 4)]): return True return False
def test_one_word(): text = '(FOO) (BAR)' trees = tree_reader.read_trees(text) assert (len(trees) == 2) assert trees[0].is_leaf() assert (trees[0].label == 'FOO') assert trees[1].is_leaf() assert (trees[1].label == 'BAR')
def make_open3d_visualiser(): vis = o3d.visualization.Visualizer() vis.create_window(window_name='test', width=1280, height=840, left=0, top=0, visible=True) vis.get_render_option().light_on = False vis.get_render_option().line_width = 100.0 return vis
def captioning(audio_path): audio_tensor = get_audio(audio_path=audio_path) if (device is not None): audio_tensor = audio_tensor.to(device) with torch.no_grad(): output = model.generate(samples=audio_tensor, num_beams=5) inference = '' number_of_chunks = range(audio_tensor.shape[0]) ...
def download_mwoz_21(destination): mwoz_21_archive = os.path.join(destination, 'MultiWOZ_21.zip') download_file(MULTIWOZ_21_DATASET_URL, mwoz_21_archive) shutil.unpack_archive(mwoz_21_archive, destination) shutil.rmtree(os.path.join(destination, '__MACOSX')) mwoz_21 = os.path.join(destination, 'Mult...
class augmentations(object): def __init__(self): self.jitter_scale_ratio = 0.001 self.jitter_ratio = 0.001 self.max_seg = 5
def setup_seed(seed=1024): torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True
class PartitionTuples_level(PartitionTuples): def __init__(self, level, category=None): if (level not in NN): raise ValueError('level must be a non-negative integer') if (category is None): category = InfiniteEnumeratedSets() super().__init__(category=category) ...
_REGISTRY.register() class Generator_RPA(nn.Module): def __init__(self, num_in_ch=3, num_out_ch=3, scale=2, num_feat=64, num_block=20): super(Generator, self).__init__() self.scale = scale self.conv1 = nn.Conv2d(num_in_ch, num_feat, 3, 1, 1) self.rpa = nn.Sequential(OrderedDict([('rp...
def log_accuracy(pred_class_logits, gt_classes, topk=(1,)): bsz = pred_class_logits.size(0) maxk = max(topk) (_, pred_class) = pred_class_logits.topk(maxk, 1, True, True) pred_class = pred_class.t() correct = pred_class.eq(gt_classes.view(1, (- 1)).expand_as(pred_class)) ret = [] for k in to...
class CategoricalVarField(CategoricalDataFrameField): def __init__(self, *args, **kwargs): super().__init__(*args, field_type='var', **kwargs)
class VAEforMNIST(nn.Module): def __init__(self, latent_dim): super().__init__() self.latent_dim = latent_dim self.fc1 = nn.Linear(784, 400) self.fc21 = nn.Linear(400, latent_dim) self.fc22 = nn.Linear(400, latent_dim) self.fc3 = nn.Linear(latent_dim, 400) sel...
def instantiate_non_scriptable_remote_module_template(): generated_module_name = f'{_FILE_PREFIX}non_sriptable' str_dict = dict(assign_module_interface_cls='module_interface_cls = None', args='*args', kwargs='**kwargs', arg_types='*args, **kwargs', arrow_and_return_type='', arrow_and_future_return_type='', jit_...
def register_Ns3FdNetDevice_methods(root_module, cls): cls.add_constructor([]) cls.add_method('AddLinkChangeCallback', 'void', [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], is_virtual=True) cls.add_me...
def evaluate(args): system_pred_file = args['output_file'] gold_file = args['gold_file'] model_file = (((args['save_dir'] + '/') + args['save_name']) if (args['save_name'] is not None) else '{}/{}_mwt_expander.pt'.format(args['save_dir'], args['shorthand'])) use_cuda = (args['cuda'] and (not args['cpu']...
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.work_dir is not None): cfg.work_dir = args.work_dir pathlib.Path(cfg.work_dir).mkdir(parents=True, exist_ok=True) cfg.gpus = args.gpus if (args.launcher == 'none'): distributed = False else: d...
class FunnelModelTester(): def __init__(self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, block_sizes=[1, 1, 2], num_decoder_layers=1, d_model=32, n_head=4, d_head=8, d_inner=37, hidden_act='gelu_new', hidden_dropout=0.1, atten...
class DivergenceEstimator(EntropyEstimator, ABC, metaclass=DivergenceEstimatorType): def __init__(self, entropy=Nsb()): super(DivergenceEstimator, self).__init__() self.input_data_ndim = 2 estimator_name = type(entropy).__name__ if (estimator_name not in entropy_estimators): ...
class ClipOutputFeatures(ModelOutput): image_embeds: Optional[torch.FloatTensor] = None image_embeds_proj: Optional[torch.FloatTensor] = None text_embeds: Optional[torch.FloatTensor] = None text_embeds_proj: Optional[torch.FloatTensor] = None
class Trainer(): def __init__(self, cfg: CfgNode, model: nn.Module, evaluator: Evaluator, device: torch.device) -> None: self.cfg = cfg self.model = model self.device = device logger.info('\tSetting up the optimizer...') self.optimizer = make_optimizer([self.model], cfg.SOLVE...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) def test_sigmoid_double_backward(seed, ctx, func_name): from nbla_test_utils import cap_ignore_region, backward_function_tester rng = np.random.RandomState(seed) inputs = [(rng.randn(2, 3, 4).astype(np.float32) * 2)] backward_function_test...