code
stringlengths
101
5.91M
class ModelAccumulator(object): def __init__(self, running_model: nn.Module, n_accum, num_model, local_bn=False, raise_err_on_early_accum=True): self.n_accum = n_accum self._cnt = 0 self.local_bn = local_bn self._weight_sum = 0 self.raise_err_on_early_accum = raise_err_on_ear...
def test_raabbvi_avgrmsprop_optimize(): for scales in [np.ones(2), np.ones(4), np.geomspace(0.1, 1, 4)]: true_value = np.arange(scales.size) objective = DummyObjective(true_value, noise=0.2, scales=scales) sgd = RAABBVI(AveragedRMSProp(0.01, diagnostics=True), rho=0.5, mcse_threshold=0.002, ...
class Clothing(torch.utils.data.Dataset): def __init__(self, root, transform, mode): self.root = root self.noisy_labels = {} self.clean_labels = {} self.data = [] self.targets = [] self.transform = transform self.mode = mode with open((self.root + 'noi...
.parametrize('multi_optimizers', (True, False)) def test_cosine_restart_lr_update_hook(multi_optimizers): with pytest.raises(AssertionError): CosineRestartLrUpdaterHook(by_epoch=False, periods=[2, 10], restart_weights=[0.5, 0.5], min_lr=0.1, min_lr_ratio=0) with pytest.raises(AssertionError): Co...
class CosineAnnealingLR(_LRScheduler): def __init__(self, optimizer, T_max, eta_min=0, last_epoch=(- 1)): self.T_max = T_max self.eta_min = eta_min super(CosineAnnealingLR, self).__init__(optimizer, last_epoch) def get_lr(self): return [(self.eta_min + (((base_lr - self.eta_min) ...
def check_all_objects_are_documented(): documented_objs = find_all_documented_objects() modules = transformers._modules objects = [c for c in dir(transformers) if ((c not in modules) and (not c.startswith('_')))] undocumented_objs = [c for c in objects if ((c not in documented_objs) and (not ignore_undo...
def load_decoder(weights, model): model.conditioning_emb[0].weight = nn.Parameter(torch.FloatTensor(weights['time_emb_dense0']['kernel'].T)) model.conditioning_emb[2].weight = nn.Parameter(torch.FloatTensor(weights['time_emb_dense1']['kernel'].T)) model.position_encoding.weight = nn.Parameter(torch.FloatTen...
def init_distributed_mode(args): args.is_slurm_job = ('SLURM_JOB_ID' in os.environ) if args.is_slurm_job: args.rank = int(os.environ['SLURM_PROCID']) args.world_size = (int(os.environ['SLURM_NNODES']) * int(os.environ['SLURM_TASKS_PER_NODE'][0])) else: args.rank = int(os.environ['RAN...
def main(config: ROSTrainerConfig) -> None: config.set_timestamp() if config.data: CONSOLE.log('Using --data alias for --data.pipeline.datamanager.dataparser.data') config.pipeline.datamanager.dataparser.data = config.data config.print_to_terminal() config.save_config() try: ...
class Agent(object): def __init__(self, height, width, channel, num_class, ksize, radix=4, kpaths=4, learning_rate=0.001, ckpt_dir='./Checkpoint'): print('\nInitializing Short-ResNeSt...') (self.height, self.width, self.channel, self.num_class, self.ksize, self.radix, self.kpaths) = (height, width, ...
class Logger(object): def __init__(self, path, header, mode='w'): self.log_file = open(path, mode=mode) self.logger = csv.writer(self.log_file, delimiter='\t') if (mode is not 'a'): self.logger.writerow(header) self.header = header def __del(self): self.log_fi...
def construct_H_with_KNN(X, K_neigs=[10], is_probH=False, m_prob=1): if (len(X.shape) != 2): X = X.reshape((- 1), X.shape[(- 1)]) if (type(K_neigs) == int): K_neigs = [K_neigs] dis_mat = cos_dis(X) H = None for k_neig in K_neigs: H_tmp = construct_H_with_KNN_from_distance(dis...
def clip_gelu(model, maxval): for (name, mod) in model.named_modules(): if (name.endswith('.output.dense') and (not name.endswith('attention.output.dense'))): amax_init = mod._input_quantizer._amax.data.detach().item() mod._input_quantizer._amax.data.detach().clamp_(max=maxval) ...
class STORAL1(DataProcessor): def __init__(self): super().__init__() def get_examples(self, data_dir, split): path = os.path.join(data_dir, f'{split}.jsonl') with open(path, encoding='utf8') as f: for line in f: example_json = json.loads(line) ...
def get_theme(name): if (name not in __themes__): raise ValueError(f"Theme '{name}' not found.") return __themes__[name]()
class UPerNet(nn.Module): def __init__(self, num_class=150, fc_dim=4096, use_softmax=False, pool_scales=(1, 2, 3, 6), fpn_inplanes=(256, 512, 1024, 2048), fpn_dim=256): super(UPerNet, self).__init__() self.use_softmax = use_softmax self.ppm_pooling = [] self.ppm_conv = [] for...
.parametrize('old_size', [141, 32, 17, 6, 3]) .parametrize('new_size', [141, 32, 17, 6, 3]) def test_resize_head_1d(old_size, new_size, depth=1000): old_shape = (old_size,) np.random.seed(0) p = 8 bits = np.random.randint((1 << p), size=((depth,) + old_shape), dtype=np.uint64) message = cs.base_mess...
def parse_nnet2_to_nnet3(line_buffer): model = Nnet3Model() model.transition_model = parse_transition_model(line_buffer) (line, model.num_components) = parse_nnet2_header(line_buffer) while True: if line.startswith('</Components>'): break (component, pairs) = parse_component(...
class ConstructEnvsSampler(TaskSampler): def __init__(self, env_constructors): self._env_constructors = env_constructors def n_tasks(self): return len(self._env_constructors) def sample(self, n_tasks, with_replacement=False): return [NewEnvUpdate(self._env_constructors[i]) for i in _...
class InfiniteBatchSampler(Sampler): def __init__(self, dataset, batch_size=1, world_size=None, rank=None, seed=0, shuffle=True): (_rank, _world_size) = get_dist_info() if (world_size is None): world_size = _world_size if (rank is None): rank = _rank self.rank...
class ResponseGenerator(): def add_refresh(response: Response, refresh_time: int) -> Response: response.headers['refresh'] = refresh_time return response def from_exception(exception: Exception) -> Response: return Response(response=str(exception), status=ResponseGenerator.get_status_cod...
def _SpikeTorchConv(*args, input_): states = [] if ((len(args) == 1) and (type(args) is not tuple)): args = (args,) for arg in args: arg = arg.to('cpu') arg = torch.Tensor(arg) arg = torch.zeros_like(input_, requires_grad=True) states.append(arg) if (len(states) =...
class MXNetRunner(object): def setup_distributed(self, env, config, model_creator, loss_creator=None, validation_metrics_creator=None, eval_metrics_creator=None): logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger() self.config = config self.model_creator = model...
def flow_embedding_module(xyz1, xyz2, feat1, feat2, radius, nsample, mlp, is_training, bn_decay, scope, bn=True, pooling='max', knn=True, corr_func='elementwise_product'): if knn: (_, idx) = knn_point(nsample, xyz2, xyz1) else: (idx, cnt) = query_ball_point(radius, nsample, xyz2, xyz1) (...
def HPF1(data, cutoff, q, order=5): (b, a) = sig.butter(order, cutoff, btype='high', analog=False) y = sig.lfilter(b, a, data) return y
def create_student_by_copying_alternating_layers(teacher: Union[(str, PreTrainedModel)], save_path: Union[(str, Path)]='student', e: Union[(int, None)]=None, d: Union[(int, None)]=None, copy_first_teacher_layers=False, e_layers_to_copy=None, d_layers_to_copy=None, **extra_config_kwargs) -> Tuple[(PreTrainedModel, List[...
_model def dm_nfnet_f1(pretrained=False, **kwargs): return _create_normfreenet('dm_nfnet_f1', pretrained=pretrained, **kwargs)
def vgg19(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> VGG: return VGG(torchvision.models.vgg19(pretrained, progress, **kwargs))
def create_iNat18(task='train'): src_root = '/path/to/iNat18' dst_root = '/diskC/xzz/iNat18' if (not os.path.exists(os.path.join(dst_root, task, '0'))): for i in range(8142): pth = os.path.join(dst_root, task, str(i)) os.makedirs(pth, exist_ok=True) with open(os.path.join...
_config def cfg_habitat(): uuid = 'habitat_core' cfg = {} cfg['learner'] = {'algo': 'ppo', 'clip_param': 0.1, 'entropy_coef': 0.0001, 'eps': 1e-05, 'gamma': 0.99, 'internal_state_size': 512, 'lr': 0.0001, 'num_steps': 1000, 'num_mini_batch': 8, 'num_stack': 4, 'max_grad_norm': 0.5, 'ppo_epoch': 8, 'recurren...
def make_master_params(param_groups_and_shapes): master_params = [] for (param_group, shape) in param_groups_and_shapes: master_param = nn.Parameter(_flatten_dense_tensors([param.detach().float() for (_, param) in param_group]).view(shape)) master_param.requires_grad = True master_params...
def init_matrix(data): for i in range(len(data)): data[i][0] = float('inf') for i in range(len(data[0])): data[0][i] = float('inf') data[0][0] = 0 return data
def test_add_edges_sum(g1, g2): assert (g1.num_e == 2) g1.add_edges((3, 2), e_weight=0.5, merge_op='sum') assert (g1.num_e == 3) assert ((2, 3) in g1.e[0]) assert ((3, 2) not in g1.e[0]) assert (g1.A[(3, 2)] == 0.5) assert (g2.num_e == 3) g2.add_edges(((1, 2), (1, 3)), e_weight=[0.1, 0.2...
def merge(b, graph): merge_rules = list(merge_coalesce_rules) merge_rules.append(merge_delete_rule) graph = apply_confluent_gts(b, graph, merge_rules, apply_cleanup_rules=False) return graph
_torch _staging_test class DynamicPipelineTester(unittest.TestCase): vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'I', 'love', 'hate', 'you'] def setUpClass(cls): cls._token = TOKEN HfFolder.save_token(TOKEN) def tearDownClass(cls): try: delete_repo(token...
class TestSequenceGenerator(unittest.TestCase): def setUp(self): (self.tgt_dict, self.w1, self.w2, src_tokens, src_lengths, self.model) = test_utils.sequence_generator_setup() self.sample = {'net_input': {'src_tokens': src_tokens, 'src_lengths': src_lengths}} def test_with_normalization(self): ...
def get_option_setter(distiller_name): distiller_class = find_distiller_using_name(distiller_name) return distiller_class.modify_commandline_options
_optimizer('adamax') class FairseqAdamax(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = Adamax(params, **self.optimizer_config) def add_args(parser): parser.add_argument('--adamax-betas', default='(0.9, 0.999)', metavar='B', help='betas for ...
def backup(src_folder, backup_files, backup_folder): if (not backup_files): print('No backup required for', src_folder) return os.chdir(src_folder) if (not os.path.exists(backup_folder)): os.makedirs(backup_folder) for file in backup_files: os.rename(file, ((backup_folder...
def collate_int_fn(batch, *, collate_fn_map: Optional[Dict[(Union[(Type, Tuple[(Type, ...)])], Callable)]]=None): return torch.tensor(batch)
class PegBoxEnv(BaseEnv, utils.EzPickle): def __init__(self, xml_path, cameras, n_substeps=20, observation_type='image', reward_type='dense', image_size=84, use_xyz=False, render=False): self.sample_large = 1 BaseEnv.__init__(self, get_full_asset_path(xml_path), n_substeps=n_substeps, observation_ty...
class OSBlockINin(nn.Module): def __init__(self, in_channels, out_channels, reduction=4, T=4, **kwargs): super(OSBlockINin, self).__init__() assert (T >= 1) assert ((out_channels >= reduction) and ((out_channels % reduction) == 0)) mid_channels = (out_channels // reduction) s...
def load_json(file): with open(file) as json_file: data = json5.load(json_file) return data
class UpDownCore(att_model.UpDownCore): def __init__(self, config, use_maxout=False): nn.Module.__init__(self) self.config = config self.drop_prob_lm = config.drop_prob_lm mask_params = {'mask_type': self.config.prune_type, 'mask_init_value': self.config.prune_supermask_init} ...
def test_compat_loader_args(): cfg = ConfigDict(dict(data=dict(val=dict(), test=dict(), train=dict()))) cfg = compat_loader_args(cfg) assert ('val_dataloader' in cfg.data) assert ('train_dataloader' in cfg.data) assert ('test_dataloader' in cfg.data) cfg = ConfigDict(dict(data=dict(samples_per_g...
class ResNet_MPNCOV(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(ResNet_MPNCOV, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d ...
class ConjugateConstraintOptimizer(Serializable): def __init__(self, cg_iters=10, verbose_cg=False, resample_inputs=False, reg_coeff=1e-05, subsample_factor=1.0, backtrack_ratio=0.8, max_backtracks=15, accept_violation=False, hvp_approach=None, num_slices=1, linesearch_infeasible_recovery=True): Serializabl...
def adjust_lr(optimizer, init_lr, epoch, decay_rate=0.1, decay_epoch=5): decay = (decay_rate ** (epoch // decay_epoch)) for param_group in optimizer.param_groups: param_group['lr'] *= decay
def evaluate(sess_config, input_hooks, model, data_init_op, steps, checkpoint_dir): model.is_training = False hooks = [] hooks.extend(input_hooks) scaffold = tf.compat.v1.train.Scaffold(local_init_op=tf.group(tf.compat.v1.local_variables_initializer(), data_init_op)) session_creator = tf.compat.v1.t...
def test_piecewise_schedule(): ps = PiecewiseSchedule([((- 5), 100), (5, 200), (10, 50), (100, 50), (200, (- 50))], outside_value=500) assert np.isclose(ps.value((- 10)), 500) assert np.isclose(ps.value(0), 150) assert np.isclose(ps.value(5), 200) assert np.isclose(ps.value(9), 80) assert np.isc...
def compute_similarity_transform(source_points, target_points): assert (target_points.shape[0] == source_points.shape[0]) assert ((target_points.shape[1] == 3) and (source_points.shape[1] == 3)) source_points = source_points.T target_points = target_points.T mu1 = source_points.mean(axis=1, keepdims...
class BitPreTrainedModel(PreTrainedModel): config_class = BitConfig base_model_prefix = 'bit' main_input_name = 'pixel_values' supports_gradient_checkpointing = True def _init_weights(self, module): if isinstance(module, nn.Conv2d): nn.init.kaiming_normal_(module.weight, mode='fa...
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 = subprocess.check_output(['sha256sum', out_file]).decode() final_file = (out_file.rstrip('.pth') +...
def create_model_from_pretrained(model_name: str, pretrained: str, precision: str='fp32', device: Union[(str, torch.device)]='cpu', jit: bool=False, force_quick_gelu: bool=False, force_custom_text: bool=False, return_transform: bool=True, image_mean: Optional[Tuple[(float, ...)]]=None, image_std: Optional[Tuple[(float,...
def validate_flags_or_throw(bert_config): tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case, FLAGS.init_checkpoint) if ((not FLAGS.do_train) and (not FLAGS.do_predict)): raise ValueError('At least one of `do_train` or `do_predict` must be True.') if FLAGS.do_train: if (not FL...
class Generic_UNet(SegmentationNetwork): DEFAULT_BATCH_SIZE_3D = 2 DEFAULT_PATCH_SIZE_3D = (64, 192, 160) SPACING_FACTOR_BETWEEN_STAGES = 2 BASE_NUM_FEATURES_3D = 30 MAX_NUMPOOL_3D = 999 MAX_NUM_FILTERS_3D = 320 DEFAULT_PATCH_SIZE_2D = (256, 256) BASE_NUM_FEATURES_2D = 30 DEFAULT_BAT...
class ActionsAdapter(): def __init__(self): self.renderer = None self.parser = None self.dataset = IGLUDataset() def action_space(self): env = gym.make('IGLUGridworldVector-v0') action_space = env.action_space del env return action_space def has_buffer...
def _reshape_raw_ferminet_orbitals(orbitals: ArrayList, ndeterminants: int) -> ArrayList: orbitals = [jnp.reshape(orb, (*orb.shape[:(- 1)], ndeterminants, (orb.shape[(- 1)] // ndeterminants))) for orb in orbitals] return [jnp.moveaxis(orb, (- 2), 0) for orb in orbitals]
def choose_label(input_file, output_file): with open(input_file, 'r') as in_file: fins = in_file.readlines() with open(output_file, 'w') as fout: for line in fins: if (len(line) < 3): fout.write(line) else: pairs = line.strip('\n').split(' ...
def Process_1000(args): random.seed(args.seed) tata_train = (args.file_path + 'TATA_scan_train.csv') notata_train = (args.file_path + 'noTATA_scan_train.csv') tata_train_file = open(tata_train, 'r', encoding='utf-8-sig') notata_train_file = open(notata_train, 'r', encoding='utf-8-sig') tata_trai...
class UniformWindowWithoutOverlapSpotClipSampler(SpotClipSampler): def __init__(self, data_source: Spot, windows_per_video: int=50, window_num_frames: int=32, sample_edges: bool=False, prevent_resample_edges: bool=True, shuffle: bool=False) -> None: super().__init__(data_source, shuffle=shuffle) sel...
def make_solved_cube(cube_size: int) -> Cube: return jnp.stack([(face.value * jnp.ones((cube_size, cube_size), dtype=jnp.int8)) for face in Face])
def mzip(x, y): if (x.dtype == tf.bfloat16): x = r_cast(x) y = r_cast(y) return zip(x, y)
class TestSummarizationDistillerMultiGPU(TestCasePlus): def setUpClass(cls): return cls _torch_multi_gpu def test_multi_gpu(self): updates = {'no_teacher': True, 'freeze_encoder': True, 'gpus': 2, 'overwrite_output_dir': True, 'sortish_sampler': True} self._test_distiller_cli_fork(up...
def glue_eval_data_collator(dataset: Dataset, batch_size: int): for i in range((len(dataset) // batch_size)): batch = dataset[(i * batch_size):((i + 1) * batch_size)] batch = {k: np.array(v) for (k, v) in batch.items()} batch = shard(batch) (yield batch)
def _create_hrnet(variant, pretrained, **model_kwargs): model_cls = HighResolutionNet features_only = False kwargs_filter = None if model_kwargs.pop('features_only', False): model_cls = HighResolutionNetFeatures kwargs_filter = ('num_classes', 'global_pool') features_only = True ...
class Basis_GauSH(Basis): def __init__(self, Name_=None): Basis.__init__(self, Name_) self.type = 'GauSH' self.RBFS = np.tile(np.array([[0.1, 0.156787], [0.3, 0.3], [0.5, 0.5], [0.7, 0.7], [1.3, 1.3], [2.2, 2.4], [4.4, 2.4], [6.6, 2.4], [8.8, 2.4], [11.0, 2.4], [13.2, 2.4], [15.4, 2.4]]), (1...
def convert_example_to_features(example, max_seq_length, tokenizer): tokens_a = example.tokens_a tokens_b = example.tokens_b _truncate_seq_pair(tokens_a, tokens_b, (max_seq_length - 3)) (tokens_a, t1_label) = random_word(tokens_a, tokenizer) (tokens_b, t2_label) = random_word(tokens_b, tokenizer) ...
def psi1(mean, var, a, b, ms): omegas = (((2.0 * np.pi) * ms) / (b - a)) Kuf_cos = tf.transpose(tf.cos((omegas * (mean - a)))) omegas = omegas[(omegas != 0)] Kuf_sin = tf.transpose(tf.sin((omegas * (mean - a)))) a = tf.transpose(tf.exp((((- tf.square(omegas)) * var) / 2))) Psi1_cos = (Kuf_cos * ...
def standard_laurent_embed(nvar, topdim, pols, verbose_level=0): from phcpy.phcpy2c3 import py2c_embed_standard_Laurent_system from phcpy.interface import store_standard_laurent_system from phcpy.interface import load_standard_laurent_system store_standard_laurent_system(pols, nbvar=nvar) py2c_embed...
class ShapeGenerator(): def generate_shape(self, name, geometry, color=None): color = ([0.5, 0.5, 0.5, 1] if (color is None) else color) return f''' <robot name="{name}"> <link name="base_link"> <visual> <!-- visual origin is defined w.r.t. link local coor...
def sepreresnet164bn_cifar10(num_classes=10, **kwargs): return get_sepreresnet_cifar(num_classes=num_classes, blocks=164, bottleneck=True, model_name='sepreresnet164bn_cifar10', **kwargs)
class BratsSampler(Sampler): def __init__(self, dataset, n_patients, n_samples): self.batch_size = (n_patients * n_samples) self.n_samples = n_samples self.n_patients = n_patients self.dataset_indices = list(range(0, len(dataset))) def __iter__(self): batch_indices = [] ...
class UniformReplay(): def sample_batch(self, batch_B): (T_idxs, B_idxs) = self.sample_idxs(batch_B) return self.extract_batch(T_idxs, B_idxs) def sample_idxs(self, batch_B): (t, b, f) = (self.t, self.off_backward, self.off_forward) high = (((self.T - b) - f) if self._buffer_full...
class EltwiseParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _ELTWISEPARAMETER
class _AssertNoLogsContext(unittest.case._AssertLogsContext): def __exit__(self, exc_type, exc_value, tb): self.logger.handlers = self.old_handlers self.logger.propagate = self.old_propagate self.logger.setLevel(self.old_level) if (exc_type is not None): return False ...
class TFBertLMHeadModel(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
def assert_scipy_wav_style(value): assert is_scipy_wav_style(value), 'Must be Tuple[int, numpy.ndarray], but got {}'.format((type(value) if (not isinstance(value, Sequence)) else '{}[{}]'.format(type(value), ', '.join((str(type(v)) for v in value)))))
def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') top5 = AverageMeter('', ':6.2f') (MI_XTs, MI_TYs) = ([], []) progress...
class SuperResIDWE4K5(SuperResIDWEXKX): def __init__(self, in_channels=None, out_channels=None, stride=None, bottleneck_channels=None, sub_layers=None, no_create=False, **kwargs): super(SuperResIDWE4K5, self).__init__(in_channels=in_channels, out_channels=out_channels, stride=stride, bottleneck_channels=bot...
def metric_fn(pred, label, metric='IC'): mask = (~ torch.isnan(label)) if (metric == 'IC'): return calc_ic(pred[mask], label[mask]) elif (metric == 'R2'): return calc_r2(pred[mask], label[mask])
class VisionTouchDataset(Dataset): def __init__(self, phase, data_lst_file, w_timewindow, trans_des=None, trans_lowres=None, trans_to_tensor=None, scale_size=None, crop_size=None, brightness=None, contrast=None, saturation=None, hue=None, loader=default_loader): self.phase = phase self.recs = open(d...
class FlavaConfig(PretrainedConfig): model_type = 'flava' is_composition = True def __init__(self, image_config: Dict[(str, Any)]=None, text_config: Dict[(str, Any)]=None, multimodal_config: Dict[(str, Any)]=None, image_codebook_config: Dict[(str, Any)]=None, hidden_size: int=768, layer_norm_eps: float=1e-1...
class FlaxBertForPreTraining(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def resnest(): device = torch.device('cpu') cfg_file = 'tests/configs/resnet-resnext/senet-skent-resnest/resnest50_2s2x40d.yaml' cfg.merge_from_file(cfg_file) model = build_recognizer(cfg, device) print(model)
def mynorm(arr): amin = np.amin(arr) return np.absolute(((arr - amin) / ((np.amax(arr) - amin) + 1e-18)))
class Dataloader(object): def __init__(self, data_location, batch_size): self.batch_size = batch_size self.data_file = data_location self.total_samples = sum((1 for _ in tf.compat.v1.python_io.tf_record_iterator(data_location))) self.n = math.ceil((float(self.total_samples) / batch_s...
class CollisionCondition(AbstractCondition): def __init__(self, not_allowed): super(CollisionCondition, self).__init__() if ((not isinstance(not_allowed, int)) and (not isinstance(not_allowed, long))): raise TypeError('collision condition requires int handle') self.not_allowed = ...
class SubDataset(object): def __init__(self, name, root, anno, frame_range, num_use, start_idx): cur_path = 'your_project_path/pysot' self.name = name self.root = os.path.join(cur_path, root) self.anno = os.path.join(cur_path, anno) self.frame_range = frame_range self...
class ASTPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class DeployModel(Model): def __init__(self, arch: Union[(NetType, CType)]): super().__init__(arch) self.eval() def step(self): raise RuntimeError(f'{self.__class__.__name__} does not support `step` method.') def schedulerStep(self, *args, **kwargs): raise RuntimeError(f'{sel...
class DependencySubmititLauncher(BaseSubmititLauncher): _EXECUTOR = 'slurm' def launch(self, job_overrides: Sequence[Sequence[str]], initial_job_idx: int) -> Sequence[JobReturn]: import submitit assert (self.config is not None) num_jobs = len(job_overrides) assert (num_jobs > 0) ...
def get_ckpt_path(name, root=None, check=False): if ('church_outdoor' in name): name = name.replace('church_outdoor', 'church') assert (name in URL_MAP) cachedir = os.environ.get('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) root = (root if (root is not None) else os.path.join(cachedir, 'dif...
def eval_step(H, data_input, target, ema_params, rng): return lax.pmean(VAE(H).apply({'params': ema_params}, data_input, target, rng), 'batch')
def test_actionAngleTorus_isochroneApprox_actions(): from galpy.actionAngle import actionAngleIsochroneApprox, actionAngleTorus from galpy.potential import MWPotential2014 aAIA = actionAngleIsochroneApprox(pot=MWPotential2014, b=0.8) tol = (- 2.5) aAT = actionAngleTorus(pot=MWPotential2014, tol=tol)...
class Evaluator(): def __init__(self, eval_env: Environment, agent: Agent, total_batch_size: int, stochastic: bool): self.eval_env = eval_env self.agent = agent self.num_local_devices = jax.local_device_count() self.num_global_devices = jax.device_count() self.num_workers = (...
def augment_and_repeat_episode_data(episode_data, problem_size, nb_runs, aug_s): node_data = episode_data[0] batch_size = node_data.shape[0] node_xy = node_data if (nb_runs > 1): assert (batch_size == 1) node_xy = node_xy.repeat(nb_runs, 1, 1) if (aug_s > 1): assert (aug_s ==...
class MolGraph(object): def __init__(self, moltree: MolTree, args: Namespace): self.moltree = moltree self.n_atoms = 0 self.n_bonds = 0 self.f_atoms = [] self.f_bonds = [] self.a2b = [] self.b2a = [] self.b2revb = [] self.n_atoms = self.moltree...
class Generator(nn.Module): def __init__(self, ct1_channels=512, ct2_channels=256, ct3_channels=128, ct4_channels=64, d_channels_in_2=False, z_size=100): super().__init__() self.ct1_channels = ct1_channels self.pheight = 4 self.pwidth = 4 if d_channels_in_2: self....
class AvalonScoring(): def __init__(self, config: AvalonBasicConfig) -> None: self.config = config def deduction_acc(self, true_player_sides, believed_player_sides) -> float: true_player_sides = np.array(true_player_sides) believed_player_sides = np.where((np.array(believed_player_sides)...