code
stringlengths
101
5.91M
class PPAS(PAS): def __init__(self, trainable_weights_shapes, lr=0.01, c=1.0, **kwargs): super(PPAS, self).__init__(trainable_weights_shapes, lr, c, **kwargs) self.__dict__.update(locals()) self.b = K.variable(c) _get_updates_support def get_updates(self, loss, params, learning_rate_...
def get_configuration_file(configuration_files: List[str]) -> str: configuration_files_map = {} for file_name in configuration_files: search = _re_configuration_file.search(file_name) if (search is not None): v = search.groups()[0] configuration_files_map[v] = file_name ...
def get_alpha_and_beta(t, scheduler): if (t < 0): return (scheduler.final_alpha_cumprod.item(), (1 - scheduler.final_alpha_cumprod.item())) if ((t.dtype == torch.long) or (t == t.long())): alpha = scheduler.alphas_cumprod[t.long()] return (alpha.item(), (1 - alpha.item())) low = t.fl...
def save_checkpoint(sess, checkpoint_dir, saver_op, step): checkpoint_name = os.path.join(checkpoint_dir, 'step') path = saver_op.save(sess, checkpoint_name, global_step=step)
class HTTPDLinuxRPO(HTTPD): def __init__(self) -> None: super().__init__() self. = '/root/mtcp/apps/lig
def _t2n(x): if (not isinstance(x, torch.Tensor)): return x return x.detach().cpu().numpy()
def cod(true, pred, pv=None): mean = np.mean(true) sum_of_squares = np.sum(((true - mean) ** 2)) sum_of_residuals = np.sum(((true - pred) ** 2)) return (1.0 - (sum_of_residuals / sum_of_squares))
_connect.numpy.implements('concatenate') _level_function() def concatenate(arrays, axis=0, *, mergebool=True, highlevel=True, behavior=None, attrs=None): if (backend_of_obj(arrays, default=None) is not None): (yield (arrays,)) else: (yield arrays) return _impl(arrays, axis, mergebool, highle...
def my_build_optimizer(cfg: CfgNode, model: torch.nn.Module) -> torch.optim.Optimizer: if (cfg.SOLVER.OPTIMIZER_CFG != ''): optim_cfg = eval(cfg.SOLVER.OPTIMIZER_CFG) register_optimizer(optim_cfg['type']) return build_optimizer(model, optim_cfg) return build_optimizer_d2(cfg, model)
class Block(nn.Module): def __init__(self, inp, outp, stride, tmp_ratio=1.0): super(Block, self).__init__() assert (stride in [1, 2]) midp = make_divisible((outp // 4)) expand_ratio = 0.25 layers = [USConv2d(inp, midp, 1, 1, 0, bias=False, ratio=[tmp_ratio, expand_ratio]), US...
class TFRobertaForMaskedLM(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
class ChineseCLIPTextConfig(PretrainedConfig): model_type = 'chinese_clip_text_model' 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=...
.parametrize('minsize', [None, 200, 20000, 40000, 80000]) .parametrize('dtype', [np.uint8, np.float32]) def test_two_image_peaks(minsize, dtype): image = np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 2, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 3, 1, 1], [1, 1, ...
def list(github, force_reload=False): repo_dir = _get_cache_or_reload(github, force_reload, True) sys.path.insert(0, repo_dir) hub_module = import_module(MODULE_HUBCONF, ((repo_dir + '/') + MODULE_HUBCONF)) sys.path.remove(repo_dir) entrypoints = [f for f in dir(hub_module) if (callable(getattr(hub_...
class SRResNet(nn.Module): def __init__(self, large_kernel_size=9, small_kernel_size=3, n_channels=64, n_blocks=16, scaling_factor=4): super(SRResNet, self).__init__() scaling_factor = int(scaling_factor) assert (scaling_factor in {2, 4, 8}), 'The scaling factor must be 2, 4, or 8!' ...
def get_random_field_order_tag(args): if args.random_field_order: return 'rfo.' else: return ''
_task('translation') class TranslationTask(FairseqTask): def add_args(parser): parser.add_argument('data', help='colon separated path to data directories list, will be iterated upon during epochs in round-robin manner') parser.add_argument('-s', '--source-lang', default=N...
def ModularFormsSubSpace(*args, **kwargs): generators = [] for arg in args: if isinstance(arg, (list, tuple)): generators += arg else: generators.append(arg) if (('reduce' in kwargs) and kwargs['reduce']): generators = [gen.full_reduce() for gen in generators]...
def copy_model_params_from_to(source, target): for (target_param, param) in zip(target.parameters(), source.parameters()): target_param.data.copy_(param.data)
class Entropy(_Loss): def __init__(self): super(Entropy, self).__init__() def forward(self, log_qy, batch_size=None, unit_average=False): if (log_qy.dim() > 2): log_qy = log_qy.squeeze() qy = th.exp(log_qy) h_q = th.sum((((- 1) * log_qy) * qy), dim=1) if unit_...
def vendor_exist(vuln_scan, vendor_name): if ('all' in vuln_scan): return True for arg_vendor in vuln_scan: if (arg_vendor.lower() not in vendor_name.lower()): continue else: return True return False
class Args(): def __init__(self, **kwargs): self.bs = 32 self.epochs = 500 self.lr = 0.001 self.hid_units = '128_64_32' self.bins = 200 self.train_num = 10000 self.__dict__.update(kwargs)
class AlignVisionModelTester(): def __init__(self, parent, batch_size=12, image_size=32, num_channels=3, kernel_sizes=[3, 3, 5], in_channels=[32, 16, 24], out_channels=[16, 24, 30], hidden_dim=64, strides=[1, 1, 2], num_block_repeats=[1, 1, 2], expand_ratios=[1, 6, 6], is_training=True, hidden_act='gelu'): ...
class DiscreteCQL(QLearningAlgoBase[(DiscreteCQLImpl, DiscreteCQLConfig)]): def inner_create_impl(self, observation_shape: Shape, action_size: int) -> None: (q_funcs, q_func_forwarder) = create_discrete_q_function(observation_shape, action_size, self._config.encoder_factory, self._config.q_func_factory, n_e...
def getEntitySegClass(tweet, annot, lower=False, getIndices=True): start = None result = [] for i in range(len(tweet)): if ('B-' in annot[i]): if (start != None): if getIndices: if (start != len(tweet)): result.append((' '.join(...
class SwitchNorm1d(nn.Module): def __init__(self, num_features, eps=1e-05, momentum=0.997, using_moving_average=True): super(SwitchNorm1d, self).__init__() self.eps = eps self.momentum = momentum self.using_moving_average = using_moving_average self.weight = nn.Parameter(torc...
def changearm(old_label): label = old_label arm1 = torch.FloatTensor((data['label'].cpu().numpy() == 11).astype(np.int)) arm2 = torch.FloatTensor((data['label'].cpu().numpy() == 13).astype(np.int)) noise = torch.FloatTensor((data['label'].cpu().numpy() == 7).astype(np.int)) label = ((label * (1 - ar...
def save(f, ob, extensions=None, **options): s = BsdfSerializer(extensions, **options) if isinstance(f, string_types): with open(f, 'wb') as fp: return s.save(fp, ob) else: return s.save(f, ob)
class FixupWideResNet(nn.Module): def __init__(self, depth, widen_factor, num_classes=10, dropRate=0.0): super(FixupWideResNet, self).__init__() nChannels = [16, (16 * widen_factor), (32 * widen_factor), (64 * widen_factor)] assert (((depth - 4) % 6) == 0) n = ((depth - 4) // 6) ...
class NetProxy(SimProxy): def __init__(self) -> None: super().__init__() self.nics: tp.List[tp.Tuple[(NICSim, bool)]] = [] self.n2ns: tp.List[tp.Tuple[(tp.Tuple[(Simulator, Simulator)], bool)]] = [] self.shm_size = 2048 def start_delay(self) -> int: return 10
def isunsigned_chararray(var): return (isarray(var) and (var.get('typespec') in ['integer', 'logical']) and (get_kind(var) == '-1'))
class DoxygenType(GeneratedsSuper): subclass = None superclass = None def __init__(self, version=None, compound=None): self.version = version if (compound is None): self.compound = [] else: self.compound = compound def factory(*args_, **kwargs_): i...
def parallel_iter(f, inputs): v = list(inputs) shuffle(v) for (args, kwds) in v: (yield ((args, kwds), f(*args, **kwds)))
def obtain_score_dict(input_file, output_file): corpus = load_all_questions(input_file) sorted_scores = rank_PPL_score(corpus) with open(output_file, 'w') as f: f.write(json.dumps(sorted_scores, indent=2))
.parametrize('dtype', [np.float32, np.float64]) .parametrize('order', [RowMajor, ColMajor], ids=['RowMajor', 'ColMajor']) def test_ger(dtype, order): ger = _ger_memview[_numpy_to_cython(dtype)] rng = np.random.RandomState(0) x = rng.random_sample(10).astype(dtype, copy=False) y = rng.random_sample(20).a...
def gpus_for_rank(world_size): visible_devices = list(range(torch.cuda.device_count())) gpus_per_process = (torch.cuda.device_count() // world_size) gpus_for_rank = [] for rank in range(world_size): gpus_for_rank.append(visible_devices[(rank * gpus_per_process):((rank + 1) * gpus_per_process)]) ...
def generate_synthetic_efficiency_instances(tokens: Dict[(str, List[TokenizationToken])], text_chunks: Dict[(str, List[str])], tokenizer: Tokenizer, num_instances: int, num_prompt_tokens: int, tokenizer_name: str, output_path: str='synthetic_efficiency_instances', base_path: str='prod_env'): tokenizer_organization:...
def tweak(fun_or_val, identifier=None): if isinstance(fun_or_val, collections.Callable): return tweakfun(fun_or_val, identifier) return tweakval(fun_or_val, identifier)
def test_min_pos(): X = np.random.RandomState(0).randn(100) min_double = min_pos(X) min_float = min_pos(X.astype(np.float32)) assert_allclose(min_double, min_float) assert (min_double >= 0)
class VocCfg(): variant: str = None parser: str = 'voc' num_classes: int = 80 img_filename: str = '%s.jpg' splits: Dict[(str, dict)] = None
class DiscreteSACImpl(DiscreteQFunctionMixin, QLearningAlgoImplBase): _modules: DiscreteSACModules _q_func_forwarder: DiscreteEnsembleQFunctionForwarder _targ_q_func_forwarder: DiscreteEnsembleQFunctionForwarder _target_update_interval: int def __init__(self, observation_shape: Shape, action_size: i...
def ConvertESubGraph_PUNGraph_PNEANet(InGraph, EIdV, RenumberNodes=False): return _snap.ConvertESubGraph_PUNGraph_PNEANet(InGraph, EIdV, RenumberNodes)
def minmax_data(xdata, ydata, dict=False): xmin = (min(xdata) if len(xdata) else (- 1)) xmax = (max(xdata) if len(xdata) else 1) ymin = (min(ydata) if len(ydata) else (- 1)) ymax = (max(ydata) if len(ydata) else 1) if dict: return {'xmin': xmin, 'xmax': xmax, 'ymin': ymin, 'ymax': ymax} ...
def create_bn_node(source_node: BaseNode, bn_node_weights: Dict[(Any, Any)]): bn_node = BaseNode(name=(source_node.name + '_reconstructed'), framework_attr={EPSILON: EPSILON_VAL, MOMENTUM: MOMENTUM_VAL}, input_shape=source_node.output_shape, output_shape=source_node.output_shape, weights=bn_node_weights, layer_clas...
def handleEntity(ctxObj, publish): print('Implement logic') print(ctxObj) sys.stdout.flush() print(ctxObj['type']) sys.stdout.flush() print(ctxObj['airmoisture']['value']) sys.stdout.flush() atemp = ctxObj['airTemp']['value'] shum = ctxObj['soilmoisture']['value'] pH = ctxObj['so...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [314]) def test_batch_det_double_backward(seed, ctx, func_name): from nbla_test_utils import backward_function_tester rng = np.random.RandomState(seed) inputs = [np.clip(rng.randn(2, 3, 3).astype(np.float32), (- 0.9), 0.9)] backward_function_test...
class Shape(): def __init__(self, pts=np.zeros((2, 0)), max_sides=4, text=''): self.pts = pts self.max_sides = max_sides self.text = text def isValid(self): return (self.pts.shape[1] > 2) def write(self, fp): fp.write(('%d,' % self.pts.shape[1])) ptsarray = se...
class DeQuantize(torch.nn.Module): def __init__(self): super(DeQuantize, self).__init__() def forward(self, Xq): return Xq.dequantize() def from_float(mod): return DeQuantize()
class LOLValidationHSV(LOLValidation): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __getitem__(self, idx): (x, t) = (Image.open(self.image_paths[idx]).convert('HSV'), Image.open(self.target_paths[idx]).convert('HSV')) (x, t) = self.transforms((x, t)) ...
class Rolling(OptTask): def __init__(self, n_parameters=4, visualize=True): super(Rolling, self).__init__(f=self._f, fprime=self._g, name='Rolling', n_parameters=n_parameters, n_objectives=1, order=1, bounds=rutils.bounds(max=([2] * n_parameters), min=([(- 2)] * n_parameters)), task={'minimize'}, labels_par...
class MoNet(torch.nn.Module): def __init__(self, dataset): super(MoNet, self).__init__() self.conv1 = GMMConv(dataset.num_features, args.hidden, dim=2, kernel_size=args.kernel_size) self.conv2 = GMMConv(args.hidden, dataset.num_classes, dim=2, kernel_size=args.kernel_size) def reset_para...
def register_Ns3CallbackImplBase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) cls.add_method('IsEqual', 'bool', [param('ns3::Pt...
def load_search_config(searchspace_path): with open(searchspace_path, 'r') as f: return yaml.load(f)
def test_all_nonzero(): array = ak.highlevel.Array([[[np.datetime64('2022'), np.datetime64('2023'), np.datetime64('2025')], [], [np.datetime64('2027'), np.datetime64('2011')], [np.datetime64('2013')]], [], [[np.datetime64('2017'), np.datetime64('2019')], [np.datetime64('2023')]]], check_valid=True) assert (to_l...
class SEAE(Model): def __init__(self, sess, args, devices, infer=False): self.args = args self.sess = sess self.keep_prob = 1.0 if infer: self.keep_prob_var = tf.Variable(self.keep_prob, trainable=False) else: self.keep_prob = 0.5 self.keep...
def list_join(L, x): if isinstance(x, string_types): x = (x, RESERVED_TOKEN) if (len(L) == 0): return ([], []) (out, out_types) = (copy.deepcopy(L[0][0]), copy.deepcopy(L[0][1])) for (v, t) in L[1:]: if x: out += [x[0]] out_types += [x[1]] out += v...
def test_indexed(): array = ak.Array(ak.contents.IndexedArray(ak.index.Index64(np.array([0, 1, 3], dtype=np.int64)), tuple)) assert ak.is_tuple(array) array = ak.Array(ak.contents.IndexedArray(ak.index.Index64(np.array([0, 1, 3], dtype=np.int64)), record)) assert (not ak.is_tuple(array))
def masses_from_heliocentric(mu, M): mu_arr = np.array(mu)[1:] M_arr = np.array(M)[1:] X = np.sqrt(((M_arr ** 2) - ((4 * M_arr) * mu_arr))) mstar_arr = (0.5 * (M_arr + X)) m_arr = (0.5 * (M_arr - X)) assert np.alltrue(np.isclose(mstar_arr, mstar_arr[0], rtol=1e-10)) mstar = np.mean(mstar_arr...
def test_isotonic_make_unique_tolerance(): X = np.array([0, 1, (1 + 1e-16), 2], dtype=np.float64) y = np.array([0, 1, 2, 3], dtype=np.float64) ireg = IsotonicRegression().fit(X, y) y_pred = ireg.predict([0, 0.5, 1, 1.5, 2]) assert_array_equal(y_pred, np.array([0, 0.75, 1.5, 2.25, 3])) assert_arr...
.ort .parametrize('break_opchecker', [True, False]) .parametrize('simplify', [True, False]) def test_squeeze(gpu, simplify, break_opchecker, sdfg_name): with (BreakOpChecker() if break_opchecker else suppress()): sdfg = dace.SDFG(sdfg_name) sdfg.add_array('X_arr', [1], dace.float32) sdfg.add...
def register_Ns3CallbackImplBase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::CallbackImplBase const &', 'arg0')]) cls.add_method('GetTypeid', 'std::string', [], is_pure_virtual=True, is_const=True, is_virtual=True) cls.add_method('IsEqual', 'bool', [param('ns3::Pt...
class ScorerLM(Scorer): JM = 'jm' DIRICHLET = 'dirichlet' def __init__(self, elastic, query, params): super(ScorerLM, self).__init__(elastic, query, params) self._field = params.get('fields', 'catchall') self._smoothing_method = params.get('smoothing_method', self.DIRICHLET).lower() ...
def bar_plots_with_protocol_table(output_path, data, protocol_settings, task): protocol_labels = data[0] protocol_ids = ['P{}'.format(i) for i in range(len(protocol_labels))] experiment_labels = data[1] metric_labels = data[2] x = np.arange(len(protocol_labels)) mpl.rc('text', usetex=True) t...
def stable_resize_token_embeddings(model: transformers.PreTrainedModel, target_size: int, jitter_new_embeddings=False): num_new_tokens = (target_size - model.get_input_embeddings().weight.size(0)) model.resize_token_embeddings(target_size) if (num_new_tokens > 0): _mode() def stable_init(emb...
def op_t5_3b_tied_lmheads_64_4_8p_bw12_async_squad1_mpipe(): return dict(model_type='t5_stateless', model_name_or_path='t5-3b', do_lower_case=False, output_past=False, stateless_tied=True, explicitly_set_dict={'return_dict': False, 'use_cache': False, 'output_only': True, 'output_attentions': False, 'precompute_mas...
class ChargingBar(Bar): suffix = '%(percent)d%%' bar_prefix = ' ' bar_suffix = ' ' empty_fill = '' fill = ''
_pipeline_test _torch _vision class DocumentQuestionAnsweringPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING _pytesseract _vision def get_test_pipeline(self, model, tokenizer, processor): dqa_pipeline = pipeline('document-question-answering', model...
class FixAudioLength(object): def __init__(self, time=1): self.time = time def __call__(self, data): length = int((self.time * SAMPLE_RATE)) if (length < len(data)): data = data[:length] elif (length > len(data)): data = np.pad(data, (0, (length - len(data...
def _unwrap_layers(module: nn.Module): for (name, sub_module) in module.named_children(): if isinstance(sub_module, Wrapper): sub_module.on_unwrap() module.add_module(name, sub_module.layer) else: _unwrap_layers(sub_module)
class TestSegmentationMask(unittest.TestCase): def __init__(self, method_name='runTest'): super(TestSegmentationMask, self).__init__(method_name) poly = [[[423.0, 306.5, 406.5, 277.0, 400.0, 271.5, 389.5, 277.0, 387.5, 292.0, 384.5, 295.0, 374.5, 220.0, 378.5, 210.0, 391.0, 200.5, 404.0, 199.5, 414....
class ThreadPoolRunner(BaseRunner): workers_num: int = 2 request_tls_verify: (bool | str) = True request_proxy: (str | None) = None request_cert: (RequestCert | None) = None def _execute(self, results: TestResultSet, stop_event: threading.Event) -> Generator[(events.ExecutionEvent, None, None)]: ...
class GraphConvolution(nn.Module): def __init__(self, in_features, out_features, residual=False, batch_norm=False, activation=F.relu, dropout=0, bias=True): super().__init__() self.in_features = in_features self.out_features = out_features self.weight = nn.Parameter(torch.Tensor(in_f...
class UpstreamExpert(UpstreamBase): def __init__(self, model_config, **kwargs): super().__init__(**kwargs) with open(model_config, 'r') as file: self.config = yaml.load(file, Loader=yaml.FullLoader) if ('kaldi' in self.config): (self.extracter, self.output_dim, frame_...
class TaggerPipelineServer(Distributed): def worker(pipeline, corpus, ngrams=5): for doc in corpus: for name in pipeline: pipeline[name].tag(doc, ngrams=ngrams) return corpus def apply(self, pipeline, documents, block_size=None): items = itertools.chain.from_i...
def cast_flat_shape(shape: Shape) -> Sequence[int]: assert (not is_tuple_shape(shape)) return shape
def vgg11(output_dim, k_lipschitz=None, p_drop=0.5): if (k_lipschitz is not None): k_lipschitz = (k_lipschitz ** (1.0 / 11.0)) return VGG(make_layers(cfg['A'], k_lipschitz=k_lipschitz), output_dim=output_dim, k_lipschitz=k_lipschitz, p_drop=p_drop)
def is_valid_date_range(start_date: str, end_date: str, lower_bound: str) -> bool: tommorrow = (datetime.today() + timedelta(days=1)) if ((tommorrow >= convert_date(end_date)) and (convert_date(start_date) >= convert_date(lower_bound))): return True else: return False
class DotAttention(nn.Module): def __init__(self): super().__init__() pass def forward(self, values, query): attention_weights = self._get_weights(values, query) representations = torch.bmm(values.transpose(1, 2), attention_weights.unsqueeze(2)).squeeze(2) return represen...
def get_datasampler(dataset, mode): return torch.utils.data.distributed.DistributedSampler(dataset, shuffle=(mode == 'train'), num_replicas=world_size(), rank=rank())
class Synthetic2DType(enum.Enum): MOONS = enum.auto() CHECKERBOARD = enum.auto() CONCENTRIC_RINGS = enum.auto() CONCENTRIC_SQUARES = enum.auto() OLYMPIC_RINGS = enum.auto() OLYMPIC_SQUARES = enum.auto()
def pesq_mos(clean: str, enhanced: str): (sr1, clean_wav) = wavfile.read(clean) (sr2, enhanced_wav) = wavfile.read(enhanced) assert (sr1 == sr2) mode = ('nb' if (sr1 < 16000) else 'wb') return pesq(sr1, clean_wav, enhanced_wav, mode)
def load_test_data(path): (sents1, sents2, labels) = ([], [], []) with open(path, 'r', encoding='utf8') as f: for line in f: line = line.strip().split('\t') if (len(line) != 3): continue sents1.append(line[0]) sents2.append(line[1]) ...
class Conv_3d(nn.Module): def __init__(self, in_ch, out_ch, kernel_size, stride=1, padding=0, bias=True, batchnorm=False): super().__init__() self.conv = [nn.Conv3d(in_ch, out_ch, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias), SEGating(out_ch)] if batchnorm: ...
class InvertibleLinear(nn.Module): def __init__(self, dim): super(InvertibleLinear, self).__init__() self.dim = dim self.weight = nn.Parameter(torch.eye(dim)[torch.randperm(dim)]) def forward(self, x, logpx=None): y = F.linear(x, self.weight) if (logpx is None): ...
def __tar_xz_parallel(args, dirname, excludes=[]): dirpath = f'{args.prefix}/{dirname}' if (not os.path.exists(dirpath)): return False flags = [f"--exclude='{e}'" for e in excludes] flag_str = ' '.join(flags) tar_cmd = cmdsplit(f'tar cf - {flag_str} {dirname}') tarproc = subprocess.Popen...
class EncoderBlock(nn.Module): def __init__(self, channel_in, channel_out): super(EncoderBlock, self).__init__() self.conv = nn.Conv2d(in_channels=channel_in, out_channels=channel_out, kernel_size=5, padding=2, stride=2, bias=False) self.bn = nn.BatchNorm2d(num_features=channel_out, momentum...
class ShuffleNet(nn.Module): def __init__(self, num_classes, loss='softmax', num_groups=3, **kwargs): super(ShuffleNet, self).__init__() self.loss = loss self.conv1 = nn.Sequential(nn.Conv2d(3, 24, 3, stride=2, padding=1, bias=False), nn.BatchNorm2d(24), nn.ReLU(), nn.MaxPool2d(3, stride=2, ...
class SummaryWriter(): def __init__(self, log_dir='', **kwargs): pass def add_scalar(self, tag, value, global_step=None, walltime=None): pass def add_scalars(self, tag, tag_scalar_dict, global_step=None, walltime=None): pass def add_histogram(self, tag, values, global_step=None, ...
class FNCSimpleLabelSchema(LabelSchema): def __init__(self): super().__init__(['agree', 'disagree', 'not enough info'])
class PosTaggingSpacy(PosTagging): def __init__(self, nlp=None, separator='|', lang='en'): if (not nlp): print('Loading Spacy model') print(('Spacy model loaded ' + lang)) else: self.nlp = nlp self.separator = separator def pos_tag_raw_text(self, text,...
def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='highs-ipm', callback=None, maxiter=None, disp=False, presolve=True, time_limit=None, dual_feasibility_tolerance=None, primal_feasibility_tolerance=None, ipm_optimality_tolerance=None, **unknown_options): pass
class LSTM_VIDEO(nn.Module): def __init__(self, cfg): super(LSTM_VIDEO, self).__init__() self.input_size = cfg.DYNAMIC_FILTER.LSTM_VIDEO.INPUT_SIZE self.num_layers = cfg.DYNAMIC_FILTER.LSTM_VIDEO.NUM_LAYERS self.hidden_size = cfg.DYNAMIC_FILTER.LSTM_VIDEO.HIDDEN_SIZE self.bia...
_model def resnest50d_4s2x40d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['resnest50d_4s2x40d'] model = ResNet(ResNestBottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, stem_type='deep', stem_width=32, avg_down=True, base_width=40, cardinality=2, bloc...
class ForwardModuleRF(_RFModuleAsPTModule): def __init__(self, rf_module: rf.Module, forward_step: Callable, extern_data: TensorDict): super().__init__(rf_module) self.forward_step_func = forward_step self.extern_data = extern_data def __call__(self, data: Dict[(str, torch.Tensor)]) -> D...
class ExtendedPopREO(BaseMetric): def __init__(self, recommendations, config, params, eval_objects, additional_data): super().__init__(recommendations, config, params, eval_objects, additional_data) self._cutoff = self._evaluation_objects.cutoff self._relevance = self._evaluation_objects.rel...
def hook_batchnormNd(m, x, y): num_ele = y.numel() flops = (2 * num_ele) if m.affine: flops += (2 * num_ele) return int(flops)
class LWNN(Estimator): def __init__(self, model, model_name, pg_est, table): super(LWNN, self).__init__(table=table, model=model_name) self.model = model.to(DEVICE) self.model.eval() self.pg_est = pg_est def query(self, query): if isinstance(query, Query): que...
class Hex(Type): def from_str(self, s): assert (s.startswith('0x') or s.startswith('0X')) return int(s, 16)
class MegatronParser(Parser): def __init__(self) -> None: if (not has_fairseq): raise ImportError('\n\nPlease install fairseq_for_pipeline:') super().__init__() def _auto_file_name(self, args) -> str: bw_str = str(args.bw).replace('.', '_') model_str = str(args.arch) ...
def random_orientation(G): from sage.graphs.graph import Graph if (not isinstance(G, Graph)): raise ValueError('the input parameter must be a Graph') D = DiGraph(data=[G.vertices(sort=False), []], format='vertices_and_edges', multiedges=G.allows_multiple_edges(), loops=G.allows_loops(), weighted=G.w...