code
stringlengths
101
5.91M
class GiraffeCombine(nn.Module): def __init__(self, in_channels, stride, fpn_config, fpn_channels, inputs_offsets, target_reduction, weight_method='attn'): super(GiraffeCombine, self).__init__() self.in_channels = in_channels self.stride = stride self.inputs_offsets = inputs_offsets ...
class Schaffer02(Benchmark): def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip(([(- 100.0)] * self.N), ([100.0] * self.N))) self.custom_bounds = [((- 10), 10), ((- 10), 10)] self.global_optimum = [[0.0 for _ in range(self.N)]] self...
def analyse_type_annotation(annotation, env, assigned_value=None): base_type = None is_ambiguous = False explicit_pytype = explicit_ctype = False if annotation.is_dict_literal: warning(annotation.pos, "Dicts should no longer be used as type annotations. Use 'cython.int' etc. directly.") ...
def laplacian(v, irho): if ((irho is None) or (irho == 1)): Lap = v.laplace elif isinstance(irho, Differentiable): so = (irho.space_order // 2) Lap = sum([getattr((irho._subs(d, (d + (d.spacing / 2))) * getattr(v, ('d%s' % d.name))(x0=(d + (d.spacing / 2)), fd_order=so)), ('d%s' % d.name...
class ResBlock(nn.Module): def __init__(self, chan_in, hidden_size, chan_out): super().__init__() self.net = nn.Sequential(nn.Conv2d(chan_in, hidden_size, 3, padding=1), nn.ReLU(), nn.Conv2d(hidden_size, hidden_size, 3, padding=1), nn.ReLU(), nn.Conv2d(hidden_size, chan_out, 1)) def forward(self...
class TestNetGradientChecker(test_util.TestCase): def test_net_gradient_checker(self): model = model_helper.ModelHelper(name='test') const = model.net.AddExternalInputs('const1', 'const2') fc = brew.fc(model, dim_in=3, dim_out=4, blob_in='X', blob_out='Y', axis=0) dist = [model.net.S...
def print_as_conll(gold_examples, predicted_target_dict): with codecs.open(out_conll_file, 'w', 'utf-8') as conll_file: for (gold, pred) in zip(gold_examples, predicted_target_dict): for target in sorted(pred): result = (gold.get_predicted_target_conll(target, pred[target][0]) + ...
(OperatorDef) def print_op(text, op): args = [(a.name, _arg_val(a)) for a in op.arg] dev_opt_txt = format_device_option(op.device_option) if dev_opt_txt: args.append(('device_option', dev_opt_txt)) if text.c2_net_name: text.add(call(((text.c2_net_name + '.') + op.type), ([list(op.input),...
class EquivariantScalar(OutputModel): def __init__(self, hidden_channels, activation='silu', allow_prior_model=True): super(EquivariantScalar, self).__init__(allow_prior_model=allow_prior_model) self.output_network = nn.ModuleList([GatedEquivariantBlock(hidden_channels, (hidden_channels // 2), activ...
def tf_2d_normal(x, y, mux, muy, sx, sy, rho): normx = tf.subtract(x, mux) normy = tf.subtract(y, muy) sxsy = tf.multiply(sx, sy) z = ((tf.square(tf.div(normx, sx)) + tf.square(tf.div(normy, sy))) - (2 * tf.div(tf.multiply(rho, tf.multiply(normx, normy)), sxsy))) negRho = (1 - tf.square(rho)) re...
.parametrize('fn', [(lambda name: True), (lambda name: False), (lambda name: ('a' in name))]) def test_set_get_summary_filter(fn: SummaryFilter) -> None: try: set_summary_filter(fn) assert (get_summary_filter() is fn) finally: set_summary_filter(default_summary_filter)
def limit_author_list(all_authors, desired_authors=[], author_list_length_limit=10): if (len(all_authors) <= author_list_length_limit): return all_authors author_list = [a for a in all_authors if (a in desired_authors)] if (not author_list): author_list = all_authors[:author_list_length_limi...
_REGISTRY.register() def build_vovnet_fpn_backbone(cfg, input_shape: ShapeSpec): bottom_up = build_vovnet_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FEATURES out_channels = cfg.MODEL.FPN.OUT_CHANNELS backbone = FPN(bottom_up=bottom_up, in_features=in_features, out_channels=out_channels, n...
def main(): frame = np.zeros((600, 800, 3), np.uint8) values = [] checked = [False] checked2 = [False] value = [1.0] value2 = [1.0] value3 = [1.0] padding = 10 img = cv2.imread('lena-face.jpg', cv2.IMREAD_COLOR) imgRed = cv2.imread('lena-face-red.jpg', cv2.IMREAD_COLOR) imgGr...
def P(alpha, m): if (alpha >= ((2 * m) - 1)): raise Exception if ((m % 2) == 0): if (alpha < m): if ((alpha % 2) == 0): b = (alpha // 2) return [((2 * a), ((((2 * a) + (2 * b)) + 1) % (2 * m))) for a in range(m)] else: b = (...
def set_node_colors(c, x, cmap, colored_nodes): node_colors = defaultdict((lambda x: '#8d8d8d')) node_edge_colors = defaultdict((lambda x: '#4d4d4d')) cnt = Counter([c[d] for d in colored_nodes]) num_groups = len(cnt) if (cmap is None): if (num_groups <= 10): cmap = sns.color_pal...
def fully_connected(inputs, num_outputs, scope, use_xavier=True, stddev=0.001, weight_decay=0.0, activation_fn=tf.nn.relu, bn=False, bn_decay=None, is_training=None): with tf.variable_scope(scope) as sc: num_input_units = inputs.get_shape()[(- 1)].value weights = _variable_with_weight_decay('weights...
class CustomSavingCallback(Callback): def __init__(self, output_dir: str, saving_freq: int, save_best_only: bool=False, keep_max_models: int=5): super(CustomSavingCallback, self).__init__() self.saving_dir = output_dir self.saving_freq = saving_freq self.save_best_only = save_best_on...
def merge_with_parent(dc: FairseqDataclass, cfg: DictConfig, remove_missing=True): if remove_missing: if is_dataclass(dc): target_keys = set(dc.__dataclass_fields__.keys()) else: target_keys = set(dc.keys()) with open_dict(cfg): for k in list(cfg.keys()): ...
(scope='module') def functional_fx(variable_x): return sn.Functional('fx', variable_x, (2 * [10]), 'tanh')
def create_integrated_db_with_infos(args, root_path): db_infos_path = args.src_db_info db_info_global_path = db_infos_path global_db_path = (root_path / (args.new_db_name + '.npy')) db_infos = pkl.load(open(db_infos_path, 'rb')) db_info_global = copy.deepcopy(db_infos) start_idx = 0 global_d...
def test_apply_parallel(): a = np.arange(144).reshape(12, 12).astype(float) expected1 = threshold_local(a, 3) result1 = apply_parallel(threshold_local, a, chunks=(6, 6), depth=5, extra_arguments=(3,), extra_keywords={'mode': 'reflect'}) assert_array_almost_equal(result1, expected1) def wrapped_gauss...
class HardSigmoidJit(nn.Module): def __init__(self, inplace: bool=False): super(HardSigmoidJit, self).__init__() def forward(self, x): return hard_sigmoid_jit(x)
class Recommender(BaseRecommender, ABC): def fit(self, dataset: Dataset) -> None: self._fit_wrap(dataset=dataset) def predict(self, dataset: Dataset, k: int, queries: Optional[Union[(SparkDataFrame, Iterable)]]=None, items: Optional[Union[(SparkDataFrame, Iterable)]]=None, filter_seen_items: bool=True, ...
class AnnotationItem(object): def __init__(self, style, text, tag='', size=0): self.style = style self.text = text self.tag = tag self.size = size def start(self): return (u"<span class='cython tag %s' title='%s'>%s" % (self.style, self.text, self.tag)) def end(self):...
class LoderunnerCtrlProblem(LoderunnerProblem): def __init__(self): super(LoderunnerCtrlProblem, self).__init__() self._max_path_length = ((((np.ceil((self._width / 2)) * self._height) + np.floor((self._height / 2))) * 2) - 1) self._reward_weights = self._reward_weights self.static_t...
def validate_iban(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]: if isinstance(df, (pd.Series, dd.Series)): return df.apply(iban.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (column != ''): ...
class EnvSpec(InOutSpec): def __init__(self, observation_space, action_space): super().__init__(action_space, observation_space) def action_space(self): return self.input_space def observation_space(self): return self.output_space _space.setter def action_space(self, action_s...
((device_cc() < 80), 'Device compute capability is insufficient for SM80 tests.') class GemmF64TensorOpSm80(unittest.TestCase): def test_SM80_Device_Gemm_f64n_f64t_f64t_tensor_op_f64_32x32x16_16x16x16(self): math_inst = MathInstruction(instruction_shape=[8, 8, 4], element_a=cutlass.float64, element_b=cutlas...
def is_exact_match(answer_object, prediction): ground_truths = get_ground_truths(answer_object) for ground_truth in ground_truths: if exact_match_score(prediction, ground_truth): return True return False
def _set_up_aliases(): type_pairs = [('complex_', 'cdouble'), ('int0', 'intp'), ('uint0', 'uintp'), ('single', 'float'), ('csingle', 'cfloat'), ('singlecomplex', 'cfloat'), ('float_', 'double'), ('intc', 'int'), ('uintc', 'uint'), ('int_', 'long'), ('uint', 'ulong'), ('cfloat', 'cdouble'), ('longfloat', 'longdouble...
_interact(expo=(lambda : slider((- 10), 10, 0.1, 2)), c_real=(lambda : slider((- 2), 2, 0.01, 0.5, label='real part const.')), c_imag=(lambda : slider((- 2), 2, 0.01, 0.5, label='imag part const.')), iterations=(lambda : slider(1, 100, 1, 20, label='# iterations')), zoom_x=(lambda : range_slider((- 2), 2, 0.01, ((- 1.5...
def test_preload(): with corenlp.CoreNLPClient(server_id='test_server_start_preload') as client: time.sleep(140) results = annotate_and_time(client, EN_DOC) compare_ignoring_whitespace(results['annotation'], EN_PRELOAD_GOLD) assert ((results['end_time'] - results['start_time']) < 3)
def augment_edit_distance(candidates_info): (reverse_properties, relation_dr, relations, upper_types, types) = process_ontology('ontology/fb_roles', 'ontology/fb_types', 'ontology/reverse_properties') matcher = SemanticMatcher(reverse_properties, relation_dr, relations, upper_types, types) hit_chance = 0 ...
class _BNBase(nn.Sequential): def __init__(self, in_size, batch_norm=None, name=''): super(_BNBase, self).__init__() self.add_module((name + 'bn'), batch_norm(in_size)) nn.init.constant_(self[0].weight, 1.0) nn.init.constant_(self[0].bias, 0)
def nodes_leq_threshold_matching(graph: Graph, node_weight_function, edge_weight_function, L, uf: UnionFind, verbose=False, record_history=False, threshold=0): prev_graph = Graph.from_other(graph) uf2 = UnionFind(elements=graph._nodes.keys()) hd = ValueSortedDict({n: node_weight_function(n) for n in graph.n...
def generate(node, environment, name, filename, stream=None, defer_init=False, optimized=True): if (not isinstance(node, nodes.Template)): raise TypeError("Can't compile non template nodes") generator = environment.code_generator_class(environment, name, filename, stream, defer_init, optimized) gene...
class DataTrainingArguments(): train_data_file: Optional[str] = field(default=None, metadata={'help': 'The input training data file (a text file).'}) eval_data_file: Optional[str] = field(default=None, metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}) ...
def cli_main(): parser = rerank_options.get_reranking_parser() args = options.parse_args_and_arch(parser) gen_and_reprocess_nbest(args)
def get_optimizer(cfg, model): base_lr = cfg.TRAIN.OPTIMIZER.BASE_LR params = [] for (name, p) in model.named_parameters(): if p.requires_grad: params.append({'params': p}) if (cfg.TRAIN.OPTIMIZER.TYPE == 'SGD'): optimizer = SGD_GC(params, lr=base_lr, momentum=cfg.TRAIN.OPTIM...
class _ValgrindWrapper(object): def __init__(self) -> None: self._commands_available: Dict[(str, bool)] = {} if torch._C._valgrind_supported_platform(): for cmd in ('valgrind', 'callgrind_control', 'callgrind_annotate'): self._commands_available[cmd] = (not subprocess.run...
def main(device='cpu'): experiment_dir = pathlib.Path(__file__).resolve().parent hparams_file = (experiment_dir / 'hyperparams.yaml') data_folder = '../../samples/ASR' data_folder = (experiment_dir / data_folder).resolve() with open(hparams_file) as fin: hparams = load_hyperpyyaml(fin) (...
def Horn(n, k): K = Simplex(n) sigma = K.n_cells(n)[0] L = K.subsimplicial_set((K.faces(sigma)[:k] + K.faces(sigma)[(k + 1):])) L.rename('({}, {})-Horn'.format(n, k)) L.rename_latex('\\Lambda^{{{}}}_{{{}}}'.format(n, k)) return L
def get_saved_model_type_and_estimator(datasource, model_name): meta = Model.load_metadata_from_db(datasource, model_name) return (meta.get_type(), meta.get_meta('class_name'))
class BroadcastRowBench(BroadcastMulBench): def __init__(self, mode, device, dtype, M, N, K): super(BroadcastRowBench, self).__init__(mode, device, dtype, 'row', M, N, K) def module(): return 'broadcast_row'
_model def tresnet_m(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['tresnet_m'] model = TResNet(layers=[3, 4, 11, 3], num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretrained: load_pretrained(model, default_cfg, n...
def train(config): if (config.train.seed is not None): pl.seed_everything(config.train.seed, workers=True) trainer = create_trainer(config) model = SequenceLightningModule(config) if (config.train.get('pretrained_model_path', None) is not None): model = SequenceLightningModule.load_from_...
def test_model(clusters, other_clusters, model, device, topic_docs, is_event, epoch, topics_counter, topics_num, threshold, use_args_feats, use_binary_feats): update_args_feature_vectors(clusters, other_clusters, model, device, is_event) (cluster_pairs, _) = generate_cluster_pairs(clusters, is_train=False) ...
_task('wsc') class WSCTask(FairseqTask): def add_args(parser): parser.add_argument('data', metavar='DIR', help='path to data directory; we load <split>.jsonl') parser.add_argument('--init-token', type=int, default=None, help='add token at the beginning of each batch item') def __init__(self, arg...
def train_aug(img, mask): (img, mask) = (np.array(img), np.array(mask)) aug = get_training_transform()(image=img.copy(), mask=mask.copy()) (img, mask) = (aug['image'], aug['mask']) return (img, mask)
_spec_function('summarization_xsum_sampled') def get_xsum_sampled_summarization_spec(temperature: float=0.3, device: str='cpu') -> RunSpec: scenario_spec = ScenarioSpec(class_name='helm.benchmark.scenarios.summarization_scenario.SummarizationScenario', args={'dataset_name': 'xsum-sampled', 'sampling_min_length': 50...
class Launcher(TmuxLauncher): def common_options(self): return [Options(dataroot='./datasets/grumpifycat', name='grumpifycat_CUT', CUT_mode='CUT'), Options(dataroot='./datasets/grumpifycat', name='grumpifycat_FastCUT', CUT_mode='FastCUT')] def commands(self): return [('python train.py ' + str(op...
def get_split_counts(input_file_size_in_gb: float, num_training_splits: Optional[int], num_dev_splits: Optional[int], num_test_splits: Optional[int], dev_ratio: Optional[float], test_ratio: Optional[float]) -> Tuple[(int, int, int, int)]: if ((num_training_splits is not None) and (num_test_splits is not None) and (...
def duplicate_naming(A, B): no = dace.define_local([number], dace.float32) number = dace.define_local([W], dace.float32) duplicate_naming_inner(A, number) (_[0:W]) def bla2(i): (inp << number[i]) (out >> B[i]) out = (2 * inp)
def register_pascal_voc(name, dirname, split, year): DatasetCatalog.register(name, (lambda : load_voc_instances(dirname, split))) MetadataCatalog.get(name).set(thing_classes=CLASS_NAMES, dirname=dirname, year=year, split=split)
class IDDecoder(Decoder): def decode(self, trg_sentence): return ' '.join(map(str, trg_sentence))
def restore_checkpoint(model, fname): logger.debug('Restoring model {0}'.format(fname)) assert tf.train.checkpoint_exists(fname) checkpointer = tf.train.Checkpoint(model=model) status = checkpointer.restore(fname) if (not tf.executing_eagerly()): status.initialize_or_restore(tf.get_default_s...
class Gamma(Augmentation): def __init__(self, gamma_range=(0.5, 1.5), p=1): super().__init__(p=p) self.gamma_range = gamma_range def __repr__(self): return f'Gamma(gamma_range={self.gamma_range}, p={self.p})' def __call__(self, image, layer=None, mask=None, keypoints=None, bounding_b...
class Squeeze(nn.Module): def __init__(self): super().__init__() def forward(self, inp): return inp.squeeze()
def DP_calc(TPR, TNR): try: X = (TPR / (1 - TPR)) Y = (TNR / (1 - TNR)) return ((math.sqrt(3) / math.pi) * (math.log(X, 10) + math.log(Y, 10))) except (ZeroDivisionError, TypeError, ValueError): return 'None'
def validate(val_loader, dataset, net, criterion, optim, scheduler, curr_epoch, writer, curr_iter, save_pth=True): net.eval() val_loss = AverageMeter() iou_acc = 0 error_acc = 0 dump_images = [] for (val_idx, data) in enumerate(val_loader): (inputs, seg_gts, ood_gts, img_names, _) = data...
def ste_round(x: tf.Tensor) -> tf.Tensor: error = tf.stop_gradient((tf.math.round(x) - x)) return (error + x)
_incremental_state class FairseqIncrementalDecoder(FairseqDecoder): def __init__(self, dictionary): super().__init__(dictionary) def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs): raise NotImplementedError def extract_features(self, prev_output_tokens,...
class KBoundedQuotientBasis(CombinatorialFreeModule): def __init__(self, kBoundedRing, prefix): CombinatorialFreeModule.__init__(self, kBoundedRing.base_ring(), kBoundedRing.indices(), category=KBoundedQuotientBases(kBoundedRing), prefix=('%s%d' % (prefix, kBoundedRing.k))) self._kBoundedRing = kBou...
def _get_time_macro_clause(node): if ((node.construction == 'AND') and (node.fields[0].construction == 'JOIN') and (node.fields[0].fields[0].construction == 'SCHEMA') and ('time_macro' in node.fields[0].fields[0].val)): return node.fields[0] else: for field in node.fields: ret_val = ...
def decompose_by_diameter(a_tree, strategy, max_size=None, min_size=None, max_diam=None): def __ini_record__(): for node in a_tree.postorder_node_iter(): __update_node__(node) def __find_midpoint_edge__(tre): u = tre.seed_node.bestLCA.anchor uel = (u.edge_length if u.edge_len...
def test_energy_decrease(): a = np.zeros((3, 3)) a[(1, 1)] = 1.0 gaussian_a = gaussian(a, preserve_range=True, sigma=1, mode='reflect') assert (gaussian_a.std() < a.std())
_cache def load_schema(schema_name: str) -> dict[(str, Any)]: path = get_schema_path(schema_name) with open(path) as fd: return load_yaml(fd)
def attach_metadata_to_scalars(field, metadata): for f in field.all_scalars(): f.set_metadata(metadata)
def parse_version_info(version_str): ver_info = [] for x in version_str.split('.'): if x.isdigit(): ver_info.append(int(x)) elif (x.find('rc') != (- 1)): patch_version = x.split('rc') ver_info.append(int(patch_version[0])) ver_info.append(f'rc{patc...
def parse_args(): parser = ArgumentParser() parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint_root', help='Checkpoint file root path') parser.add_argument('--img', default='demo/demo.jpg', help='Image file') parser.add_argument('--aug', action='store_true', ...
class ShowProgress(): def __init__(self, iterable, total, desc, silent, start_delay): self.iter = iter(iterable) self.start_time = time.time() self.pbar = None self.total = total self.desc = desc self.start_delay = start_delay self.silent = silent self...
def pretokenize(in_path: str, out_path: str, src: str, tgt: str): Args = namedtuple('Args', ['moses_source_lang', 'moses_target_lang', 'moses_no_dash_splits', 'moses_no_escape']) args = Args(moses_source_lang=src, moses_target_lang=tgt, moses_no_dash_splits=False, moses_no_escape=False) pretokenizer = Moses...
class FeatureExtractor(nn.Sequential): def __init__(self, in_channel, out_channel, ker_size, padding, stride, num_blocks=2, return_linear=False): super(FeatureExtractor, self).__init__() (self.add_module('conv_block_0', ConvBlock2DSN(in_channel, out_channel, ker_size, padding, stride)),) for...
def main(): args = ArgParser().parse_args() config = load_model_config(os.path.join(args.model_path, 'config.json')) emap_file = args.entity_mfile rmap_file = args.rel_mfile data_files = args.data_files if (args.format == 'h_r_t'): if args.raw_data: assert (emap_file is not N...
.qhsri def test_pareto_sample_diverse_subset_raises_too_large_sample_size() -> None: observations = tf.constant([[1.0, (- 1.0)], [(- 1.0), 1.0]]) pareto_set = Pareto(observations) with pytest.raises(ValueError): pareto_set.sample_diverse_subset(3, allow_repeats=False)
class read_port(): def __init__(self): self.latency = 1 def set_params(self, latency): self.latency = latency def get_latency(self): return self.latency def service_reads(self, incoming_requests_arr_np, incoming_cycles_arr): out_cycles_arr = (incoming_cycles_arr + self.la...
def writeEdgesAndLabels(edges, labels, output_file): with codecs.open(output_file, 'w', 'utf-8') as outfile: for (edge, label) in itertools.izip(edges, labels): outfile.write(('%s\t%s\n' % (label, edge))) return
def get_knowledge_fn(): gkf = GraphKnowledgeHessFunc(total_feature_num=4) adjacency = np.zeros((4, 4)) adjacency[(0, 1)] = adjacency[(1, 0)] = 3.0 adjacency[(2, 3)] = adjacency[(3, 2)] = (- 2.0) (intr_idx, intr_eff) = gkf.convert_adjacency_to_knowledge(adjacency) gkf.knowledge_encoder(intr_idx, ...
def is_pythran_buffer(type_): return (type_.is_numpy_buffer and is_pythran_supported_dtype(type_.dtype) and (type_.mode in ('c', 'strided')) and (not type_.cast))
def get_belief_openaigpt(sent): if ('< | belief | >' in sent): tmp = sent.strip(' ').split('< | belief | >')[(- 1)].split('< | action | >')[0] else: return [] tmp = tmp.strip(' .,') tmp = tmp.replace('< | endofbelief | >', '') tmp = tmp.replace('< | endoftext | >', '') belief = t...
class Partition6(nn.Module): LAYER_SCOPES = ['VisionTransformer/ModuleList[blocks]/Block[17]/Attention[attn]/Linear[proj]', 'VisionTransformer/ModuleList[blocks]/Block[17]/Attention[attn]/Dropout[proj_drop]', 'VisionTransformer/ModuleList[blocks]/Block[17]/Identity[drop_path]', 'VisionTransformer/ModuleList[blocks]...
def make_schema(schema_name: str='simple_swagger.yaml', **kwargs: Any) -> dict[(str, Any)]: schema = load_schema(schema_name) return merge_recursively(kwargs, schema)
def get_keys_to_not_convert(model): tied_model = deepcopy(model) tied_model.tie_weights() tied_params = find_tied_parameters(tied_model) if isinstance(tied_params, dict): tied_keys = list(tied_params.values()) else: tied_keys = sum([x[1:] for x in tied_params], []) has_tied_param...
def parse_args(): parser = argparse.ArgumentParser(description='Extract DeepSpeech features from audio file', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--input', type=str, required=True, help='path to input audio file or directory') parser.add_argument('--output', type=str...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None): super(Bottleneck, self).__init__() if (stride == 2): kplanes = planes self.bottleneck_shared = BottleneckShared(inplanes) self.conv1 = conv1x1(inplanes,...
class BatchSampler(BaseSampler): def __init__(self, algo): self.algo = algo def start_worker(self): parallel_sampler.populate_task(self.algo.env, self.algo.policy, scope=self.algo.scope) def shutdown_worker(self): parallel_sampler.terminate_task(scope=self.algo.scope) def obtain_...
class Fringe(object): def __init__(self, grid): self.fringe_list = [] self.distribution = [] self.grid = grid def add(self, item): if (item not in self.fringe_list): self.fringe_list.append(item) self.update_probs() def pop(self): assert (len(s...
class TestFCLTransformConversion(unittest.TestCase): def test_from_SE3(self): M = pin.SE3.Random() fcl_transform = pin.hppfcl.Transform3f(M) self.assertTrue((M.rotation == fcl_transform.getRotation()).all()) self.assertTrue((M.translation == fcl_transform.getTranslation()).all()) ...
def format_result(r): repr_str = repr(r) if ('\n' in repr_str): repr_str = repr(repr_str) if (len(repr_str) > resultlimit): repr_str = (repr_str[:resultlimit] + ' ...') result = ('<%s 0x%x> (%s)' % (type(r).__name__, id(r), repr_str)) return result
def ResBody10(net, from_layer, num_output, expend, eps=0.001): kwargs = {'param': [dict(lr_mult=1, decay_mult=1)], 'weight_filler': dict(type='gaussian', std=0.01), 'bias_term': False} bn_kwargs = {'param': [dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0), dict(lr_mult=0, decay_mult=0)], 'eps': eps...
def load_model(model_path='', mode='all', scene_hop=5000, **kwds): model = get_basic_model(mode=mode, scene_hop=scene_hop, **kwds) return model
class _SubsampleMetaSplitter(): def __init__(self, *, base_cv, fraction, subsample_test, random_state): self.base_cv = base_cv self.fraction = fraction self.subsample_test = subsample_test self.random_state = random_state def split(self, X, y, **kwargs): for (train_idx, t...
def get_glad_result_names(result_type): if (result_type == 'batch'): return ['loda_glad', 'loda', 'loda_aad'] else: raise ValueError(('Invalid result type: %s' % result_type))
class ExplainerBase(metaclass=ExplainerABCMeta): def __init__(self): pass def explain(self, **kwargs): raise NotImplementedError def explanation_type(self): return 'local' def __getstate__(self): return {k: deepcopy(v) for (k, v) in self.__dict__.items()} def __setsta...
class Dialog(object): def __init__(self, agents, args): assert (len(agents) == 2) self.agents = agents self.args = args self.domain = domain.get_domain(args.domain) self.metrics = MetricsContainer() self._register_metrics() self.reward_func = args.reward d...
_module() class TensorRTRecognizer(EncodeDecodeRecognizer): def __init__(self, trt_file: str, cfg: Any, device_id: int, show_score: bool=False): if ('type' in cfg.model): cfg.model.pop('type') EncodeDecodeRecognizer.__init__(self, **cfg.model) from mmcv.tensorrt import TRTWrapper...
class Scheduler(): def __init__(self, optimizer: torch.optim.Optimizer, param_group_field: str, noise_range_t=None, noise_type='normal', noise_pct=0.67, noise_std=1.0, noise_seed=None, initialize: bool=True) -> None: self.optimizer = optimizer self.param_group_field = param_group_field self....
class WrappedSocket(object): def __init__(self, connection, socket, suppress_ragged_eofs=True): self.connection = connection self.socket = socket self.suppress_ragged_eofs = suppress_ragged_eofs self._makefile_refs = 0 self._closed = False def fileno(self): return...
class TestRequirementsCheck(): def test_passes_on_process_project(self): self.uut = RequirementsCheck() assert_equals([self.uut], self.uut.run()) def test_checks_requirements_on_start(self): self.test_requirement = Requirement('-test-requirement-') self.test_requirement.check = M...