code
stringlengths
101
5.91M
def resnet101_mpncov_160(pretrained=False, progress=True, **kwargs): return _resnet_mpncov_160('resnet101_mpncov_160', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
class decoder(nn.Module): def __init__(self, in_channel=1, out_channel=10): super(decoder, self).__init__() self.fc3 = nn.Linear(16, 256) self.fc4 = nn.Linear(256, 8192) self.deconv1 = nn.Sequential(nn.ConvTranspose2d(32, 32, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(32), n...
class QuantizableResNet(ResNet): def __init__(self, *args, **kwargs): super(QuantizableResNet, self).__init__(*args, **kwargs) self.quant = torch.quantization.QuantStub() self.dequant = torch.quantization.DeQuantStub() def forward(self, x): x = self.quant(x) x = self._for...
class BeatIntervalOption(CommandLineOption): arg = 'BEAT_INTERVAL' arg_description = 'Time between two heartbeat events measured in seconds.' def apply(cls, args, run): run.beat_interval = float(args)
class RelationType(): def __init__(self, labels, index, short_name, verbose_name): self._labels = labels self._index = index self._short_name = short_name self._verbose_name = verbose_name def identifiers(self): return self._labels[0].identifier def index(self): ...
class DataProcessor(object): def get_src_train_examples(self, data_dir): return self._create_examples(self._read_pkl(os.path.join(data_dir, 'en_conll_train.pkl')), 'conll_train') def get_src_dev_examples(self, data_dir): return self._create_examples(self._read_pkl(os.path.join(data_dir, 'en_conl...
class Audio2Mel(torch.nn.Module): def __init__(self, hop_length, sampling_rate, n_mel_channels, win_length=1024, n_fft=None, mel_fmin=0.0, mel_fmax=None): super().__init__() n_fft = (win_length if (n_fft is None) else n_fft) window = torch.hann_window(win_length).float() mel_basis = ...
class TranslateY(object): def __init__(self, fillcolor=(128, 128, 128)): self.fillcolor = fillcolor def __call__(self, x, magnitude): return x.transform(x.size, Image.AFFINE, (1, 0, 0, 0, 1, ((magnitude * x.size[1]) * random.choice([(- 1), 1]))), fillcolor=self.fillcolor)
class Cell(nn.Module): def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev): super(Cell, self).__init__() if reduction_prev: self.preprocess0 = FactorizedReduce(C_prev_prev, C) else: self.preprocess0 = ReLUConvBN(C_prev_prev, C, 1, 1, 0) ...
_end_docstrings(PIPELINE_INIT_ARGS, '\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `"default"`):\n The function to apply to the mode...
class SSLS4L(ssl_base._SSLBase): NAME = 'ssl_s4l' SUPPORTED_TASK_TYPES = [REGRESSION, CLASSIFICATION] def __init__(self, args): super(SSLS4L, self).__init__(args) self.task_model = None self.rotation_classifier = None self.model = None self.optimizer = None se...
def time_llvm_rthroughput(arch, verbose, code): output = time_llvm_base(arch, verbose, code) total_cycles_line = output.split('\n')[11] cycles = total_cycles_line.split()[2] return (float(cycles) * 100)
def separate2midi(midi_instruments, out_path, ticks_per_beat=TICKS_PER_BEAT, tempo=TEMPO, check_out_of_range_notes=False): midi = miditoolkit.midi.parser.MidiFile() midi.ticks_per_beat = ticks_per_beat midi.tempo_changes.append(miditoolkit.TempoChange(tempo=tempo, time=0)) for (ch, midi_instrument) in e...
def load_dart(split): assert (split in SPLITS) with open((data_dir / f'{prefix}-full-{split}.json')) as f: return json.load(f)
class PythonMsg(): def __setattr__(self, key, value): if (not hasattr(self, key)): raise TypeError(('Cannot add new field "%s" to frozen class %s' % (key, self))) else: object.__setattr__(self, key, value) def print(self, depth=0, name=None): print_str = '' ...
class Logger(): def __init__(self, ckpt_path, name='train'): self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(message)s', datefmt=blue('[%Y-%m-%d,%H:%M:%S]')) fh = logging.FileHandler(os.path.join(ckpt_path, '{}.log'.fo...
_metaclass(abc.ABCMeta) class BaseDataTest(tf.test.TestCase): def setUp(self, data_wrapper, num_classes, expected_num_samples, required_tensors_shapes, default_label_key='label'): super(BaseDataTest, self).setUp() self.data_wrapper = data_wrapper self.expected_num_samples = expected_num_samp...
class Founta2018(dataset.Dataset): name = 'founta2018' url = ' hash = '35f19a5746eac9be27cd635a09b9ceddf10d84fb140cacef' files = [{'name': 'founta2018en.csv', 'language': 'en', 'type': 'training', 'platform': 'twitter'}] comment = ' ' license = 'UNKNOWN' def process(cls, tmp_file_path, datas...
def make_ik_env(): env = Swift() env.launch(realtime=True, browser='notebook') env.add(panda) env.add(ee_axes) env.add(goal_axes) return env
class LTAE(nn.Module): def __init__(self, in_channels=128, n_head=16, d_k=8, n_neurons=[256, 128], dropout=0.2, d_model=256, T=1000, max_temporal_shift=100, max_position=365): super(LTAE, self).__init__() self.in_channels = in_channels self.n_neurons = copy.deepcopy(n_neurons) self.m...
class BouncingBallExample(nn.Module): def __init__(self, radius=0.2, gravity=9.8, adjoint=False): super().__init__() self.gravity = nn.Parameter(torch.as_tensor([gravity])) self.log_radius = nn.Parameter(torch.log(torch.as_tensor([radius]))) self.t0 = nn.Parameter(torch.tensor([0.0])...
def make_follower(args, vocab): enc_hidden_size = ((hidden_size // 2) if args.bidirectional else hidden_size) glove_path = osp.join(file_path, 'data', 'train_glove.npy') glove = (np.load(glove_path) if args.use_glove else None) if (args.useObjLabelOrVis == 'none'): (feature_size, action_embeddin...
_module() class WrapFieldsToLists(): def __call__(self, results): for (key, val) in results.items(): results[key] = [val] return results def __repr__(self): return f'{self.__class__.__name__}()'
def test_main(capsys): main(['7']) captured = capsys.readouterr() assert ('The 7-th Fibonacci number is 13' in captured.out)
class Small_CNN(nn.Module): def __init__(self, hidden_size=20000): super(Small_CNN, self).__init__() self.cnn = nn.Sequential(nn.Conv2d(3, 32, 3, padding=1), nn.ReLU(), nn.Conv2d(32, 32, 3, padding=1, stride=2), nn.ReLU(), nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.Conv2d(64, 64, 3, padding=1, s...
def config_parallelisation(config, igpu, ngpus): if (ngpus < 2): pass elif (ngpus >= 2): config_list = list(ParameterGrid(param_grid=config)) config = [config_list[i] for i in list(range(igpu, len(config_list), ngpus))] return config
class NCPruner(WeightPruner): def __init__(self, args, model, teacher, train_loader, test_loader): super(NCPruner, self).__init__(args, model, teacher, train_loader, test_loader) def prune_record(self, log): print(log) self.logger.write((log + '\n')) def init_prune(self): rat...
def get_etypes(annots: list[str]) -> list[(None | str)]: return [(annot[2:] if (annot != 'O') else None) for annot in annots]
def diapreresnet164bn_cifar10(num_classes=10, **kwargs): return get_diapreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name='diapreresnet164bn_cifar10', **kwargs)
def find_2d_configuration(): cudnn.deterministic = False cudnn.benchmark = True patch_size = (512, 512) max_num_features = 512 num_modalities = 1 num_classes = 3 batch_size = 12 blocks_per_stage_encoder = FabiansUNet.default_blocks_per_stage_encoder blocks_per_stage_decoder = Fabians...
def load_data(args): train_dataset = depthDataset(csv_file=os.path.join(args.data_dir, 'nyu2_train.csv'), transform=transforms.Compose([Scale(240), CenterCrop([304, 228], [304, 228]), ToTensor(is_test=False)])) train_dataloader = DataLoader(train_dataset, 256, shuffle=False, num_workers=16, pin_memory=False) ...
_start_docstrings(VISION_TEXT_DUAL_ENCODER_START_DOCSTRING) class TFVisionTextDualEncoderModel(TFPreTrainedModel): config_class = VisionTextDualEncoderConfig base_model_prefix = 'vision_text_dual_encoder' load_weight_prefix = 'tf_vision_text_dual_encoder_model' def __init__(self, config: Optional[Vision...
class BaseTrainer(): def __init__(self, config, model, train_loader, test_loader=None, device=None): self.config = config self.metric_criterion = 'abs_rel' if (device is None): device = (torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')) self.devi...
class Net(nn.Module): def __init__(self, in_count, out_count): super(Net, self).__init__() self.fc1 = nn.Linear(in_count, 50) self.fc2 = nn.Linear(50, 25) self.fc3 = nn.Linear(25, out_count) self.softmax = nn.Softmax(dim=1) def forward(self, x): x = F.relu(self.fc...
def side_branch(x, nc, factor, initializer=tf.random_normal_initializer(0, 0.02), kernel_regularizer=tf.contrib.layers.l2_regularizer(0.0001), bias_regularizer=tf.contrib.layers.l2_regularizer(0.0001)): y = tf.layers.conv2d(x, nc, kernel_size=1, strides=(1, 1), padding='same', kernel_initializer=initializer, kernel...
def row_to_dict(schema, row): row_dict = {} for (k, field) in schema.items(): if (field.feature_type == FeatureType.IMAGE): row_dict[k] = row[k] elif (field.feature_type == FeatureType.NDARRAY): row_dict[k] = decode_ndarray(row[k]) else: row_dict[k] = ...
def taskonomy_features_transform_collated(task_path, encoder_type='taskonomy', dtype=np.float32): _rescale_thunk = rescale_centercrop_resize((3, 256, 256)) _pixels_as_state_thunk = pixels_as_state((8, 16, 16)) if ((task_path != 'pixels_as_state') and (task_path != 'blind')): if (encoder_type == 'tas...
def robosuite_action_adjustment(robosuite_env, verbose=False): if verbose: action_space = robosuite_env.action_space high = action_space.high same_high = np.all((high == high[0])) low = action_space.low same_low = np.all((low == low[0])) shape = action_space.shape[0] ...
class MSSSIM(torch.nn.Module): def __init__(self, window_size=11, size_average=True, channel=3): super(MSSSIM, self).__init__() self.window_size = window_size self.size_average = size_average self.channel = channel def forward(self, img1, img2): return msssim(img1, img2, ...
def test_statcast_batter_exitvelo_barrels() -> None: min_bbe = 250 result: pd.DataFrame = statcast_batter_exitvelo_barrels(2019, min_bbe) assert (result is not None) assert (not result.empty) assert (len(result.columns) == 18) assert (len(result) > 0) assert (len(result[(result['attempts'] <...
class Exp(MyExp): def __init__(self): super(Exp, self).__init__() self.num_classes = 1 self.depth = 1.33 self.width = 1.25 self.exp_name = os.path.split(os.path.realpath(__file__))[1].split('.')[0] self.train_ann = 'train.json' self.val_ann = 'val_half.json' ...
def construct_exp_name(arg_dict: dict): focus_item = OrderedDict({'input_size': 's', 'batch_size': 'bs', 'epoch_num': 'e', 'warmup_epoch': 'we', 'use_amp': 'amp', 'lr': 'lr', 'lr_type': 'lt', 'optim': 'ot', 'use_aux_loss': 'al', 'use_bigt': 'bi', 'size_list': 'ms', 'info': 'info'}) exp_name = f"{arg_dict['model...
def bleu(refs, candidate, ground=0, smooth=1): refs = cook_refs(refs) test = cook_test(candidate, refs) return score_cooked([test], ground=ground, smooth=smooth)
def trans_conv(dim=2): if (dim == 2): return nn.ConvTranspose2d return nn.ConvTranspose3d
def inquire_confirm(msg): return prompt([{'type': 'confirm', 'message': (msg + ' Confirm?'), 'name': 'confirm', 'default': True}], style=custom_style_2)['confirm']
def pretrain(): T = Trainer() T.task = 'debug' T.note = f'debug' T.batch = 64 T.epochs = 800 T.warmup_epochs = 40 T.input_size = 224 T.accum_iter = 16 T.device = '0,1,2,3' T.dataset = 'ImageNet-LT' T.model = f'mae_vit_base_patch16' T.mask_ratio = 0.75 T.blr = 0.00015 ...
def train(data, datadir, model, num_cls, outdir='', num_epoch=100, batch=128, lr=0.0001, betas=(0.9, 0.999), weight_decay=0): if torch.cuda.is_available(): kwargs = {'num_workers': 1, 'pin_memory': True} else: kwargs = {} net = get_model(model, num_cls=num_cls) print('-------Training net...
def texture(tex, uv, uv_da=None, filter_mode='auto', boundary_mode='wrap', tex_const=False, max_mip_level=None): assert ((tex_const is True) or (tex_const is False)) if (filter_mode == 'auto'): filter_mode = ('linear-mipmap-linear' if (uv_da is not None) else 'linear') tex_const = (tex_const or _is_...
_sentencepiece class M2M100TokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = M2M100Tokenizer test_rust_tokenizer = False test_seq2seq = False test_sentencepiece = True def setUp(self): super().setUp() vocab = ['</s>', '<unk>', 'This', 'is', 'a', 't', 'est',...
class _Open3DArgumentParser(argparse.ArgumentParser): def error(self, message): print(f'''Error: {message} ''', file=sys.stderr) self.exit(2)
def _get_filenames_with_labels(mode, data_dir, split_dir): if (mode == 'train'): scenario_list_file = os.path.join(split_dir, 'train.txt') elif (mode == 'eval'): scenario_list_file = os.path.join(split_dir, 'eval.txt') elif (mode == 'test'): scenario_list_file = os.path.join(split_di...
def loss_ISD(x, y): y = (y + 1e-10) ret = torch.sum((((x / y) - torch.log((x / y))) - 1)) return ret
def assert_dict_equal(source, target): assert (len(target) == len(source)) for (k, v) in target.items(): assert (v == source[k])
def pixel_deflection_without_map(img, deflections, window): img = np.copy(img) (H, W, C) = img.shape while (deflections > 0): for c in range(C): (x, y) = (randint(0, (H - 1)), randint(0, (W - 1))) while True: (a, b) = (randint(((- 1) * window), window), randin...
_module() class SingleStageInstanceSegmentor(BaseDetector): def __init__(self, backbone: ConfigType, neck: OptConfigType=None, bbox_head: OptConfigType=None, mask_head: OptConfigType=None, train_cfg: OptConfigType=None, test_cfg: OptConfigType=None, data_preprocessor: OptConfigType=None, init_cfg: OptMultiConfig=No...
class Upsampling(nn.Module): def __init__(self, n_filters_in, n_filters_out, stride=2, normalization='none'): super(Upsampling, self).__init__() ops = [] ops.append(nn.Upsample(scale_factor=stride, mode='trilinear', align_corners=False)) ops.append(nn.Conv3d(n_filters_in, n_filters_o...
class FWMRNN(nn.Module): def __init__(self, isize, hsize, withFWM, params, wdrop=0.5): super().__init__() s_size = params['s_size'] r_size = params['r_size'] t_size = params['t_size'] self.rnn = nn.LSTM(isize, hsize, 1, dropout=0) if withFWM: self.fwm = FW...
def getList(): btenvs = [('- ' + spec.id) for spec in gym.envs.registry.all() if (spec.id.find('Bullet') >= 0)] return btenvs
def as_tensor(data, dtype=None): if isinstance(data, torch.Tensor): if ((dtype is None) or (data.dtype == dtype)): return data return data.type(dtype=dtype) return torch.as_tensor(data, dtype=dtype)
class TestWeightSharingAcc(unittest.TestCase): def setUpClass(self): self.skipTest(self, 'currently not support Unit Test for dispatcher, but this function is supported. Will improve Unit Test very soon.') code = '\nimport time\nimport math\nimport os\nimport sys\nimport numpy as np\nfrom transforme...
class LinearClassifier(nn.Module): def __init__(self, name='cnn6', num_classes=4, device='cpu'): super(LinearClassifier, self).__init__() (_, feat_dim) = model_dict[name] self.fc = nn.Linear(feat_dim, num_classes).to(device) def forward(self, features): return self.fc(features)
class TestClipGradNorm(unittest.TestCase): (((not torch.cuda.is_available()) or (torch.cuda.device_count() < 2)), 'No gpu available for cuda tests') def test_fsdp_strategy_clip_grad_norm(self): world_size = 2 mp.spawn(_fsdp_strategy_clip_grad_norm, args=(world_size, find_free_port()), nprocs=wor...
_experiment def categorical_cnn_policy(ctxt, env_id, seed): deterministic.set_seed(seed) with LocalTFRunner(ctxt, max_cpus=12) as runner: env = GarageEnv(normalize(gym.make(env_id))) policy = CategoricalCNNPolicy(env_spec=env.spec, conv_filters=hyper_params['conv_filters'], conv_strides=hyper_pa...
def convert(path): tg = textgrid.TextGrid.fromFile(path) word_time = [tg[0][j].maxTime for j in range(len(tg[0]))] word_text = [tg[0][j].mark for j in range(len(tg[0]))] word_time = ','.join(map(str, word_time)) word_text = ','.join(word_text) return (word_time, word_text)
class TestGroupedBatchSampler(unittest.TestCase): def test_missing_group_id(self): sampler = SequentialSampler(list(range(100))) group_ids = ([1] * 100) s = GroupedBatchSampler(sampler, group_ids, 2) for k in s: self.assertEqual(len(k), 2) def test_groups(self): ...
class OrderedEasyDict(OrderedDict): def __init__(self, d=None, **kwargs): super(OrderedEasyDict, self).__init__() if (d is None): d = OrderedDict() if kwargs: d.update(**kwargs) for (k, v) in d.items(): setattr(self, k, v) for k in self.__c...
def gather_targets(roots, col_sent): targets = [] exp_root_idxs = dict([(token.id, {}) for token in roots]) for token in col_sent: if (len(token.scope) > 0): for (idx, label) in token.scope: if ((idx in exp_root_idxs) and ('targ' in label)): exp_root_i...
class Graphviz(object): def __init__(self): self.internal_color = 'lavenderblush4' self.colors = ['aquamarine', 'bisque', 'blue', 'blueviolet', 'brown', 'cadetblue', 'chartreuse', 'coral', 'cornflowerblue', 'crimson', 'darkgoldenrod', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkorange', 'darkred',...
_param('conf', param_alias='config') def fit(model, conf, eval_func=None, eval_dataloader=None, eval_metric=None, **kwargs): if (eval_dataloader is not None): check_dataloader(eval_dataloader) if (conf.precisions in conf.excluded_precisions): logger.warning('Target precision is in excluded_preci...
def load_fields_from_vocab(vocab, data_type='text'): vocab = dict(vocab) n_src_features = len(collect_features(vocab, 'src')) n_qa_features = len(collect_features(vocab, 'qa')) n_tgt_features = len(collect_features(vocab, 'tgt')) fields = get_fields(n_src_features, n_qa_features, n_tgt_features, dat...
def test_double_solve(vrblvl=0): polynomials = ['x^3 + 2*x*y - x^2;', 'x + y - x^3;'] set_double_system(2, polynomials, vrblvl) (nbr, roco) = solve_double_system(vrblvl) if (vrblvl > 0): print('number of solutions :', nbr) print('root counts :\n', roco) write_double_solutions(vrb...
def test_ignore_main(): from unittest.mock import Mock (name, type) = ('test', 'loss') Mock.__module__ = '__main__' with pytest.warns(UserWarning): _ = register(name, type)(Mock) assert (name not in LOSS_REG), 'Class from `__main__` not ignored.'
class OntoNotesNERProcessor(Processor): def __init__(self, label_list=None, path=None, padding=None, unknown=None, bert_model='bert-base-cased', max_length=256): super().__init__(label_list, path, padding=padding, unknown=unknown, bert_model=bert_model, max_length=max_length) def process(self, dataset):...
class Evaluator(): default_metrics = ['False Positive Rate', 'Dice', 'Jaccard', 'Precision', 'Recall', 'Accuracy', 'False Omission Rate', 'Negative Predictive Value', 'False Negative Rate', 'True Negative Rate', 'False Discovery Rate', 'Total Positives Test', 'Total Positives Reference'] default_advanced_metric...
class MapIterator(CheckpointableIterator): def __init__(self, source_iterator: CheckpointableIterator, transform: Callable[([str], Any)]): if (not isinstance(source_iterator, CheckpointableIterator)): raise ValueError('source_iterator has to be a CheckpointableIterator') self._source_ite...
def main(): lvl = 10 fail = test_double_functions(lvl) fail = (fail + test_double_solution_class(lvl)) if (fail == 0): print('=> All tests passed.') else: print('Number of failed tests :', fail)
def test(args, model, dataloader, criterion): model.eval() loss_stack = [] label_stack = [] pred_stack = [] for (imgs_train, imgs_test, imgs_label, imgs_idx) in tqdm(dataloader, ncols=60): imgs_test = imgs_test.cuda() (_, pred_cls) = model(imgs_test) img_onehot_labels = torch...
def has_vowel(w): for ch in w: if (ch in VOWELS): return True return False
_model def nf_regnet_b2(pretrained=False, **kwargs): return _create_normfreenet('nf_regnet_b2', pretrained=pretrained, **kwargs)
(True, 'Failed on gpu, accl is not installed') class DistributedCudaAcclTest(unittest.TestCase): def test_init_distributed_accl(self): res = init_distributed('accl') self.assertTrue(res) self.assertEqual(world_size(), 1) self.assertEqual(rank(), 0) self.assertEqual(local_rank...
class TestMemory(unittest.TestCase): def setUp(self): return super().setUp() def tearDown(self) -> None: return super().tearDown() def test_memory(self): query = 'hello' answer = "Hello! It's nice to meet you. Is there something I can help you with or would you like to chat?"...
class Athame(BaseDagger): def __init__(self): super().__init__('athame', weight=10, damage=D.Dice.from_str('d3'), material=M.Iron, hit=2)
class GoalDirectedMotionOption(AbstractOption): def __init__(self, world, goal, pose, pose_tolerance=(0.001, 0.01), joint_velocity_tolerance=0.025, closed_loop=False, *args, **kwargs): super(GoalDirectedMotionOption, self).__init__(name='goal_directed_motion') self.goal = goal self.goal_id =...
def new_scale_plan_watcher(platform, job_name, namespace, job_uuid): logger.info('New %s NodeWatcher', platform) if (platform in (PlatformType.KUBERNETES, PlatformType.PY_KUBERNETES)): from dlrover.python.master.watcher.k8s_watcher import K8sScalePlanWatcher return K8sScalePlanWatcher(job_name, ...
def reproduc(seed, benchmark=False, deterministic=True): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.benchmark = benchmark torch.backends.cudnn.deterministic = deterministic
def image_train(dataset, resize_size=256, crop_size=224): if (dataset == 'dg5'): return transforms.Compose([transforms.Resize((32, 32)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])...
class BPEWordSplitter(object): def __init__(self, model_path): super().__init__() from subword_nmt.apply_bpe import BPE with open(model_path) as f: self.model = BPE(f) def split(self, string): return self.model.process_line(string).split() def end_idx_last_full_wo...
class StudentsTLossFunction(nn.Module): def __init__(self, num_dims, float_dtype, device, scale_lo=1e-05, scale_init=1.0): super(StudentsTLossFunction, self).__init__() if (not np.isscalar(scale_lo)): raise ValueError('`scale_lo` must be a scalar, but is of type {}'.format(type(scale_lo)...
class ChineseTextToSpeech(): def __init__(self): self.tts_executor = TTSExecutor() def text2speech(self, input, output_audio_path): self.tts_executor(text=input, output=output_audio_path, am='fastspeech2_csmsc', am_config=None, am_ckpt=None, am_stat=None, spk_id=0, phones_dict=None, tones_dict=N...
class DocDataset(Dataset): def __init__(self, docs, n_vocab, device): super(DocDataset, self).__init__() self.docs = docs self.n_vocab = n_vocab self.device = device def __getitem__(self, item): d = self.docs[item] v = np.zeros(self.n_vocab, dtype=np.float32) ...
def _lws_processor(hparams): import lws return lws.lws(hparams.n_fft, get_hop_size(hparams), fftsize=hparams.win_size, mode='speech')
class FlaxXGLMPreTrainedModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def plot_bytes_written_and_read(sys_metrics, rolling_window=10, figsize=(10, 8), title_fontsize=16, **kwargs): plt.figure(figsize=figsize) server_metrics = sys_metrics.groupby(NUM_ROUND_KEY, as_index=False).sum() rounds = server_metrics[NUM_ROUND_KEY] server_metrics = server_metrics.rolling(rolling_wind...
def get_resnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): if (blocks == 14): layers = [1, 1, 1, 1] elif (blocks == 26): layers = [2, 2, 2, 2] elif (blocks == 38): layers = [3, 3, 3, 3] elif (bl...
class SaintEncoder(nn.Module): def __init__(self, input_dim: int, n_heads: int, use_bias: bool, attn_dropout: float, ff_dropout: float, activation: str, n_feat: int): super(SaintEncoder, self).__init__() self.n_feat = n_feat self.col_attn = MultiHeadedAttention(input_dim, n_heads, use_bias, ...
def test_memoryview_from_buffer_empty_shape(): view = m.test_memoryview_from_buffer_empty_shape() assert isinstance(view, memoryview) assert (view.format == 'B') assert (bytes(view) == b'')
class PayloadModule(MsfModule): def __init__(self, rpc, payload): super(PayloadModule, self).__init__(rpc, 'payload', payload)
def _gen_mixnet_m(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs): arch_def = [['ds_r1_k3_s1_e1_c24'], ['ir_r1_k3.5.7_a1.1_p1.1_s2_e6_c32', 'ir_r1_k3_a1.1_p1.1_s1_e3_c32'], ['ir_r1_k3.5.7.9_s2_e6_c40_se0.5_nsw', 'ir_r3_k3.5_a1.1_p1.1_s1_e6_c40_se0.5_nsw'], ['ir_r1_k3.5.7_s2_e6_c80...
def resnet101(pretrained=False, att_position=[[], [], [], []], att_dim=128, **kwargs): model = ResNet(Bottleneck, [3, 4, 23, 3], att_position, att_dim, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
def simulate_from_dag_lg(tam, n_sample, mean=0, variance=1): num_nodes = len(tam) def get_value(i, e): if (values[i] == None): val = e[i] for j in range(num_nodes): if (tam[j][i] != 0.0): val += (get_value(j, e) * tam[j][i]) values[...