code
stringlengths
101
5.91M
_utils.test(arch=supported_archs_cgraph) def test_repeated_arg_name(): n = 4 def test1(pos: ti.types.ndarray(ndim=1)): for i in range(n): pos[i] = 2.5 def test2(v: ti.f32): for i in range(n): print(v) sym_pos = ti.graph.Arg(ti.graph.ArgKind.NDARRAY, 'pos', ti.f32,...
def test_regular_numpy_2_parm(): text = '[0 * int64[parameters={"foo": "bar"}], parameters={"bla": "bloop"}]' parsedtype = ak.types.from_datashape(text, highlevel=False) assert isinstance(parsedtype, ak.types.RegularType) assert (str(parsedtype) == text)
def test_fit_online_cartpole_with_dqn() -> None: env = gym.make('CartPole-v1') eval_env = gym.make('CartPole-v1') algo = DQNConfig().create() buffer = ReplayBuffer(InfiniteBuffer(), env=env) explorer = LinearDecayEpsilonGreedy() algo.fit_online(env, buffer, explorer, n_steps=100, eval_env=eval_e...
.parametrize('fraction, subsample_test, expected_train_size, expected_test_size', [(0.5, True, 40, 10), (0.5, False, 40, 20), (0.2, True, 16, 4), (0.2, False, 16, 20)]) def test_subsample_splitter_shapes(fraction, subsample_test, expected_train_size, expected_test_size): n_samples = 100 (X, y) = make_classifica...
class BertConfig(PretrainedConfig): model_type = 'bert' def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=2, initia...
def extend_sssp_graph(ssspG, vars, ops, opG, node_order, index, input_vars, output_vars, binding, split_vars, split_idx='0', prev_split_idx=None): split_vars = set(split_vars) for i in range(len(node_order)): prev_split_idx = (prev_split_idx or split_idx) op = ops[node_order[i]] vars_to_...
def test_imperative_pf(): import nnabla.parametric_functions as PF x = nn.NdArray([2, 3, 4, 5]) y = PF.batch_normalization(x)
def parse_args(args): parser = argparse.ArgumentParser(description='MMDet test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('--work-dir', help='the directory to save the file containing evaluation metrics') parser.add_argument('--out', help='output...
def tmx2raw(tmx, debug): to_file = tmx[0:(len(tmx) - len('.tmx'))] to_folder = os.path.join(*os.path.split(tmx)[:(- 1)]) if os.path.exists(f'{to_folder}/bitext.en'): (debug and print(f'{tmx} already extracted to {to_file}; so skip')) return to_file cmd = f'(cd {to_folder}; {TMX_TOOL} {tm...
def main(): lexer = new() line = '' while 1: try: line += raw_input('=>> ').decode('string_escape') print(len(line), [c for c in line]) except EOFError: reload(sys.modules['lexer.py']) lexer.input(line) print(list((tok for tok in le...
class MathOpsPlan(BenchmarkPlan): def __init__(self, arch: str): super().__init__('math_ops', arch, basic_repeat_times=10) math_dtype = DataType() math_dtype.remove_integer() self.create_plan(MathOps(), math_dtype, ElementNum(), ForLoopCycle(), MetricType()) self.add_func(['e...
def convert_mr_to_table(mr): mr = mr.split(',') table = [] for x in mr: k = fix_key(x.split('[')[0].strip()).capitalize() v = x.split('[')[1].split(']')[0].strip().capitalize() table.append([k, v]) return table
class LoraLmConfig(): initialize_from_hf: str lora: LoraConfig = field(default_factory=LoraConfig) data: LMDatasetConfig = field(default_factory=LMDatasetConfig) trainer: TrainerConfig = field(default_factory=TrainerConfig) optimizer: OptimizerConfig = field(default_factory=OptimizerConfig) peft...
class OpenAIGPTTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, merges_file, unk_token='<unk>', **kwargs): super(OpenAIGPTTok...
def weight_translate(k, w): k = key_translate(k) if k.endswith('.weight'): if (w.dim() == 2): w = w.t() elif (w.dim() == 1): pass else: assert (w.dim() == 4) w = w.permute(3, 2, 0, 1) return w
def Parallelize_GPU_BMUF(*args, **kwargs): kwargs['cpu_device'] = False Parallelize_BMUF(*args, **kwargs)
def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, bert_config_file, pytorch_dump_path): config = BertConfig.from_json_file(bert_config_file) print(f'Building PyTorch model from configuration: {config}') model = BertForPreTraining(config) load_tf_weights_in_bert(model, config, tf_checkpoint_path) ...
def DSIN(dnn_feature_columns, sess_feature_list, sess_max_count=5, bias_encoding=False, att_embedding_size=1, att_head_num=8, dnn_hidden_units=(256, 128, 64), dnn_activation='relu', dnn_dropout=0, dnn_use_bn=False, l2_reg_dnn=0, l2_reg_embedding=1e-06, seed=1024, task='binary'): hist_emb_size = sum(map((lambda fc: ...
.operations('text') def test_unknown_content_type(any_app_schema): (_, *others, finished) = from_schema(any_app_schema, checks=(content_type_conformance,), hypothesis_settings=hypothesis.settings(max_examples=1, deadline=None)).execute() assert finished.has_failures check = others[1].result.checks[0] as...
def dump(data, encoding): code_type_map = encoding['code_type_map'] code_beat_map = encoding['code_beat_map'] code_position_map = encoding['code_position_map'] code_pitch_map = encoding['code_pitch_map'] code_duration_map = encoding['code_duration_map'] code_instrument_map = encoding['code_instr...
_quantizer(quantization_target=QuantizationTarget.Weights, quantization_method=[QuantizationMethod.POWER_OF_TWO, QuantizationMethod.SYMMETRIC, QuantizationMethod.UNIFORM, QuantizationMethod.LUT_POT_QUANTIZER, QuantizationMethod.LUT_SYM_QUANTIZER], identifier=ConfigurableQuantizerIdentifier.CONFIGURABLE_ID) class Config...
def build_factors(num_poses: int, num_landmarks: int) -> T.Iterator[Factor]: for i in range((num_poses - 1)): (yield Factor(residual=odometry_residual, keys=[f'poses[{i}]', f'poses[{(i + 1)}]', f'distances[{i}]', 'epsilon'])) for i in range(num_poses): for j in range(num_landmarks): ...
def safe_open(file_path: str, mode: str, newline: str=None): create_file_path(file_path) return open(file_path, mode, newline=newline, encoding='utf-8')
def parse_iperf_run(data, skip=1, use=8): tp_pat = re.compile('\\[ *\\d*\\] *([0-9\\.]*)- *([0-9\\.]*) sec.*Bytes *([0-9\\.]*) ([GM])bits.*') tps_time = {} for hn in fnmatch.filter(data['sims'].keys(), 'host.client.*'): sim = data['sims'][hn] for l in sim['stdout']: m = tp_pat.ma...
def CharFromBv(ch, ctx=None): if (not is_expr(ch)): raise Z3Expression('Bit-vector expression needed') return _to_expr_ref(Z3_mk_char_from_bv(ch.ctx_ref(), ch.as_ast()), ch.ctx)
class TestGPTQLossFunctions(unittest.TestCase): SHAPE = [1, 16, 16, 3] def _build_model(self) -> tf.keras.Model: inputs = layers.Input(shape=self.SHAPE[1:]) x1 = layers.Conv2D(3, 4, use_bias=False)(inputs) x = layers.ReLU()(x1) x2 = layers.Conv2D(7, 8, use_bias=False)(x) ...
def get_confusion_matrix_elements(groundtruth_list, predicted_list): _assert_valid_lists(groundtruth_list, predicted_list) if (_all_class_1_predicted_as_class_1(groundtruth_list, predicted_list) is True): (tn, fp, fn, tp) = (0, 0, 0, np.float64(len(groundtruth_list))) elif (_all_class_0_predicted_as...
def getEvalData_parseval(sen, edus): span_list = re.split(' ', sen) dic = {} for i in range(len(span_list)): temp = span_list[i] IDK = re.split('[:,=]', temp) nuclearity = (IDK[1][0] + IDK[5][0]) relation1 = IDK[2] relation2 = IDK[6] relation = (relation1 if (...
def create_pattern_layout(): return dbc.Row([dbc.Col(html.Div([create_description_card(), create_control_card(), html.Div(['initial child'], id='output-clientside', style={'display': 'none'})]), width=2), dbc.Col(html.Div([dbc.Row([dbc.Col(dbc.Card(dbc.CardBody([html.H4('Summary'), html.Div(id='log-summarization-su...
class Cluster(object): sgx_image = '10.75.0.2:5000/sgx-app-mem:1.2' standard_image = '10.75.0.2:5000/standard-app-mem:1.2' def __init__(self): kubernetes.config.load_kube_config() self.api = CoreV1Api() def pod_requests_sgx(pod: V1Pod) -> bool: for container in pod.spec.container...
def balanced_binary_cross_entropy_with_logits(logits: Tensor, targets: Tensor, gamma: float=1.0, ignore_index: Optional[int]=None, reduction: str='mean') -> Tensor: pos_targets: Tensor = targets.eq(1).sum() neg_targets: Tensor = targets.eq(0).sum() num_targets = (pos_targets + neg_targets) pos_weight = ...
def next_id_by_width(id_val, inc=1, width=16): new_id = (id_val + inc) while (new_id >= (1 << width)): new_id -= (1 << width) return new_id
class Src2TrgIO(IO): def __init__(self, tokenize_callback=None, trg_tokenize_callback=None, encoding=None, verbose: bool=True, **token_kwargs): super().__init__(is_tokenized=False, tokenize_callback=tokenize_callback, encoding=encoding, verbose=verbose, **token_kwargs) self.trg_tokenize_callback = t...
class TransformerSentenceEncoderLayer(nn.Module): def __init__(self, embedding_dim: int=768, ffn_embedding_dim: int=3072, num_attention_heads: int=8, dropout: float=0.1, attention_dropout: float=0.1, activation_dropout: float=0.1, activation_fn: str='relu', export: bool=False) -> None: super().__init__() ...
class TransformerDecoderLayer(rf.Module): def __init__(self, encoder_dim: Dim, out_dim: Dim=Dim(512, name='transformer-dec-default-out-dim'), *, ff_dim: Dim=NotSpecified, ff_activation: Callable[([Tensor], Tensor)]=rf.relu, dropout: float=0.1, num_heads: int=8, self_att: Optional[Union[(rf.CausalSelfAttention, rf.R...
class MIMOUNet(nn.Module): def __init__(self, num_res=8): super(MIMOUNet, self).__init__() base_channel = 32 self.Encoder = nn.ModuleList([EBlock(base_channel, num_res), EBlock((base_channel * 2), num_res), EBlock((base_channel * 4), num_res)]) self.feat_extract = nn.ModuleList([Basi...
.lower_builtin(operator.getitem, RecordViewType, numba.types.StringLiteral) def lower_getitem_field_record(context, builder, sig, args): (_, (recordviewtype, wheretype)) = (sig.return_type, sig.args) (recordviewval, whereval) = args return recordviewtype.arrayviewtype.type.lower_getitem_field_record(context...
class UnicodeSerializer(FileSerializer): def to_line(self, obj): u = ensure_unicode(obj) return u.encode('utf-8') def from_line(self, line): return line.decode('utf-8')
def plot(data_name='score.pkl'): file_path = ['seq2seq', 'seq2seq-all'] name_maps = ['Leap', 'KG-MIML-Net'] df = pd.DataFrame() for (idx, i) in enumerate(file_path): df[name_maps[idx]] = pickle.load(open(os.path.join('saved', i, data_name), 'rb'))[0:30] ax = df.plot(title='Jaccard_similarity...
def eval(prediction_file, gold_file): with open(prediction_file) as f: prediction = json.load(f) with open(gold_file) as f: gold = json.load(f) metrics = {'em': 0, 'f1': 0, 'prec': 0, 'recall': 0, 'sp_em': 0, 'sp_f1': 0, 'sp_prec': 0, 'sp_recall': 0, 'joint_em': 0, 'joint_f1': 0, 'joint_prec...
class ServiceGenderizer(): def __init__(self, db_client, genderize_cache_col, genderapi_cache_col): self.genderize_cache_col = db_client['genderCache'][genderize_cache_col] self.genderapi_cache_col = db_client['genderCache'][genderapi_cache_col] def get_genderize_gender(self, full_name): ...
class Stream_lmul(Stream_scalar): def get_coefficient(self, n): return (self._series[n] * self._scalar)
def test_unary(): import time t = time.time() grad_test((lambda x: ti.sqrt(x)), (lambda x: np.sqrt(x))) grad_test((lambda x: ti.exp(x)), (lambda x: np.exp(x))) grad_test((lambda x: ti.log(x)), (lambda x: np.log(x))) ti.core.print_profile_info() print('Total time {:.3f}s'.format((time.time() ...
def learn_weights(algorithm, observed_sampler, learning_proposal, fit_probability, B=15000): S = selection_stat = observed_sampler.center new_sampler = copy(observed_sampler) learning_sample = [] for _ in range(B): T = learning_proposal() new_sampler = copy(observed_sampler) new_...
def bench(factory, X, Y, X_test, Y_test, ref_coef): gc.collect() tstart = time() clf = factory(alpha=alpha).fit(X, Y) delta = (time() - tstart) print(('duration: %0.3fs' % delta)) print(('rmse: %f' % rmse(Y_test, clf.predict(X_test)))) print(('mean coef abs diff: %f' % abs((ref_coef - clf.co...
.mpl_image_compare def test_random_summary_dot_with_data(): np.random.seed(0) fig = plt.figure() shap.summary_plot(np.random.randn(20, 5), np.random.randn(20, 5), plot_type='dot', show=False) fig.set_layout_engine('tight') return fig
class KeepOpenFile(object): def __init__(self, file): self._file = file def __getattr__(self, name): return getattr(self._file, name) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): pass def __repr__(self): return repr(self._file)...
_module('numpy') def ascontiguousarray(a, dtype=None): return array(a, dtype, copy=False, order='C', ndmin=1)
def novelty(individual: IndividualLike, container: Sequence, k: int=1, dist: Union[(str, Callable)]='euclidean', ignore_first: bool=False, default_novelty: float=0.1) -> float: if (len(container) == 0): return default_novelty n_k = min(len(container), k) distances: Sequence = features_distances(indi...
.operations('empty') def test_empty_response_interaction(any_app_schema): (_, *others, _) = from_schema(any_app_schema, store_interactions=True).execute() interactions = [event for event in others if isinstance(event, events.AfterExecution)][0].result.interactions for interaction in interactions: as...
def test_tasklet_with_global_state(): sdfg = dace.SDFG('test_tasklet_with_global_state') state = sdfg.add_state() sdfg.add_array('output', [1], dace.int32) tasklet = state.add_tasklet('print_global_str', {}, {'out'}, 'out = *__state->global_int;', language=dace.dtypes.Language.CPP, state_fields=['int *g...
def val(model, dataloaders, criterion, optimizer, config): since = time.time() test_dev = [] for phase in ['val']: model.train(False) running_loss = 0.0 lent = len(dataloaders[phase]) pbar = tqdm(total=(lent * config.batchSize)) for ide in range(lent): dat...
class AirGraph(): def __init__(self, graph_dir, config_graph, gpu_id): device = ('cuda:%d' % gpu_id) (use_graph, fix_weight) = (config_graph['use'], config_graph['fix_weight']) tempp_diag_zero = config_graph['tempp_diag_zero'] distri_type = config_graph['distri_type'] self.A_...
class TimeBasedSamplingDecorator(SamplingDecorator): min_samples: int max_samples: int def __init__(self, base_alg: QDAlgorithm, min_samples=5, max_samples=100, **kwargs): self.min_samples = min_samples self.max_samples = max_samples assert (self.min_samples >= 1) assert (sel...
class ResNet(nn.Module): def __init__(self, bottleneck=False): super(ResNet, self).__init__() depth = 50 num_classes = 1000 blocks = {50: Bottleneck} layers = {50: [3, 4, 6, 3]} assert layers[depth], 'invalid detph for ResNet (depth should be one of 18, 34, 50, 101, 1...
class ScheduleInitTest(unittest.TestCase): m = torch.nn.Linear(50, 50) optimizer = AdamW(m.parameters(), lr=10.0) num_steps = 10 def assertListAlmostEqual(self, list1, list2, tol): self.assertEqual(len(list1), len(list2)) for (a, b) in zip(list1, list2): self.assertAlmostEqua...
def make_robotics_env(env_id, seed, rank=0): set_global_seeds(seed) env = gym.make(env_id) env = FlattenDictWrapper(env, ['observation', 'desired_goal']) env = Monitor(env, (logger.get_dir() and os.path.join(logger.get_dir(), str(rank))), info_keywords=('is_success',)) env.seed(seed) return env
def resnext152(**kwargs): model = ResNeXt(ResNeXtBottleneck, [3, 8, 36, 3], **kwargs) return model
def _mutation_type_error(data): if (data[2] is None): del data[2] return_str = (str(data) + ' is not a valid quiver mutation type') return_str += "\n Finite types have the form [ '?', n ] for type ? and rank n" return_str += "\n Affine type A has the form [ 'A', [ i, j ], 1...
def cvt_mask_palette_VOC(data): (src_path, dst_path) = data mask = np.array(load_image_in_PIL(src_path, 'P')) mask[(mask > 20)] = 0 mask = Image.fromarray(mask) mask.putpalette(mask_palette) mask.save(dst_path)
def test_kernel_print(): N = 10000 ti.init() def is_prime(n: int): result = True for k in range(2, (int((n ** 0.5)) + 1)): if ((n % k) == 0): result = False break return result def count_primes(n: int) -> int: count = 0 ...
class IEncoder(rf.Module, ABC): out_dim: Dim def __call__(self, source: Tensor) -> Tensor: raise NotImplementedError
def _traverse(node, fn, visited, depth): if ((node is None) or (node in visited)): return else: visited.add(node) if hasattr(node, 'saved_tensors'): for ten in node.saved_tensors: fn(node, ten, True) if hasattr(node, 'variable'): fn(node, node.variable.data, F...
class GAP(NodeClassification): supported_activations = {'relu': torch.relu_, 'selu': torch.selu_, 'tanh': torch.tanh} def __init__(self, num_classes, hops: Annotated[(int, ArgInfo(help='number of hops', option='-k'))]=2, hidden_dim: Annotated[(int, ArgInfo(help='dimension of the hidden layers'))]=16, encoder_la...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313]) .parametrize('delta', [0.5, 1.0, 1.5]) def test_huber_loss_double_backward(seed, ctx, func_name, delta): from nbla_test_utils import cap_ignore_region, backward_function_tester rng = np.random.RandomState(seed) inputs = [(rng.randn(2, 3, 4).as...
def sinabs_to_exodus(model: torch.nn.Module): mapping_list = [(sinabs_class, (lambda module, replacement=exodus_class: replacement(**module.arg_dict))) for (sinabs_class, exodus_class) in module_map.items()] for (class_to_replace, mapper_fn) in mapping_list: model = sinabs.conversion.replace_module(mode...
class PreciseBN(HookBase): def __init__(self, period, model, data_loader, num_iter): self._logger = logging.getLogger(__name__) if (len(get_bn_modules(model)) == 0): self._logger.info('PreciseBN is disabled because model does not contain BN layers in training mode.') self._di...
class LexerThread(): def __init__(self, lexer, text): self.lexer = lexer self.state = lexer.make_lexer_state(text) def lex(self, parser_state): return self.lexer.lex(self.state, parser_state) def __copy__(self): copied = object.__new__(LexerThread) copied.lexer = self...
def get_numpy(tensor): if isinstance(tensor, TorchVariable): return get_numpy(tensor.data) if _use_gpu: return tensor.cpu().numpy() return tensor.numpy()
def _maybe_get_const(value, desc): if (_is_value(value) and (value.node().kind() == 'onnx::Constant')): return _parse_arg(value, desc) return value
def setup_petsc_options(ksps: List[PETSc.KSP], ksp_options: List[_typing.KspOption]) -> None: fenics.PETScOptions.clear() opts = PETSc.Options() for i in range(len(ksps)): opts.clear() for (key, value) in ksp_options[i].items(): opts.setValue(key, value) ksps[i].setFromOp...
def test_arrow_nested_nested_array(): a = pyarrow.array([[[1.1, 2.2], [3.3], []], [], [[4.4, 5.5]]]) assert (to_list(ak._connect.pyarrow.handle_arrow(a)) == [[[1.1, 2.2], [3.3], []], [], [[4.4, 5.5]]])
def register_Ns3EpcS11SapMme_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::EpcS11SapMme const &', 'arg0')]) cls.add_method('CreateSessionResponse', 'void', [param('ns3::EpcS11SapMme::CreateSessionResponseMessage', 'msg')], is_pure_virtual=True, is_virtual=True) cls....
def reshape(source: Tensor, in_dims: Sequence[Dim], out_dims: Sequence[Dim]) -> Tensor: return source._raw_backend.reshape(source, in_dims=in_dims, out_dims=out_dims)
class OrAttributeFilter(Filter): def __init__(self, *filters: AttributeFilter): self.filters = filters def match(self, layer_config: Dict[(str, Any)]) -> bool: for f in self.filters: if f.match(layer_config): return True return False def __repr__(self): ...
def get_scheduler(optimizer, opt): if (opt.lr_policy == 'lambda'): def lambda_rule(epoch): lr_l = (1.0 - (max(0, (((epoch + 1) + opt.iter) - opt.niter)) / float((opt.niter_decay + 1)))) return lr_l scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif (...
class LogDataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for (key, val) in self.encodings.items()} item['labels'] = torch.tensor(self.labels[i...
class DiscreteFlattenPreprocessor(Preprocessor): def __init__(self, space: spaces.Discrete): super(DiscreteFlattenPreprocessor, self).__init__(space) self._size = space.n def size(self): return self._size def shape(self): return (self._size,) def transform(self, data, nes...
def get_3D_maze_blocks(map): return {(i, k, j): get_tile(map[k][j][i]) for k in range(len(map)) for j in range(len(map[k])) for i in range(len(map[k][j]))}
def configShower(textWidth=64): config = configReader() customPrint((Fore.YELLOW + 'Hyperparameters and Configurations'), textWidth=textWidth) for c in config: customPrint((('{}:'.format(c).upper() + Fore.YELLOW) + '{}'.format(config[c])), textWidth=textWidth, style='-')
class DirichletNeumann(CompositeBase): def __init__(self, N, quad='LG', bc=(0, 0), domain=((- 1), 1), dtype=float, padding_factor=1, dealias_direct=False, coordinates=None, **kw): if isinstance(bc, (tuple, list)): bc = BoundaryConditions({'left': {'D': bc[0]}, 'right': {'N': bc[1]}}, domain=doma...
class HawksTests(unittest.TestCase): def test_multiconfig_deep(self): config = {'dataset': {'num_examples': [10, 100, 1000]}, 'constraints': {'overlap': {'limit': ['upper', 'lower']}}, 'ga': {'num_gens': [50, 100, 10, 200], 'mut_args_mean': {'random': {'dims': ['each', 'all']}}}} obj = hawks.create_...
class RIDNET(nn.Module): def __init__(self, args): super(RIDNET, self).__init__() n_feats = args.n_feats kernel_size = 3 reduction = args.reduction rgb_mean = (0.4488, 0.4371, 0.404) rgb_std = (1.0, 1.0, 1.0) self.sub_mean = common.MeanShift(args.rgb_range, rg...
def plot_corr_heatmap(corr_map, path): sns.set(style='whitegrid', font_scale=1.5) plt.figure(figsize=(20, 10)) pl = sns.heatmap(corr_map, annot=True, annot_kws={'size': 8}, fmt='.1g') pl.get_figure().savefig(path, bbox_inches='tight') plt.close()
def get_states(states: dict): reference = {} for (domain, frame) in states.items(): for (slot, values) in frame['slot_values'].items(): if (slot != 'requested_slots'): reference[slot] = values return reference
def test_load_img_from_numpy(): result = {'img': np.ones((32, 100, 3), dtype=np.uint8)} load = LoadImageFromNdarray(color_type='color') output = load(result) assert (output['img'].shape[2] == 3) assert (len(output['img'].shape) == 3) result = {'img': np.ones((32, 100, 1), dtype=np.uint8)} lo...
class Garment(object): def __init__(self, name, type): self.name = name self.type = type def to_filter_string(self): return ((self.type + '/') + self.name) def to_rel_folder(self): return os.path.join(self.type, self.name) def to_abs_path(self, data_root): return ...
class BaseModel(): def _create_model(self, X, Y): raise NotImplementedError('') def _update_model(self, X_all, Y_all, itr=0): return def predict(self, X): return def predict_withGradients(self, X): return
.service(**PAYLOAD_TOO_LARGE) .openapi_version('3.0') def test_too_large_payload(cli, schema_url, service): result = cli.run(schema_url, 'my-api', '--report', f'--schemathesis-io-token={service.token}', f'--schemathesis-io-url={service.base_url}') assert (result.exit_code == ExitCode.TESTS_FAILED), result.stdou...
def prepare_args(args=None): parser = argparse.ArgumentParser() parser.add_argument('config', help='train config file path') parser.add_argument('--cfg-options', nargs='+', action=DictAction, help='override some settings in the used config, the key-value pair in xxx=yyy format will be merged into config fil...
def resnet50(cuda=True, model_root=None): print('Building and initializing resnet-50 parameters') from imagenet import resnet m = resnet.resnet50(True, model_root) if cuda: m = m.cuda() return (m, dataset.get, True)
class TFRobertaForMultipleChoice(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def get_keywords(): git_refnames = ' (HEAD -> main)' git_full = 'bdec5d6c54c5fa0af4bfe70b641b6d90' git_date = '2023-12-22 15:23:06 +0100' keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date} return keywords
class WRGAT(torch.nn.Module): def __init__(self, num_features, num_classes, num_relations, dims=16, drop=0, root=True): super(WRGAT, self).__init__() self.conv1 = WeightedRGATConv(num_features, dims, num_relations=num_relations, root_weight=root) self.conv2 = WeightedRGATConv(dims, num_class...
def test(): ak_array = ak.Array([1, 2, 3]) assert (ak.operations.singletons(ak_array).to_list() == [[1], [2], [3]])
def expand_sub(substr, names): substr = substr.replace('\\>', '') substr = substr.replace('\\<', '') lnames = find_repl_patterns(substr) substr = named_re.sub('<\\1>', substr) def listrepl(mobj): thelist = conv(mobj.group(1).replace('\\,', '')) if template_name_re.match(thelist): ...
class LinearRankMetricCodeNearestNeighborDecoder(Decoder): def __init__(self, code): super().__init__(code, code.ambient_space(), code._default_encoder_name) def __eq__(self, other): return (isinstance(other, LinearRankMetricCodeNearestNeighborDecoder) and (self.code() == other.code())) def ...
def load_arch_lib(arch): archlib_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), (arch.name + '_defs.py')) return load_module(archlib_path)
def split_dataset(dataset, n_splits): return [Subset(dataset, np.arange(i, len(dataset), n_splits)) for i in range(n_splits)]
def to_dataloader(dataset, bsz): return torch.utils.data.DataLoader(dataset, batch_size=bsz, shuffle=True)