code
stringlengths
101
5.91M
def get_idx_list_from_words_test(): idx_list = vector_initializer.get_idx_list_from_words('[PAD]') print(idx_list) idx_list = vector_initializer.get_idx_list_from_words(['i', 'love', 'you']) print(idx_list)
def rnn_relu_cell(input, hidden, w_ih, w_hh, b_ih, b_hh): igates = (torch.mm(input, w_ih.t()) + b_ih) hgates = (torch.mm(hidden, w_hh.t()) + b_hh) return torch.relu((igates + hgates))
def inference_cot(args, question_pool, qes_limit, given_prompt): correct = 0 qes_count = 0 wrong_list = [] QA_record = [] for (qes_num, qes) in enumerate(question_pool): if ((qes_limit is not None) and (qes_count == qes_limit)): break all_self_consistency_ans = [] ...
class PDELU_VGG(nn.Module): def __init__(self, vgg_name): super(PDELU_VGG, self).__init__() self.features = self._make_layers(cfg[vgg_name]) self.classifier = nn.Linear(512, 10) def forward(self, x): out = self.features(x) out = out.view(out.size(0), (- 1)) out = ...
_properties class Enumerator(): debug = Property(desc='Debug mode', default=False, dtype=bool) def __init__(self, sdfg: SDFG, graph: SDFGState, subgraph: SubgraphView=None, condition_function: Callable=None): self._sdfg = sdfg self._graph = graph self._subgraph = subgraph self._s...
def _colliding_remote_schema(testdir): testdir.makefile('.json', bar='{"bar": {"properties": {"a": {"$ref": "b.json#/a"}, "b": {"$ref": "b.json#/ab"}}, "type": "object", "required": ["a", "b"]}}') testdir.makefile('.json', b='{"a": {"$ref": "bc.json#/d"}, "ab": {"$ref": "c.json#/d"}}') testdir.makefile('.js...
def logical_xor_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): return ([None] * (len(grad_inputs) + len(inputs)))
class ScaleEqualizationMidActivation(BaseScaleEqualization): def __init__(self, quant_config: QuantizationConfig, fw_info: FrameworkInfo): super().__init__(quant_config=quant_config, fw_info=fw_info, matcher_instance=MATCHER_MID, kernel_str=KERNEL, bias_str=BIAS)
class CBAM(nn.Module): def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False): super(CBAM, self).__init__() self.ChannelGate = ChannelGate(gate_channels, reduction_ratio, pool_types) self.no_spatial = no_spatial if (not no_spatial): ...
def meta_testing(test_dataset, model, epochs=10, episodes=1000, ways=5, shots=5, query_num=15): module_info = utils.get_info_str('protonet', test_dataset, model, (str(ways) + 'ways'), (str(shots) + 'shots')) (loss_list, acc_list) = ([], []) model.eval() for epoch in range(epochs): (test_loss, te...
class Clip(core.Clip): def __init__(self, clip_id, data_home, dataset_name, index, metadata): super().__init__(clip_id, data_home, dataset_name, index, metadata) self.audio_path = self.get_path('audio') def audio(self) -> Optional[Tuple[(np.ndarray, float)]]: return load_audio(self.audio...
def get_fused_cname(fused_cname, orig_cname): assert (fused_cname and orig_cname) return StringEncoding.EncodedString(('%s%s%s' % (Naming.fused_func_prefix, fused_cname, orig_cname)))
def exact_set_match(gold: str, pred: str) -> float: (gold_set, pred_set) = extract_gold_pred_sets(gold, pred) return float((gold_set == pred_set))
class Critic(nn.Module): def __init__(self, body: nn.Module, output_dim: int, use_layer_init: bool=True): super().__init__() self.body = body if use_layer_init: self.fc = layer_init(nn.Linear(self.body.feature_dim, output_dim), w_scale=0.1) else: self.fc = nn....
class TestAll(TestCasePlus): ([MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM]) def test_seq2seq_dataset_truncation(self, tok_name): tokenizer = AutoTokenizer.from_pretrained(tok_name) tmp_dir = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir()) max_len_source = max((l...
class TestDBLDetector(): def setup(self): pass def test_dbl(self, log_counter_df): counter_df = log_counter_df ts_df = counter_df[[constants.LOG_COUNTS]] ts_df.index = counter_df[constants.LOG_TIMESTAMPS] counter_df['attribute'] = counter_df.drop([constants.LOG_COUNTS, co...
def process_class_names(instance): try: words = instance words = words[:10] clss = '' start = words.index('class') end = words.index('(') clss = words[(start + 1)] for i in range((start + 2), end): clss = ((clss + ' ') + words[i]) original_...
class OverlapPatchEmbed(nn.Module): def __init__(self, patch_size=7, stride=4, in_chans=3, embed_dim=768, norm_cfg=dict(type='BN', requires_grad=True)): super().__init__() patch_size = (patch_size, patch_size) self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=stride, ...
def applyWord2VecMostSimilar(modelname='../data/skip_nostop_single_100features_10minwords_5context', word='#donaldtrump', top=10): model = word2vec.Word2Vec.load(modelname) print('Find ', top, ' terms most similar to ', word, '...') for res in model.most_similar(word, topn=top): print(res) print...
.parametrize('observation_shape', [(4, 84, 84), (100,)]) .parametrize('action_size', [2]) .parametrize('batch_size', [32]) .parametrize('encoder_factory', [DefaultEncoderFactory()]) def test_create_deterministic_policy(observation_shape: Sequence[int], action_size: int, batch_size: int, encoder_factory: EncoderFactory)...
def prepare_data(data_path): train_path = os.path.join(data_path, 'sst.train.sentences.txt') if (not tf.gfile.Exists(train_path)): url = ' files = ['stsa.binary.phrases.train', 'stsa.binary.dev', 'stsa.binary.test'] for fn in files: tx.data.maybe_download((url + fn), data_pat...
class Partition23(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/T5Block[6]/T5LayerFF[2]/Dropout[dropout]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[7]/T5LayerSelfAttention[0]/T5LayerNorm[layer_norm]', 'T5ForConditionalGeneration/T5Stack[decoder]/T5Block[7]/T5LayerSelfAttention...
def main(): arg_parser = ArgumentParser() arg_parser.add_argument('bliss_filename') arg_parser.add_argument('--subset_segment_file') arg_parser.add_argument('--output_type', default='', help='e.g. segment_name') arg_parser.add_argument('--merge_swb_ab', action='store_true') arg_parser.add_argume...
def video_processing(ref, dist): video = {} video_type = ['ref', 'dist'] for i_type in video_type: if (i_type == 'ref'): video_name = ref else: video_name = dist video_name_dis = video_name video_capture = cv2.VideoCapture() video_capture.o...
.parametrize('sparse_feature_num,dense_feature_num', [(2, 0), (0, 2)]) def test_WDL(sparse_feature_num, dense_feature_num): if (version.parse(tf.__version__) >= version.parse('2.0.0')): return model_name = 'WDL' sample_size = SAMPLE_SIZE (x, y, feature_columns) = get_test_data(sample_size, spars...
def run_pool(poolsize, chunksize): client = utils.init_client(MONGO_ARGS) id_collection = client[DB_NAME][READ_COL] query = utils.prepare_query(filters) document_ids = id_collection.find(query).distinct('_id') logger.info(f'Obtained ID list for {len(document_ids)} articles.') if (DOC_LIMIT > 0):...
def BlanusaSecondSnarkGraph(): c0 = ((- 1), 0) c1 = ((- 1), 1) g = Graph({c0: [(0, 0), (1, 4), c1], c1: [(0, 3), (1, 1)], (0, 2): [(0, 5)], (0, 6): [(0, 4)], (0, 7): [(0, 1)], (1, 7): [(1, 2)], (1, 0): [(1, 6)], (1, 3): [(1, 5)]}, name='Blanusa Second Snark Graph') g.add_cycle([(0, i) for i in range(5)]...
def get_all_models(dirname): dirs = [d for d in os.listdir(dirname) if ('evaluate.json' in os.listdir(os.path.join(dirname, d)))] if (len(dirs) == 0): return None return [os.path.join(dirname, d) for d in dirs]
_metric def ppl_wend(opts): ppl = perceptual_path_length.compute_ppl(opts, num_samples=50000, epsilon=0.0001, space='w', sampling='end', crop=True, batch_size=2) return dict(ppl_wend=ppl)
def print(*args, **kwargs): __builtin__.print(*args, **kwargs) with open(out_path, 'a') as fp: __builtin__.print(*args, file=fp, **kwargs)
def compute_a(sigma, q, lmbd, verbose=False): lmbd_int = int(math.ceil(lmbd)) if (lmbd_int == 0): return 1.0 a_lambda_first_term_exact = 0 a_lambda_second_term_exact = 0 for i in range((lmbd_int + 1)): coef_i = (scipy.special.binom(lmbd_int, i) * (q ** i)) (s1, s2) = (0, 0) ...
class BoolQ(): def all_speedups_boolq(): (seq_gpipe_dict, seq_gpipe_times) = Hack.get_boolq_seq_hack_gpipe_times_and_dict() seq_stale_fn = 'results/FOR_PAPER/all_results_new_t5_layer_graph_t5_3b_tied_lmheads_512_4_8p_bw12_squad1_pipedream_t5_tfds_stale_bs_20_se_10_seed_42_layer_graph_t5_3b_tied_lmhe...
def pooling_with_mask(rep_tensor, rep_mask, method='max', scope=None): with tf.name_scope((scope or ('%s_pooling' % method))): if (method == 'max'): rep_tensor_masked = exp_mask_for_high_rank(rep_tensor, rep_mask) output = tf.reduce_max(rep_tensor_masked, (- 2)) elif (method ...
class InvariantModule(tf.keras.Model): def __init__(self, settings, **kwargs): super().__init__(**kwargs) self.s1 = Sequential([Dense(**settings['dense_s1_args']) for _ in range(settings['num_dense_s1'])]) self.s2 = Sequential([Dense(**settings['dense_s2_args']) for _ in range(settings['num_...
class AlphaDropout(_DropoutNd): def forward(self, input: Tensor) -> Tensor: return cF.complex_fcaller(F.alpha_dropout, input, self.p, self.training)
def _get_head_stage(arch, head_name, blocks): if (head_name not in arch): head_name = 'head' head_stage = arch.get(head_name) ret = mbuilder.get_blocks(arch, stage_indices=head_stage, block_indices=blocks) return ret['stages']
def _wrap(fn, kwargs, error_queue): _prctl_pr_set_pdeathsig(signal.SIGINT) try: fn(**kwargs) except KeyboardInterrupt: pass except EarlyStopping: sys.exit(signal.SIGUSR1) except Exception: import traceback error_queue.put(traceback.format_exc()) sys.ex...
.parametrize('seed', [313]) .parametrize('axis', [0, 3]) .parametrize('decay_rate', [0.9]) .parametrize('eps', [1e-05]) .parametrize('nonlinearity', ['relu']) .parametrize('output_stat', [False]) .parametrize('add', [True, False]) .parametrize('ctx, func_name', ctxs) .parametrize('no_scale, no_bias', [[False, False], [...
def get_rowspace_projection(W: np.ndarray) -> np.ndarray: if np.allclose(W, 0): w_basis = np.zeros_like(W.T) else: w_basis = scipy.linalg.orth(W.T) w_basis = (w_basis * np.sign(w_basis[0][0])) P_W = w_basis.dot(w_basis.T) return P_W
def isic_time(u, v, model, **kwargs): w = (u[0].indices[0].spacing * model.irho) ics = kwargs.get('icsign', 1) return (w * sum(((((uu * vv.dt2) * model.m) + (ics * inner_grad(uu, vv))) for (uu, vv) in zip(u, v))))
class submission_writer(object): def __init__(self, job_name, out_dir, memory, asr_pth, skp_pth, emo_pth, lang_pth): self.job_name = job_name self.out_dir = out_dir self.memory = memory self.tasks = {'ASR': asr_pth, 'spk_id': skp_pth, 'EMO': emo_pth, 'LANG': lang_pth} def write(s...
def get_wilds_ood_test_loader(dataset, data_dir, data_fraction=1.0, model_seed=0): config = get_default_config(dataset, data_fraction=data_fraction) dataset_kwargs = ({'fold': POVERTY_FOLDS[model_seed]} if (dataset == 'poverty') else {}) full_dataset = get_dataset(dataset=dataset, root_dir=data_dir, **datas...
def get_dataloader(rank, world_size): train_df = dataset_utils.create_df(config.train_dir) valid_df = dataset_utils.create_df(config.valid_dir) pseudo_df = 'pseudo_df.csv' train_df = train_df.append(pseudo_df) flood_label_paths = train_df['flood_label_path'].values.tolist() train_has_masks = lis...
class AudioEncoder(nn.Module): def __init__(self, num_output_length, if_tanh=False): super(AudioEncoder, self).__init__() self.if_tanh = if_tanh self.block1 = BasicBlock(1, 16, kernel_size=3, stride=1) self.block2 = BasicBlock(16, 32, kernel_size=3, stride=2) self.block3 = Ba...
def test_partial_fit(): X = Xdigits.copy() rbm = BernoulliRBM(n_components=64, learning_rate=0.1, batch_size=20, random_state=9) n_samples = X.shape[0] n_batches = int(np.ceil((float(n_samples) / rbm.batch_size))) batch_slices = np.array_split(X, n_batches) for i in range(7): for batch i...
def optimize_inference_for_dag(net, input_blobs, namescope=''): netproto = copy.deepcopy(net.Proto()) external_input = set(net.Proto().external_input) external_output = set(net.Proto().external_output) def is_activation_blob(b): return ((b not in external_input) and (b not in external_output)) ...
def process_triple(j, AVRO_FILE, triple, start_time, len_local_entity_mentions_map, job_object: PipelineJob): if (triple['confidence_score'] < 0.3): return None if ('PRP$' in [w['pos'] for w in triple['dropped_words_subject']]): return None if ('no' in [v for (k, v) in triple['quantities'].i...
def sort_auto_mapping(fname, overwrite: bool=False): with open(fname, 'r', encoding='utf-8') as f: content = f.read() lines = content.split('\n') new_lines = [] line_idx = 0 while (line_idx < len(lines)): if (_re_intro_mapping.search(lines[line_idx]) is not None): indent ...
class TestTransform(): def __init__(self, size): self.transform = Compose([Resize(size), Normalize(), ToTensor()]) def __call__(self, image): (image, _, _) = self.transform(image) return image
_utils.test() def test_offset_for_vector(): a = ti.field(dtype=ti.i32, shape=16, offset=(- 48)) b = ti.field(dtype=ti.i32, shape=16, offset=None) offset = 16 shape = 16 c = ti.Vector.field(n=1, dtype=ti.i32, shape=shape, offset=offset) def test(): for i in c: c[i][0] = (2 * i...
class _ModuleNode(_PathNode): __slots__ = ['source_file'] def __init__(self, source_file: str): self.source_file = source_file
def eval_model_val(checkpoint, logger, att_feats, train_data, val_data, classes): logger.info('building model...') states = torch.load(checkpoint) net = CVAE(x_dim=states['x_dim'], s_dim=states['s_dim'], z_dim=states['z_dim'], enc_layers=states['enc_layers'], dec_layers=states['dec_layers']) dis = Discr...
def get_evaluation_chunk_logits_data_key(evaluation_chunk_id): return 'evaluation_chunks/{}_logits_data.bytes'.format(evaluation_chunk_id)
class FairseqEncoderDecoderModel(BaseFairseqModel): def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder assert isinstance(self.encoder, FairseqEncoder) assert isinstance(self.decoder, FairseqDecoder) def forward(self, src...
def _init_weight_alt(m, n=''): if isinstance(m, nn.Conv2d): fan_out = ((m.kernel_size[0] * m.kernel_size[1]) * m.out_channels) fan_out //= m.groups m.weight.data.normal_(0, math.sqrt((2.0 / fan_out))) if (m.bias is not None): if ('class_net.predict' in n): ...
def gene_data(aug_dials_file, ori_dial_file, aug_type): data = [] with open(aug_dials_file) as f: aug_dials = json.load(f) with open(ori_dial_file) as f: dials = json.load(f) for dial_dict in tqdm(dials): for (ti, turn) in enumerate(dial_dict['dialogue']): ...
class TableEncoder(json.JSONEncoder): def tablToJson(self, o): rd = o.records() if (len(rd) > 0): if isinstance(rd[0], (str, Lib)): return rd try: name = (x.name for x in dc.fields(rd[0]) if (x.repr == True)) out = {n: [getattr(...
def read_selected_sentences(filename): xml_to_sent_dict = {} with open(filename, 'rb') as csv_file: reader = csv.reader(csv_file, delimiter=',') reader.next() for line in reader: xml_filename = '{}_{}.xml'.format(line[0], line[1]) sent_id = int(line[2]) ...
def test_emptyarray(): assert (ak_from_buffers(*ak_to_buffers([])).to_list() == []) assert (ak_from_buffers(*ak_to_buffers([[], [], []])).to_list() == [[], [], []]) assert (pickle.loads(pickle.dumps(ak_Array([]), (- 1))).to_list() == []) assert (pickle.loads(pickle.dumps(ak_Array([[], [], []]), (- 1)))....
def read_array(fp, allow_pickle=False, pickle_kwargs=None): version = read_magic(fp) _check_version(version) (shape, fortran_order, dtype) = _read_array_header(fp, version) if (len(shape) == 0): count = 1 else: count = numpy.multiply.reduce(shape, dtype=numpy.int64) if dtype.haso...
class Experiment(ABC): def __init__(self, config_path: str): self.config_path = config_path self.root = Path(config_path).parent gin.parse_config_file(self.config_path) () def build(self, experiment_name: str, module: str, repeat: int, variables_dict: Dict[(str, SearchSpace)]): ...
def generate_virtual_adversarial_perturbation(x, logit, is_training=True): d = tf.random_normal(shape=tf.shape(x)) for _ in range(FLAGS.num_power_iterations): d = (FLAGS.xi * get_normalized_vector(d)) logit_p = logit logit_m = forward((x + d), update_batch_stats=False, is_training=is_tra...
def get_val(config_cmd, att): words = config_cmd.split(' ') i = words.index('--{}'.format(att)) val = words[(i + 1)] return val
def convert_to_bool(x: str) -> bool: if (x.lower() in ['1', 'y', 'yes', 'true']): return True if (x.lower() in ['0', 'n', 'no', 'false']): return False raise ValueError(f'{x} is not a value that can be converted to a bool.')
def keyword_while(A: dace.float32[N], B: dace.float32[N]): i = dace.define_local_scalar(dtype=dace.int32) i = 0 while True: B[i] = ((A[i] + i) - i) i += 1 if (i < N): continue else: break
class FixedAcquisitionRule(AcquisitionRule[(TensorType, SearchSpace, ProbabilisticModel)]): def __init__(self, query_points: SequenceN[Sequence[float]]): self._qp = tf.constant(query_points, dtype=tf.float64) def __repr__(self) -> str: return f'FixedAcquisitionRule({self._qp!r})' def acquire...
class Caffe2CppRep(BackendRep): def __init__(self, cpp_rep): super(Caffe2CppRep, self).__init__() self.__core = cpp_rep self.__external_outputs = cpp_rep.external_outputs() self.__external_inputs = cpp_rep.external_inputs() self.__uninitialized_inputs = cpp_rep.uninitialized_...
.parametrize('type_', ('string', 'integer', 'array', 'object', 'boolean', 'number')) def test_cookies(testdir, type_): testdir.make_test('\()\(suppress_health_check=[HealthCheck.filter_too_much, HealthCheck.data_too_large], deadline=None, max_examples=20)\ndef test_(case):\n assert_str(case.cookies["token"])\n ...
def count_type_citizens(model, condition, exclude_jailed=True): count = 0 for agent in model.schedule.agents: if (agent.breed == 'cop'): continue if (exclude_jailed and agent.jail_sentence): continue if (agent.condition == condition): count += 1 re...
def main(version: str, data_root: str, submission_path: str, config_name: str='predict_2020_icra.json') -> None: predictions = json.load(open(submission_path, 'r')) nusc = NuScenes(version=version, dataroot=data_root) helper = PredictHelper(nusc) config = load_prediction_config(helper, config_name) ...
def fuzzy_string_match(str_ref, str_hyp): return (fuzz.token_sort_ratio(str_ref, str_hyp) / 100.0)
def tok2int_sent(sentence, tokenizer, max_seq_length): (sent_a, sent_b) = sentence tokens_a = tokenizer.tokenize(sent_a) tokens_b = None if sent_b: tokens_b = tokenizer.tokenize(sent_b) _truncate_seq_pair(tokens_a, tokens_b, (max_seq_length - 3)) elif (len(tokens_a) > (max_seq_length...
def write_results(results): filename = mktemp() with open(filename, 'w') as f: json.dump(results, f) return filename
def launch_job(cfg, init_method, func, daemon=False): if (cfg.NUM_GPUS > 1): torch.multiprocessing.spawn(mpu.run, nprocs=cfg.NUM_GPUS, args=(cfg.NUM_GPUS, func, init_method, cfg.SHARD_ID, cfg.NUM_SHARDS, cfg.DIST_BACKEND, cfg), daemon=daemon) else: func(cfg=cfg)
def parse_example_proto(example_serialized): feature_map = {'image/filename': tf.FixedLenFeature([], dtype=tf.string, default_value=''), 'image/class/label': tf.FixedLenFeature([1], dtype=tf.int64, default_value=(- 1)), 'image/class/text': tf.FixedLenFeature([], dtype=tf.string, default_value='')} sparse_float3...
class DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=10): super(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=False) ...
def get_settings(args=None): if (not args): args = get_args() settings = experiment_settings.ExperimentSettings(args) assert (args.rho_scale_lower >= args.rho_scale_upper) return settings
class NLPDataLoader(KerasDataLoader): def __init__(self, collaborator_count, split_ratio, num_samples, data_path, batch_size, **kwargs): self.shard_num = data_path self.data_path = dlu.download_data_() self.batch_size = batch_size (train, valid, details) = dlu.load_shard(collaborator...
class ForgotForm(Form): email = TextField('Email', validators=[DataRequired(), Length(min=6, max=40)])
class TFXLNetPreTrainedModel(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def graph_constructor(X, bihierarchy, constraint_structure): S = {index for (index, x) in np.ndenumerate(X)} (A, B) = bihierarchy (A.append(S), B.append(S)) for x in S: (A.append({x}), B.append({x})) for x in S: constraint_structure.update({frozenset({x}): (0, 1)}) R1 = nx.DiGrap...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReL...
.torch def test_callback_for_cardinality(sequential_info): schema = TensorSchema([TensorFeatureInfo('user_id', feature_type=FeatureType.CATEGORICAL, is_seq=True), TensorFeatureInfo('item_id', feature_type=FeatureType.CATEGORICAL, is_seq=True), TensorFeatureInfo('some_user_feature', feature_type=FeatureType.CATEGORI...
.parametrize('csr_container', CSR_CONTAINERS) def test_unsorted_indices(csr_container): (X, y) = load_digits(return_X_y=True) X_test = csr_container(X[50:100]) (X, y) = (X[:50], y[:50]) X_sparse = csr_container(X) coef_dense = svm.SVC(kernel='linear', probability=True, random_state=0).fit(X, y).coef...
def interpolate_tracking_boxes(left_box: TrackingBox, right_box: TrackingBox, right_ratio: float) -> TrackingBox: def interp_list(left, right, rratio): return tuple((((1.0 - rratio) * np.array(left, dtype=float)) + (rratio * np.array(right, dtype=float)))) def interp_float(left, right, rratio): ...
def show_metric_table(base): di = {} for p in sorted(base.parent.glob('*/hydra/overrides.yaml')): for l in OmegaConf.load(str(p)): (k, v) = l.split('=') if (k in di.keys()): di[k].append(v) else: di[k] = [v] with open((p.parent....
class PairDataset(VisionDataset): def __init__(self, root, dataset_name, index, prompt, pairs_file=None, extensions='.jpg', height=512, Train=True, down_scale=1, break_iter=None): assert ((down_scale == 1) or (down_scale == 2)), 'only support resolution of 1024X512 and 512X256' self.downscale = down...
class NumpySimpleITKImageBridge(): def convert(array: np.ndarray, properties: ImageProperties) -> sitk.Image: is_vector = False if (not (array.shape == properties.size[::(- 1)])): if (array.ndim == 1): array = array.reshape(properties.size[::(- 1)]) elif (arra...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313, 999]) def test_gelu_forward_backward(seed, ctx, func_name): from nbla_test_utils import function_tester rng = np.random.RandomState(seed) inputs = [rng.randn(2, 3, 4).astype(np.float32)] function_tester(rng, F.gelu, ref_gelu, inputs, ctx=ct...
def get_default_hyperparams(model_name): defaults = {'dropout_rate': [0.1, 0.2, 0.3, 0.4, 0.5], 'hidden_layer_size': [5, 10, 25, 50, 100, 150], 'minibatch_size': [256, 512, 1024], 'learning_rate': np.logspace((- 4), 0, 5), 'max_norm': [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0]} if ('rnf' in model_name): prin...
def train(epoch, model, optimizer, scheduler): global global_step epoch_loss = 0.0 running_loss = [0.0, 0.0, 0.0] model.train() display_step = 100 for (batch_idx, (x, c)) in enumerate(train_loader): scheduler.step() global_step += 1 (x, c) = (x.to(device), c.to(device)) ...
def get_site_symmetries(wyckoff): ssyms = [] for w in wyckoff: ssyms += [('"%-6s"' % w_s['site_symmetry']) for w_s in w['wyckoff']] damp_array_site_symmetries(ssyms)
class TestTextFileReader(TestCase): def test_text_file_reader(self): schema = Struct(('field1', Scalar(dtype=str)), ('field2', Scalar(dtype=str)), ('field3', Scalar(dtype=np.float32))) num_fields = 3 col_data = [['l1f1', 'l2f1', 'l3f1', 'l4f1'], ['l1f2', 'l2f2', 'l3f2', 'l4f2'], [0.456, 0.78...
def _init_nd_shape_and_axes(x, shape, axes): noshape = (shape is None) noaxes = (axes is None) if (not noaxes): axes = _iterable_of_int(axes, 'axes') axes = [((a + x.ndim) if (a < 0) else a) for a in axes] if any((((a >= x.ndim) or (a < 0)) for a in axes)): raise ValueErr...
_tf class TFTransfoXLModelLanguageGenerationTest(unittest.TestCase): ('Skip test until #12651 is resolved.') def test_lm_generate_transfo_xl_wt103(self): model = TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103') input_ids = tf.convert_to_tensor([[33, 1297, 2, 1, 1009, 4, 1109, 11739, 47...
def dist0(x, *, c=1.0, keepdim=False): c = torch.as_tensor(c).type_as(x) return _dist0(x, c, keepdim=keepdim)
def measure_cpu_gpu_instant_load(): gpu_load = [] if gpu_load_backend_ok: global gpu_a_load global gpu_m_count gpu_m_count += 1 try: comm = current_communicator() if comm: index = comm.local_rank elif ('cuda' in str(nn.get_curre...
class NameMap(dict): def __getitem__(self, k): assert isinstance(k, SDFG) if (k not in self): self[k] = {} return super().__getitem__(k) def get(self, k): return self[k] def __setitem__(self, k, v) -> None: assert isinstance(k, SDFG) return super()...
class TernaryTransformer(Transformer): def __init__(self): self.lossy = True def forward(self, data, **kwargs): mean_topk = np.mean(np.abs(data)) out_ = np.where((data > 0.0), mean_topk, 0.0) out = np.where((data < 0.0), (- mean_topk), out_) (int_array, int2float_map) = s...
def test_cx(): circuit = Circuit(2) circuit.cx(0, 1) expect = array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]) assert array_equal(expect, circuit.get_unitary_matrix())