code
stringlengths
101
5.91M
class FileDataset(): def __init__(self, path, tokenizer=nltk.RegexpTokenizer('\\b[a-zA-Z]{2,}\\b')): self.path = path self.tokenizer = tokenizer def __iter__(self): lines = list(open(self.path)) lines_tok = self.tokenizer.tokenize_sents(map(str.lower, lines)) return iter(...
def IntSort(ctx=None): ctx = _get_ctx(ctx) return ArithSortRef(Z3_mk_int_sort(ctx.ref()), ctx)
class SNodeHostAccessor(): def __init__(self, snode): if _ti_core.is_real(snode.data_type()): write_func = snode.write_float read_func = snode.read_float else: def write_func(key, value): if (value >= 0): snode.write_uint(key, v...
class _SplitDataset(torch.utils.data.Dataset): def __init__(self, underlying_dataset, keys): super(_SplitDataset, self).__init__() self.underlying_dataset = underlying_dataset self.keys = keys def __getitem__(self, key): return self.underlying_dataset[self.keys[key]] def __le...
def retrive_var(scopes): var = [] for scope in scopes: var += tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=scope) return var
def sdfg_with_children(A: dp.float32[(N, N)], B: dp.float32[(N, N)]): def elements(i: _[0:N], j: _[0:N]): def init(): (inp << A[(i, j)]) (out >> B[(i, j)]) out = inp for k in range(4): def do(): (inp << A[(i, j)]) (oin <...
def init_test_mot16(): config['resume'] = '/home/ssm/ssj/weights/MOT17/weights0326-I50k-M80-G30/ssj300_0712_80000.pth' config['mot_root'] = '/home/ssm/ssj/dataset/MOT16' config['batch_size'] = 1 config['write_file'] = True config['tensorboard'] = True config['save_combine'] = False config['t...
def export_onnx(pretrained): net = SYEISPNetS(channels=12) checkpoint = torch.load(pretrained) net.load_state_dict(checkpoint) net.eval() net = net.slim().eval() net.body.block1.weight = nn.Parameter(net.body.block1.weight.reshape((3, 4, 12, 3, 3)).permute([1, 0, 2, 3, 4]).reshape((12, 12, 3, 3)...
_level_function() def from_avro_file(file, limit_entries=None, *, debug_forth=False, highlevel=True, behavior=None, attrs=None): import awkward._connect.avro if isinstance(file, (str, bytes, PathLike)): file = fsdecode(file) with open(file, 'rb') as opened_file: (form, length, contai...
class Transition(nn.Module): def __init__(self, in_planes, out_planes): super(Transition, self).__init__() self.bn = nn.BatchNorm2d(in_planes) self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False) self.pau = PAU() def forward(self, x): out = self.conv(se...
class ProcessGroupRpcAgentTestFixture(RpcAgentTestFixture): def rpc_backend(self): return rpc.backend_registry.BackendType['PROCESS_GROUP'] def rpc_backend_options(self): try: return self._rpc_backend_options except AttributeError: return rpc.backend_registry.cons...
def train(args, model, classifier, train_loader, criterion, optimizer, epoch): model.train() classifier.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() total_feats = [] total_targets = [] end = time.time() for (batch_idx, (input1, target)) in en...
class TFLxmertMainLayer(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def _add_category_id_to_contiguous_id_maps_to_metadata(merged_categories: _MergedCategoriesT): merged_categories_per_dataset = {} for (contiguous_cat_id, cat_id) in enumerate(sorted(merged_categories.keys())): for cat in merged_categories[cat_id]: if (cat.dataset_name not in merged_categorie...
def run_ddp(rank, world_size, prepared): ddp_setup(rank, world_size) prepared.cuda() prepared = torch.nn.parallel.DistributedDataParallel(prepared, device_ids=[rank]) prepared.to(rank) model_with_ddp = prepared optimizer = torch.optim.SGD(model_with_ddp.parameters(), lr=0.0001) train_one_epo...
def write_embeddings(filename, dict, embeddings): with open(filename, 'w') as file: for i in range(len(embeddings)): str = dict.idxToLabel[i].encode('utf-8') for j in range(len(embeddings[0])): str = (str + (' %5f' % embeddings[i][j])) file.write((str + '\...
class MovingAverageActionWrapperActorPolicy(BaseActorPolicy): def __init__(self, policy, widow_size=8, initial_value=0): super(BaseActorPolicy, self).__init__() self.__widow_size = widow_size self.__buffer = ([(initial_value / widow_size)] * widow_size) self.__avg = initial_value ...
def average_time_of_func(func, num_iter=10000, ms=False): duration = timeit.timeit(func, number=num_iter) avg_time = (duration / num_iter) if ms: avg_time *= 1000 logger.info('{} {} ms/iter'.format(func.__name__, avg_time)) else: logger.info('{} {} s/iter'.format(func.__name__, a...
class MapTilingWithOverlapTest(unittest.TestCase): def semantic_eq(self, tile_sizes): A = np.random.rand(16, 16).astype(np.float32) B1 = np.zeros((16, 16), dtype=np.float32) B2 = np.zeros((16, 16), dtype=np.float32) sdfg = copy.to_sdfg() sdfg(inp=A, out=B1, I=A.shape[0], J=A....
def get_utterances_from_file(dialog_csv_file, dialog_csv_filename): reader = csv.DictReader(dialog_csv_file) path = dialog_csv_filename.split('\\') return [_dict_to_dialog_utterance(du_dict, path[(- 1)]) for du_dict in reader]
def test_weka(filename): (data, meta) = loadarff(filename) print(len(data.dtype)) print(data.size) for i in meta: print_attribute(i, meta[i], data[i])
def check_in_repo(): if (not os.path.isfile('setup.py')): return 'Not in root-level PyTorch repo, no setup.py found' with open('setup.py') as f: s = f.read() if ('PyTorch' not in s): return "Not in PyTorch repo, 'PyTorch' not found in setup.py"
class ImageNetDataset(Dataset): def __init__(self, split, bucket_name, streaming=True, data_download_dir=None, transform=None): assert (split in ['train', 'validation']), 'split {} not in (train, validation)'.format(split) self._split = split self._bucket_name = bucket_name self._tar...
def test_reduce_1d_strided(): non_contiguous_array = np.arange(64, dtype=np.int64)[::3] layout = ak.contents.NumpyArray(non_contiguous_array) assert (not layout.is_contiguous) assert (ak.sum(layout, axis=(- 1)) == np.sum(non_contiguous_array, axis=(- 1)))
def read_concode_examples(filename, data_num): examples = [] with open(filename) as f: for (idx, line) in enumerate(f): x = json.loads(line) examples.append(Example(idx=idx, source=x['nl'].strip(), target=x['code'].strip())) idx += 1 if (idx == data_num): ...
def test_module_parameter_path(): x = nn.Variable((4, 3, 32, 32)) e = Example() h = e(x) e2 = Example() assert (not e2.get_parameters()), "It doesn't have any parameters so far." e2.set_parameters(e.get_parameters()) assert (e.get_parameters() == e2.get_parameters()), 'They have the same par...
def numpy_set_unused(v): if (v is None): return assert isinstance(v, numpy.ndarray) if isinstance(v.base, SharedNumpyArray): assert v.base.is_in_use() v.base.set_unused()
class Decoder(DecoderBase): tiu_head_length = 50 dma_head_length = 39 def decode_tiu_cmd(self, reg_buf: memoryview, *, offset, subnet_id) -> BaseTpuCmd: head = TiuHead.from_buffer(reg_buf, offset) op_info = tiu_index.get((bool(head.cmd_short), head.tsk_typ, head.tsk_eu_typ), None) as...
def test_mrmr_regression_with_scores(): (selected_features, relevance, redundancy) = mrmr.polars.mrmr_regression(df=df_polars, K=4, target_column=target_column_regression, features=features, denominator='mean', only_same_domain=False, return_scores=True, show_progress=True) assert (set(selected_features) == set...
def validate(val_loader, model, criterion, args, epoch, tb_logger): batch_time = AverageMeter('Time', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') top5 = AverageMeter('', ':6.2f') progress = ProgressMeter(len(val_loader), [batch_time, losses, top1, top5], prefix='T...
def test_gc_head(): head = GCHead(in_channels=4, channels=4, num_classes=19) assert (len(head.convs) == 2) assert hasattr(head, 'gc_block') inputs = [torch.randn(1, 4, 23, 23)] if torch.cuda.is_available(): (head, inputs) = to_cuda(head, inputs) outputs = head(inputs) assert (outputs...
def _evalcode_python(executor, code, input_type): global_dict = gdb.parse_and_eval('PyEval_GetGlobals()') local_dict = gdb.parse_and_eval('PyEval_GetLocals()') if ((pointervalue(global_dict) == 0) or (pointervalue(local_dict) == 0)): raise gdb.GdbError('Unable to find the locals or globals of the mo...
class WSGenerator(dataset.Generator): def __init__(self, sizes, density_alpha=1.3, rewire_alpha=2, rewire_beta=2, **kwargs): super(WSGenerator, self).__init__(sizes, **kwargs) self.density_alpha = density_alpha self.rewire_alpha = rewire_alpha self.rewire_beta = rewire_beta def g...
def _get_repo(repo): assert isinstance(repo, str) obj = _repo_cache.get(repo) if obj: return obj obj = _Repo(repo) _repo_cache[repo] = obj return obj
_numpy_output(check_dtype=True) def test_ufunc_square_f(A: dace.float32[10]): return np.square(A)
_paths def parse_args(args=None, namespace=None): parser = argparse.ArgumentParser(description='Extract audio from videos.') parser.add_argument('-i', '--in_dir', default=pathlib.Path('data/vggsound/vggsound/'), type=pathlib.Path, help='input directory') parser.add_argument('-o', '--out_dir', default=pathli...
class XLMRobertaConverter(SpmConverter): def vocab(self, proto): vocab = [('<s>', 0.0), ('<pad>', 0.0), ('</s>', 0.0), ('<unk>', 0.0)] vocab += [(piece.piece, piece.score) for piece in proto.pieces[3:]] vocab += [('<mask>', 0.0)] return vocab def unk_id(self, proto): unk_...
def converId(img_id): img_id = img_id.split('-') if ('train' in img_id[0]): new_id = int(img_id[1]) elif ('val' in img_id[0]): new_id = (int(img_id[1]) + 1000000) elif ('test' in img_id[0]): new_id = (int(img_id[1]) + 2000000) else: pdb.set_trace() return new_id
def layout(): children_list = [html.Div([html.H2('Daily proportion of women quoted'), html.Div(dcc.Markdown('\n The below charts showcase a 7-day moving average of the daily\n proportion of women quoted for each outlet since October 2018.\n The pi...
def convert_examples_to_features(examples, label_list, label_list_tagging, max_seq_length, tokenizer, sel_prob, train_type='train'): label_map = {label: i for (i, label) in enumerate(label_list)} label_tagging_map = {label: i for (i, label) in enumerate(label_list_tagging)} features = [] for (ex_index, ...
class _PackageResourceReader(): def __init__(self, importer, fullname): self.importer = importer self.fullname = fullname def open_resource(self, resource): from io import BytesIO return BytesIO(self.importer.load_binary(self.fullname, resource)) def resource_path(self, resou...
class MLPMergeModel(Model): def __init__(self, output_dim, name='MLPMergeModel', hidden_sizes=(32, 32), concat_layer=(- 2), hidden_nonlinearity=tf.nn.relu, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), output_nonlinearity=None, output_w_...
class LnStructured(BasePruningMethod): PRUNING_TYPE = 'structured' def __init__(self, amount, n, dim=(- 1)): _validate_pruning_amount_init(amount) self.amount = amount self.n = n self.dim = dim def compute_mask(self, t, default_mask): _validate_structured_pruning(t) ...
def get_logger(logpath, filepath, package_files=[], displaying=True, saving=True, debug=False): logger = logging.getLogger() if debug: level = logging.DEBUG else: level = logging.INFO logger.setLevel(level) if saving: info_file_handler = logging.FileHandler(logpath, mode='a')...
class DirectoryLocator(Locator): def __init__(self, path, **kwargs): self.recursive = kwargs.pop('recursive', True) super(DirectoryLocator, self).__init__(**kwargs) path = os.path.abspath(path) if (not os.path.isdir(path)): raise DistlibException(('Not a directory: %r' % ...
def get_scores_for_imputer(imputer, X_missing, y_missing): estimator = make_pipeline(imputer, regressor) impute_scores = cross_val_score(estimator, X_missing, y_missing, scoring='neg_mean_squared_error', cv=N_SPLITS) return impute_scores
def fit_str(string, colwidth=16): if (len(string) < colwidth): return (((colwidth - len(string)) * ' ') + string) else: return string[:colwidth]
def boomerang_force_calculator(location, orientation): gravity = np.array([0.0, 0.0, ((- 1.0) * sum(M))]) r_vectors = get_boomerang_r_vectors_15(location[0], orientation[0]) repulsion = 0.0 for k in range(len(r_vectors)): h = r_vectors[k][2] repulsion += np.array([0.0, 0.0, (((REPULSION_...
def test_nested_default_arg_reuse_2(): class MyClass(): def __call__(self, arr: dace.float64[20], qmin: float=0.0): self.nested(arr, qmin) def nested(self, arr: dace.float64[20], qmin: float): arr[:] = qmin a = MyClass() def tester(arr: dace.float64[20], arr2: dace.fl...
class AdainResBlk(nn.Module): def __init__(self, dim_in, dim_out, style_dim=64, w_hpf=0, actv=nn.LeakyReLU(0.2), upsample='none'): super().__init__() self.w_hpf = w_hpf self.actv = actv self.upsample = UpSample(upsample) self.learned_sc = (dim_in != dim_out) self._bui...
class SELayer(nn.Module): def __init__(self, channels, ratio=16, conv_cfg=None, act_cfg=(dict(type='ReLU'), dict(type='HSigmoid', bias=3.0, divisor=6.0))): super(SELayer, self).__init__() if isinstance(act_cfg, dict): act_cfg = (act_cfg, act_cfg) assert (len(act_cfg) == 2) ...
def get_padded_batch(file_list, batch_size, input_size, output_size, num_enqueuing_threads=4, num_epochs=1, shuffle=True): file_queue = tf.train.string_input_producer(file_list, num_epochs=num_epochs, shuffle=shuffle) reader = tf.TFRecordReader() (_, serialized_example) = reader.read(file_queue) sequenc...
class _grid_encode(Function): _fwd def forward(ctx, inputs, embeddings, offsets, per_level_scale, base_resolution, calc_grad_inputs=False, gridtype=0, align_corners=False, interpolation=0): inputs = inputs.contiguous() (B, D) = inputs.shape L = (offsets.shape[0] - 1) C = embeddin...
class UnetSkipConnectionBlock(nn.Module): def __init__(self, outer_nc, inner_nc, input_nc=None, submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False): super(UnetSkipConnectionBlock, self).__init__() self.outermost = outermost if (type(norm_layer) == ...
class BoundingBox(): def __init__(self, image_name, class_id=None, coordinates=None, type_coordinates=CoordinatesType.ABSOLUTE, img_size=None, bb_type=BBType.GROUND_TRUTH, confidence=None, format=BBFormat.XYWH): self._image_name = image_name self._type_coordinates = type_coordinates self._co...
def set_separate_embeddings(model, mapping): model.set_input_embeddings(MyEmbedding2(model.transformer.wte, mapping))
class SemEvalHook(Hook): def __init__(self, batcher, placeholders, at_every_epoch): self.batcher = batcher self.placeholders = placeholders self.at_every_epoch = at_every_epoch def __call__(self, sess, epoch, iteration, model, loss): if ((iteration == 0) and ((epoch % self.at_eve...
def test_ngrams_for_evaluation(): from speechbrain.lm.counting import ngrams_for_evaluation assert (list(ngrams_for_evaluation(['a', 'b', 'c'], max_n=3)) == [('b', ('a',)), ('c', ('a', 'b'))]) assert (list(ngrams_for_evaluation(['a', 'b', 'c'], max_n=3, predict_first=True)) == [('a', ()), ('b', ('a',)), ('c...
def test_hist(): hist = glob.glob('test_trainer_outputs/history.npy') assert (len(hist) == 1)
def execute_onnx(model, input_dict, return_full_exec_context=False, start_node=None, end_node=None): if (not model.check_all_tensor_shapes_specified()): raise Exception('Found unspecified tensor shapes, try infer_shapes') ret = model.analysis(ta.nodes_topologically_sorted) assert (ret['nodes_topolog...
def normalize_args_vectorspace(*args, **kwds): from sage.rings.integer_ring import ZZ if (len(args) == 1): V = args[0] try: degree = V.dimension_relative() except AttributeError: degree = V.dimension() ring = V.base_ring() if (len(args) == 2): ...
def test_conv1d_same_out(): time_dim = Dim(Tensor('time', [batch_dim], dtype='int32')) in_dim = Dim(7, name='in') extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')}) class _Net(rf.Module): def __init__(self): super().__init__() ...
def make_cc_vector(sequence_list, lag, phyche_value, k): phyche_values = list(phyche_value.values()) len_phyche_value = len(phyche_values[0]) vec_cc = [] for sequence in sequence_list: len_seq = len(sequence) each_vec = [] for temp_lag in range(1, (lag + 1)): for i1 i...
def _default_template_ctx_processor(): reqctx = _request_ctx_stack.top appctx = _app_ctx_stack.top rv = {} if (appctx is not None): rv['g'] = appctx.g if (reqctx is not None): rv['request'] = reqctx.request rv['session'] = reqctx.session return rv
def parse_args(): parser = argparse.ArgumentParser(description='None') parser.add_argument('--config', help='config file path') parser.add_argument('--seed', type=int, default=42, help='random seed') parser.add_argument('--phase', choices=['test', 'train'], default='test') parser.add_argument('--wor...
class Runner(): def __init__(self): self.t0 = time() self.hours_pretrained = 0 if c.TEST_ONLY: print('TESTING ONLY') self.tst_file_list = [] for data_dir in c.TEST_DIRS: self.tst_file_list += sorted(glob.glob((data_dir + '/**/*.wav'), recur...
def edit_distance(str1, str2): try: import Levenshtein d = (Levenshtein.distance(str1, str2) / float(max(len(str1), len(str2)))) except: d = (1.0 - SequenceMatcher((lambda x: (x == ' ')), str1, str2).ratio()) return d
def normal_prior(prior_std): def prior_fn(dtype, shape, name, trainable, add_variable_fn): tfd = tfp.distributions dist = tfd.Normal(loc=tf.zeros(shape, dtype), scale=dtype.as_numpy_dtype(prior_std)) batch_ndims = tf.size(input=dist.batch_shape_tensor()) return tfd.Independent(dist, ...
class RecencyWeightedVariance(Variance): mean_class = ExponentialMovingAverage def __init__(self, recency_weight: float, **kwargs): super().__init__(**kwargs) self.recency_weight = recency_weight def recency_weight(self): return self._recency_weight _weight.setter def recency...
def Cyclic(R, n=None, homog=False, singular=None): from .rational_field import RationalField if n: if (n > R.ngens()): raise ArithmeticError('n must be <= R.ngens()') else: n = R.ngens() if (singular is None): from sage.interfaces.singular import singular as singular_...
class AdvContrastiveNMT(nn.Module): def __init__(self, args): super(AdvContrastiveNMT, self).__init__() self.tau = args.tau self.pos_eps = args.pos_eps self.neg_eps = args.neg_eps self.t5_model = T5ForConditionalGeneration.from_pretrained(args.t5_model) self.projectio...
def main(): save_dir = f'exp/{args.probe_type}/{args.eval_dataset}/{args.framework}_{args.text_type}_{args.text_rep}/{args.lr}_{args.batch_size}' (pretrain_model, _, config) = get_model(args) (task_type, output_dim, loss_fn) = get_cls_config(args) model = CLSLayer(audio_encoder=pretrain_model.audio_enco...
_module() class mit_b1(MixVisionTransformer): def __init__(self, **kwargs): super(mit_b1, self).__init__(patch_size=4, embed_dims=[64, 128, 320, 512], num_heads=[1, 2, 5, 8], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], **k...
def main(file_name, starting_value): file_name = file_name starting_value = starting_value training_data = [] for i in list(range(4))[::(- 1)]: print((i + 1)) time.sleep(1) last_time = time.time() paused = False print('STARTING!!!') while True: if (not paused): ...
class NystromformerForMultipleChoice(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def hop(entities, constraints, top_predicates, verbose=False, max_triples=500000, bl_p=[68655]): n_constraints = len(constraints) if entities: n_constraints += 1 top_entities = (entities + constraints) all_entities_ids = [_id for e in top_entities for _id in e] top_predicates_ids = [_id for ...
def _reject_cdef_modifier_in_py(s, name): if ((s.sy == 'IDENT') and (name in _CDEF_MODIFIERS)): s.error(("Cannot use cdef modifier '%s' in Python function signature. Use a decorator instead." % name), fatal=False) return p_ident(s) return name
class OneOf(): def __init__(self, contents): self._contents = contents def contents(self): return self._contents def __eq__(self, other): if isinstance(other, OneOf): return (set(self._contents) == set(other._contents)) else: return False def __rep...
def run_ml_pipeline(nlpPipelineDF, num_topics, max_iterations, vocabSize, minDF, maxDF): cv = CountVectorizer(inputCol='allTokens', outputCol='features', vocabSize=vocabSize, minDF=minDF, maxDF=maxDF, minTF=1.0) idf = IDF(inputCol='features', outputCol='idf') lda = LDA(k=num_topics, maxIter=max_iterations, ...
def main(): args = get_args() out = args.out (max_peaks, min_inten) = (args.max_peaks, args.min_inten) (num_bins, upper_limit) = (args.num_bins, args.upper_limit) num_workers = args.num_workers form_folder = Path(args.form_folder) form_files = list(form_folder.glob('*.json')) if (out is ...
def meta_training(train_dataset, valid_dataset, model, classifier, lr=None, optimizer=None, epochs=100, episodes=1000, ways=5, shots=5, query_num=15, report_epoch=1, lr_step_epoch=10, save_model_epoch=20, save_model_root='~/trained_models'): lr = (0.001 if (lr is None) else lr) if (optimizer is None): o...
class AdjacencyField(Field[torch.Tensor]): _already_warned_namespaces: Set[str] = set() def __init__(self, indices: List[Tuple[(int, int)]], sequence_field: SequenceField, labels: List[str]=None, label_namespace: str='labels', padding_value: int=(- 1)) -> None: self.indices = indices self.labels...
class TestThresholdedRelu(serial.SerializedTestCase): (input=hu.tensor(), engine=st.sampled_from(['', 'CUDNN']), **hu.gcs) def test_thresholded_relu_1(self, input, gc, dc, engine): X = input op = core.CreateOperator('ThresholdedRelu', ['X'], ['Y'], engine=engine) def defaultRef(X): ...
class ArrayStreamer(BaseStreamer): def __init__(self, shuffle=False): self.shuffle = shuffle def iter(self, X, y=None): indices = list(range(len(X))) if self.shuffle: np.random.shuffle(indices) if (y is None): for i in indices: (yield X[i])...
def do_naive_bayes_prediction(X, observed_class_distribution: dict, attribute_observers: dict): observed_class_sum = sum(observed_class_distribution.values()) if ((observed_class_distribution == {}) or (observed_class_sum == 0.0)): return {0: 0.0} votes = {} for (class_index, observed_class_val)...
def main(): set_seeds(2020) args = vars(parser.parse_args()) alphabet = Protein() cfgs = [] data_cfg = config.DataConfig(args['data_config']) cfgs.append(data_cfg) if (args['lm_model_config'] is None): model_cfg = config.ModelConfig(args['model_config'], input_dim=len(alphabet), num_...
class VectorField(MultivectorField): def __init__(self, vector_field_module, name=None, latex_name=None): MultivectorField.__init__(self, vector_field_module, 1, name=name, latex_name=latex_name) MultivectorField._init_derived(self) self._init_dependencies() def _repr_(self): des...
def latent_optimise(zs, fake_labels, gen_model, dis_model, conditional_strategy, latent_op_step, latent_op_rate, latent_op_alpha, latent_op_beta, trans_cost, default_device): batch_size = zs.shape[0] for step in range(latent_op_step): drop_mask = (torch.FloatTensor(batch_size, 1).uniform_() > (1 - laten...
def test_estimate_bandwidth(): bandwidth = estimate_bandwidth(X, n_samples=200) assert (0.9 <= bandwidth <= 1.5)
class ExecutorBase(): def __init__(self, n_workers: int, verbose: bool=False): self.verbose = verbose self.n_workers = n_workers self.n_free_workers = n_workers self.n_busy_workers = 0 self._queue = [] self._running_tasks = [] self._completed_tasks = [] de...
def parameter_parser(): parser = argparse.ArgumentParser(description='Run GETNext.') parser.add_argument('--seed', type=int, default=42, help='Random seed') parser.add_argument('--device', type=str, default=device, help='') parser.add_argument('--data-adj-mtx', type=str, default='dataset/NYC/graph_A.csv...
('/list_sessions', methods=['GET']) def list_sessions(): limit = request.args.get('limit', None) skip = request.args.get('skip', None) return api.get_all_sessions(limit, skip)
def test_nothing_on_after_test_case_execution(): stopping = DummyStopping() stopping.after_test_case_execution_inside_thread(None, None)
class Discriminator(nn.Module): def __init__(self, nc): super(Discriminator, self).__init__() self.enc = Encoder(nc) self.dec = Decoder(nc, True) def forward(self, input): return self.dec(self.enc(input))
def test_chrono_duration_subtraction_equivalence(): date1 = datetime.datetime.today() date2 = datetime.datetime.today() diff = (date2 - date1) cpp_diff = m.test_chrono4(date2, date1) assert (cpp_diff.days == diff.days) assert (cpp_diff.seconds == diff.seconds) assert (cpp_diff.microseconds =...
def test_isinstance(): objects = ([tuple(), dict(), m.Pet('Polly', 'parrot')] + ([m.Dog('Molly')] * 4)) expected = (True, True, True, True, True, False, False) assert (m.check_instances(objects) == expected)
def ascii_art(*obj, **kwds): (separator, baseline, sep_baseline) = _ascii_art_factory.parse_keywords(kwds) if kwds: raise ValueError('unknown keyword arguments: {0}'.format(list(kwds))) if (len(obj) == 1): return _ascii_art_factory.build(obj[0], baseline=baseline) if (not isinstance(sepa...
def collate(samples, pad_idx, eos_idx, left_pad_source=False, left_pad_target=False): if (len(samples) == 0): return {} def merge(key, left_pad, move_eos_to_beginning=False): return data_utils.collate_tokens([s[key] for s in samples], pad_idx, eos_idx, left_pad, move_eos_to_beginning) id = n...
def qa_for_label_file(dict_paragraphs: dict, label_file2: str, output_dir: str, separate=True): with open(label_file2, 'r') as fp: labels = json.load(fp) dict_paragraphs_train = {} for key in labels.keys(): dict_paragraphs_train.update({key: dict_paragraphs.get(key)}) base_case_to_qa_fil...
class OracleSelectionMethod(SelectionMethod): name = 'test-domain validation set (oracle)' def run_acc(self, run_records): run_records = run_records.filter((lambda r: (len(r['args']['test_envs']) == 1))) if (not len(run_records)): return None test_env = run_records[0]['args']...