code
stringlengths
101
5.91M
def build_server_model(): inputs = Input(shape=21632) x = Dense(128, activation='relu')(inputs) outputs = Dense(10)(x) return Model(inputs=inputs, outputs=outputs, name='vfl_server_model')
.parametrize('dtype', [np.float32, np.float64]) def test_compute_ssim_gray(dtype: np.dtype) -> None: np_gray_img = (data.camera().astype(dtype) / 255) pt_gray_img = torch.as_tensor(np_gray_img) for sigma in [0, 0.01, 0.03, 0.1, 0.3]: noise = (torch.randn_like(pt_gray_img) * sigma) noisy_pt_g...
class RoCBertForQuestionAnswering(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class SparseFastSigmoid(torch.autograd.Function): '\n Surrogate gradient of the Heaviside step function.\n\n **Forward pass:** Heaviside step function shifted.\n\n .. math::\n\n S=\\begin{cases} 1 & \\text{if U U$_{\\rm thr}$} \\\\\n 0 & \\text{if U < U$_{\\rm thr}$}\n ...
def build_from_path(in_dir, out_dir, num_workers=1): executor = ProcessPoolExecutor(max_workers=num_workers) futures = [] index = 1 with open(os.path.join(in_dir, 'metadata.csv'), encoding='utf-8') as f: for line in f: parts = line.strip().split('|') wav_path = os.path.jo...
def save_results_mimic(results_file_path, repetition_num, match_mean, auc_score, apr_score): with open(results_file_path, 'a') as f: writer = csv.writer(f) writer.writerow((repetition_num, match_mean, auc_score, apr_score))
class DenseBlock(nn.Module): def __init__(self, in_channels, out_channels, bottleneck_size): super(DenseBlock, self).__init__() inc_channels = ((out_channels - in_channels) // 2) mid_channels = (inc_channels * bottleneck_size) self.branch1 = PeleeBranch1(in_channels=in_channels, out_...
def _get_mcmc_fns(run_config: ConfigDict, log_psi_apply: ModelApply[P], apply_pmap: bool=True) -> Tuple[(mcmc.metropolis.BurningStep[(P, dwpa.DWPAData)], mcmc.metropolis.WalkerFn[(P, dwpa.DWPAData)])]: metrop_step_fn = dwpa.make_dynamic_pos_amp_gaussian_step(log_psi_apply, run_config.nmoves_per_width_update, dwpa.m...
class _SyncBatchNorm(_BatchNorm): def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True): super(_SyncBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine) self._sync_master = SyncMaster(self._data_parallel_master) self._parallel_id = None ...
class _Trainer(): def __init__(self, c): if (c.SEED is None): c.SEED = torch.initial_seed() else: torch.manual_seed(c.SEED) np.random.seed(c.SEED) c.get_outdirs() c.save_constants_file() print(c) if ((c.DEVICE != 'cpu') and torch.cuda.i...
def plot_embedding(X, Y, cid, ohidcs, A): plt.figure(figsize=(20, 20)) for i in xrange(Y.shape[0]): if (i == cid): c = 'g' s = 500 elif (Y[i] == Y[cid]): c = 'r' s = 20 else: c = 'b' s = 20 plt.scatter(X[(i, ...
def get_split_loader(split_dataset, training=False, testing=False, weighted=False): kwargs = ({'num_workers': 4} if (device.type == 'cuda') else {}) if (not testing): if training: if weighted: weights = make_weights_for_balanced_classes_split(split_dataset) lo...
def set_window_pos_callback(window, cbfun): window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if (window_addr in _window_pos_callback_repository): previous_callback = _window_pos_callback_repository[window_addr] else: previous_callback = None ...
def get_dataset(name, split='train', transform=None, target_transform=None, download=True, datasets_path='~/Datasets'): train = (split == 'train') root = os.path.join(os.path.expanduser(datasets_path), name) if (name == 'cifar10'): return datasets.CIFAR10(root=root, train=train, transform=transform,...
def fedat_test(fed, running_model, val_loaders, val_adversaries, att_BNn, detector, loss_fun, device, client_num, set_name='Val'): acc_list = [None for _ in range(client_num)] loss_mt = AverageMeter() for client_idx in range(client_num): fed.model_accum.load_model(running_model, client_idx) ...
def test_imageparam_bug(): 'see x = Var('x') y = Var('y') fx = Func('fx') input = ImageParam(UInt(8), 1, 'input') fx[(x, y)] = input[y] return
def make_sentences(root, split, file, processing): sentences = load_file(os.path.join(root, ((split + '.') + file))) return split_sentences(sentences, processing)
def build_nasnet_mobile(images, num_classes, is_training=True, final_endpoint=None, config=None, current_step=None): hparams = (mobile_imagenet_config() if (config is None) else copy.deepcopy(config)) _update_hparams(hparams, is_training) if (tf.test.is_gpu_available() and (hparams.data_format == 'NHWC')): ...
def run_simulation(Lx, Ly, betas=[1.0], n_updates_measure=10000, n_bins=10): (spins, op_string, bonds) = init_SSE_square(Lx, Ly) n_sites = len(spins) n_bonds = len(bonds) Es_Eerrs = [] for beta in betas: print('beta = {beta:.3f}'.format(beta=beta), flush=True) op_string = thermalize(...
class TestTextFeature(ZooTestCase): def test_text_feature_with_label(self): feature = TextFeature(text, 1) assert (feature.get_text() == text) assert (feature.get_label() == 1) assert feature.has_label() assert (set(feature.keys()) == {'text', 'label'}) assert (featur...
def UNTESTED_from_jsonable(ebm, jsonable): warn('JSON formats are in beta. The JSON format may change in a future version without compatibility between releases.') obj_type = f'{ebm.__class__.__module__}.{ebm.__class__.__name__}' if (obj_type == 'interpret.glassbox._ebm._ebm.EBMModel'): is_classific...
class FlaxMT5ForConditionalGeneration(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def main(A, t_max, M, R, exec_type, theta): print('{}-armed Bernoulli bandit with MC-BUCB policies for {} time-instants and {} realizations'.format(A, M, t_max, R)) dir_string = '../results/{}/A={}/t_max={}/R={}/M={}/theta={}'.format(os.path.basename(__file__).split('.')[0], A, t_max, R, M, '_'.join(str.strip(n...
def _extrapolate(img, class_info, magnitude): m = float_parameter(magnitude, 1) x = img mu = class_info['mean'] x_hat = (((x - mu) * m) + x) return (x_hat, [])
class QResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(QResNet, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d self._no...
def test_intersection_module() -> None: box1 = TFBoxTensor(tf.Variable([[[1, 1], [3, 5]], [[1, 1], [3, 3]]])) box2 = TFBoxTensor(tf.Variable([[[2, 0], [6, 2]], [[3, 2], [4, 4]]])) res = TFBoxTensor(tf.Variable([[[2, 1], [3, 2]], [[3, 2], [3, 3]]])) assert (res == TFHardIntersection()(box1, box2))
class HugginfaceBertEncoderMapper(SimpleMapper): RULES = [RegexRule('layer\\.(\\d+)\\.attention\\.self\\.(query|key|value)', 'layers.\\1.attention.\\2_projection'), RegexRule('layer\\.(\\d+)\\.attention\\.output\\.dense', 'layers.\\1.attention.out_projection'), RegexRule('layer\\.(\\d+)\\.attention\\.output\\.Layer...
_module() class DynamicMVXFasterRCNN(MVXTwoStageDetector): def __init__(self, **kwargs): super(DynamicMVXFasterRCNN, self).__init__(**kwargs) _grad() _fp32() def voxelize(self, points): coors = [] for res in points: res_coors = self.pts_voxel_layer(res) co...
def load_model(model, dir): model_dict = model.state_dict() print('loading model from :', dir) pretrained_dict = torch.load(dir)['params'] if ('encoder' in list(pretrained_dict.keys())[0]): if ('module' in list(pretrained_dict.keys())[0]): pretrained_dict = {k[7:]: v for (k, v) in pr...
class TensorflowModelZooBertDataLoader(DefaultDataLoader): def _generate_dataloader(self, dataset, batch_size, last_batch, collate_fn, sampler, batch_sampler, num_workers, pin_memory, shuffle, distributed): if shuffle: logging.warning('Shuffle is not supported yet in TensorflowBertDataLoader, ig...
def pspnet_resnetd50b_coco(pretrained_backbone=False, num_classes=21, aux=True, **kwargs): backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features del backbone[(- 1)] return get_pspnet(backbone=backbone, num_classes=num_classes, aux=aux, model_name='pspnet_resn...
def block(mod, output, stride): inp = mod.get_current()[1][(- 1)] aa = mod.get_current() if (inp == output): if (stride == 1): l0 = mod.get_current() else: l0 = mod.maxpoolLayer(stride) else: l0 = mod.convLayer(1, output, activation=M.PARAM_RELU, batch_nor...
class ChannelPool(nn.Module): def forward(self, x): return torch.cat((torch.max(x, 1)[0].unsqueeze(1), torch.mean(x, 1).unsqueeze(1)), dim=1)
def set_cursor_pos_callback(window, cbfun): window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_long)).contents.value if (window_addr in _cursor_pos_callback_repository): previous_callback = _cursor_pos_callback_repository[window_addr] else: previous_callback = None ...
def main(config_, save_path): global config, log, writer config = config_ (log, writer) = utils.set_save_path(save_path) with open(os.path.join(save_path, 'config.yaml'), 'w') as f: yaml.dump(config, f, sort_keys=False) (train_loader, val_loader) = make_data_loaders() if (config.get('dat...
def test_amuse_NFWPotential(): np = potential.NFWPotential(normalize=1.0, a=3.0) tmax = 3.0 (vo, ro) = (200.0, 7.0) o = Orbit([1.0, 0.5, 1.3, 0.3, 0.1, 0.4], ro=ro, vo=vo) run_orbitIntegration_comparison(o, np, tmax, vo, ro) return None
def ndim(x): dims = x.get_shape()._dims if (dims is not None): return len(dims) return None
class ConditionalImageHusky(ConditionalImage): def __init__(self, taskdef, *args, **kwargs): super(ConditionalImageHusky, self).__init__(taskdef, *args, **kwargs) self.num_options = HuskyNumOptions() self.null_option = HuskyNullOption() def _makeModel(self, image, pose, *args, **kwargs):...
def read_compress_raw_img(img_path): img = cv2.imread(img_path) encoded_img_arr = cv2.imencode('.jpg', img)[1] return encoded_img_arr
.dataclass class FlaxSeq2SeqModelOutput(ModelOutput): last_hidden_state: jnp.ndarray = None past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None decoder_hidden_states: Optional[Tuple[jnp.ndarray]] = None decoder_attentions: Optional[Tuple[jnp.ndarray]] = None cross_attentions: Optional[Tuple[...
def load_network(params, device): state = Checkpoints.load_network(params['path']) return initialize_network(None, device, state, params['runtime'])
class PPOConfig(): exp_name: str = os.path.basename(sys.argv[0])[:(- len('.py'))] seed: int = 0 log_with: Optional[Literal[('wandb', 'tensorboard')]] = None task_name: Optional[str] = None model_name: Optional[str] = None query_dataset: Optional[str] = None reward_model: Optional[str] = None...
def combine_and_merge_gold_pred(input_gold_conll, input_pred_conll): all_files = Read_txt_Files_in_Input_Folder(input_gold_conll) combined_pred_file = 'predictions.txt' fout = open(combined_pred_file, 'w') fout.close() for file in all_files: file_name = file.split('/')[(- 1)] gold_fi...
class RefineNet(Network): def setup(self): self.feed('color_image', 'depth_image').concat(axis=3, name='concat_image') self.feed('concat_image').conv_bn(3, 32, 1, name='refine_conv0').conv_bn(3, 32, 1, name='refine_conv1').conv_bn(3, 32, 1, name='refine_conv2').conv(3, 1, 1, relu=False, name='refine...
def process_folder(q, data_dir, output_dir, stride=1): while True: if q.empty(): break folder = q.get() image_path = os.path.join(data_dir, folder, 'image_2/') dump_image_path = os.path.join(output_dir, folder) if (not os.path.isdir(dump_image_path)): ...
def gaussian_log_likelihood(mu, data, obsrv_std): log_p = (((mu - data) ** 2) / ((2 * obsrv_std) * obsrv_std)) neg_log_p = ((- 1) * log_p) return neg_log_p
def _dist_train(model, train_dataset, cfg, eval_dataset=None, vis_dataset=None, validate=False, logger=None): data_loaders = [build_data_loader(train_dataset, cfg.data.imgs_per_gpu, cfg.data.workers_per_gpu, dist=True)] if cfg.apex.synced_bn: model = apex.parallel.convert_syncbn_model(model) model =...
def test_q3_q1_range(barrel): q3q1range = barrel.q3_q1_range() assert isinstance(q3q1range, np.ndarray)
def run_parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--task', choices=['train', 'dev', 'eval'], required=True) parser.add_argument('--output_dir', type=str, default=f'./data/train') parser.add_argument('--msmarco_dir', type=str, default=f'./data/msmarco-passage') parser.add_...
def test_nonlocal1d(): imgs = torch.randn(2, 3, 20) nonlocal_1d = NonLocal1d(3) if (torch.__version__ == 'parrots'): if torch.cuda.is_available(): imgs = imgs.cuda() nonlocal_1d.cuda() out = nonlocal_1d(imgs) assert (out.shape == imgs.shape) imgs = torch.randn(2, ...
def build_strong_weak_aug_dataset(cfg, mode='train', is_source=True, epochwise=False, logger=None): assert (mode in ['train', 'val', 'test']) logger.info('currently using strong weak augmentation!!!') iters = None if (mode == 'train'): if (not epochwise): iters = (cfg.SOLVER.MAX_ITER...
def offline_actor_update(buffer, agent, actor_optimizer, encoder_optimizer, batch_size, actor_clip, update_encoder, encoder_clip, augmenter, actor_lambda, aug_mix, premade_replay_dicts=None, per=True, discrete=False, filter_=True): logs = {} loss = 0.0 for ensemble_idx in range(agent.ensemble_size): ...
def get_num_features(data_type, corpus_file, side): return TextDataset.get_num_features(corpus_file, side)
def list_pretrained_models_by_tag(tag: str): models = [] for k in _PRETRAINED.keys(): if (tag in _PRETRAINED[k]): models.append(k) return models
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments, AdapterTrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args, adapter_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) ...
def cfg_base(): task = 'autoencoding' model_base_path = '/mnt/models/' store_representation = True store_prediction = True folders_to_convert = None split_to_convert = None batch_size = 64 n_dataloader_workers = 8 data_dir = '/mnt/data' save_dir = '/mnt/data'
class Conv2DLayer(object): def __init__(self, input_layer, n_filters, filter_size, weights_std, init_bias_value, stride=1, nonlinearity=layers.rectify, dropout=0.0, partial_sum=None, pad=0, untie_biases=False, trainable=True): self.input_layer = input_layer self.input_shape = self.input_layer.get_ou...
class InvertedResidual(nn.Module): def __init__(self, in_chs, out_chs, dw_kernel_size=3, stride=1, pad_type='', act_layer=nn.ReLU, noskip=False, exp_ratio=1.0, exp_kernel_size=1, pw_kernel_size=1, se_ratio=0.0, se_kwargs=None, norm_layer=nn.BatchNorm2d, norm_kwargs=None, conv_kwargs=None, drop_connect_rate=0.0): ...
class BasicTokenizer(object): def __init__(self, do_lower_case=False, never_split=None, tokenize_chinese_chars=True): if (never_split is None): never_split = [] self.do_lower_case = do_lower_case self.never_split = never_split self.tokenize_chinese_chars = tokenize_chines...
def process_checkpoint(in_file, out_file): checkpoint = torch.load(in_file, map_location='cpu') if ('optimizer' in checkpoint): del checkpoint['optimizer'] torch.save(checkpoint, out_file) sha = calculate_file_sha256(out_file) final_file = (out_file.rstrip('.pth') + f'-{sha[:8]}.pth') os...
class AbstractActionSpace(abc.ABC): def step(self, state, action): pass def reset(self, state): pass def random_action(self): pass def action_spec(self): pass
def STFT(fl): (f, t, Zxx) = signal.stft(fl, nperseg=64) img = (np.abs(Zxx) / len(Zxx)) return img
class Segment(): def __init__(self, model: str, class_idx: Optional[int]=None, threshold_direction: str='less'): import slideflow.segment if (threshold_direction not in ['less', 'greater']): raise ValueError('Invalid threshold_direction: {}. Expected one of: less, greater'.format(thresho...
class Timer(object): def __init__(self): self.total = 0 def start(self): self.start_time = time.time() def finish(self): self.total += (time.time() - self.start_time)
class FairseqLanguageModel(BaseFairseqModel): def __init__(self, decoder): super().__init__() self.decoder = decoder def forward(self, src_tokens, **kwargs): return self.decoder(src_tokens, **kwargs) def max_positions(self): return self.decoder.max_positions() def support...
class DLA(nn.Module): def __init__(self, levels, channels, output_stride=32, num_classes=1000, in_chans=3, cardinality=1, base_width=64, block=DlaBottle2neck, residual_root=False, drop_rate=0.0, global_pool='avg'): super(DLA, self).__init__() self.channels = channels self.num_classes = num_c...
def test_dummy_parameter_encoder_can_be_instantiated(): model = DummyParameterEncoder((1, 1)) assert (model is not None)
def latent_noise(latent, strength): noise = (torch.randn_like(latent) * strength) return (latent + noise)
def test_compute_calls(snapshot): assert (json.dumps(eia_api_v2.EIASession().compute_facet_options(eia_api_v2.ROUTES)) == snapshot(name='Output from compute_facet_options'))
class colour3(): def __init__(self, nR=0, nG=0, nB=0): self.R = nR self.G = nG self.B = nB
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 _bhy_threshold(pvals, reshaping_function=None, fdr=0.1): n_features = len(pvals) pvals_sorted = np.sort(pvals) selected_index = (2 * n_features) if (reshaping_function is None): temp = np.arange(n_features) sum_inverse = np.sum((1 / (temp + 1))) return _bhq_threshold(pvals, (...
class DreamerLearnerConfig(DreamerConfig): def __init__(self): super().__init__() self.MODEL_LR = 0.0002 self.ACTOR_LR = 0.0005 self.VALUE_LR = 0.0005 self.CAPACITY = 500000 self.MIN_BUFFER_SIZE = 100 self.MODEL_EPOCHS = 1 self.EPOCHS = 1 self....
def load_model(type, folder, checkpoint, temperature, device, dataset='cifar10', load_temp=False, model_params=None): dataset = dataset.lower() if (dataset == 'cifar10'): dataset_dir = 'Cifar10Models' num_classes = 10 model_family = 'Cifar32' elif (dataset == 'cifar100'): dat...
def _export_pytorch_model(f, pytorch_model, dummy_input): kwargs = {'do_constant_folding': False, 'export_params': True, 'enable_onnx_checker': False, 'input_names': ['input'], 'output_names': ['output']} try: torch.onnx.export(pytorch_model, dummy_input, f, **kwargs) except TypeError: kwarg...
class Reducer(nn.Module): def __init__(self, dim, exclude_self=True, exists=True): super().__init__() self.dim = dim self.exclude_self = exclude_self self.exists = exists def forward(self, inputs): shape = inputs.size() (inp0, inp1) = (inputs, inputs) if s...
def set_reactivity(line_: str) -> None: line_ = line_.lower().strip() usage = f'Usage: %flow reactivity [{ReactivityMode.BATCH}|{ReactivityMode.INCREMENTAL}]' if (line_ in ('batch', 'incremental')): reactivity = ReactivityMode(line_) else: warn(usage) return flow().mut_settin...
class TestRetryDifferentOnError(): def test_default(self): class TmpData(Dataset, retry_exc=Exception, silent=False, max_retries=None, use_blacklist=False): def getitem(self, item): if ((item % 2) == 0): raise ValueError return ({'item': item},...
def rescale(img): (w, h) = img.size min_len = min(w, h) (new_w, new_h) = (min_len, min_len) scale_w = ((w - new_w) // 2) scale_h = ((h - new_h) // 2) box = (scale_w, scale_h, (scale_w + new_w), (scale_h + new_h)) img = img.crop(box) return img
def train_topmine_ngrammer(documents, threshhold=1, max_ngramm_len=3, min_word_len=2, regexp='[.,!?;: ]', stopwords=None): splitted_docs = [] for doc in documents: if isinstance(doc, str): splitted_docs.append(split_document_by_delimeters(doc, regexp, min_word_len=min_word_len, stopwords=sto...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--apply', dest='apply', action='store_true', default=False, help='Apply style to files in-place.') parser.add_argument('--no_parallel', dest='no_parallel', action='store_true', default=False, help='Disable parallel execution.') parser.a...
class LitResnet(pl.LightningModule): def __init__(self, lr=0.1, dataset_size=50000): super().__init__() self.rng = torch.Generator().manual_seed(40) self.lr = lr self.n_classes = 10 self.dims = (3, 32, 32) self.datasize = dataset_size self.model = modified_res...
def get_latest_checkpoint_number(base_directory): glob = os.path.join(base_directory, 'sentinel_checkpoint_complete.*') def extract_iteration(x): return int(x[(x.rfind('.') + 1):]) try: checkpoint_files = tf.gfile.Glob(glob) except tf.errors.NotFoundError: return (- 1) try: ...
class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 self.lists = [] def update(self, val, n=1): self.val = val self.sum += (val * n) self.count += n ...
class Tee(): def __init__(self, fname, mode='a'): self.stdout = sys.stdout self.file = open(fname, mode) def write(self, message): self.stdout.write(message) self.file.write(message) self.flush() def flush(self): self.stdout.flush() self.file.flush()
class CIFARSEResNet(nn.Module): def __init__(self, channels, init_block_channels, bottleneck, in_channels=3, in_size=(32, 32), num_classes=10): super(CIFARSEResNet, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() self.fea...
class LukeForEntitySpanClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TFDPRPretrainedQuestionEncoder(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def init_settings(args): args.methods = [x.lower() for x in args.methods] os.makedirs('results', exist_ok=True) if (args.dataset == 'kitti'): if (not args.model): args.model = 'yolov3' if args.tasks: globals.TASKS = args.tasks else: globals.TASKS =...
def dmcp_resnet18(num_classes=1000, input_size=224, width=None, prob_type='exp'): if (width is None): width = [0.1, 1.0, 0.1] return DMCPResNet(DMCPBasicBlock, [2, 2, 2, 2], num_classes, input_size, width, prob_type)
def log1mexp(x: tf.Tensor, split_point: float=_log1mexp_switch, exp_zero_eps: float=1e-07) -> tf.Tensor: logexpm1_switch = (x > split_point) Z = tf.zeros_like(x) logexpm1 = tf.math.log(tf.clip_by_value((- tf.math.expm1(x[logexpm1_switch])), clip_value_min=1e-323, clip_value_max=float('inf'))) logexpm1_b...
('eval', timer=False) def evaluate(dataset, model): with hlog.task('train', timer=False): visualize(make_batch([dataset.sample_comp_train()], dataset.vocab, staged=True), dataset.vocab, model) print()
def train(): model.train() total_loss = 0 start_time = time.time() ntokens = len(corpus.dictionary) hidden = model.init_hidden(args.batch_size) for (batch, i) in enumerate(range(0, (train_data.size(0) - 1), args.bptt)): (data, targets) = get_batch(train_data, i) hidden = repackag...
class MultiprocessingPdb(pdb.Pdb): _stdin_fd = sys.stdin.fileno() _stdin = None _stdin_lock = multiprocessing.Lock() def __init__(self): pdb.Pdb.__init__(self, nosigint=True) def _cmdloop(self): stdin_bak = sys.stdin with self._stdin_lock: try: if ...
class RemBertTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=False, remove_space=True, keep_accents=True, bos_token='[...
def metric(pred, true): mae = MAE(pred, true) mse = MSE(pred, true) rmse = RMSE(pred, true) mape = MAPE(pred, true) mspe = MSPE(pred, true) return (mae, mse, rmse, mape, mspe)
class GridSamplerMine3dBackwardFunction(Function): def forward(ctx, input, grid, grad_output): ctx.save_for_backward(input, grid, grad_output) return GridSamplerMine.backward(input, grid, grad_output, 0, 1) def backward(ctx, grad_output_input, grad_output_grid): (input, grid, grad_output...
class PKT(nn.Module): 'Probabilistic Knowledge Transfer for deep representation learning\n Code from author: def __init__(self): super(PKT, self).__init__() def forward(self, f_s, f_t): return self.cosine_similarity_loss(f_s, f_t) def cosine_similarity_loss(output_net, target_net, ep...
def train_model(epoch, model, dloader, dloader_val, optim, sched): model.train() print('[epoch {:03d}] training ...'.format(epoch)) print('[epoch {:03d}] # batches = {}'.format(epoch, len(dloader))) st = time.time() for (batch_idx, batch_samples) in enumerate(dloader): model.zero_grad() ...
def main(): parser = argparse.ArgumentParser(description='Create an AWS instance to run Ithemal') parser.add_argument('identity', help='Key identity to create with') parser.add_argument('-n', '--name', help='Name to start the container with', default=None) parser.add_argument('-t', '--type', help='Insta...