code
stringlengths
101
5.91M
class energy_50_RL(nn.Module): def __init__(self): super(energy_50_RL, self).__init__() self.name = 'energy_RL' self.feature = nn.Sequential(nn.Linear((50 * 51), 128), nn.Softplus(), nn.Linear(128, 128), nn.Softplus()) self.value = nn.Sequential(nn.Linear(128, 64), nn.Tanhshrink(), n...
class Config(): def __init__(self): self.det_head = 'pip' self.net_stride = 32 self.batch_size = 16 self.init_lr = 0.0001 self.num_epochs = 60 self.decay_steps = [30, 50] self.input_size = 256 self.backbone = 'resnet50' self.pretrained = True ...
def ssl_null(args, model_dict, optimizer_dict, lrer_dict, criterion_dict, task_func): if (not (len(model_dict) == len(optimizer_dict) == len(lrer_dict) == len(criterion_dict) == 1)): logger.log_err('The len(element_dict) of SSL_NULL should be 1\n') elif (list(model_dict.keys())[0] != 'model'): l...
def load_states_from_checkpoint(model_file: str) -> CheckpointState: print(f'Reading saved model from {model_file}') state_dict = torch.load(model_file, map_location=(lambda s, l: default_restore_location(s, 'cpu'))) return CheckpointState(**state_dict)
def get_augmentation_v1(patch_size): return Compose([Rotate(((- 15), 15), (0, 0), (0, 0), p=0.5), RandomCropFromBorders(crop_value=0.1, p=0.5), ElasticTransform((0, 0.25), interpolation=2, p=0.1), RandomDropPlane(plane_drop_prob=0.1, axes=(0, 1, 2), p=0.5), Resize(patch_size, interpolation=1, always_apply=True, p=1...
def parse_args(argv): parser = argparse.ArgumentParser(description='Example training script.') parser.add_argument('-m', '--model', default='bmshj2018-factorized', choices=models.keys(), help='Model architecture (default: %(default)s)') parser.add_argument('-d', '--dataset', type=str, required=True, help='T...
def cbam_resnet101(**kwargs): return get_resnet(blocks=101, model_name='cbam_resnet101', **kwargs)
def get_splits(lines, line_counts): all_lines = [] line_idx = [] file_mappings = [] for (i, l) in enumerate(lines): all_lines.extend(l) line_idx.extend(list(range(len(l)))) file_mappings.extend(([i] * len(l))) indices = list(range(len(all_lines))) random.shuffle(indices) ...
def model_creator_multiple_metrics(config): model = tf.keras.models.Sequential([tf.keras.layers.Dense(1)]) model.compile(loss='mse', optimizer='sgd', metrics=['mse', 'mae']) return model
def test_he_normal_receptive_field(): from lasagne.init import HeNormal sample = HeNormal().sample((50, 50, 2)) assert ((- 0.01) < sample.mean() < 0.01) assert (0.09 < sample.std() < 0.11)
class ECABasicBlock(BasicBlock): def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, dimension=3): super(ECABasicBlock, self).__init__(inplanes, planes, stride=stride, dilation=dilation, downsample=downsample, dimension=dimension) self.eca = ECALayer(planes, gamma=2, b=1) ...
class XfunReTrainer(FunsdTrainer): def __init__(self, **kwargs): super().__init__(**kwargs) self.label_names.append('relations') def prediction_step(self, model: nn.Module, inputs: Dict[(str, Union[(torch.Tensor, Any)])], prediction_loss_only: bool, ignore_keys: Optional[List[str]]=None) -> Tupl...
class AverageMeter(object): def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += ...
def testGetGeneralActivationBound(): u = (torch.ones(1) * 5) l = (torch.ones(1) * (- 4)) activation = 'relu' func = Activation[activation][0] (kl, bl, ku, bu) = getConvenientGeneralActivationBound(l, u, activation, use_constant=True) x = ((torch.rand(1000) * (u - l)) + l) func_x = func(x) ...
def open_image(image, ext): if ((ext == '.jpg') or (ext == '.jpeg')): return Image.open(image).convert('RGB') if (ext == '.png'): return Image.open(image).convert('RGB') if (ext == '.dcm'): ds = pydicom.dcmread(image) if ('WindowWidth' in ds): img = apply_voi_lut(...
def find_latest_checkpoint(path, suffix='pth'): if (not osp.exists(path)): warnings.warn('The path of checkpoints does not exist.') return None if osp.exists(osp.join(path, f'latest.{suffix}')): return osp.join(path, f'latest.{suffix}') checkpoints = glob.glob(osp.join(path, f'*.{suf...
def is_chunk_start(prev_tag, tag): (prefix1, chunk_type1) = split_tag(prev_tag) (prefix2, chunk_type2) = split_tag(tag) if (prefix2 == 'O'): return False if (prefix1 == 'O'): return (prefix2 != 'O') if (chunk_type1 != chunk_type2): return True return ((prefix2 in ['B', 'S...
class ChatCompletionChunkChoice(TypedDict): index: int delta: ChatCompletionChunkDelta finish_reason: Optional[str]
class TestInitialStateBridge(BridgeTest): def _create_bridge(self, **kwargs): return InitialStateBridge(encoder_outputs=self.encoder_outputs, decoder_state_size=self.decoder_cell.state_size, params=kwargs, mode=tf.contrib.learn.ModeKeys.TRAIN) def _assert_correct_outputs(self, initial_state_): n...
def check_file_integrity(results_dir): config_file = os.path.join(results_dir, 'sweep_config.json') with open(config_file, 'r') as fp: flags = json.load(fp) flags['data_path'] = 'dummy' flags['save_path'] = 'dummy' (_, train_args) = hparams_sweep.make_args_list(flags) missing_files = 0 ...
class VGG(extractor.BaseModule): def __init__(self, config, name): super(VGG, self).__init__() self.name = name cfg = config['cfg'] in_channels = config['channels'] batch_norm = config['batch_norm'] self.features = make_layers(cfgs[cfg], batch_norm=batch_norm, in_chan...
def train(train_data, val_data, model, args): if args.maml: return maml.train(train_data, val_data, model, args) else: return regular.train(train_data, val_data, model, args)
def create_annotation_info(annotation_id, image_id, category_info, binary_mask, score=None, image_size=None, tolerance=2, bounding_box=None): if (image_size is not None): binary_mask = resize_binary_mask(binary_mask, image_size) binary_mask_encoded = mask.encode(np.asfortranarray(binary_mask.astype(np.u...
class DeepLabv3(nn.Module): def __init__(self, backbone='resnet101', output_stride=16, num_classes=21, norm_layer=nn.BatchNorm2d, freeze_bn=False, bn_mom=0.05, aspp_depth=256, pretrained=True): super(DeepLabv3, self).__init__() self.aspp_depth = aspp_depth self.output_stride = output_stride ...
def eval_single_ckpt(model, test_loader, args, eval_output_dir, logger, epoch_id, dist_test=False): model.load_params_from_file(filename=args.ckpt, logger=logger, to_cpu=dist_test) model.cuda() eval_utils.eval_one_epoch(cfg, model, test_loader, epoch_id, logger, dist_test=dist_test, result_dir=eval_output_d...
def sample_lp_star(preds): preds_ = preds[:] pred_num = len(preds) graph_depth = random.randint(2, (pred_num // 2)) width = (pred_num // graph_depth) preds_0 = preds_[:(pred_num % graph_depth)] preds_ = preds_[(pred_num % graph_depth):] rules = [] levels = [] prev_level = [[x, random...
_model_architecture('masked_lm', 'xlm_base') def xlm_architecture(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.share_encoder_input_output_embed = getattr(args, 'share_encoder_input_output_embed', True) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_...
def rdata_to_csv_for_aq(file_rdata, file_csv_output, rdata_df): call(['Rscript', '--vanilla', 'data_processing/rdata_to_csv_for_aq.r', file_rdata, file_csv_output, rdata_df])
def supported_features_mapping(*supported_features: str, onnx_config_cls: str=None) -> Dict[(str, Callable[([PretrainedConfig], OnnxConfig)])]: if (onnx_config_cls is None): raise ValueError('A OnnxConfig class must be provided') config_cls = transformers for attr_name in onnx_config_cls.split('.'):...
def action_invariance_constraint(logs, replay_dict, agent, ensemble_idx, a=None): (oo, _) = replay_dict['original_obs'] (ao, _) = replay_dict['augmented_obs'] actor = agent.actors[ensemble_idx] with torch.no_grad(): os_rep = agent.encoder(oo) o_dist = actor(os_rep) if (a is None)...
class D2vAudioConfig(D2vModalityConfig): type: Modality = Modality.AUDIO extractor_mode: str = 'layer_norm' feature_encoder_spec: str = field(default='[(512, 10, 5)] + [(512, 3, 2)] * 4 + [(512,2,2)] + [(512,2,2)]', metadata={'help': 'string describing convolutional feature extraction layers in form of a py...
class MaskedSoftmax(nn.Module): def __init__(self, dim): super(MaskedSoftmax, self).__init__() self.dim = dim def forward(self, logit, mask=None): if (mask is None): dist = F.softmax((logit - torch.max(logit, dim=self.dim, keepdim=True)[0]), dim=self.dim) else: ...
def _grad_boosting_hp_space(name_func, learning_rate=None, n_estimators=None, subsample=None, min_samples_split=None, min_samples_leaf=None, max_depth=None, init=None, random_state=None, max_features=None, verbose=0, max_leaf_nodes=None, warm_start=False, presort='auto'): hp_space = dict(learning_rate=(_grad_boosti...
def test_iterable(): sampler1 = UniformFloatSampler() sampler1._value = 0.5 sampler2 = UniformFloatSampler() sampler2._value = 0.5 sampler3 = UniformFloatSampler() sampler3._value = 0.5 assert (sampler3 not in [sampler1, sampler2])
def writeTrainValImageLabelPathPairsToTxtFile(data_home='../', useTrain=True, useVal=False): assert (useTrain or useVal), 'Error: None of the training set or the validation set is used.' train_home = osp.join(data_home, 'train') train_paths = os.listdir(train_home) val_home = osp.join(data_home, 'valid'...
def url_to_filename(url, etag=None): url_bytes = url.encode('utf-8') url_hash = sha256(url_bytes) filename = url_hash.hexdigest() if etag: etag_bytes = etag.encode('utf-8') etag_hash = sha256(etag_bytes) filename += ('.' + etag_hash.hexdigest()) return filename
_tokenizers class BertJapaneseCharacterTokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = BertJapaneseTokenizer def setUp(self): super().setUp() vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '', '', '', '', '', '', '', '', '', ''] self.vocab_file = os.path.join(sel...
def init_seed(seed): torch.cuda.cudnn_enabled = False torch.backends.cudnn.deterministic = True random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed)
class VehicleID(BaseImageDataset): dataset_dir = 'VehicleID_V1.0' def __init__(self, root='', verbose=True, test_size=800, **kwargs): super(VehicleID, self).__init__() self.dataset_dir = osp.join(root, self.dataset_dir) self.img_dir = osp.join(self.dataset_dir, 'image') self.spli...
class HelperFunction(AbstractMetaFeature): def __init__(self): super(HelperFunction, self).__init__() self.type_ = 'HELPERFUNCTION'
def check(opt): if (opt.model == 'pix2pix'): assert (opt.task in ['edges2shoes-r', 'map2sat', 'cityscapes', 'cityscapes_fast', 'edges2shoes-r_fast', 'map2sat_fast']) elif (opt.model == 'cycle_gan'): assert (opt.task in ['horse2zebra', 'horse2zebra_fast']) elif (opt.model == 'gaugan'): ...
def _find_human_readable_labels(synsets, synset_to_human): humans = [] for s in synsets: assert (s in synset_to_human), ('Failed to find: %s' % s) humans.append(synset_to_human[s]) return humans
class ResGN(nn.Module): def __init__(self, indim, outdim): super().__init__() self.res1 = ResBlock(indim, outdim) self.res2 = ResBlock(outdim, outdim) def forward(self, x): return self.res2(self.res1(x))
def csr_to_problem_nojit(l, x_val, x_ind, x_rowptr, prob_val, prob_ind, prob_rowptr): for i in range(l): x_slice = slice(x_rowptr[i], x_rowptr[(i + 1)]) prob_slice = slice(prob_rowptr[i], (prob_rowptr[(i + 1)] - 2)) prob_ind[prob_slice] = (x_ind[x_slice] + 1) prob_val[prob_slice] = x...
class Datagen_deepcom(): def __init__(self, X, Y, batch_size, code_dic, nl_dic, train=True): self.X = X self.Y = Y self.batch_size = batch_size self.code_dic = code_dic self.nl_dic = nl_dic self.train = train def __len__(self): return len(range(0, len(self...
def Swish(data, name=None): name = (GetLayerName.get('swish') if (name is None) else name) x = (data * mx.sym.sigmoid(data)) return x
class Mine_estimator(nn.Module): def __init__(self, input_dim=2048, hidden_dim=512): super(Mine_estimator, self).__init__() self.mine_model = Mine(input_dim, hidden_dim) def forward(self, X, Y): Y_shffle = Y[torch.randperm(len(Y))] loss_joint = self.mine_model(X, Y) loss_...
def imagenet_beit_base_in22k_pretrained(output_dim): model = timm.create_model('beit_base_patch16_224_in22k', pretrained=True) return _vit_replace_fc(model, output_dim)
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, max_norm: float=0): model.train() criterion.train() metric_logger = utils.MetricLogger(delimiter=' ') metric_logger.add_meter('lr', utils.Sm...
def set_seed(seed, use_cuda=True): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if use_cuda: torch.cuda.manual_seed_all(seed)
def get_teacher(args, data_info): heads = (([args.t_num_heads] * args.t_num_layers) + [args.t_num_out_heads]) model = GAT(data_info['g'], args.t_num_layers, data_info['num_feats'], args.t_num_hidden, data_info['n_classes'], heads, F.elu, args.in_drop, args.attn_drop, args.alpha, args.residual) return model
class CudaBuildExt(setuptools_build_ext): def run(self): if (CUDA is not None): def wrap_new_compiler(func): def _wrap_new_compiler(*args, **kwargs): try: return func(*args, **kwargs) except errors.DistutilsPlatformE...
class PSRoIPool(nn.Module): def __init__(self, output_size: int, spatial_scale: float): super(PSRoIPool, self).__init__() self.output_size = output_size self.spatial_scale = spatial_scale def forward(self, input: Tensor, rois: Tensor) -> Tensor: return ps_roi_pool(input, rois, se...
class ReacherBulletEnv_v1(ReacherBulletEnv): def __init__(self): self.robot = Reacher_v1() MJCFBaseBulletEnv.__init__(self, self.robot) def _step(self, a): assert (not self.scene.multiplayer) self.robot.apply_action(a) self.scene.global_step() state = self.robot.c...
def process_rollout(rollout, gamma, lambda_=1.0): batch_si = np.asarray(rollout.states) batch_a = np.asarray(rollout.actions) rewards = np.asarray(rollout.rewards) vpred_t = np.asarray((rollout.values + [rollout.r])) rewards_plus_v = np.asarray((rollout.rewards + [rollout.r])) batch_r = discount...
def plot_scatter(x, y, c, s, xlab: str, ylab: str, colorlab: str, sizelab: str, markersize_rescaling: int, figsize=(7, 3)): (fig, ax) = plt.subplots(dpi=500, figsize=figsize, facecolor='w') scatter = ax.scatter(x, y, c=c, s=s, alpha=1) plt.yscale('symlog') plt.xscale('symlog') leg_els = [Line2D([0],...
def move_dataset(): if on_cc(): from contrastyou import DATA_PATH return (f' find {DATA_PATH} ' + "-name '*.zip' -exec cp {} $SLURM_TMPDIR \\;") return ''
def parse_uri(path): path = path.strip() scheme = None if path.startswith(TFConstants.FILE_SCHEME()): scheme = TFConstants.FILE_SCHEME() elif path.startswith(TFConstants.FAKE_SCHEME()): scheme = TFConstants.FAKE_SCHEME() else: raise ValueError(('Wrong path provided: %s' % pat...
class T5Tokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'attention_mask'] def __init__(self, vocab_file, eos_token='</s>', un...
def to_tensor(value, device): if isinstance(value, RolloutBatch): return RolloutBatch(*to_tensor(list(value), device)) elif isinstance(value, list): return [to_tensor(x, device) for x in value] elif isinstance(value, tuple): return tuple(to_tensor(list(value), device)) elif isins...
def adjust_lr(optimizer, init_lr, epoch, decay_rate=0.1, decay_epoch=30): decay = (decay_rate ** (epoch // decay_epoch)) for param_group in optimizer.param_groups: param_group['lr'] *= decay
class BurgersNode(PdeNode): def __init__(self, u: str='u', v='v'): super().__init__() (x, t) = symbols('x t') input_variables = {'x': x, 't': t} assert (type(u) == str), 'u needs to be string' u = symbolize(u, input_variables) v = symbolize(v, input_variables) ...
def condensenet74_c4_g4(**kwargs): return get_condensenet(num_layers=74, groups=4, model_name='condensenet74_c4_g4', **kwargs)
def train(): cube_len = FLAGS.cube_len output_dir = os.path.join(FLAGS.output_dir, FLAGS.category) checkpoint_dir = os.path.join(output_dir, 'checkpoints') synthesis_dir = os.path.join(output_dir, 'recovery') log_dir = os.path.join(output_dir, 'log') obs = tf.placeholder(tf.float32, [None, cube_...
def initialize(n_parallel): try: signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGINT]) singleton_pool.initialize(n_parallel) singleton_pool.run_each(_worker_init, [(id,) for id in range(singleton_pool.n_parallel)]) finally: signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.S...
class View(Module): def __init__(self, *args): super(View, self).__init__() if ((len(args) == 1) and isinstance(args[0], torch.Size)): self.size = args[0] else: self.size = torch.Size(args) def forward(self, input): return input.view(self.size)
def load_ckpt(args, model, optimizer=None, scheduler=None, val_err=[]): if os.path.isfile(args.load_ckpt): logger.info('loading checkpoint %s', args.load_ckpt) checkpoint = torch.load(args.load_ckpt, map_location=(lambda storage, loc: storage), pickle_module=dill) model_state_dict_keys = mod...
def split_data_TM(x_TM, y_TM, seq_len_TM, split_indices): x_TM_split = [] y_TM_split = [] seq_len_TM_split = [] for i in split_indices: x_TM_split.append(x_TM[i]) y_TM_split.append(y_TM[i]) seq_len_TM_split.append(seq_len_TM[i]) return (np.array(x_TM_split), np.array(y_TM_spl...
class TestPatientSampler(TestCase): def setUp(self) -> None: super().setUp() self.dataset_root = './' self.dataset_subfolders = ['img', 'gt'] if Path(self.dataset_root, ACDCDataset.folder_name).exists(): shutil.rmtree(Path(self.dataset_root, ACDCDataset.folder_name), igno...
def make_k_circles(k=2, n_samples=100, shuffle=False, noise=None, random_state=None, factor=0.8, c=None, rot=None): if ((not (factor is None)) and ((factor >= 1) or (factor < 0))): raise ValueError("'factor' has to be between 0 and 1.") if ((factor is None) and (c is None)): raise ValueError("on...
class TRPOIPOBuffer(): def __init__(self, obs_dim, act_dim, size, gamma=0.99, lam=0.95): self.obs_buf = np.zeros(core.combined_shape(size, obs_dim), dtype=np.float32) self.act_buf = np.zeros(core.combined_shape(size, act_dim), dtype=np.float32) self.adv_buf = np.zeros(size, dtype=np.float32)...
def test_point_assigner_with_empty_boxes_and_gt(): self = PointAssigner() points = torch.FloatTensor([]) gt_bboxes = torch.FloatTensor([]) assign_result = self.assign(points, gt_bboxes) assert (len(assign_result.gt_inds) == 0)
class DenoiseBlock(nn.Module): def __init__(self, in_channels, inner_channels, out_channels, levels): super().__init__() self.levels = [(l / 255) for l in levels] self.conv_0 = HyperConv(self.levels, in_channels, inner_channels, kernel_size=3, padding=1) self.conv_1 = HyperConv(self....
class ConcatDataset(FairseqDataset): def cumsum(sequence, sample_ratios): (r, s) = ([], 0) for (e, ratio) in zip(sequence, sample_ratios): curr_len = int((ratio * len(e))) r.append((curr_len + s)) s += curr_len return r def __init__(self, datasets, sam...
def masked_gaussian_log_density(mu, data, obsrv_std, mask, temporal_weights=None): (n_traj_samples, n_traj, n_timepoints, n_dims) = mu.size() assert (data.size()[(- 1)] == n_dims) func = (lambda mu, data: gaussian_log_likelihood(mu, data, obsrv_std=obsrv_std)) res = compute_masked_likelihood(mu, data, m...
def write_feature_info(out_path): event_des = EventDescription() outf = file(out_path, 'w') for event_id in range(2, (max(event_des.id2rtype.keys()) + 1)): rtype = event_des.id2rtype[event_id] names = event_des.get_name(rtype) obj = {'event_id': event_id, 'rtype': rtype, 'text_featur...
class DenSPIServer(object): def __init__(self, args): self.args = args self.base_ip = args.base_ip self.query_port = args.query_port self.doc_port = args.doc_port self.index_port = args.index_port self.mips = None def load_query_encoder(self, device, args): ...
class TestMetrics(unittest.TestCase): def test_nesting(self): with metrics.aggregate() as a: metrics.log_scalar('loss', 1) with metrics.aggregate() as b: metrics.log_scalar('loss', 2) self.assertEqual(a.get_smoothed_values()['loss'], 1.5) self.assertEq...
class Proper_Noun_Rate(object): def __init__(self, sentence_objs): self.sentence_objs = sentence_objs def handle(self): (tot_num_pron, tot_num_words) = (0, 0) for so in self.sentence_objs: tot_num_pron += so.pos_tag_counter.get_pos_tag_count(PROPER_NOUN) tot_num_w...
class ResizeVideo(object): def __init__(self, target_size, interpolation_mode='bilinear'): self.target_size = target_size self.interpolation_mode = interpolation_mode def __call__(self, clip): return F.resize(clip, self.target_size, self.interpolation_mode) def __repr__(self): ...
class _FP16OptimizerMixin(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._multiply_factor = 1.0 def has_flat_params(self): return (torch.is_tensor(self.fp32_params) or (isinstance(self.fp32_params, dict) and all((torch.is_tensor(t) for t in self.fp32...
_module class DefaultFormatBundle(object): def __call__(self, results): if ('img' in results): img = results['img'] if (len(img.shape) < 3): img = np.expand_dims(img, (- 1)) img = np.ascontiguousarray(img.transpose(2, 0, 1)) results['img'] = DC...
def MSLE(y_true: 'ndarray', y_pred: 'ndarray', multioutput: str='raw_values') -> Union[(float64, 'ndarray')]: (y_true, y_pred, original_shape) = _standardize_input(y_true, y_pred, multioutput) result = mean_squared_log_error(y_true, y_pred, multioutput=multioutput) if (multioutput == 'raw_values'): ...
def test_cross_module_exceptions(msg): with pytest.raises(RuntimeError) as excinfo: cm.raise_runtime_error() assert (str(excinfo.value) == 'My runtime error') with pytest.raises(ValueError) as excinfo: cm.raise_value_error() assert (str(excinfo.value) == 'My value error') with pytest...
class FeedForward(nn.Module): def __init__(self, dim, dropout=0.0, mult=4.0): super().__init__() self.net = nn.Sequential(nn.Linear(dim, ((dim * mult) * 2)), GEGLU(), nn.Dropout(dropout), nn.Linear((dim * mult), dim)) def forward(self, x): return self.net(x)
class Compose(object): def __init__(self, mytransforms: list): self.transforms = mytransforms for t in mytransforms: assert any([isinstance(t, Resize), isinstance(t, RandomCrop), isinstance(t, RandomHorizontalFlip), isinstance(t, RandomVerticalFlip), isinstance(t, transforms.ToTensor), i...
def singularize(word, pos=NOUN, custom={}): if (word in custom): return custom[word] w = word.lower() if (pos == 'DT'): if (w in ('i', 'gli')): return 'il' if (w == 'el'): return 'la' return w if (len(w) < 3): return w if (w in singular...
class LxmertEncoder(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test_trainer(trainer, iterations=30, allow_gpu=False): create_env = trainer.unwrapped.create_env def wrap_env(env): (env, original) = fake_env(env) print(('Faked environment: %s' % original.__class__.__name__)) return env def _create_env(*args, **kwargs): env = create_env...
class DIAResUnit(nn.Module): def __init__(self, in_channels, out_channels, stride, padding=1, dilation=1, bottleneck=True, conv1_stride=False, attention=None): super(DIAResUnit, self).__init__() self.resize_identity = ((in_channels != out_channels) or (stride != 1)) if bottleneck: ...
def resolve_precision(precision: str): assert (precision in ('amp', 'float16', 'bfloat16', 'float32')) use_amp = False model_dtype = torch.float32 data_dtype = torch.float32 if (precision == 'amp'): use_amp = True elif (precision == 'float16'): model_dtype = torch.float16 ...
def process_document(doc_name, part_name, gold_doc, auto_doc, out, remove_singletons=True): for ofile in [out['out'], out['short out']]: print('', file=ofile) print(('-' * 79), file=ofile) print(doc_name, part_name, file=ofile) print(('-' * 79), file=ofile) print('', file=ofi...
def read_fed_dataset(cfg: DictConfig): if cfg.name.startswith('comb/'): from .multi_domain import MDFedDataset as FedDataset elif ((cfg.name in ('Mnist', 'MnistM', 'SVHN', 'USPS')) or cfg.name.startswith('ReviewBow') or cfg.name.startswith('ReviewTok') or cfg.name.startswith('Office31') or cfg.name.star...
def all_reduce_dict(data: Mapping[(str, Any)], device, group=None) -> Dict[(str, Any)]: data_keys = list(data.keys()) cpu_data = OrderedDict() device_data = OrderedDict() for k in data_keys: t = data[k] if (not torch.is_tensor(t)): cpu_data[k] = torch.tensor(t, dtype=torch.do...
def copy_file(source_file: str, destination_file: str) -> str: os.makedirs(os.path.dirname(destination_file), exist_ok=True) shutil.copyfile(source_file, destination_file) return destination_file
def wrap_agent_env(thunk): from ..common.env import ScaledFloatFrame, TransposeImage def _thunk(): env = thunk() env = TransposeImage(env) env = ScaledFloatFrame(env) return env return _thunk
def cal_PMI(data_root_path, vocab_root_path, min_count, phase='train', window_size=6, min_cooccurence=2): vocab = get_vocab_list(data_root_path, vocab_root_path, min_count) all_text = get_content(data_root_path) all_text = text_padding(all_text) d = dict(zip(vocab, range(len(vocab)))) pair_count_mat...
def rollout_representation(representation_model, steps, obs_embed, action, prev_states, done): priors = [] posteriors = [] for t in range(steps): (prior_states, posterior_states) = representation_model(obs_embed[t], action[t], prev_states) prev_states = posterior_states.map((lambda x: (x * (...
class GaussianDropout(ZooKerasLayer): def __init__(self, p, input_shape=None, **kwargs): super(GaussianDropout, self).__init__(None, float(p), (list(input_shape) if input_shape else None), **kwargs)
def check_env_flag(name: str, default: bool=False) -> bool: if default: return (not (os.getenv(name, '').upper() in ['OFF', '0', 'FALSE', 'NO', 'N'])) else: return (os.getenv(name, '').upper() in ['ON', '1', 'TRUE', 'YES', 'Y'])