code
stringlengths
101
5.91M
class EDSR(nn.Module): def __init__(self, num_channels=3, input_channel=64, factor=4, width=64, depth=16, kernel_size=3, conv=default_conv): super(EDSR, self).__init__() n_resblock = depth n_feats = width kernel_size = kernel_size scale = factor act = nn.ReLU() ...
('catx.network_module.CATXHaikuNetwork.__abstractmethods__', set()) def test_network_module(key: PRNGKey) -> None: def _forward() -> None: netowrk = CATXHaikuNetwork(depth=2) assert hasattr(netowrk, 'depth') forward = hk.transform(_forward) params = forward.init(rng=key) forward.apply(pa...
class TransferNet(nn.Module): def __init__(self, num_class, base_net='resnet50', transfer_loss='mmd', use_bottleneck=True, bottleneck_width=256, max_iter=1000, **kwargs): super(TransferNet, self).__init__() self.num_class = num_class self.base_network = backbones.get_backbone(base_net) ...
def test_gather_commands(ing): ing2 = Ingredient('other', ingredients=[ing]) def foo(): pass .command def bar(): pass commands = list(ing2.gather_commands()) assert (('other.bar', bar) in commands) assert (('tickle.foo', foo) in commands)
class WNConv2d(nn.Conv2d): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True): super(WNConv2d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias) def forward(self, x): weight = self.weight ...
def fake_environment(time_limit: int=10) -> FakeEnvironment: return FakeEnvironment(time_limit=time_limit)
def VarGRUCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None, noise_in=None, noise_hidden=None): input = (input.expand(3, *input.size()) if (noise_in is None) else (input.unsqueeze(0) * noise_in)) hx = (hidden.expand(3, *hidden.size()) if (noise_hidden is None) else (hidden.unsqueeze(0) * noise_hidden)) g...
class Decoder(nn.Module): def __init__(self, feat_dim, n_obj_classes): super(Decoder, self).__init__() self.layer = nn.Sequential(nn.Conv2d(feat_dim, 128, kernel_size=7, stride=1, padding=3, bias=False), nn.BatchNorm2d(128), nn.ReLU(inplace=True), nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=...
class Benchmark(ABC): args: BenchmarkArguments configs: PretrainedConfig framework: str def __init__(self, args: BenchmarkArguments=None, configs: PretrainedConfig=None): self.args = args if (configs is None): self.config_dict = {model_name: AutoConfig.from_pretrained(model_n...
def save_config(config, path): if isinstance(config, argparse.Namespace): config = to_dict(config) with open(path, 'w') as file: yaml.dump(config, file)
def main(): args = parse_args() if (args.device == 'cpu'): args.device = None cfg = Config.fromfile(args.model_config) if (args.model_type == 'det'): if (args.backend == 'TensorRT'): model = TensorRTDetector(args.model_file, cfg, 0) else: model = ONNXRunti...
_module class Reformat(object): def __init__(self, **kwargs): double_flip = kwargs.get('double_flip', False) self.double_flip = double_flip def __call__(self, res, info): meta = res['metadata'] points = res['lidar']['points'] voxels = res['lidar']['voxels'] data_b...
def traverse_dir(root_dir, extension=('mid', 'MID'), amount=None, str_=None, is_pure=False, verbose=False, is_sort=False, is_ext=True): if verbose: print('[*] Scanning...') file_list = [] cnt = 0 for (root, _, files) in os.walk(root_dir): for file in files: if file.endswith(e...
def build_optimizer_constructor(cfg): constructor_type = cfg.get('type') if (constructor_type in OPTIMIZER_BUILDERS): return build_from_cfg(cfg, OPTIMIZER_BUILDERS) elif (constructor_type in MMCV_OPTIMIZER_BUILDERS): return build_from_cfg(cfg, MMCV_OPTIMIZER_BUILDERS) else: raise...
class JsonWriter(): def __init__(self, path: str, algorithm_name: str, task_name: str, environment_name: str, seed: int): self.path = path self.file_name = 'metrics.json' self.run_data = {'absolute_metrics': {}} if os.path.isfile(f'{self.path}/{self.file_name}'): with ope...
def safe_exp(value): try: ans = math.exp(value) except OverflowError: ans = float('inf') return ans
class AffNIST(Dataset): url = ' files = ['training_and_validation_batches', 'test_batches'] def __init__(self, root, train=True, transform=None): self.root = osp.expanduser(osp.normpath(root)) self.raw_dir = osp.join(self.root, 'raw') self.processed_dir = osp.join(self.root, 'process...
_module() class InferencerLoader(BaseTransform): def __init__(self, **kwargs) -> None: super().__init__() self.from_file = TRANSFORMS.build(dict(type='LoadImageFromFile', **kwargs)) self.from_ndarray = TRANSFORMS.build(dict(type='mmdet.LoadImageFromNDArray', **kwargs)) def transform(self...
class ChannelsLast(): data_loader = create_data_loader(data_dir, batch_size, num_workers, data_transform, subset=dataset_size) test_data_loader = create_test_data_loader(data_dir, batch_size, num_workers, data_transform, subset=dataset_size) def setUp(self): test_dir = os.path.dirname(__file__) ...
def pytest_addoption_shared(parser): option = '--make-reports' if (option not in pytest_opt_registered): parser.addoption(option, action='store', default=False, help='generate report files. The value of this option is used as a prefix to report names') pytest_opt_registered[option] = 1
def test_decay_period(env): policy = ConstantPolicy(env.action_space.sample()) exp_policy = AddGaussianNoise(env, policy, max_sigma=1.0, min_sigma=0.0, decay_period=2) assert (exp_policy.get_action(None)[0] != policy.get_action(None)[0]).all() exp_policy.reset() assert (exp_policy.get_action(None)[0...
def _put_tensors_in_obj(obj: Any, tensors: List[torch.Tensor]) -> Any: if isinstance(obj, _TensorPlaceholder): return tensors[obj.index] elif isinstance(obj, dict): return {k: _put_tensors_in_obj(v, tensors) for (k, v) in obj.items()} elif isinstance(obj, list): return [_put_tensors_...
class TestOuterProductMean(unittest.TestCase): def test_shape(self): c = 31 opm = OuterProductMean(consts.c_m, consts.c_z, c) m = torch.rand((consts.batch_size, consts.n_seq, consts.n_res, consts.c_m)) mask = torch.randint(0, 2, size=(consts.batch_size, consts.n_seq, consts.n_res)) ...
def overfeat(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='overfeat'): with tf.variable_scope(scope, 'overfeat', [inputs]) as sc: end_points_collection = (sc.name + '_end_points') with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2...
def train(ep, sess, lr): global batch_size, total_steps total_loss = 0 start_time = time.time() correct = 0 counter = 0 for (batch_idx, indices) in index_generator(len(X_train), batch_size): x = X_train[indices] y = Y_train[indices] x = np.reshape(x, (x.shape + (1,))) ...
def _get_file(tablename: str, quotechar: str="'") -> pd.DataFrame: z = get_lahman_zip() f = f'{base_string}/{tablename}' data = pd.read_csv((f'{path.join(cache.config.cache_directory, f)}' if (z is None) else z.open(f)), header=0, sep=',', quotechar=quotechar) return data
class HPOConfig(): def __init__(self, search_space, searcher='xgb', higher_is_better=True, loss_type='reg', min_train_samples=10, seed=42): self.search_space = search_space self.searcher = searcher self.higher_is_better = higher_is_better self.loss_type = loss_type self.min_t...
class FlaxTimestepEmbedding(nn.Module): time_embed_dim: int = 32 dtype: jnp.dtype = jnp.float32 def __call__(self, temb): temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name='linear_1')(temb) temb = nn.silu(temb) temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name='li...
def GetUtteranceGroups(min_duration, merge_within_speakers_only, spk2utt, utt2dur): utt_groups = [] group_durations = [] for i in range(len(spk2utt)): (spk, utts) = spk2utt[i] durations = [] for utt in utts: try: durations.append(utt2dur[utt]) ...
class MyNanoLoadStateDict(TorchNano): def train(self, lr): dataset = TensorDataset(torch.tensor([[0.0], [0.0], [1.0], [1.0]]), torch.tensor([[0.0], [0.0], [0.0], [0.0]])) train_loader = DataLoader(dataset=dataset, batch_size=2, shuffle=False) loss_func = nn.MSELoss() origin_model = L...
def consume_token(token, line): if (token != line.split(None, 1)[0]): logger.error("Unexpected token, expected '{0}', got '{1}'.".format(token, line.split(None, 1)[0])) return line.partition(token)[2]
class answer_json(): def __init__(self): self.answers = [] def add(self, ques_id, ans): res = {'question_id': ques_id, 'answer': ans} self.answers.append(res)
class DogGenHillclimberParts(): model: doggen.DogGen scorer: opt_utils.PropertyEvaluator reactant_vocab_set: typing.Set[str] rng: np.random.RandomState dataloader_factory: typing.Callable prepare_batch: typing.Callable loss_fn: typing.Callable device: typing.Union[(str, torch.device)]
def actor_loss(imag_states, actions, av_actions, old_policy, advantage, actor, ent_weight): (_, new_policy) = actor(imag_states) if (av_actions is not None): new_policy[(av_actions == 0)] = (- .0) actions = actions.argmax((- 1), keepdim=True) rho = (F.log_softmax(new_policy, dim=(- 1)).gather(2,...
def reduce_timeout_pending_node_resource(node: Node): now = time.time() if (node.is_released or (not node.create_time) or (node.config_resource.gpu_num > 0)): return False pending_time = (now - node.create_time.timestamp()) if (pending_time < _dlrover_context.seconds_to_wait_pending_pod): ...
def parse_key_info(label, anno_file): if ('===' not in label): text = clean_ocr(label) entity = (['O'] * len(text)) return (text, entity) info_ = label.split('===') assert (len(info_) >= 5), f'''Invalid anno: {label} file: {anno_file}''' assert (((len(info_) - 1) % 4) == 0), f'...
class CenterCrop3D(ImagePreprocessing3D): def __init__(self, crop_depth, crop_height, crop_width, bigdl_type='float'): super(CenterCrop3D, self).__init__(bigdl_type, crop_depth, crop_height, crop_width)
(version='2.0') def strategy_registry(cls): assert cls.__name__.endswith('TuneStrategy'), "The name of subclass of TuneStrategy should end with 'TuneStrategy' substring." if (cls.__name__[:(- len('TuneStrategy'))].lower() in EXP_STRATEGIES): raise ValueError('Cannot have two strategies with the same nam...
def get_bn(channels): if use_sync_bn: return nn.SyncBatchNorm(channels) else: return nn.BatchNorm2d(channels)
def test_linacc_changingacc_xyz_accellsrframe_scalarfuncomegaz(): lp = potential.MiyamotoNagaiPotential(normalize=1.0, a=1.0, b=0.2) dp = potential.DehnenBarPotential(omegab=1.8, rb=0.5, Af=0.03) diskpot = (lp + dp) x0 = [(lambda t: ((((- 0.03) * (t ** 2.0)) / 2.0) - (((0.03 * (t ** 3.0)) / 6.0) / 20.0)...
def perform_analysis(sent_keys, gold_sents, pred_sents, negation_sents, element='Polar_expression'): analysis_dict = {'in_neg_scope': set(), 'in_neg_scope_with_wrong_polarity': set(), 'in_neg_scope_not_predicted': set(), 'in_neg_scope_correct': set(), 'not_in_neg_scope': set(), 'not_in_neg_scope_with_wrong_polarity...
def log_prior_gaussian(z, Mu=0.0, Sigma=1.0): logprob = ((- ((0.5 * np.log((2 * np.pi))) + tf.log(Sigma))) - (0.5 * (((z - Mu) / Sigma) ** 2))) return tf.reduce_sum(logprob, 1)
def check_valid(annots: list[str]) -> bool: allowed_pattern = re.compile('^(O$|B-.+$|I-.+$)') annots = (['O'] + annots) n = len(annots) if any(((allowed_pattern.match(annot) is None) for annot in annots)): return False for i in range(1, n): annot = annots[i] if annot.startswi...
def test_slog_to_array(): (expected_vals, slogs) = _get_array_and_slog_vals() vals = helpers.array_from_slog(slogs) assert_pytree_allclose(vals, expected_vals)
def get_vocab(vocab_root_path, text_min_count): with open(os.path.join(vocab_root_path, 'vocab_new', (('vocab-' + str(text_min_count)) + '.txt'))) as f: print('geting vocab') vocab = f.read() vocab = vocab.split('\n') print('the length of vocab is: ', len(vocab)) return vocab
def set_quantizer(name, mod, quantizer, k, v): quantizer_mod = getattr(mod, quantizer, None) if (quantizer_mod is not None): assert hasattr(quantizer_mod, k) setattr(quantizer_mod, k, v) else: logger.warning(f'{name} has no {quantizer}')
def eval(): with tf.Graph().as_default() as g: noise = tf.random.normal(mean=0.0, stddev=1.0, shape=(50, NOISE_DIM)) step = tf.train.get_or_create_global_step() with tf.variable_scope('Generator'): one_hot = tf.one_hot(tf.concat(([tf.range(0, 10)] * 5), axis=0), 10) f...
class MyDataParallel(torch_geometric.nn.DataParallel): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __getattr__(self, name): if (name == 'module'): return self._modules['module'] else: return getattr(self.module, name)
class DataTrainingArguments(): data_dir: Optional[str] = field(default=None, metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'}) use_tfds: Optional[bool] = field(default=True, metadata={'help': 'If TFDS should be used or not.'}) max_seq_length: int = field(default=12...
def subsample_indices(indices: List[int], n: int, split_seed=0): if (n > len(indices)): print('Warning: n == {} > len(indices) == {}'.format(n, len(indices))) state = np.random.RandomState(split_seed) indices = state.permutation(indices) return sorted(indices[:n].tolist())
def create_path_model(context, model_params, ds_train, path_output, train_onehotencoder): path_model = Path(path_output, context[ConfigKW.MODEL_NAME]) if (not path_model.is_dir()): logger.info(f'Creating model directory: {path_model}') path_model.mkdir(parents=True) if ((ModelParamsKW.FI...
def test_mnist(): BNN_ROOT_DIR = os.path.dirname(os.path.realpath(__file__)) test_image_mnist = os.path.join(BNN_ROOT_DIR, 'Test_image', '3.image-idx3-ubyte') classifier = bnn.LfcClassifier(bnn.NETWORK_LFCW1A1, 'mnist', bnn.RUNTIME_HW) out = classifier.classify_mnist(test_image_mnist) print('Inferre...
def allocate(lengths: np.ndarray, numseqs: np.ndarray, lengths_cumsum: np.ndarray, rank: int, c: int, n: int): s = 0 start_index = 0 result = [] result_totseqs = [] while True: l = 1 r = (1 + np.searchsorted(lengths_cumsum[start_index:], (s + (c * n)), 'right')) while ((r - l...
def func_io(file_name, param, out_type): print(' output interaction = ', file_name) num_param = len(np.nonzero(param)[0]) f = open(file_name, 'wt') f.write(('' + '\n')) f.write((('num ' + '{0:8d}'.format(num_param)) + '\n')) f.write(('' + '\n')) f.write(('' + '\n')) f.write(('' + '\n'))...
_module() class Mask2FormerHead(MaskFormerHead): def __init__(self, in_channels, feat_channels, out_channels, num_things_classes=80, num_stuff_classes=53, num_queries=100, num_transformer_feat_level=3, pixel_decoder=None, enforce_decoder_input_project=False, transformer_decoder=None, positional_encoding=None, loss_...
def scan_reform(data): xy = [] for row in data: sentences = row['sentence_span'] i = (- 1) for s in sentences: i += 1 if (len(s[0]) != 0): xy.append({'sentence_span': s[0], 'y': s[1], 'token_ev_labels': row['token_ev_labels'][i]}) return xy
class ModelFedCon_noheader(nn.Module): def __init__(self, base_model, out_dim, n_classes, net_configs=None): super(ModelFedCon_noheader, self).__init__() if (base_model == 'resnet18'): basemodel = models.resnet18(pretrained=False) self.features = nn.Sequential(*list(basemodel...
def create_optimizer(args, model, filter_bias_and_bn=True): opt_lower = args.opt.lower() weight_decay = args.weight_decay if (('adamw' in opt_lower) or ('radam' in opt_lower)): weight_decay /= args.lr if (weight_decay and filter_bias_and_bn): parameters = add_weight_decay(model, weight_d...
class ResClassifier(nn.Module): def __init__(self, class_num=12, extract=False, dropout_p=0.5): super(ResClassifier, self).__init__() self.fc1 = nn.Sequential(nn.Linear(2048, 1000), nn.BatchNorm1d(1000, affine=True), nn.ReLU(inplace=True), nn.Dropout(p=dropout_p)) self.fc2 = nn.Linear(1000, ...
class DQNModel(nn.Module): def __init__(self, num_outputs): super().__init__() def init_weights(m): if (type(m) == nn.Linear): nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0) self.trunk = nn.Sequential(nn.Conv2d(6, 32, 8, stride=4), nn.ReLU(...
def _test_exact_gpr(config: ConfigDense, model: GPR, Xnew: tf.Tensor) -> tf.Tensor: (X, y) = model.data Kyy = model.kernel(X, full_cov=True) Kyy = tf.linalg.set_diag(Kyy, (tf.linalg.diag_part(Kyy) + model.likelihood.variance)) Lyy = tf.linalg.cholesky(Kyy) count = 0 L_joint = None samples = ...
def resnet152(pretrained=False): model = ResNet(Bottleneck, [3, 8, 36, 3]) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
class TrainingSummary(): model_name: str language: Optional[Union[(str, List[str])]] = None license: Optional[str] = None tags: Optional[Union[(str, List[str])]] = None finetuned_from: Optional[str] = None tasks: Optional[Union[(str, List[str])]] = None dataset: Optional[Union[(str, List[str...
def adaptive_clip_grad(parameters, clip_factor=0.01, eps=0.001, norm_type=2.0): if isinstance(parameters, torch.Tensor): parameters = [parameters] for p in parameters: if (p.grad is None): continue p_data = p.detach() g_data = p.grad.detach() max_norm = unitwi...
class RoIPointPool3dFunction(Function): def forward(ctx, points, point_features, boxes3d, pool_extra_width, num_sampled_points=512): assert ((points.shape.__len__() == 3) and (points.shape[2] == 3)) (batch_size, boxes_num, feature_len) = (points.shape[0], boxes3d.shape[1], point_features.shape[2]) ...
def get_batch_indices(array, batch_size): indices = [0] s = 0 for (i, v) in enumerate(array): s += v.item() if (s > batch_size): indices.append(i) s = v.item() indices.append(len(array)) return indices
class PrecisionRecallCurve(PytorchMetric): def __init__(self): import torchmetrics self.internal_curve = torchmetrics.PrecisionRecallCurve() def __call__(self, preds, targets): self.internal_curve.update(preds, targets.to(torch.int64)) def compute(self): return self.internal_...
def temporal_padding(x, padding=(1, 1)): assert (len(padding) == 2) pattern = [[0, 0], [padding[0], padding[1]], [0, 0]] return tf.pad(x, pattern)
class GeneralTask(AbstractTask): def __init__(self, task, config, prompt, seed=42): self.task = task self.name = task self.config = config self.seed = seed self.prompt = prompt print('') print(self.task) print() print(self.config) print...
def CleanseComments(line): commentpos = line.find('//') if ((commentpos != (- 1)) and (not IsCppString(line[:commentpos]))): line = line[:commentpos].rstrip() return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
class AdamW(Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-06, weight_decay=0.0, correct_bias=True): if (lr < 0.0): raise ValueError('Invalid learning rate: {} - should be >= 0.0'.format(lr)) if (not (0.0 <= betas[0] < 1.0)): raise ValueError('Inv...
_module() class DAFormerHead(BaseDecodeHead): def __init__(self, **kwargs): super(DAFormerHead, self).__init__(input_transform='multiple_select', **kwargs) assert (not self.align_corners) decoder_params = kwargs['decoder_params'] embed_dims = decoder_params['embed_dims'] if i...
class TemporalDataset(BaseDataset): def initialize(self, opt): assert (opt.dataset == 'cityscapes') self.opt = opt self.height = int((opt.loadSize / 2.0)) self.width = opt.loadSize self.isTrain = opt.isTrain self.static = opt.static if (opt.isTrain == True): ...
class DPRReaderState(DPRState): def load_dpr_model(self): model = DPRReader(DPRConfig(**BertConfig.get_config_dict('bert-base-uncased')[0])) print(f'Loading DPR reader from {self.src_file}') saved_state = load_states_from_checkpoint(self.src_file) state_dict = {'encoder.bert_model.em...
def logs2pil(logs, keys=['sample']): imgs = dict() for k in logs: try: if (len(logs[k].shape) == 4): img = custom_to_pil(logs[k][(0, ...)]) elif (len(logs[k].shape) == 3): img = custom_to_pil(logs[k]) else: print(f'Unkno...
class PyPrint(PyStatement): def __init__(self, arg): self.arg = arg def __repr__(self): if isinstance(self.arg, PyStrAppend): try: if (self.arg.left.name == VAR_OUT): return ('print %s' % str(self.arg.right)) elif (self.arg.right.na...
class SelectAdaptivePool2d(nn.Module): def __init__(self, output_size=1, pool_type='avg', flatten=False): super(SelectAdaptivePool2d, self).__init__() self.output_size = output_size self.pool_type = pool_type self.flatten = flatten if (pool_type == 'avgmax'): self...
def compute_ard_masks(module, *, prefix='', **kwargs): if (not isinstance(module, torch.nn.Module)): return {} relevance = named_relevance(module, prefix=prefix, **kwargs) return {((name + ('.' if name else '')) + 'mask'): mask for (name, mask) in relevance}
def saveToFile(images_processed, results, outFile): f = open(outFile, 'a') if (results[0][0] == (- 1)): for i in range(len(images_processed)): f.write('{} {}\n'.format(images_processed[i], results[i][1])) else: for i in range(len(images_processed)): f.write('{} {} {}\...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--dataset', default='TaoBao', type=str, help='Dataset to use') parser.add_argument('--seed', default=2022, type=int, help='seed for experiment') parser.add_argument('--embed_size', default=32, type=int, help='embedding size for al...
def test_copy(): cfg_file = osp.join(data_path, 'config/n.py') cfg = Config.fromfile(cfg_file) new_cfg = copy.copy(cfg) assert isinstance(new_cfg, Config) assert (new_cfg is not cfg) assert (new_cfg._cfg_dict is cfg._cfg_dict) assert (new_cfg._filename == cfg._filename) assert (new_cfg._...
_torch class TransfoXLModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = ((TransfoXLModel, TransfoXLLMHeadModel) if is_torch_available() else ()) all_generative_model_classes = ((TransfoXLLMHeadModel,) if is_torch_available() else ()) test_pruning = False test_torchscript = False te...
class TFOptimization(): def __init__(self, model: PreTrainedModel, args, train_dataset=None, eval_dataset=None, compute_metrics: Optional[Callable]=None, criterion=None, optimizer=None, task_type=None, task_id=None, strategy=None): self.model = model self.teacher_model = None self.component ...
def parse_fast(line, grammar, grammar_len, sparse_matches=False): matches = None if sparse_matches: matches = list() else: matches = [0 for x in range(grammar_len)] for line_index in range(len(line)): unit = line[line_index] candidates = _get_candidates(unit, grammar) ...
def squareform(tensor): assert isinstance(tensor, tf.Tensor), 'tensor_utils.squareform: Input must be a `tensorflow.Tensor` instance.' tensor_shape = tensor.shape.as_list() n_elements = tensor_shape[0] if _is_vector(tensor): if (n_elements == 0): return tf.zeros((1, 1), dtype=tensor....
def SkipConnectFastGRUCell(input, hidden, hidden_skip, w_ih, w_hh, b_ih=None, b_hh=None, noise_in=None, noise_hidden=None): if (noise_in is not None): input = (input * noise_in) hx = torch.cat([hidden, hidden_skip], dim=1) if (noise_hidden is not None): hx = (hx * noise_hidden) gi = F.li...
def test_quad_double_track(vrblvl=0): mickey = ['x^2 + 4*y^2 - 4;', '2*y^2 - x;'] (start, startsols) = total_degree_start_system(mickey, vrblvl=vrblvl) print('the start system :') for pol in start: print(pol) print('the start solutions :') for (idx, sol) in enumerate(startsols): ...
class BatchTensorToVars(object): def __init__(self, use_cuda=True): self.use_cuda = use_cuda def __call__(self, batch): batch_var = {} for (key, value) in batch.items(): if (isinstance(value, torch.Tensor) and (not self.use_cuda)): batch_var[key] = Variable(va...
class __DisplMixin(): def displ_item(self, index): (sample, ann) = (self.__getitem__(index), self.annotation[index]) return OrderedDict({'file_L': ann['images'][0], 'file_R': ann['images'][1], 'sentence': ann['sentence'], 'label': ann['label'], 'image': [sample['image0'], sample['image1']]})
class ExportForecastingPipeline(nn.Module): def __init__(self, preprocess: nn.Module, inference: nn.Module, postprocess: nn.Module) -> None: super().__init__() self.preprocess = preprocess self.inference = inference self.postprocess = postprocess def forward(self, data): ...
class nnUNetTrainerV2_Loss_TopK10(nnUNetTrainerV2): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_...
class StructuralDataset(GraphDataset): def __init__(self, distance_matrix_key='distance_matrix', feature_matrix_key='feature_matrix', **kwargs): super().__init__(**kwargs) self.distance_matrix_key = distance_matrix_key self.feature_matrix_key = feature_matrix_key def __getitem__(self, in...
_registry(operator_type='Where') class Where(Operator): def __init__(self): super().__init__() def set_attr(self, framework, node): if (framework == 'torch'): if (type(node.inputsAt(2).toIValue()) == float): self._attr['mask_value'] = node.inputsAt(2).toIValue() ...
def compute_cov_a(a, classname, layer_info, fast_cnn): batch_size = a.size(0) if (classname == 'Conv2d'): if fast_cnn: a = _extract_patches(a, *layer_info) a = a.view(a.size(0), (- 1), a.size((- 1))) a = a.mean(1) else: a = _extract_patches(a, *lay...
class CaffeEltWiseLayer(CaffeLayerGenerator): def __init__(self, name, operation): super(CaffeEltWiseLayer, self).__init__(name, 'Eltwise') self.operation = operation def write(self, f): param_str = '\n bottom: "{}"\n eltwise_param{{\n operation: {}\n }}'.format(self.bottom[1], sel...
def auto_tune(input_graph_path, batch_size): dataset = Dataset() dataloader = DataLoader(framework='tensorflow', dataset=dataset, batch_size=batch_size) tuning_criterion = TuningCriterion(max_trials=100) config = PostTrainingQuantConfig(approach='static', tuning_criterion=tuning_criterion, accuracy_crit...
class Base(torch.nn.Module): def __init__(self): super().__init__() def _set_child_attribute(self, attr, value): if hasattr(self, attr): setattr(self, attr, value) for module in self.modules(): if hasattr(module, attr): setattr(module, attr, value)...
_torch class PipelineTesterMixin(): required_optional_params = frozenset(['num_inference_steps', 'num_images_per_prompt', 'generator', 'latents', 'output_type', 'return_dict']) test_attention_slicing = True test_xformers_attention = True def get_generator(self, seed): device = (torch_device if (...
def run_network_check(config, entrypoint): cmd_args = ['-m', 'dlrover.trainer.torch.run_network_check'] for _ in range(2): success = network_check(config=config, entrypoint=entrypoint, args=cmd_args) if success: logger.info('Network check pass.') return success el...
def get_feature_importance(RBM, data, weights=None, Nchains=500, Nthermalize=1000, Nstep=10, Lchains=100, init='data'): if (init == 'data'): h = RBM.mean_hiddens(data) initial_points = data[KMPP_choose_centroids(h, Nchains)] else: initial_points = [] (data_gen, _) = RBM.gen_data(Nthe...