code
stringlengths
101
5.91M
class MixtureGroupNorm(nn.Module): __constants__ = ['num_groups', 'num_channels', 'k', 'eps', 'weight', 'bias'] def __init__(self, k, num_groups, num_channels, eps=1e-05): super(MixtureGroupNorm, self).__init__() self.k = k self.num_groups = num_groups self.num_channels = num_cha...
class ScriptArguments(): model_type: str = field(default=None, metadata={'help': ('Model type selected in the list: ' + ', '.join(MODEL_CLASSES.keys()))}) model_name_or_path: Optional[str] = field(default=None, metadata={'help': 'The model checkpoint for weights initialization.'}) tokenizer_name_or_path: Op...
def axiom(axiom): def with_axiom(self): return self._with_axiom(axiom) with_axiom.__name__ = axiom return with_axiom
def main(): args = parser.parse_args() if (not os.path.exists(args.save_path)): os.makedirs(args.save_path, exist_ok=True) if (args.seed is not None): random.seed(args.seed) torch.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed...
def register_Ns3ArpL3Protocol_methods(root_module, cls): cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_static_attribute('PROT_NUMBER', 'uint16_t const', is_const=True) cls.add_constructor([]) cls.add_method('SetNode', 'void', [param('ns3::Ptr< ns3::Node >', 'node')]) cls.add...
def trim_collate(batch): _use_shared_memory = True error_msg = 'batch must contain tensors, numbers, dicts or lists; found {}' elem_type = type(batch[0]) if torch.is_tensor(batch[0]): out = None if (1 < batch[0].dim()): max_num_boxes = max([x.size(0) for x in batch]) ...
def softmax(g, input, dim=None): if (dim < 0): dim = (len(input.type().sizes()) + dim) if (len(input.type().sizes()) != (dim + 1)): return _unimplemented('dim', 'ONNX and PyTorch use different strategies to split the input.') return g.op('Softmax', input, axis_i=dim)
def find_zero_result(fn, l): for prec in prec_seq(): result = None ambig = False for v in l: intv = fn(v, prec) if intv.contains_zero(): if (result is not None): ambig = True break result = v ...
def cantilever_problem(config_top): gamma = 100.0 E = 1.0 nu = 0.3 plane_stress = True mu = (E / (2.0 * (1.0 + nu))) lambd = ((E * nu) / ((1.0 + nu) * (1.0 - (2.0 * nu)))) if plane_stress: lambd = (((2 * mu) * lambd) / (lambd + (2.0 * mu))) alpha_in = 1.0 alpha_out = 0.001 ...
def find_package(import_name): (root_mod_name, _, _) = import_name.partition('.') package_path = _find_package_path(root_mod_name) (site_parent, site_folder) = os.path.split(package_path) py_prefix = os.path.abspath(sys.prefix) if package_path.startswith(py_prefix): return (py_prefix, packag...
class Norm(): def __call__(self, perturbations): raise NotImplementedError() def normalize(self, gradients): raise NotImplementedError() def scale(self, gradients): raise NotImplementedError()
class LitTrainer(): def __init__(self, f): cudnn.benchmark = True global beta beta = f.beta self.distributed = (torch.cuda.device_count() > 1) if (not os.path.exists(f.save_dir)): os.makedirs(f.save_dir) if (not os.path.exists(f.log_dir)): os.m...
def test_case108(): url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert') headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'} r = requests.post(url, data=json.dumps(ld_data.subdata108), headers=headers) print(r.conten...
def _impl(array, pattern, ignore_case, highlevel, behavior, attrs): from awkward._connect.pyarrow import import_pyarrow_compute pc = import_pyarrow_compute('ak.str.match_substring') with HighLevelContext(behavior=behavior, attrs=attrs) as ctx: layout = ctx.unwrap(array, allow_record=False, allow_unk...
class RNNLayer(nn.Module): def __init__(self, input_dim, module, bidirection, dim, dropout, layer_norm, sample_rate, proj): super(RNNLayer, self).__init__() rnn_out_dim = ((2 * dim) if bidirection else dim) self.out_dim = rnn_out_dim self.dropout = dropout self.layer_norm = l...
_module() class Shared2FCBBoxHead(ConvFCBBoxHead): def __init__(self, fc_out_channels=1024, *args, **kwargs): super(Shared2FCBBoxHead, self).__init__(*args, num_shared_convs=0, num_shared_fcs=2, num_cls_convs=0, num_cls_fcs=0, num_reg_convs=0, num_reg_fcs=0, fc_out_channels=fc_out_channels, **kwargs)
def _save(im, fp, filename): if ((_handler is None) or (not hasattr('_handler', 'save'))): raise OSError('BUFR save handler not installed') _handler.save(im, fp, filename)
def test_suppress_warnings_type(): my_mod = _get_fresh_mod() assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) with suppress_warnings() as sup: sup.filter(UserWarning) warnings.warn('Some warning') assert_warn_len_equal(my_mod, 0) sup = suppress_warnings() sup.filter(U...
def name_feature(name, toplevel=None): if (toplevel is None): try: import sage.all as toplevel except ImportError: return None try: obj = getattr(toplevel, name) except AttributeError: return None from sage.misc.dev_tools import find_object_modules...
def make_parse(): parser = argparse.ArgumentParser() parser.add_argument('--base-loss', default='CrossEntropyLoss', type=str) args = parser.parse_args() return args
_builder('msrvtt_qa_instruct') class MSRVTTQAInstructBuilder(VideoQABuilder): train_dataset_cls = VideoQAInstructDataset eval_dataset_cls = VideoQAInstructDataset DATASET_CONFIG_DICT = {'default': 'configs/datasets/msrvtt/defaults_qa_instruct.yaml'}
def write_results(results_file, results): with open(results_file, mode='w') as cf: dw = csv.DictWriter(cf, fieldnames=results[0].keys()) dw.writeheader() for r in results: dw.writerow(r) cf.flush()
class PSPModule(nn.Module): def __init__(self, features, out_features=512, sizes=(1, 2, 3, 6)): super(PSPModule, self).__init__() self.stages = [] self.stages = nn.ModuleList([self._make_stage(features, out_features, size) for size in sizes]) self.bottleneck = nn.Sequential(nn.Conv2d...
class OneFormerModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test_transform_float_int_2d_different_one_to_one(): this = ak.contents.ListOffsetArray(ak.index.Index64(np.array([0, 3, 4], dtype='int64')), ak.contents.NumpyArray(np.array([1.0, 2.0, 3.0, 4.0], dtype='float64')), parameters={'name': 'this'}) that = ak.contents.ListOffsetArray(ak.index.Index64(np.array([0, ...
def result_region(finding): region_dict = {} for (f, r) in (('line', 'startLine'), ('column', 'startColumn'), ('line_end', 'endLine'), ('column_end', 'endColumn')): if (f in finding): region_dict[r] = int(finding[f]) if region_dict: return region_dict for (a, l, c) in (('addr...
_axis_nan_policy_factory((lambda x: x), n_outputs=1, result_to_tuple=(lambda x: (x,))) def variation(a, axis=0, nan_policy='propagate', ddof=0, *, keepdims=False): n = a.shape[axis] NaN = _get_nan(a) if ((a.size == 0) or (ddof > n)): shp = np.asarray(a.shape) shp = np.delete(shp, axis) ...
.parametrize('pct_accuracy', [(- 1.0), (- 0.5), 0.0, 1.01]) def test_check_pct_accuracy_value(pct_accuracy, create_X_y): (X, y) = create_X_y with pytest.raises(ValueError): desmi = DESMI(pct_accuracy=pct_accuracy) desmi.fit(X, y)
class Block(chainer.Chain): def __init__(self, in_channels, out_channels, hidden_channels=None, ksize=3, pad=1, activation=F.relu, upsample=False, n_classes=0): super(Block, self).__init__() initializer = chainer.initializers.GlorotUniform(math.sqrt(2)) initializer_sc = chainer.initializers....
def prune_heads(args, model, eval_dataloader, head_mask): before_time = datetime.now() (_, _, loss) = compute_heads_importance(args, model, eval_dataloader, compute_entropy=False, compute_importance=False, head_mask=head_mask) score_masking = (1 / loss) original_time = (datetime.now() - before_time) ...
class WeightCharacter(Element): def __init__(self, parent): Element.__init__(self, parent) self._p = self.parent().prime() def base_extend(self, R): return self.parent().base_extend(R).coerce(self) def is_even(self) -> bool: return (self((- 1)) != (- 1)) def pAdicEisenste...
class Median(CombinerBase): def _combine_univariates(self, univariates: List[UnivariateTimeSeries]) -> UnivariateTimeSeries: non_none = [var for var in univariates if (var is not None)] v = non_none[0] if (self.abs_score and (sum(self.models_used) > 1)): signs = np.median(np.sign...
class BaseNNIndexer(): def __init__(self, config): super(BaseNNIndexer, self).__init__() self.token_dim = config['token_dim'] self.use_gpu = config['faiss_use_gpu'] self.use_fp16 = (config['token_dtype'] == 'float16') def prepare(self, data_chunks: List[numpy.ndarray], subsample=...
class WithForegroundSelection(SelectionStrategy): def __call__(self, sample) -> bool: return sample[defs.KEY_LABELS].any()
class LReLU_MobileNet(nn.Module): cfg = [64, (128, 2), 128, (256, 2), 256, (512, 2), 512, 512, 512, 512, 512, (1024, 2), 1024] def __init__(self, num_classes=10): super(LReLU_MobileNet, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False) self.bn...
def _build_egg(egg, tarball, to_dir): tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) tar = tarfile.open(tarball) _extractall(tar) tar.close() subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) ...
class Choice(ParamType): name = 'choice' def __init__(self, choices, case_sensitive=True): self.choices = choices self.case_sensitive = case_sensitive def get_metavar(self, param): return '[{}]'.format('|'.join(self.choices)) def get_missing_message(self, param): return '...
() ('names', nargs=(- 1)) def run(names): if (not names): raise click.BadParameter('Empty names!') if (len(names) != len(set(names))): raise click.BadParameter('Duplicate names!') options = _get_all_options() for name in names: if (name not in options): raise click.Ba...
def whiten(values: Tensor, shift_mean=True, epsilon=1e-08) -> Tensor: assert (values.size(0) >= 8), f'Internal error: Minibatch size {values.size(0)} is insufficient for whitening.' (mean, std) = (values.mean(), values.std(unbiased=False)) whitened = ((values - mean) / (std + epsilon)) if (not shift_mea...
def get_node_csv(node_file): node_procs = {} df = pd.read_csv(node_file) for (name, group) in zip(df['name'], df['group']): node_procs[name] = group return node_procs
class BayesianLinReg(ConjPrior): def __init__(self, sample=None): self.w_0 = np.zeros(2) self.Lambda_0 = (np.array([[0, 0], [0, 1]]) + _epsilon) self.alpha = (1 + _epsilon) self.beta = _epsilon super().__init__(sample=sample) def n_params(self) -> int: return 8 ...
def clean_py_ruc(df: Union[(pd.DataFrame, dd.DataFrame)], column: str, output_format: str='standard', inplace: bool=False, errors: str='coerce', progress: bool=True) -> pd.DataFrame: if (output_format not in {'compact', 'standard'}): raise ValueError(f'output_format {output_format} is invalid. It needs to b...
def check_optimization_criteria(nnp, batch_size): def find_network(nnp, exe): net = None for network in nnp.protobuf.network: if (network.name == exe.network_name): net = network return net def get_input_info(exec_info, network): input_dict = collectio...
class SGDMixin(StepwiseMixin, abc.ABC): def step(self, **kwargs): if ('x' in kwargs): x = kwargs['x'] else: raise TypeError('x argument is missing in step function.') if ('grad' in kwargs): grad = kwargs['grad'] else: raise TypeError('g...
class Timer(): def __init__(self, start=True, print_tmpl=None): self._is_running = False self.print_tmpl = (print_tmpl if print_tmpl else '{:.3f}') if start: self.start() def is_running(self): return self._is_running def __enter__(self): self.start() ...
def _lookfor_generate_cache(module, import_modules, regenerate): global _lookfor_caches import inspect if (sys.version_info[0] >= 3): from io import StringIO else: from StringIO import StringIO if (module is None): module = 'numpy' if isinstance(module, str): try:...
def process(model, clip, path_indata, dname, frame_no, args, img_size): with torch.no_grad(): smap = model(clip.to(device)).cpu().data[0] smap = smap.numpy() _id = frame_no.split('.')[0].split('_')[(- 1)] gt = cv2.imread(join(path_indata, 'annotations/DIEM', dname, 'maps', 'eyeMap_{}.jpg'.format...
class AbstractPlayer(): def __init__(self): self.lastSsoType = LEARNING_SSO_TYPE.JSON def init(self, sso, timer): pass def act(self, sso, timer): pass def result(self, sso, timer): pass
def flatten_to_tuple(outputs): result = [] if isinstance(outputs, torch.Tensor): result.append(outputs) elif isinstance(outputs, (list, tuple)): for v in outputs: result.extend(flatten_to_tuple(v)) elif isinstance(outputs, dict): for (_, v) in outputs.items(): ...
class TrainerDeviceMixin(ABC): def configure_seed(self): seed = self.config.training.seed if (seed is None): return torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def configure_device(self): if (self.config.training.get('devic...
def test_array_highlevel_true(): form = ak.forms.from_dict(form_dict) (array, report) = ak.typetracer.typetracer_with_report(form, highlevel=True) assert isinstance(array, ak.Array) y = array.y assert (len(report.data_touched) == 0) assert (len(report.shape_touched) == 0) ak.sum(y) asser...
class Generator(keras.Model): def __init__(self, data, learning_rate=0.001, l_w=0, l_b=0, l_gan=0, num_users=100, num_items=100, name='CFGAN-GEN', **kwargs): super().__init__(name=name, **kwargs) self._learning_rate = learning_rate self._l_w = l_w self._l_b = l_b self._l_gan ...
.gpu .parametrize('dl', LAYOUTS) def test_layouts(dl): with change_default(blas, 'cuBLAS'): _test_matmul(('cuBLAS float ' + dl), dace.float32, 'cuBLAS', dace.StorageType.GPU_Global, data_layout=dl)
_model def tv_resnext50_32x4d(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['tv_resnext50_32x4d'] model = ResNet(Bottleneck, [3, 4, 6, 3], cardinality=32, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pretra...
def _make_arg(kwargs: Dict[(str, Any)]): assert ('tag' in kwargs) _deprecate_arg_args(kwargs) proc = {ArgKind.SCALAR: _make_arg_scalar, ArgKind.NDARRAY: _make_arg_ndarray, ArgKind.MATRIX: _make_arg_matrix, ArgKind.TEXTURE: _make_arg_texture, ArgKind.RWTEXTURE: _make_arg_rwtexture} tag = kwargs['tag'] ...
def register_Ns3ConstantRandomVariable_methods(root_module, cls): cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_constructor([]) cls.add_method('GetConstant', 'double', [], is_const=True) cls.add_method('GetValue', 'double', [param('double', 'constant')]) cls.add_method('GetI...
def fnmatchcase(name, pat, case_sensitive=True): match = _compile_pattern(pat, case_sensitive) return (match(name) is not None)
def _get_all_lines(graph_parse, is_variable): assert isinstance(graph_parse, GraphParse) items = [] for (a_key, b_key) in graph_parse.line_graph.edges(): items.extend(_get_lines(graph_parse, is_variable, a_key, b_key).iteritems()) return dict(items)
def tactics(ctx=None): ctx = _get_ctx(ctx) return [Z3_get_tactic_name(ctx.ref(), i) for i in range(Z3_get_num_tactics(ctx.ref()))]
def make_args_list(n_trials, dataset_names, algorithms, n_hparams_from, n_hparams, steps, data_dir, task, holdout_fraction, single_test_envs, hparams): args_list = [] for trial_seed in range(n_trials): for dataset in dataset_names: for algorithm in algorithms: if single_test_...
class TransformerAlgoConfig(Config): tokenizer_config: dict = {'name': 'auto', 'model': 'bert-base-cased'} trainer_config: dict = {}
def configurator(forward_dict, mode='posterior', scale_data=12): if (mode == 'posterior'): input_dict = _config_posterior(forward_dict, scale_data) elif (mode == 'likelihood'): input_dict = _config_likelihood(forward_dict, scale_data) elif (mode == 'joint'): input_dict = {} i...
def conjugacy_test(jlist, verbose=False): from sage.sets.set import Set jQ = next((j for j in jlist if (j in QQ)), None) if jQ: if verbose: print('Yes: an isogenous curve has rational j-invariant {}'.format(jQ)) x = polygen(QQ) return [(x - jQ)] K = jlist[0].parent() ...
def to_value(original_string, corenlp_value=None): if isinstance(original_string, Value): return original_string if (not corenlp_value): corenlp_value = original_string amount = NumberValue.parse(corenlp_value) if (amount is not None): return NumberValue(amount, original_string) ...
class FakeOwner(): def __init__(self): self.generator = None def get_generator(self): return self.generator
def find_files(folder, extension): return sorted([Path(os.path.join(folder, f)) for f in os.listdir(folder) if f.endswith(extension)])
def register_Ns3SystemThread_methods(root_module, cls): cls.add_constructor([param('ns3::SystemThread const &', 'arg0')]) cls.add_constructor([param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) cls.add_meth...
def hdf_dump_from_dataset(dataset, hdf_dataset, parser_args): hdf_dataset.dump_from_dataset(dataset=dataset, epoch=parser_args.epoch, start_seq=parser_args.start_seq, end_seq=parser_args.end_seq, use_progress_bar=True)
def extract_batch(args, model, batch, options, clusterings): batch = to_device(batch, args.computation.device) data = batch['data'] features = model(data) return _extract_batch(args, batch, features, clusterings)
class DDPCommHookType(Enum): ALLREDUCE = partial(_ddp_comm_hook_wrapper, comm_hook=default.allreduce_hook) FP16_COMPRESS = partial(_ddp_comm_hook_wrapper, comm_hook=default.fp16_compress_hook) QUANTIZE_PER_TENSOR = partial(_ddp_comm_hook_wrapper, comm_hook=quantization.quantization_pertensor_hook) QUANT...
def process_files(args): print(f'listing files', flush=True) files = [f for f in glob(f'{args.data_bucket_path}/*')] random.seed(args.seed) random.shuffle(files) print(f'splitting {len(files)} files into {args.n_workers} partitions', flush=True) files_chunks = split(files, args.n_workers) pr...
_function def modulated_conv2d(x, weight, styles, noise=None, up=1, down=1, padding=0, resample_filter=None, demodulate=True, flip_weight=True, fused_modconv=True): batch_size = x.shape[0] (out_channels, in_channels, kh, kw) = weight.shape misc.assert_shape(weight, [out_channels, in_channels, kh, kw]) m...
def slide_split(train, test): train_list = [i for i in train] data_map = {} data_map['data1'] = [DLBCL_1, nonDLBCL_1] data_map['data2'] = [DLBCL_2, nonDLBCL_2] data_map['data3'] = [DLBCL_3, nonDLBCL_3] data_map['data4'] = [DLBCL_4, nonDLBCL_4] data_map['data5'] = [DLBCL_5, nonDLBCL_5] tr...
def dgp_model(test_data): (X, Y) = test_data (num_data, x_dim) = X.shape (_, y_dim) = Y.shape w_dim = 1 return build_LVGPGP_model(x_dim, w_dim, y_dim, num_data)
class MyCorpus(): def __init__(self, data_path): self.data_path = data_path self.bnltk = NLTKTokenizer() def __iter__(self): for line in open(self.data_path): sentences = self.bnltk.sentence_tokenize(line) for sentence in sentences: tokens = self.b...
def test_getSubscription23(): url = (brokerIp + '/ngsi10/updateContext') headers = {'Content-Type': 'application/json'} r = requests.post(url, data=json.dumps(data_ngsi10.subdata39), headers=headers) resp_content1 = r.content resInJson = resp_content1.decode('utf8').replace("'", '"') resp1 = jso...
def _mean(tensor: FloatTensor, dim: Optional[int]=None, keepdim: bool=False) -> FloatTensor: if (dim is None): return torch.mean(tensor) else: if isinstance(dim, int): dim = [dim] dim = sorted(dim) for d in dim: tensor = tensor.mean(dim=d, keepdim=True) ...
def draw_bounding_boxes(image, boxes, **kwargs): if isinstance(image, Image.Image): image = PILToTensor()(image) assert isinstance(image, torch.Tensor), '' if (not isinstance(boxes, torch.Tensor)): boxes = torch.as_tensor(boxes) assert isinstance(boxes, torch.Tensor) return _draw_bou...
def is_partition_valid(prob, nodes_in_part): G_sub = prob.G.subgraph(nodes_in_part) tm = prob.traffic_matrix.tm for (src, target) in permutations(G_sub.nodes, 2): if (tm[(src, target)] == 0.0): continue if (not nx.has_path(G_sub, src, target)): print(src, target) ...
def test_unet_skip_connection_block(): _cfg = dict(outer_channels=1, inner_channels=1, in_channels=None, submodule=None, is_outermost=False, is_innermost=False, norm_cfg=dict(type='BN'), use_dropout=True) feature_shape = (1, 1, 8, 8) feature = _demo_inputs(feature_shape) input_shape = (1, 3, 8, 8) i...
_HEADS_REGISTRY.register() class AttrHead(EmbeddingHead): def __init__(self, cfg): super().__init__(cfg) num_classes = cfg.MODEL.HEADS.NUM_CLASSES self.bnneck = nn.BatchNorm1d(num_classes) self.bnneck.apply(weights_init_kaiming) def forward(self, features, targets=None): ...
def sortkey(K): return (K.degree(), abs(K.discriminant()), (K.discriminant() > 0), K.polynomial())
def _get_logger_dict_helper(mod, target_dict, prefix=''): def get_prefix(prefix): return (prefix if (prefix == '') else (prefix + '.')) for (name, child) in mod.named_children(): if isinstance(child, Logger): target_dict[(get_prefix(prefix) + 'stats')] = child.stats break...
def simplify_chain_generic(expr): if (expr.number_of_operands() == 0): return expr expr = expr.simplify_factorial() expr = expr.simplify_rectform() expr = expr.simplify_trig() expr = expr.simplify_rational() expr = expr.expand_sum() return expr
class _History(keras.callbacks.Callback): def __init__(self, data, model, save_weights=False, *args, **kwargs): self.trace_data = data self.trace_model = model self.save_weights = save_weights if save_weights: self.weights = [] self.trace = [] super().__in...
class NetworkWrapper(nn.Module): def get_args(parser): parser.add('--emb_num_channels', default=64, type=int, help='minimum number of channels') parser.add('--emb_max_channels', default=512, type=int, help='maximum number of channels') parser.add('--emb_no_stickman', action='store_true', hel...
def img2video(path, size, seq, frame_start, frame_end, marks, fps=10): file_path = join(path, '{}.avi'.format(seq)) os.makedirs(dirname(path), exist_ok=True) path = join(path, '{}'.format(seq)) fourcc = cv2.VideoWriter_fourcc(*'MJPG') video = cv2.VideoWriter(file_path, fourcc, fps, size) for i i...
def is_pythran_supported_node_or_none(node): return (node.is_none or is_pythran_supported_type(node.type))
class TFAlbertModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def test_parameter_list(): time_dim = Dim(Tensor('time', [batch_dim], dtype='int32')) in_dim = Dim(7, name='in') extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')}) class _Net(rf.Module): def __init__(self): super().__init__() ...
def register_Ns3Mac48AddressValue_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::Mac48Address const &', 'value')]) cls.add_constructor([param('ns3::Mac48AddressValue const &', 'arg0')]) cls.add_method('Copy', 'ns3::Ptr< ns3::AttributeValue >', [], is_const=True, is_v...
def reinit(): if (wrapped_stdout is not None): sys.stdout = wrapped_stdout if (wrapped_stderr is not None): sys.stderr = wrapped_stderr
class CallHLS(): def __init__(self, backend='vivado_hls'): self.tcl_script = '' self.ipgen_path = '' self.code_gen_dir = '' self.ipgen_script = '' assert (backend in ['vivado_hls', 'vitis_hls']), 'Unrecognized backend for CallHLS' self.backend = backend def append...
class MixDataset(torch.utils.data.Dataset): def __init__(self, filename, split, n_mix=2, audio_len=80000, audio_rate=16000, n_fft=1024, hop_len=256, win_len=1024, n_frames=3, stride_frames=1, img_size=224, fps=1, preprocess_func=None, max_sample=None, return_waveform=True, repeat=None, frame_margin=None, audio_only...
class ModeFilter(Filter): name = 'Mode' def __init__(self, size=3): self.size = size def filter(self, image): return image.modefilter(self.size)
def align(input_file, output_file, nbest): skipped = 0 total = 0 source_to_targets = defaultdict(list) for line in input_file: fields = line.rstrip().split('\t') source_tokens = fields[0].split() target_tokens = fields[1].split() total += 1 if (len(source_tokens) ...
def print_node_family_to_file(G, f, nodetype): if (nodetype == 'root'): node_family = [n for n in G.nodes() if ((G.out_degree(n) > 0) and (G.in_degree(n) == 0))] node_family = sorted(node_family, key=(lambda x: sort_key(x))) elif (nodetype == 'leaf'): node_family = [n for n in G.nodes() ...
def get_dataset(dataset, task): if (task == 'mot'): return JointDataset else: return None
def _hard_rmtree(path): shutil.rmtree(path, ignore_errors=True) try: with tempfile.TemporaryDirectory() as trash_dir: shutil.move(str(path), trash_dir) except FileNotFoundError: pass
class CFGDenoiser(nn.Module): def __init__(self, model): super().__init__() self.inner_model = model def forward(self, z, sigma, cond, uncond, text_cfg_scale, image_cfg_scale=1.0): if ('c_crossattn' in cond): cfg_z = einops.repeat(z, '1 ... -> n ...', n=3) cfg_sig...