code
stringlengths
101
5.91M
def build_lstm_lm3(input_shape, output_size): vocab_size = output_size model = Sequential([Embedding((vocab_size + 1), 128, mask_zero=True, input_length=input_shape[0]), LSTM(650, unroll=True, return_sequences=True), Dropout(0.5), LSTM(650, unroll=True), Dropout(0.5), Dense(output_size), Activation('softmax')])...
class OpenAIGPTTokenizerFast(metaclass=DummyObject): _backends = ['tokenizers'] def __init__(self, *args, **kwargs): requires_backends(self, ['tokenizers'])
class Res16UNetSN34(Res16UNet34): NORM_TYPE = NormType.SPARSE_SWITCH_NORM BLOCK = BasicBlockSN
class AugmentationConfig(object): def __init__(self): self.color = ColorAugmentation.AGGRESSIVE self.crop = True self.distort_aspect_ratio = AspectRatioAugmentation.NORMAL self.quality = True self.erasing = True self.rotate90 = False self.rotate45 = False ...
def parse_cmdline_kwargs(args): def parse(v): assert isinstance(v, str) try: return eval(v) except (NameError, SyntaxError): return v return {k: parse(v) for (k, v) in parse_unknown_args(args).items()}
class SingleDataset(BaseDataset): def initialize(self, opt): self.opt = opt self.root = opt.dataroot self.dir_A = os.path.join(opt.dataroot) self.A_paths = make_dataset(self.dir_A) self.A_paths = sorted(self.A_paths) self.transform = get_transform(opt) def __getit...
def load_pretrained(cfg: NamespaceMap, Module: Optional[Type[pl.LightningModule]], stage: str, **kwargs) -> pl.LightningModule: save_path = Path(cfg.paths.pretrained.load) filename = BEST_CHECKPOINT.format(stage=stage) checkpoint = get_latest_match((save_path / filename)) loaded_module = Module.load_fro...
_module() class GPT4Gen(MInstrDataset): def __init__(self, *args, version, **kwargs): super().__init__(*args, **kwargs, placeholders=(IMAGE_PLACEHOLDER, QUESTION_PLACEHOLDER)) self.version = version assert (version in ['a', 'c', 'bc']) def __getitem__(self, item): raw = self.get_...
def check_target_type(y, indicate_one_vs_all=False): type_y = type_of_target(y) if (type_y == 'multilabel-indicator'): if np.any((y.sum(axis=1) > 1)): raise ValueError('Imbalanced-learn currently supports binary, multiclass and binarized encoded multiclasss targets. Multilabel and multioutpu...
class Rescaling(nn.Module): def __init__(self, bias, scaling_mat): super(Rescaling, self).__init__() self.bias = nn.Parameter(bias, requires_grad=False) self.scaling_mat = nn.Parameter(scaling_mat, requires_grad=False) def forward(self, x): output = (x - self.bias) output...
def test_digits_precomputed_two_stage(): model1 = FacilityLocationSelection(100) model2 = GraphCutSelection(100) model = MixtureSelection(100, [model1, model2], [1.0, 0.3], metric='precomputed', optimizer='two-stage') model.fit(X_digits_cosine_cupy) assert_array_equal(model.ranking, digits_cosine_ra...
class MCD(BaseDetector): def __init__(self, contamination=0.1, store_precision=True, assume_centered=False, support_fraction=None, random_state=None): super(MCD, self).__init__(contamination=contamination) self.store_precision = store_precision self.assume_centered = assume_centered ...
def main(A, t_max, M, N_max, R, exec_type, theta): print('{}-armed Bernoulli bandit with optimal, TS and sampling policies with {} MC samples for {} time-instants and {} realizations'.format(A, M, t_max, R)) dir_string = '../results/{}/A={}/t_max={}/R={}/M={}/N_max={}/theta={}'.format(os.path.basename(__file__)...
def mergeGuide(dct_lst): output_lst = list() line_prev = dct_lst[0] for line_dct in dct_lst[1:]: episode_id = int(line_dct['Episode_ID']) turn_id = int(line_dct['Turn_ID']) speaker = line_dct['Speaker'] if (episode_id == int(line_prev['Episode_ID'])): if ((speaker...
def if_skip(api): skip_list = ['tf.keras.Input', 'tf.keras.layers.Input'] if (api in skip_list): return True skip_keyword = ['initializers', 'tf.keras.applications.'] for k in skip_keyword: if (k in api): return True return False
def get_dataset(task): (X, y, _, _) = task.get_dataset().get_data(task.target_name) return (X, y)
def load_or_encode_corpus(model_args: ModelArguments, data_args: DataArguments, eval_args: EvalArguments): out_index_path = os.path.join(data_args.out_corpus_dir, 'index') out_corpus_ids_path = os.path.join(data_args.out_corpus_dir, 'corpus_ids.npy') if (os.path.exists(out_index_path) and os.path.exists(out...
def set_recursively(hf_pointer, key, value, full_name, weight_type): for attribute in key.split('.'): hf_pointer = getattr(hf_pointer, attribute) if (weight_type is not None): hf_shape = getattr(hf_pointer, weight_type).shape else: hf_shape = hf_pointer.shape if (hf_shape != valu...
def move(board: Board, action: int) -> Tuple[(Board, float)]: board = transform_board(board, action) (board, reward) = move_left(board) board = transform_board(board, action) return (board, reward)
class BertForNextSentencePrediction(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TensorFlowTransformer(object): def __init__(self, def_path, data_path, verbose=True, phase='test'): self.verbose = verbose self.phase = phase self.load(def_path, data_path, phase) self.params = None self.source = None def load(self, def_path, data_path, phase): ...
def collect_results(args): dirs = os.listdir(args.path) print('[*] ===== total {} files in TPE dir'.format(len(dirs))) count = 0 penalty_k = [] scale_lr = [] wi = [] big_sz = [] small_sz = [] ratio = [] eao = [] count = 0 for d in dirs: param_path = os.path.join(a...
class KeypointRCNNFeatureExtractor(nn.Module): def __init__(self, cfg): super(KeypointRCNNFeatureExtractor, self).__init__() resolution = cfg.MODEL.ROI_KEYPOINT_HEAD.POOLER_RESOLUTION scales = cfg.MODEL.ROI_KEYPOINT_HEAD.POOLER_SCALES sampling_ratio = cfg.MODEL.ROI_KEYPOINT_HEAD.POOL...
def get_dataset_splits(dataset): dataset_keys = ['x', 't', 'd', 'y', 'y_normalized'] train_index = dataset['metadata']['train_index'] val_index = dataset['metadata']['val_index'] test_index = dataset['metadata']['test_index'] dataset_train = dict() dataset_val = dict() dataset_test = dict() ...
def terminal_format(args): line = '' for x in args: if (len(x) == 3): line += (('{}={' + str(x[2])) + '}').format(str(x[0]), x[1]) elif (len(x) == 2): line += (('{' + str(x[1])) + '}').format(x[0]) line += ' ' return line
def _graph_network_no_node_update(graph_tuple): update_node_fn = None update_edge_fn = (lambda e, sn, rn, g: e) update_global_fn = (lambda gn, ge, g: g) net = nn.GraphNetwork(update_edge_fn, update_node_fn, update_global_fn) return net(graph_tuple)
.no_cover .timeout(40) def test_trpo_cubecrash(): env = os.environ.copy() env['GARAGE_EXAMPLE_TEST_N_EPOCHS'] = '1' assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'tf/trpo_cubecrash.py')), '--batch_size', '4'], check=False, env=env).returncode == 0)
def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('-m', '--model', dest='model', required=True, type=str, help='Path to .pt model.', metavar=imed_utils.Metavar.file) parser.add_argument('-d', '--dimension', dest='dimension', required=True, type=int, help='Input dimension (2 for 2D inp...
.parametrize('proj_head_dims', [[None, [16, 8]], [[16, 8], None], [[16, 8], [16, 8]]]) def test_projection_head_value_error(proj_head_dims): cat_embed_cols = ['col1', 'col2'] continuous_cols = ['col3', 'col4'] preprocessor = TabPreprocessor(cat_embed_cols=cat_embed_cols, continuous_cols=continuous_cols, wit...
def convert_type(function): (function) def wrap(image, *args, **kwargs): image_type = image.dtype image = tf.image.convert_image_dtype(image, tf.float32) if (len(args) >= 1): bboxes = args[0] bboxes_type = bboxes.dtype bboxes_absolute = bboxes_type.is_...
class HeuristicMultivariateDifferentiablePointProcess(POMultivariatePointProcess): def expconcrete_dist(self): if (not hasattr(self, '_expconcrete_dist')): self._expconcrete_dist = ExpConcreteDistribution((self.hidden_dim + 1)) return self._expconcrete_dist def e_step_obj_func(self, ...
class EventWriter(): def write(self): raise NotImplementedError def close(self): pass
class UploadCommand(Command): description = 'Build and publish the package.' user_options = [] def status(s): print('\x1b[1m{0}\x1b[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Remo...
class Top5Accuracy(PytorchMetric): def __init__(self): self.total = torch.tensor(0) self.correct = torch.tensor(0) def __call__(self, preds, targets): batch_size = targets.size(0) (_, preds) = preds.topk(5, dim=(- 1), largest=True, sorted=True) preds = preds.type_as(targe...
_REGISTRY.register() def build_timm_backbone(cfg, input_shape): model = TIMM(cfg.MODEL.TIMM.BASE_NAME, cfg.MODEL.TIMM.OUT_LEVELS, freeze_at=cfg.MODEL.TIMM.FREEZE_AT, norm=cfg.MODEL.TIMM.NORM, pretrained=cfg.MODEL.TIMM.PRETRAINED) return model
def copy_fold(in_folder: str, out_folder: str): shutil.copy(join(in_folder, 'debug.json'), join(out_folder, 'debug.json')) shutil.copy(join(in_folder, 'model_final_checkpoint.model'), join(out_folder, 'model_final_checkpoint.model')) shutil.copy(join(in_folder, 'model_final_checkpoint.model.pkl'), join(out_...
class WarpCTC(chainer.Chain): def __init__(self, odim, eprojs, dropout_rate): super(WarpCTC, self).__init__() from chainer_ctc.warpctc import ctc as warp_ctc self.ctc = warp_ctc self.dropout_rate = dropout_rate self.loss = None with self.init_scope(): self...
def extract_hyperparameters_from_keras(model): import tensorflow as tf hyperparameters = {} if (hasattr(model, 'optimizer') and (model.optimizer is not None)): hyperparameters['optimizer'] = model.optimizer.get_config() else: hyperparameters['optimizer'] = None hyperparameters['train...
class GPTJModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TestImageResizeTransform(unittest.TestCase): def test_image_resize_1(self): images_batch = (torch.ones((3, 100, 100, 3), dtype=torch.uint8) * 100) transform = ImageResizeTransform() images_transformed = transform(images_batch) IMAGES_GT = (torch.ones((3, 3, 800, 800), dtype=tor...
(scope='module') def sconv2dlstm_hidden_reset_subtract_instance(): return snn.SConv2dLSTM(1, 8, 3, init_hidden=True, reset_mechanism='subtract')
def write_json(json_data): file_name = 'all_data.json' dir_path = os.path.join(parent_path, 'data', 'all_data') if (not os.path.exists(dir_path)): os.mkdir(dir_path) file_path = os.path.join(dir_path, file_name) print('writing {}'.format(file_name)) with open(file_path, 'w') as outfile: ...
class Adam_GC(Optimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('Invalid epsilon value: {}'.for...
def is_verified_rect(rect): if ('uhrs' in rect): judge_result = rect['uhrs'] assert (judge_result.get('1', 0) >= judge_result.get('2', 0)) return True if (('class' not in rect) or ('rect' not in rect)): return False if ('uhrs_confirm' in rect): assert (rect['uhrs_conf...
def evaluate_3rd_user_task_fastgcnnew(valid_batch_index, model, sess, valid_data, is_training): (valid_target_user, valid_k_shot_item, valid_second_order_uesrs, valid_third_order_items, valid_oracle_user_ebd, valid_mask_num_second_order_user, valid_mask_num_third_order_item) = valid_data (evaluate_loss, evaluat...
def add_scores(): script_dir = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(script_dir, '../data/drd3_scores.pickle'), 'rb') as f: scored_smiles = pickle.load(f) df = pd.read_csv(os.path.join(script_dir, 'moses_train.csv'), index_col=0) smiles = df.smiles scores = [] ...
class EpsProposal(object): def __init__(self, T): self.T = T self.reset() def __iter__(self): return self def __next__(self): return self.next() def next(self): if (self.t >= self.T): raise StopIteration() eps_val = self(self.t) self.t ...
class RetreivalDataset(Dataset): def __init__(self, task: str, dataroot: str, annotations_jsonpath: str, split: str, image_features_reader: ImageFeaturesH5Reader, gt_image_features_reader: ImageFeaturesH5Reader, tokenizer: BertTokenizer, padding_index: int=0, max_seq_length: int=20, max_region_num: int=37): ...
class AttResU_Net(nn.Module): def __init__(self, img_ch=3, output_ch=1): super(AttResU_Net, self).__init__() self.Maxpool = nn.MaxPool2d(kernel_size=2, stride=2) self.Conv1 = res_conv_block(ch_in=img_ch, ch_out=64) self.Conv2 = res_conv_block(ch_in=64, ch_out=128) self.Conv3 ...
def center_crop(): data = np.arange((3 * 5)).reshape(3, 5) print(data) m = CenterCrop(size=(3, 3), p=1.0) print(m) res = m(data) print(res)
class Speech2TextPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def vad_collector(sample_rate, frame_duration_ms, padding_duration_ms, vad, frames): num_padding_frames = int((padding_duration_ms / frame_duration_ms)) ring_buffer = collections.deque(maxlen=num_padding_frames) triggered = False voiced_frames = [] for frame in frames: is_speech = vad.is_spe...
class DPDataset(Dataset): def __init__(self, corpus, dialogs, context_size=2, min_reply_length=None, max_reply_length=None): self.corpus = corpus self.contexts = [] self.replies = [] for dialog in dialogs: max_start_i = (len(dialog) - context_size) for start_i...
class Trainer(object): def __init__(self, output_dir): self.model_dir = os.path.join(output_dir, 'Model') os.makedirs(self.model_dir) self.image_dir = os.path.join(output_dir, 'Image') os.makedirs(self.image_dir) self.dataloader = get_dataloader() self.batch_size = cf...
def load_custom_testing_dataset_multiclass_str(): data = [['a', 1, 'zero'], ['b', 5, 'one'], ['c', 2, 'two'], ['a', 3, 'one'], ['c', 4, 'zero']] return pd.DataFrame(data, columns=['Categorical', 'Numerical', 'Outcome'])
class Equalizer(Processor): def __init__(self, name='EQUALIZER', block_size=512, sample_rate=44100, gain_range=((- 10.0), 5.0), q_range=(5.0, 30.0), hard_clip=False): super().__init__(name, None, block_size, sample_rate) MIN_GAIN = gain_range[0] MAX_GAIN = gain_range[1] MIN_Q = q_ran...
def llama_model_quantize(fname_inp: bytes, fname_out: bytes, ftype: c_int, nthread: c_int) -> int: return _lib.llama_model_quantize(fname_inp, fname_out, ftype, nthread)
def random_subset_indices(np_array, n_first_subset): idx = np.arange(0, len(np_array)) np.random.shuffle(idx) idx1 = idx[0:n_first_subset] idx2 = idx[n_first_subset:] return (idx1, idx2)
class FlaxStableDiffusionImg2ImgPipeline(metaclass=DummyObject): _backends = ['flax', 'transformers'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax', 'transformers']) def from_config(cls, *args, **kwargs): requires_backends(cls, ['flax', 'transformers']) def from_pr...
def ani(index): i1.set_data(observations[index][0].transpose(1, 2, 0)) i2.set_data(observations[index][1].transpose(1, 2, 0))
.register('Constant') class OpConstantProp(mx.operator.CustomOpProp): def __init__(self, val_str, shape_str, type_str='float32'): super(OpConstantProp, self).__init__(need_top_grad=False) val = [float(x) for x in val_str.split(',')] shape = [int(x) for x in shape_str.split(',')] self...
def get_covariance_matrix(f_map, eye=None): eps = 1e-05 (B, C, H, W) = f_map.shape HW = (H * W) if (eye is None): eye = torch.eye(C).cuda() f_map = f_map.contiguous().view(B, C, (- 1)) f_cor = (torch.bmm(f_map, f_map.transpose(1, 2)).div((HW - 1)) + (eps * eye)) return (f_cor, B)
def main(): args = parse_args() cfg = Config.fromfile(args.config) logger = get_logger(cfg.log_level) if (args.launcher == 'none'): dist = False logger.info('Disabled distributed training.') else: dist = True init_dist(**cfg.dist_params) world_size = torch.dis...
def tag_arxiv_more(line): line = RE_ARXIV_CATCHUP.sub('\\g<suffix>/\\g<year>\\g<month>\\g<num>', line) for (report_re, report_repl) in RE_OLD_ARXIV: report_number = (report_repl + '/\\g<num>') line = report_re.sub(((u'<cds.ARXIV>' + report_number) + u'</cds.ARXIV>'), line) return line
class OmniglotConv(nn.Module): def __init__(self, taskcla, sparsity=0.5): super(OmniglotConv, self).__init__() self.conv1 = SubnetConv2d(1, 64, 3, sparsity=sparsity, bias=False) s = compute_conv_output_size(28, 3, stride=1, padding=0) self.conv2 = SubnetConv2d(64, 64, 3, sparsity=spa...
class _RandomGPBase(): def __init__(self, size_in, prior_factor=1.0, weight_prior_std=1.0, bias_prior_std=3.0, **kwargs): self._params = OrderedDict() self._param_dists = OrderedDict() self.prior_factor = prior_factor self.gp = VectorizedGP(size_in, **kwargs) for (name, shape...
def schedule(epoch): t = (epoch / (args.swa_start if args.swa else args.epochs)) lr_ratio = ((args.swa_lr / args.lr_init) if args.swa else 0.01) if (t <= 0.5): factor = 1.0 elif (t <= 0.9): factor = (1.0 - (((1.0 - lr_ratio) * (t - 0.5)) / 0.4)) else: factor = lr_ratio re...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_args,...
def uncompressed_rle(mask): l = mask.flatten(order='F').tolist() counts = [] p = False cnt = 0 for i in l: if (i == p): cnt += 1 else: counts.append(cnt) p = i cnt = 1 counts.append(cnt) return {'counts': counts, 'size': [mask.s...
class MinitaurEnvRandomizer(env_randomizer_base.EnvRandomizerBase): def __init__(self, minitaur_base_mass_err_range=MINITAUR_BASE_MASS_ERROR_RANGE, minitaur_leg_mass_err_range=MINITAUR_LEG_MASS_ERROR_RANGE, battery_voltage_range=BATTERY_VOLTAGE_RANGE, motor_viscous_damping_range=MOTOR_VISCOUS_DAMPING_RANGE): ...
.parametrize('add_batch_size, max_length, add_sequence_length, sample_sequence_length, sample_period', [(1, 8, 3, 3, 4)]) .parametrize('add_iter, expected_priority_indices, expected_priority_values', [(0, [0], [1.0]), (1, [1], [0.0]), (2, [1], [1.0]), (3, [0], [1.0]), (4, [1], [1.0]), (5, [0], [0.0]), (6, [0], [1.0]), ...
class Concat(Container): def __init__(self, dimension, bigdl_type='float'): super(Concat, self).__init__(None, bigdl_type, dimension)
def process_flickr8k(): if (not os.path.exists('flickr8k')): os.makedirs('flickr8k') if (not os.path.exists('flickr8k/Flickr8k_Dataset.zip')): gdd.download_file_from_google_drive(file_id='1WNY8pV-u8xtBYBVal03qwjQs4VKurUZn', dest_path='./flickr8k/Flickr8k_Dataset.zip', unzip=True, showsize=True) ...
def placeholder_fit(trainer, module, datamodule): trainer.data_connector.attach_data(module, datamodule=datamodule) if hasattr(module, 'hparams'): parsing.clean_namespace(module.hparams) trainer.config_validator.verify_loop_configurations(module) trainer.callback_connector.attach_model_logging_f...
def test_aggregator_pipeline(saliency_mt_model: HuggingfaceEncoderDecoderModel): out = saliency_mt_model.attribute('This is a test.', attribute_target=True, step_scores=['probability'], device='cpu', show_progress=False) seqattr = out.sequence_attributions[0] squeezesum = AggregatorPipeline([ContiguousSpanA...
_name('contract_matseq') def test_contract_matseq_large_bonddim(benchmark): contract_matseq_runner(benchmark, bond_dim=100)
def build_vocab(vocab_root_path, train_all_text, text_min_count): print('building vocab,train') vocab = [] for text in train_all_text: words = text.split(' ') for word in words: if (word not in vocab): vocab.append(word) freq = dict(zip(vocab, [0 for i in rang...
def concretize_op(op: Union[(AbsOpBase, Placeholder)], model: Optional[z3.ModelRef]) -> Union[(AbsOpBase, Placeholder)]: if (isinstance(op, Constant) or isinstance(op, Input)): ret_op = deepcopy(op) values = [] for (idx, s) in enumerate(op.abs_tensor.shape): if isinstance(s, z3.E...
def backward(W, h=[0.0625, 0.25, 0.375, 0.25, 0.0625]): nX = np.shape(W) Lh = np.size(h) rec = sp2.Starlet2D(nX[1], nX[2], nX[0], (nX[3] - 1), Lh).backward_omp(np.real(W)) return rec
def sigmoid_ce_loss_(inputs: torch.Tensor, targets: torch.Tensor): num_masks = max(inputs.size(0), 1.0) loss = F.binary_cross_entropy(inputs, targets, reduction='none') return (loss.flatten(1).mean(1).sum() / num_masks)
def show_curves(): step_size = 0.1 all_curves = {} for log_dir in tqdm(list(logs_dir.iterdir())): cfg = utils.read_config(str((log_dir / 'config.yml'))) data = load_data(cfg) if (data is None): continue if (cfg.experiment_name not in all_curves): all_c...
class RandomStatePredictor(): def __init__(self): pass def predict(self, state: State, next_states) -> dict: raise NotImplementedError
def reindex(es, source_index, target_index): helpers.reindex(es, source_index=source_index, target_index=target_index)
def require_non_multigpu(test_case): if (not _torch_available): return unittest.skip('test requires PyTorch')(test_case) import torch if (torch.cuda.device_count() > 1): return unittest.skip('test requires 0 or 1 GPU')(test_case) else: return test_case
class TestTorchOP(unittest.TestCase): def setUpClass(self): pass def tearDownClass(self): os.remove('conf.yaml') pass def test_1(self): text = "\nmodel:\n name: model\n operator:\n input_data:\n type: Input\n output:\n input_ids.1:\n dtype: s32\...
class ParallelCompile(object): __slots__ = ('envvar', 'default', 'max', 'old') def __init__(self, envvar=None, default=0, max=0): self.envvar = envvar self.default = default self.max = max self.old = [] def function(self): def compile_function(compiler, sources, outpu...
def _check_supported_json_output_versions(version): return (version in _SchemaVersions.ALL_VERSIONS)
class DenseGaussianVariable(object): def __init__(self, batch_size, n_variables, const_prior_var, n_input, update_form, posterior_form='gaussian', learn_prior=True): self.batch_size = batch_size self.n_variables = n_variables assert (update_form in ['direct', 'highway']), 'Latent variable up...
def smplPvis(): smplPbu.switch() if (smplPbu.status() == 'Shide'): smplP.off() elif (smplPbu.status() == 'Sshow'): smplP.on()
class Attention(Model): _compatible_windows = (window_module.Sliding, window_module.Expanding) def __init__(self, in_channels, out_channels, residual_channels, num_heads, hidden_channels, num_layers, dropout=0, activation='relu'): super(Attention, self).__init__() self.in_channels = in_channels ...
def unfreeze_model(model): if (type(model) == QuantAct): model.unfix() elif (type(model) == nn.Sequential): mods = [] for (n, m) in model.named_children(): unfreeze_model(m) else: for attr in dir(model): mod = getattr(model, attr) if (isins...
def _get_augmented_positions(s: str, spec: AugmentationSpec) -> List[int]: return [pos[1] for pos in replace_tokens_and_get_augmented_positions(s, spec)[1]]
def test_tuple_rvalue_getter(): pop = 1000 tup = tuple(range(pop)) m.tuple_rvalue_getter(tup)
class SquadExample(object): def __init__(self, qas_id, question_text, doc_tokens, orig_answer_text=None, start_position=None, end_position=None): self.qas_id = qas_id self.question_text = question_text self.doc_tokens = doc_tokens self.orig_answer_text = orig_answer_text self...
def addLaserCalibration(laser_num, key, val): global calibration if (laser_num < len(calibration['lasers'])): calibration['lasers'][laser_num][key] = val else: calibration['lasers'].append({key: val})
def get_log(event_path, tag): try: a = {} a[tag] = [] a['step'] = [] for e in summary_iterator(event_path): for v in e.summary.value: if (v.tag == tag): a['step'].append(e.step) a[tag].append(v.simple_value) ...
class ColorJitter(object): def __init__(self, brightness=0, contrast=0, saturation=0, hue=0): self.brightness = brightness self.contrast = contrast self.saturation = saturation self.hue = hue self.tv_F = tv_t.ColorJitter(self.brightness, self.contrast, self.saturation, self.h...
class FlaxMarianPreTrainedModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
.parametrize('input_data,expected', testdata) def test_pascal(input_data, expected): assert (pascal(*input_data) == expected)
def _compute_aspect_ratios_coco_dataset(dataset, indices=None): if (indices is None): indices = range(len(dataset)) aspect_ratios = [] for i in indices: img_info = dataset.coco.imgs[dataset.ids[i]] aspect_ratio = (float(img_info['width']) / float(img_info['height'])) aspect_r...