code
stringlengths
101
5.91M
def test_default_edge_func(): (g, n) = pixel_graph(image, spacing=np.array([0.78, 0.78])) num_edges = (len(g.data) // 2) assert (num_edges == 12) np.testing.assert_almost_equal(g[(0, 1)], (0.78 * np.abs((image[(0, 0)] - image[(0, 1)])))) np.testing.assert_array_equal(n, np.arange(image.size))
def paramdec(dec): (dec) def layer(*args, **kwargs): from dace import data if ((len(kwargs) == 0) and (len(args) == 1) and callable(args[0]) and (not isinstance(args[0], (typeclass, data.Data)))): return dec(*args, **kwargs) (dec) def repl(f): return dec(f...
class Speech2TextProcessor(): def __init__(self, *args, **kwargs): requires_sentencepiece(self)
def tensor1d(min_len=1, max_len=64, dtype=np.float32, elements=None): return tensor(1, 1, dtype, elements, min_value=min_len, max_value=max_len)
def ldo_setup(graph: Graph): n = len(graph) degrees = None location = None max_deg = 0 if isinstance(graph, DictGraph): degrees = {v: graph.in_degree(v) for v in graph} location = {v: None for v in graph} max_deg = max(degrees.values()) else: degrees = [graph.in_d...
def load_state_dict(checkpoint_path: str, map_location: str='cpu', model_key='model|module|state_dict'): checkpoint = torch.load(checkpoint_path, map_location=map_location) for mk in model_key.split('|'): if (isinstance(checkpoint, dict) and (mk in checkpoint)): state_dict = checkpoint[mk] ...
def get_kw_to_default_map(func): kw_to_default = {} fsig = inspect.signature(func) for (name, info) in fsig.parameters.items(): if (info.kind is info.POSITIONAL_OR_KEYWORD): if (info.default is not info.empty): kw_to_default[name] = info.default return kw_to_default
def DictionaryOfType(ofType: type) -> ConfigDictionaryOfType.__class__: return ConfigDictionaryOfType.buildWith(ofType)
def CombineConditions(name, condition_nets, relation): if (not condition_nets): return None if (not isinstance(condition_nets, list)): raise ValueError('condition_nets must be a list of nets.') if (len(condition_nets) == 1): condition_blob = GetConditionBlobFromNet(condition_nets[0])...
def OA_from_Vmt(m, t, V): (Fq, M) = QDM_from_Vmt(m, t, V) return OA_from_quasi_difference_matrix(M, Fq, add_col=False)
def get_op_quantization_configs() -> Tuple[(OpQuantizationConfig, List[OpQuantizationConfig])]: eight_bits = tp.OpQuantizationConfig(activation_quantization_method=tp.QuantizationMethod.POWER_OF_TWO, weights_quantization_method=tp.QuantizationMethod.SYMMETRIC, activation_n_bits=8, weights_n_bits=8, weights_per_chan...
def compute_activations(model, train_loader, num_samples): activation = {} num_samples_processed = 0 def get_activation(name): def hook(model, input, output): print('num of samples seen before', num_samples_processed) if (name not in activation): activation[na...
def test_setup(in_model, keras_impl, mixed_precision_candidates_list): qc = MixedPrecisionQuantizationConfig(DEFAULTCONFIG) graph = prepare_graph_with_configs(in_model, keras_impl, DEFAULT_KERAS_INFO, representative_dataset, (lambda name, _tp: get_tpc(mixed_precision_candidates_list)), qc=qc, mixed_precision_en...
_utils.test() def test_python_scope_compare(): v = ti.math.vec3(0, 1, 2) assert ((v < 1)[0] == 1)
def collect_rmse_per_dataset(config_multierror_list, algorithms): algorithm_rmse = {'trans_err': {}, 'rot_err': {}} print('\n>>> Collecting RMSE per dataset...') for (idx, alg_i) in enumerate(algorithms): config_mt_error = config_multierror_list[idx] algorithm_rmse['trans_err'][alg_i] = [] ...
(torch.backends.xnnpack.enabled, ' XNNPACK must be enabled for these tests. Please build with USE_XNNPACK=1.') class TestXNNPACKOps(TestCase): (batch_size=st.integers(0, 3), data_shape=hu.array_shapes(1, 3, 2, 64), weight_output_dim=st.integers(2, 64), use_bias=st.booleans()) def test_linear(self, batch_size, d...
def model_train_mode(args, feeder, hparams, global_step): with tf.variable_scope('Tacotron_model', reuse=tf.AUTO_REUSE) as scope: model = create_model('Tacotron', hparams) model.initialize(feeder.inputs, feeder.input_lengths, feeder.speaker_embeddings, feeder.mel_targets, feeder.token_targets, targe...
class AffoMiner(LightningModule): def __init__(self, min_cont_affo_frames=2, max_side_frames=31, max_num_hands=2, hand_state_nms_thresh=0.5, contact_state_threshold=0.99, fps=5): super().__init__() self.hand_state_detector = HandStateRCNN(box_detections_per_img=max_num_hands) self.min_cont_a...
def shearx_grid(output_size, ulim=((- 1), 1), vlim=((- 5), 5), out=None, device=None): (nv, nu) = output_size urange = torch.linspace(ulim[0], ulim[1], nu, device=device) vrange = torch.linspace(vlim[0], vlim[1], nv, device=device) (vs, us) = torch.meshgrid([vrange, urange]) ys = us xs = (us * v...
def query_on_triline(query, feature, min_, max_, use_ste=False, boundary_check=False, ctx=None): func = CosineQueryOnTriline(ctx, min_, max_, use_ste, boundary_check) return func(query, feature)
class UnetBlock(nn.Module): def __init__(self, input_nc, outer_nc, inner_nc, submodule=None, outermost=False, innermost=False, norm_layer=None, nl_layer=None, use_dropout=False, upsample='basic', padding_type='zero'): super(UnetBlock, self).__init__() self.outermost = outermost p = 0 ...
def transform(s): if pd.isna(s): return 4 if (s == 'Macroinvertebrates'): return 0 if ('Fishes' in s): return 1 if ('Producer' in s): return 2 if ('Microfauna' in s): return 3 return 4
def convert_to_localized_md(model_list, localized_model_list, format_str): def _rep(match): (title, model_link, paper_affiliations, paper_title_link, paper_authors, supplements) = match.groups() return format_str.format(title=title, model_link=model_link, paper_affiliations=paper_affiliations, paper...
def assign_entities(subfolder, subfolder_entities, nkjp_dir): morph_path = os.path.join(nkjp_dir, subfolder, MORPH_FILE) rt = parse_xml(morph_path) morph_pars = rt.findall(('{%s}TEI/{%s}text/{%s}body/{%s}p' % (NAMESPACE, NAMESPACE, NAMESPACE, NAMESPACE))) par_id_to_segs = {} for par in morph_pars: ...
def alias_draw(J, q): K = len(J) kk = int(np.floor((np.random.rand() * K))) if (np.random.rand() < q[kk]): return kk else: return J[kk]
class LbfgsOptimizer(Serializable): def __init__(self, max_opt_itr=20, callback=None): Serializable.quick_init(self, locals()) self._max_opt_itr = max_opt_itr self._opt_fun = None self._target = None self._callback = callback def update_opt(self, loss, target, inputs, ext...
def register_Ns3Histogram_methods(root_module, cls): cls.add_constructor([param('ns3::Histogram const &', 'arg0')]) cls.add_constructor([param('double', 'binWidth')]) cls.add_constructor([]) cls.add_method('AddValue', 'void', [param('double', 'value')]) cls.add_method('GetBinCount', 'uint32_t', [par...
class SqueezeExpandDilatedDecoder(nn.Module): def __init__(self, in_channels, num_classes, inter_channels, feature_scales, foreground_channel=False, ConvType=nn.Conv3d, PoolType=nn.AvgPool3d, NormType=nn.Identity): super().__init__() assert (tuple(feature_scales) == (4, 8, 16, 32)) PoolingLa...
class TestOpenposeComponents(TestCase): def test_openpose_components_total_points(self): actual_total_points = 0 for component in OpenPose_Components: num_keypoints = len(component.points) actual_total_points += num_keypoints self.assertEqual(actual_total_points, OPEN...
def test_fowlkes_mallows_score(): score = fowlkes_mallows_score([0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 2, 2]) assert_almost_equal(score, (4.0 / np.sqrt((12.0 * 6.0)))) perfect_score = fowlkes_mallows_score([0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0]) assert_almost_equal(perfect_score, 1.0) worst_score = fowlke...
def resample_uv_tensors_to_bbox(u: torch.Tensor, v: torch.Tensor, labels: torch.Tensor, box_xywh_abs: IntTupleBox) -> torch.Tensor: (x, y, w, h) = box_xywh_abs w = max(int(w), 1) h = max(int(h), 1) u_bbox = F.interpolate(u, (h, w), mode='bilinear', align_corners=False) v_bbox = F.interpolate(v, (h, ...
def _validate_vector(u, dtype=None): u = np.asarray(u, dtype=dtype, order='c') if (u.ndim == 1): return u raise ValueError('Input vector should be 1-D.')
def validate(val_loader, model, criterion, args, logger, epoch): 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='Test...
class ResNet101(TorchVisionModel): def __init__(self, tasks, model_args): super(ResNet101, self).__init__(models.resnet101, tasks, model_args)
def stop_worker(thread_id: int) -> None: ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id), ctypes.py_object(SystemExit))
class TilerConfigurationCallback(Callback): def __init__(self, enable: bool=False, tile_size: (int | Sequence)=256, stride: ((int | Sequence) | None)=None, remove_border_count: int=0, mode: str='padding', tile_count: int=4) -> None: self.enable = enable self.tile_size = tile_size self.stride...
class NDCG(object): def __init__(self, K): self.K = K self.name = '{}'.format(K) def apply(self, suggestions, targets): def _ndcg_at_k(rank, k): dcg = 0.0 for (rel, pos) in rank: if (pos <= k): dcg += (float(((2 ** rel) - 1)) / ...
def _default_key_normalizer(key_class, request_context): context = request_context.copy() context['scheme'] = context['scheme'].lower() context['host'] = context['host'].lower() for key in ('headers', '_proxy_headers', '_socks_options'): if ((key in context) and (context[key] is not None)): ...
def random_crop_params(img, scale, ratio=((3 / 4), (4 / 3))): (width, height) = img.size area = (height * width) for _ in range(10): target_area = (random.uniform(*scale) * area) log_ratio = (math.log(ratio[0]), math.log(ratio[1])) aspect_ratio = math.exp(random.uniform(*log_ratio)) ...
class TestIo(): def setup(self): self.temp_dir = mkdtemp() self.test_file = join(self.temp_dir, 'some-subdirectory', 'some-file.txt') def teardown(self): rmtree(self.temp_dir, ignore_errors=True) def test_creates_file(self): makedirs(dirname(self.test_file)) create_fi...
def register_methods(root_module): register_Ns3Address_methods(root_module, root_module['ns3::Address']) register_Ns3AllocationRetentionPriority_methods(root_module, root_module['ns3::AllocationRetentionPriority']) register_Ns3AttributeConstructionList_methods(root_module, root_module['ns3::AttributeConstru...
def sample_patches(datas, patch_size, n_samples, valid_inds=None, verbose=False): ((len(patch_size) == datas[0].ndim) or _raise(ValueError())) if (not all(((a.shape == datas[0].shape) for a in datas))): raise ValueError(('all input shapes must be the same: %s' % ' / '.join((str(a.shape) for a in datas))...
.parametrize('dtype_in, dtype_out', [(np.float32, np.float32), (np.float64, np.float64), (int, np.float64)]) def test_transformer_dtypes_casting(dtype_in, dtype_out): X = Xdigits[:100].astype(dtype_in) rbm = BernoulliRBM(n_components=16, batch_size=5, n_iter=5, random_state=42) Xt = rbm.fit_transform(X) ...
class SrcInfoGuard(): def __init__(self, info_stack, info): self.info_stack = info_stack self.info = info def __enter__(self): self.info_stack.append(self.info) def __exit__(self, exc_type, exc_val, exc_tb): self.info_stack.pop()
def createButtonsInfig(fig): basis_ax = plt.axes([0.88, 0.44, 0.1, 0.075]) end_ax = plt.axes([0.78, 0.44, 0.1, 0.075]) bell2_ax = plt.axes([0.78, 0.365, 0.1, 0.075]) bell3_ax = plt.axes([0.88, 0.365, 0.1, 0.075]) h_ax_p = plt.axes([0.78, 0.83, 0.1, 0.075]) x_ax_p = plt.axes([0.78, 0.755, 0.1, 0....
class GrabBGZF_Random(object): def __init__(self, filename): self.reader = BgzfReader(filename, 'rt') ch = self.reader.read(1) if (ch == '>'): iter_fn = my_fasta_iter elif (ch == ''): iter_fn = my_fastq_iter else: raise Exception('unknown s...
def sac(variant): expl_env = gym.make(variant['env_name']) eval_env = gym.make(variant['env_name']) expl_env.seed(variant['seed']) eval_env.set_eval() mode = variant['mode'] archi = variant['archi'] if (mode == 'her'): variant['her'] = dict(observation_key='observation', desired_goal...
def flow_through_node(flow_seq, target_node): for i in range(len(flow_seq)): ((u, v), l) = flow_seq[i] if (v == target_node): assert (i < len(flow_seq)) ((u_next, v_next), l_next) = flow_seq[(i + 1)] assert (l == l_next) assert (v == u_next) ...
class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.initialized = False def initialize(self): self.parser.add_argument('--dataroot', type=str, default='/home/u176443/Documents/ARPE/soccer_tracking/dat...
def test_get_component_order_mapping(): dataset = sbd.DummyDataset(missing_components='pad') with pytest.raises(AssertionError): get_component_order_mapping(dataset) dataset.missing_components = 'ignore' dataset._metadata.loc[(0, 'trace_component_order')] = 'Z' dataset._metadata.loc[(1, 'tra...
def profiling(model, use_cuda): print('Start model profiling, use_cuda:{}.'.format(use_cuda)) for width_mult in sorted(FLAGS.width_mult_list, reverse=True): model.apply((lambda m: setattr(m, 'width_mult', width_mult))) print('Model profiling with width mult {}x:'.format(width_mult)) verb...
_model_architecture('masked_lm', 'bert_base') def bert_base_architecture(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.share_encoder_input_output_embed = getattr(args, 'share_encoder_input_output_embed', True) args.no_token_positional_embeddings = getattr(args, 'no_token_posit...
class TestSimpleInterpreter(unittest.TestCase): def setUp(self): self._builder = D.Builder(spec) self._interp = BoolInterpreter() self._domain = [False, True] def test_interpreter0(self): b = self._builder p0 = b.make_param(0) p1 = b.make_param(1) p = b.ma...
class Preprocess(): def __init__(self, dialect, script, numeral='Latin'): with open(klpt.get_data('data/preprocess_map.json'), encoding='utf-8') as preprocess_file: self.preprocess_map = json.load(preprocess_file) configuration = Configuration({'dialect': dialect, 'script': script, 'nume...
def sequence_to_code(sequence, code_dict): id_to_code = {i: c for (c, i) in code_dict.items()} return ' '.join([id_to_code[i] for i in sequence])
class TestSequenceGenerator(unittest.TestCase): def setUp(self): (self.tgt_dict, self.w1, self.w2, src_tokens, src_lengths, self.model) = test_utils.sequence_generator_setup() self.encoder_input = {'src_tokens': src_tokens, 'src_lengths': src_lengths} def test_with_normalization(self): g...
class ResNet(nn.Module): def __init__(self, orig_resnet): super(ResNet, self).__init__() self.conv1 = orig_resnet.conv1 self.bn1 = orig_resnet.bn1 self.relu1 = orig_resnet.relu1 self.conv2 = orig_resnet.conv2 self.bn2 = orig_resnet.bn2 self.relu2 = orig_resnet...
class Extractor(): keepLinks = False keepSections = True HtmlFormatting = False toJson = False def __init__(self, id, revid, urlbase, title, page): self.id = id self.revid = revid self.url = get_url(urlbase, id) self.title = title self.page = page self...
def infer_dataset_impl(path): if IndexedRawTextDataset.exists(path): return 'raw' elif IndexedDataset.exists(path): with open(index_file_path(path), 'rb') as f: magic = f.read(8) if (magic == IndexedDataset._HDR_MAGIC): return 'cached' elif (ma...
class FP16Compressor(Compressor): def compress(tensor, name=None): tensor_compressed = tensor if tensor.dtype.is_floating_point: tensor_compressed = tensor.type(torch.float16) return (tensor_compressed, tensor.dtype) def decompress(tensor, ctx): tensor_decompressed = ...
class TestVoronoiFPS(TestFPS): def setUp(self): super().setUp() def test_restart(self): selector = VoronoiFPS(n_to_select=1, initialize=self.idx[0]) selector.fit(self.X) for i in range(2, len(self.idx)): selector.n_to_select = i selector.fit(self.X, warm_s...
class ExtraTreesForecasterConfig(_TreeEnsembleForecasterConfig): def __init__(self, min_samples_split: int=2, **kwargs): super().__init__(**kwargs) self.min_samples_split = min_samples_split
def points_in_boxes_gpu(points, boxes): assert (boxes.shape[0] == points.shape[0]) assert ((boxes.shape[2] == 7) and (points.shape[2] == 3)) (batch_size, num_points, _) = points.shape box_idxs_of_pts = points.new_zeros((batch_size, num_points), dtype=torch.int).fill_((- 1)) roiaware_pool3d_cuda.poin...
def main(args): cfg = setup(args) if args.eval_only: model = Trainer.build_model(cfg) DetectionCheckpointer(model, save_dir=cfg.OUTPUT_DIR).resume_or_load(cfg.MODEL.WEIGHTS, resume=args.resume) res = Trainer.test(cfg, model) if cfg.TEST.AUG.ENABLED: res.update(Trainer...
class Dataset(): def compute_batches(self, batch_size, vocabs, max_camel, rank, num_gpus, decoder_type, randomize=True, trunc=(- 1), no_filter=False): timer = time.process_time() self.batches = [] curr_batch = [] total = 0 for i in range(rank, len(self.examples), num_gpus): ...
class DWConv2d_BN(nn.Module): def __init__(self, in_ch, out_ch, kernel_size=1, stride=1, norm_layer=nn.BatchNorm2d, act_layer=nn.Hardswish, bn_weight_init=1): super().__init__() self.dwconv = nn.Conv2d(in_ch, out_ch, kernel_size, stride, ((kernel_size - 1) // 2), groups=out_ch, bias=False) s...
def check_consistent_length(*arrays): lengths = [_num_samples(X) for X in arrays if (X is not None)] uniques = np.unique(lengths) if (len(uniques) > 1): raise ValueError(('Found input variables with inconsistent numbers of samples: %r' % [int(l) for l in lengths]))
def test_data_format(): adata = synthetic_iid() protein_adata = synthetic_iid() mdata = mudata.MuData({'rna': adata, 'protein': protein_adata}) old_x = adata.X old_pro = protein_adata.X old_obs = adata.obs adata.X = np.asfortranarray(old_x) protein_adata.X = np.asfortranarray(old_pro) ...
def get_embedding(wav_path, encoder): wav = preprocess_wav(wav_path) embedding = encoder.embed_utterance(wav) return embedding
def toks_to_words(token_ids): indices = [] for (i, token_id) in enumerate(token_ids): token_text = v[token_id] if token_text.startswith('##'): indices.append(i) else: if indices: toks = [v[token_ids[t]] for t in indices] word = ''.j...
def test_reassignment_view(): anarray = np.ones((3,)) anotherarray = np.ones((3,)) def func(new_sym): new_sym[...] = 7.0 func = func.to_sdfg(new_sym=dace.data.Array(shape=(3,), dtype=dace.float64)) def testf(maybe_none=None): if (maybe_none is None): new_sym = anotherarra...
def azimuthalAverage(image, center=None): (y, x) = np.indices(image.shape) if (not center): center = np.array([((x.max() - x.min()) / 2.0), ((y.max() - y.min()) / 2.0)]) r = np.hypot((x - center[0]), (y - center[1])) ind = np.argsort(r.flat) r_sorted = r.flat[ind] i_sorted = image.flat[i...
class Gdma(Dma): def __init__(self, core_id, writer, sheet_name): super().__init__(core_id, writer) self.sheet_name = ((sheet_name + '_') + str(core_id)) def load(self, reg_info_file, gdma_layer_map): super().load(reg_info_file, gdma_layer_map) new_reg_list = [] for reg_d...
class IonNumberDensityHeNLTE(ProcessingPlasmaProperty): outputs = ('ion_number_density', 'electron_densities', 'helium_population_updated') latex_name = ('N_{i,j}', 'n_{e}') def __init__(self, plasma_parent, ion_zero_threshold=1e-20, electron_densities=None): super(IonNumberDensityHeNLTE, self).__in...
def extract_domain_type_facts(entity_lexicon_file): for line in open(entity_lexicon_file): entity = line.split('\t')[0] entities.add(entity) for line in sys.stdin: parts = line.strip().split('\t') parts[2] = parts[2].strip('.') if ((parts[0] in entities) or (parts[2] in e...
def test_mmd(): (X, Y) = sample_blobs_same(n=1000) mmd_1 = mmd(X=X, Y=Y, implementation='tp_sutherland') mmd_2 = mmd(X=X, Y=Y, implementation='tp_djolonga') assert torch.allclose(mmd_1, mmd_2, rtol=0.0001, atol=0.0001)
def is_lean_def_first_line(line: str) -> bool: if ((not line) or line.isspace()): return False line = strip_def_attr(line) tokens = re.split('[:\\s]+', line.strip()) return (tokens[0] in LEAN_DEF_PREFIXES)
def main(args): mt = sacremoses.MosesTokenizer(lang=args.lang) def tok(s): return mt.tokenize(s, return_str=True) for line in sys.stdin: parts = list(map(tok, line.split('\t'))) print(*parts, sep='\t', flush=True)
class NumericFactor(): def __init__(self, keys: T.Sequence[str], optimized_keys: T.Sequence[str], linearization_function: T.Callable[(..., T.Tuple[(np.ndarray, np.ndarray, np.ndarray, np.ndarray)])]) -> None: self.keys = keys self.optimized_keys = optimized_keys self.linearization_function =...
def all_extracted_files(split, src, tgt, extracted_folders, split_urls): def get_url(url): if isinstance(url, tuple): (url, downloaded_file) = url return url return [f for url in split_urls for f in my_glob(extracted_folders[str(get_url(url))])]
def pearson_and_spearman(preds, labels): warnings.warn(DEPRECATION_WARNING, FutureWarning) requires_backends(pearson_and_spearman, 'sklearn') pearson_corr = pearsonr(preds, labels)[0] spearman_corr = spearmanr(preds, labels)[0] return {'pearson': pearson_corr, 'spearmanr': spearman_corr, 'corr': ((p...
def _get_intent(text): scores = intent_classifier.get_scores(text) (max_intent, max_intent_score) = intent_classifier.knn(text) print(scores, max_intent, max_intent_score) return (max_intent, max_intent_score)
def plot_total_contribution_sums(ax, total_comp_sums, bar_order, top_n, bar_dims, plot_params): comp_bar_heights = [] for b in bar_order: if (b == 'total'): h = 0 elif (b == 'neg_total'): h = ((total_comp_sums['neg_s'] + total_comp_sums['neg_s_pos_p']) + total_comp_sums['...
class BaseDetector(ABC): def compute_score(self, caption: str, image_location: str, references: Dict[(str, Any)]) -> float: pass
class GoogleSearchNewsSearch(VirtualFunctionTool): name = 'GoogleSearchNewsSearch' summary = 'Perform a news search on Google with a given keyword or phrase and return the search results.' parameters: List[ArgParameter] = [{'name': 'keyword', 'type': 'string', 'description': 'The keyword or phrase to search...
def test_repr_mimebundle_(): tree = DecisionTreeClassifier() output = tree._repr_mimebundle_() assert ('text/plain' in output) assert ('text/html' in output) with config_context(display='text'): output = tree._repr_mimebundle_() assert ('text/plain' in output) assert ('text/h...
def overwrite_model(model_from, model_to): model_from_vars = tf.trainable_variables(model_from.scope) model_to_vars = tf.trainable_variables(model_to.scope) overwrite_variables(model_from_vars, model_to_vars)
def looking_at_call(s): position = (s.start_line, s.start_col) result = (looking_at_expr(s) == u'(') if (not result): (s.start_line, s.start_col) = position return result
.parametrize('observation_shape', [(100,), ((100,), (200,))]) .parametrize('action_size', [2]) .parametrize('batch_size', [32]) .parametrize('gamma', [0.99]) def test_continuous_mean_q_function_forwarder(observation_shape: Shape, action_size: int, batch_size: int, gamma: float) -> None: encoder = DummyEncoderWithAc...
.parametrize('dropout_rate', [0.2, 0.5, 0.8]) def test_locked_dropout(dropout_rate): BATCH_SIZE = 100 MAX_LEN = 200 HID_DIM = 500 x = torch.ones(BATCH_SIZE, MAX_LEN, HID_DIM) dropout = LockedDropout(p=dropout_rate) dropout.eval() x_locked_dropouted = dropout(x) assert (x_locked_dropouted...
class BaseChangeQuantizationMethodQCAttrTest(BaseKerasFeatureNetworkTest): def __init__(self, unit_test, edit_filter, action, prepare_graph_func): self.edit_filter = edit_filter self.action = action self.prepare_graph_func = prepare_graph_func super().__init__(unit_test) def get_...
def test_singletons(): array = ak.Array([None, [None], [{'x': None, 'y': None}], [{'x': [None], 'y': [None]}], [{'x': [1], 'y': [[None]]}], [{'x': [2], 'y': [[1, 2, 3]]}]]) assert (ak.singletons(array, axis=0).tolist() == [[], [[None]], [[{'x': None, 'y': None}]], [[{'x': [None], 'y': [None]}]], [[{'x': [1], 'y...
def get_left_span(span, sentence=None, window=None): sentence = (sentence if sentence else span.sentence) j = span.char_to_word_index(span.char_start) i = (max((j - window), 0) if window else 0) if (i == j == 0): return Span(char_start=0, char_end=(- 1), sentence=sentence) (start, end) = (se...
def set_last_dropout(model, dropout): if isinstance(model, ElectraForSequenceClassification): if isinstance(model.classifier, ElectraClassificationHeadCustom): model.classifier.dropout2 = dropout else: model.classifier.dropout else: model.dropout = dropout
def create_model(opt): model = opt['model'] if (model == 'srgan'): from .SRGAN_model import SRGANModel as M else: raise NotImplementedError('Model [{:s}] not recognized.'.format(model)) m = M(opt) logger.info('Model [{:s}] is created.'.format(m.__class__.__name__)) return m
def _coerce_seq(s, ctx=None): if isinstance(s, str): ctx = _get_ctx(ctx) s = StringVal(s, ctx) if (not is_expr(s)): raise Z3Exception('Non-expression passed as a sequence') if (not is_seq(s)): raise Z3Exception('Non-sequence passed as a sequence') return s
class MetricStats(): def __init__(self, metric, n_jobs=1, batch_eval=True): self.metric = metric self.n_jobs = n_jobs self.batch_eval = batch_eval self.clear() def clear(self): self.scores = [] self.ids = [] self.summary = {} def append(self, ids, *arg...
def get_feature_and_linear_resnet50(model: nn.Module): m = model feature = nn.Sequential(m.conv1, m.bn1, m.relu, m.maxpool, m.layer1, m.layer2, m.layer3, m.layer4) linear = m.fc factor = 32 return (feature, linear, factor)
class TestUfunclike(object): def test_isposinf(self): a = nx.array([nx.inf, (- nx.inf), nx.nan, 0.0, 3.0, (- 3.0)]) out = nx.zeros(a.shape, bool) tgt = nx.array([True, False, False, False, False, False]) res = ufl.isposinf(a) assert_equal(res, tgt) res = ufl.isposinf(...
def update_alpha_parameters(model, vision_layers, transformer_layers, p, pi, print_info=True): standarlization = (lambda x, mean, std: ((x - mean) / std)) alpha_grad_attn_vision = torch.stack([getattr(model.module.visual.transformer.resblocks, str(i)).attn.alpha.grad for i in range(vision_layers)]) alpha_gr...