code
stringlengths
101
5.91M
def choose_devices(target_abi, target_ids): device_clazz = device_class(target_abi) devices = device_clazz.list_devices() if (target_ids == 'all'): run_devices = devices elif (target_ids == 'random'): unlocked_devices = [dev for dev in devices if (not util.is_device_locked(dev))] ...
def set_ro(ro): from ..util._optional_deps import _APY_LOADED if _APY_LOADED: from astropy import units if (_APY_LOADED and isinstance(ro, units.Quantity)): ro = ro.to(units.kpc).value __config__.set('normalization', 'ro', str(ro))
class ExternalProcess(object): _ACTION = 1 _RESET = 2 _CLOSE = 3 _ATTRIBUTE = 4 _TRANSITION = 5 _OBSERV = 6 _EXCEPTION = 7 _VALUE = 8 def __init__(self, constructor): (self._conn, conn) = multiprocessing.Pipe() self._process = multiprocessing.Process(target=self._work...
def test(config, test_dataset, testloader, model, sv_dir='./', sv_pred=True): model.eval() with torch.no_grad(): for (_, batch) in enumerate(tqdm(testloader)): (image, size, name) = batch size = size[0] pred = test_dataset.single_scale_inference(config, model, image.c...
def get_xdensenet_cifar(num_classes, blocks, growth_rate, bottleneck, expand_ratio=2, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): assert (num_classes in [10, 100]) if bottleneck: assert (((blocks - 4) % 6) == 0) layers = ([((blocks - 4) // 6)] * 3) ...
class IntensiveReader(BaseReader): name: str = 'intensive' def postprocess(self, output: EvalLoopOutput, eval_examples: datasets.Dataset, eval_dataset: datasets.Dataset, log_level: int=logging.WARNING, mode: str='evaluate') -> Union[(List[Dict[(str, Any)]], EvalPrediction)]: (predictions, nbest_json, sc...
def gen_CNN(channels, conv=nn.Conv1d, bias=True, activation=nn.ReLU, batch_norm=None, instance_norm=None): layers = [] for i in range((len(channels) - 1)): (in_size, out_size) = channels[i:(i + 2)] layers.append(conv(in_size, out_size, 1, bias=bias)) if (batch_norm is not None): ...
def main(args): if (args.seed is not None): print('* absolute seed: {}'.format(args.seed)) random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed training. This will turn ...
def ControlTypeChange(choice): if (choice == 'pos'): return gr.update(visible=False) elif (choice == 'sentiment'): return gr.update(visible=True)
def test_scatter(): input = torch.zeros([1, 3, 3, 3]) output = scatter(input=input, devices=[(- 1)]) assert torch.allclose(input, output) inputs = [torch.zeros([1, 3, 3, 3]), torch.zeros([1, 4, 4, 4])] outputs = scatter(input=inputs, devices=[(- 1)]) for (input, output) in zip(inputs, outputs): ...
def short_hash(name): if (name not in _model_sha256): raise ValueError('Pretrained model for {name} is not available.'.format(name=name)) return _model_sha256[name][:8]
class TFWorkerWrapper(Worker): def __init__(self): self._inner_worker = None self._sess = None self._sess_entered = None self.worker_init() def worker_init(self): self._sess = tf.compat.v1.get_default_session() if (not self._sess): self._sess = tf.comp...
def get_latest_scene(s3_scene_jsons): scenes = [open_remote_pb_object(scene_json, Scene) for scene_json in s3_scene_jsons] creation_ts = [_s.creation_date.ToMicroseconds() for _s in scenes] index = creation_ts.index(max(creation_ts)) return (scenes[index], s3_scene_jsons[index])
class SparkEvaluator(Evaluator[S]): def __init__(self, processes: int=8): self.spark_conf = SparkConf().setAppName('jmetalpy').setMaster(f'local[{processes}]') self.spark_context = SparkContext(conf=self.spark_conf) logger = self.spark_context._jvm.org.apache.log4j logger.LogManager....
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, cardinality=1, base_width=64, reduce_first=1, dilation=1, first_dilation=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, attn_layer=None, aa_layer=None, drop_block=None, drop_path=None): super(...
def _fused_batch_norm(inputs, decay=0.999, center=True, scale=False, epsilon=0.001, activation_fn=None, param_initializers=None, param_regularizers=None, updates_collections=ops.GraphKeys.UPDATE_OPS, is_training=True, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, data_format=DATA_FOR...
def _create_local(name, shape, collections=None, validate_shape=True, dtype=tf.float32): collections = list((collections or [])) collections += [ops.GraphKeys.LOCAL_VARIABLES] return variables.Variable(initial_value=array_ops.zeros(shape, dtype=dtype), name=name, trainable=False, collections=collections, va...
def rank_by_significance(embeddings, class_embeddings): similarities = cosine_similarity_embeddings(embeddings, class_embeddings) significance_score = [np.max(softmax(similarity)) for similarity in similarities] significance_ranking = {i: r for (r, i) in enumerate(np.argsort((- np.array(significance_score))...
def is_torchdynamo_available(): if (not is_torch_available()): return False try: import torch._dynamo as dynamo return True except Exception: return False
def blend_images(image, image2, should_blend=0, alpha=0.5, scope=None): with tf.name_scope(scope, 'blend_images', [image, image2]): if (should_blend == 0): return image else: image = tf.py_func(blend_images_np, [image, image2, alpha]) return image
def parse_args(input_args=None): parser = argparse.ArgumentParser(description='Simple example of a training script.') parser.add_argument('--pretrained_model_name_or_path', type=str, default=None, required=True, help='Path to pretrained model or model identifier from huggingface.co/models.') parser.add_argu...
def accuracy(logits, labels): (_, indices) = torch.max(logits, dim=1) if (len(indices.shape) > 1): indices = indices.view((- 1)) labels = labels.view((- 1)) correct = torch.sum((indices == labels)) return ((correct.item() * 1.0) / len(labels))
def mobilenet_v2(pretrained: bool=False, include_top: bool=False, freeze: bool=False): model = torchvision.models.mobilenet_v2(pretrained) if freeze: set_parameter_requires_grad(model, 'classifier') if (not include_top): output_size = model.classifier[1].in_features model.classifier ...
class NonMaximaSuppression2d(nn.Module): def __init__(self, kernel_size: Tuple[(int, int)]): super(NonMaximaSuppression2d, self).__init__() self.kernel_size: Tuple[(int, int)] = kernel_size self.padding: Tuple[(int, int, int, int)] = self._compute_zero_padding2d(kernel_size) self.ker...
def _fake_roi_head(with_shared_head=False): if (not with_shared_head): roi_head = Config(dict(type='StandardRoIHead', bbox_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=1, featmap_strides=[4, 8, 16, 32]), bbox_head=dict(type='Sha...
def resnet50s16(pretrained=False, finetune_layers=(), s16_feats=('layer4',), s8_feats=('layer2',), s4_feats=('layer1',), **kwargs): model = ResNetS16(finetune_layers, s16_feats, s8_feats, s4_feats, Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['re...
def logging(s, log_path, print_=True, log_=True): if print_: print(s) if log_: with open(log_path, 'a+') as f_log: f_log.write((s + '\n'))
class ConfigDense(NamedTuple): seed: int = 0 floatx: Any = 'float64' jitter: float = 1e-06 num_test: int = 128 num_cond: int = 32 num_samples: int = 16384 shard_size: int = 1024 input_dims: int = 3 kernel_variance: float = 0.9 rel_lengthscales_min: float = 0.05 rel_lengthscal...
class TestVisualization(TestCase): def test_import_should_okay(self): try: from bigdl.nano.automl.hpo.visualization import plot_optimization_history except ImportError: self.fail('cannot import plot_optimization_history from nano.aotoml.hpo.visualization.') try: ...
class _IndexToTokenDefaultDict(_NamespaceDependentDefaultDict): def __init__(self, non_padded_namespaces: Set[str], padding_token: str, oov_token: str) -> None: super(_IndexToTokenDefaultDict, self).__init__(non_padded_namespaces, (lambda : {0: padding_token, 1: oov_token}), (lambda : {}))
def format_if_possible(format, value): try: return (format % value) except: return ('%s' % value)
def extract_valid_amino_acid(m, amino_acids): ms = SplitMolByPDBResidues(m) valid_ms = [ms[k] for k in ms.keys()] ret_m = None for i in range(len(valid_ms)): if (i == 0): ret_m = valid_ms[0] else: ret_m = CombineMols(ret_m, valid_ms[i]) return ret_m
class TestTPProfile(unittest.TestCase): def test_isothermal(self): profile = Profile(num_profile_heights=130) profile.set_isothermal(1300) self.assertEqual(len(profile.pressures), 130) self.assertEqual(len(profile.temperatures), 130) self.assertTrue(np.all((profile.temperatur...
_module() class Mask2Former(MaskFormer): 'Implementation of `Masked-attention Mask\n Transformer for Universal Image Segmentation\n < def __init__(self, backbone, neck=None, panoptic_head=None, panoptic_fusion_head=None, train_cfg=None, test_cfg=None, init_cfg=None): super().__init__(backbone, nec...
def uniform(lower: float, upper: float) -> 'tune.sample.Float': return tune.uniform(lower, upper)
class NiftiEvaluator(Evaluator): def __init__(self, *args, **kwargs): self.test_nifti = None self.reference_nifti = None super(NiftiEvaluator, self).__init__(*args, **kwargs) def set_test(self, test): if (test is not None): self.test_nifti = sitk.ReadImage(test) ...
def test_chrono_system_clock(): date1 = m.test_chrono1() date2 = datetime.datetime.today() assert isinstance(date1, datetime.datetime) diff = abs((date1 - date2)) assert (diff.days == 0) assert (diff.seconds == 0) assert (diff.microseconds < 500000)
def reduce_loss_dict(loss_dict): world_size = get_world_size() if (world_size < 2): return loss_dict with torch.no_grad(): loss_names = [] all_losses = [] for k in sorted(loss_dict.keys()): loss_names.append(k) all_losses.append(loss_dict[k]) a...
class EZ_agent(): def __init__(self, args, logger): self.args = args self.lr = args.lr self.noise_dim = self.args.noise_dim self.state_shape = self.args.state_shape self.policy = Policy(args) self.optimizer = optim.Adam(self.policy.parameters(), lr=self.lr) se...
def create_bio_labels(text, opinions): offsets = [l[0] for l in tk.span_tokenize(text)] columns = ['Source', 'Target', 'Polar_expression'] labels = {c: (['O'] * len(offsets)) for c in columns} anns = {c: [] for c in columns} for o in opinions: try: anns['Source'].extend(get_bio_h...
class SingletonMeter(meter.Meter): def __init__(self, maxlen=1): super(SingletonMeter, self).__init__() self.__val = None def reset(self): old_val = self.__val self.__val = None return old_val def add(self, value): self.__val = value def value(self): ...
def mouse_release(event): global fixed_left, fixed_right, fixed_top, fixed_bottom, root currentx = (root.winfo_pointerx() - root.winfo_rootx()) currenty = (root.winfo_pointery() - root.winfo_rooty()) for frame in root.winfo_children(): frame.grid_forget() if (move_fixed_area == True): ...
def ze_grad(pred, target, classes, gpu): pred_grad = torch.zeros_like(pred).to(gpu) target_grad = torch.zeros_like(target).to(gpu) pred_argm = torch.argmax(pred, 1) target_argm = torch.argmax(target, 1) for i in range(target.shape[0]): pred_grad[(i, pred_argm[i])] += 1.0 target_grad[...
def test_audio_dataset_init_reproducible(fs, mocker): dataset_a = audio_dataset(fs, mocker) dataset_b = AudioDataset(TEST_DATA_DIR, TEST_META_FILE, TEST_SAMPLE_RATE, TEST_NUM_SAMPLES) assert (dataset_a.file_list == dataset_b.file_list)
def _variable_assign(var, new_value): return state_ops.assign(var, new_value, name=(var.op.name + '_assign'))
def main(): args = parse_args() cfg = Config.fromfile(args.config) if (args.cfg_options is not None): cfg.merge_from_dict(args.cfg_options) if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_imports']) ...
def save_model(model, args, save_dir, model_name, should_print=True): save_path = ('%s/model_%s' % (save_dir, str(model_name))) save_dict = {'model': model.state_dict(), 'args': args} torch.save(save_dict, save_path) if should_print: print(('Model saved to: %s' % save_path))
class MockS3Client(): def __init__(self, enable_mc=True): self.enable_mc = enable_mc def Get(self, filepath): with open(filepath, 'rb') as f: content = f.read() return content
class CLAM_SB(nn.Module): def __init__(self, gate=True, size_arg='small', dropout=False, k_sample=8, n_classes=2, instance_loss_fn=nn.CrossEntropyLoss(), subtyping=False): super(CLAM_SB, self).__init__() self.size_dict = {'small': [1024, 512, 256], 'big': [1024, 512, 384]} size = self.size_d...
class ShuffleUnit(nn.Module): def __init__(self, in_channels, out_channels, groups=3, first_block=True, combine='add', conv_cfg=None, norm_cfg=dict(type='BN'), act_cfg=dict(type='ReLU'), with_cp=False): norm_cfg = copy.deepcopy(norm_cfg) act_cfg = copy.deepcopy(act_cfg) super().__init__() ...
def make_line_magic(flow_: 'NotebookFlow'): line_magic_names = [name for (name, val) in globals().items() if inspect.isfunction(val)] def _handle(cmd, line): cmd = cmd.replace('-', '_') if (cmd in ('enable', 'disable', 'on', 'off')): return toggle_dataflow(cmd) elif (cmd in (...
def get_model_from_config(model_config: ConfigDict, nelec: Array, ion_pos: Array, ion_charges: Array, dtype=jnp.float32) -> Module: spin_split = get_spin_split(nelec) compute_input_streams = get_compute_input_streams_from_config(model_config.input_streams, ion_pos) backflow = get_backflow_from_config(model_...
class ReplayBuffer(Dataset): def __init__(self, observation_space: gym.spaces.Box, action_dim: int, capacity: int): observations = np.empty((capacity, *observation_space.shape), dtype=observation_space.dtype) actions = np.empty((capacity, action_dim), dtype=np.float32) rewards = np.empty((ca...
def collate(samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False, input_feeding=True): if (len(samples) == 0): return {} def merge(key, left_pad, move_eos_to_beginning=False): return data_utils.collate_tokens([s[key] for s in samples], pad_idx, eos_idx, left_pad, move_eos_to_be...
def evaluations_scipy(ty, pv): if (not ((scipy != None) and isinstance(ty, scipy.ndarray) and isinstance(pv, scipy.ndarray))): raise TypeError('type of ty and pv must be ndarray') if (len(ty) != len(pv)): raise ValueError('len(ty) must be equal to len(pv)') ACC = (100.0 * (ty == pv).mean()) ...
class Annotator(object): def __init__(self, config, filenames, current_mode, args): self.current_mode = current_mode self.current_num = None self.search_term = '' self.partial_typing = '' self.cfilename = (- 1) self.filename = None self.filenames = filenames ...
class dataset_iitnn(Dataset): def __init__(self, data_dir, input1, input2, augmentation1, normalize_1, normalize_2, sup=True, num_images=None, **kwargs): super(dataset_iitnn, self).__init__() img_paths_1 = [] img_paths_2 = [] mask_paths = [] image_dir_1 = ((data_dir + '/') + ...
def describe_graph(graph: str, expert_description='an expert statistician and data scientist.', y_axis_description='', special_task_description='', dataset_description='', include_assistant_response=True): prompt = (('{{#system~}}\n' + f'''You are {expert_description} You interpret global explanations produced by a...
def kaiming_init(module, mode='fan_out', nonlinearity='relu', bias=0, distribution='normal'): assert (distribution in ['uniform', 'normal']) if (distribution == 'uniform'): nn.init.kaiming_uniform_(module.weight, mode=mode, nonlinearity=nonlinearity) else: nn.init.kaiming_normal_(module.weig...
def ibn_pre_conv1x1_block(in_channels, out_channels, stride=1, use_ibn=False, return_preact=False): return IBNPreConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride, padding=0, use_ibn=use_ibn, return_preact=return_preact)
_module() class PISARetinaHead(RetinaHead): _fp32(apply_to=('cls_scores', 'bbox_preds')) def loss(self, cls_scores, bbox_preds, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None): featmap_sizes = [featmap.size()[(- 2):] for featmap in cls_scores] assert (len(featmap_sizes) == self.prior_gen...
def make_data_config(config: ml_collections.ConfigDict, mode: str, num_res: int) -> Tuple[(ml_collections.ConfigDict, List[str])]: cfg = copy.deepcopy(config) mode_cfg = cfg[mode] with cfg.unlocked(): if (mode_cfg.crop_size is None): mode_cfg.crop_size = num_res feature_names = cfg.c...
def default_auto_wrap_policy(module: nn.Module, recurse: bool, unwrapped_params: int, min_num_params: int=int(.0), force_leaf_modules: Optional[Set[Type[nn.Module]]]=None, exclude_wrap_modules: Optional[Set[Type[nn.Module]]]=None) -> bool: force_leaf_modules = (default_auto_wrap_policy.FORCE_LEAF_MODULES if (force_...
def get_config(FLAGS): config = Config for (k, v) in FLAGS.__flags.items(): if hasattr(config, k): setattr(config, k, v.value) return config
class DataLoader(): def __init__(self, csv_file='data/nyu2_train.csv', DEBUG=False): self.shape_rgb = (480, 640, 3) self.shape_depth = (240, 320, 1) self.read_nyu_data(csv_file, DEBUG=DEBUG) def nyu_resize(self, img, resolution=480, padding=6): from skimage.transform import resiz...
def build_lr_scheduler(config, optimizer): assert isinstance(config, dict) lr_type = config['lr_type'].upper() warmup_type = config.get('warmup_type', 'NO') warmup_iters = config.get('warmup_iters', 0) warmup_factor = config.get('warmup_factor', 0.1) if (lr_type not in _ALLOWED_LR_TYPES): ...
def add_jitter(models, sd=0.1): for a_model in models: a_model.kernel = add_jitter_k([a_model.kernel], sd=sd)[0] return models
class _SimpleSegmentationModel(nn.Module): def __init__(self, backbone, classifier, im_num, ex_num): super(_SimpleSegmentationModel, self).__init__() self.backbone = backbone self.classifier = classifier self.bat_low = _bound_learner(hidden_features=128, im_num=im_num, ex_num=ex_num)...
def build_and_train(slot_affinity_code, log_dir, run_ID, config_key): affinity = affinity_from_code(slot_affinity_code) config = configs[config_key] variant = load_variant(log_dir) config = update_config(config, variant) config['eval_env']['game'] = config['env']['game'] sampler = AsyncSerialSam...
class BaseDataset(): def __init__(self): pass def get_pair(self, cls, shuffle): raise NotImplementedError
def learn(env, policy_func, reward_giver, expert_dataset, rank, pretrained, pretrained_weight, *, g_step, d_step, entcoeff, save_per_iter, ckpt_dir, log_dir, timesteps_per_batch, task_name, gamma, lam, max_kl, cg_iters, cg_damping=0.01, vf_stepsize=0.0003, d_stepsize=0.0003, vf_iters=3, max_timesteps=0, max_episodes=0,...
def get_delta(pca, latent, idx, strength): w_centered = (latent - pca['mean'].to('cuda')) lat_comp = pca['comp'].to('cuda') lat_std = pca['std'].to('cuda') w_coord = (torch.sum((w_centered[0].reshape((- 1)) * lat_comp[idx].reshape((- 1)))) / lat_std[idx]) delta = (((strength - w_coord) * lat_comp[id...
def train(model, device, dataset, fold, restart, seed): params_bb = ({param for param in model.learner.image_encoder.parameters()} - {param for param in model.learner.image_encoder.terminal_module_dict.parameters()}) params_new = ({param for param in model.parameters()} - params_bb) parameters = [{'params':...
class InducedNormConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=True, coeff=0.97, domain=2, codomain=2, n_iterations=None, atol=None, rtol=None, **unused_kwargs): del unused_kwargs super(InducedNormConv2d, self).__init__() self.in_channels...
def flatten_observation_spaces(observation_spaces, observation_excluded=()): if (not isinstance(observation_excluded, (list, tuple))): observation_excluded = [observation_excluded] lower_bound = [] upper_bound = [] for (key, value) in observation_spaces.spaces.items(): if (key not in obs...
class TestSequeneceGenerator(TestSequenceGeneratorBase): 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...
def val(test_loader, model, epoch, save_path, writer): global best_mae, best_epoch model.eval() with torch.no_grad(): mae_sum = 0 for i in range(test_loader.size): (images, shorts, gt, name, scene) = test_loader.load_data() inputs = torch.cat([images, shorts], 2) ...
def check_labels(labels, estimator): label_encoder = None if (estimator._estimator_type == 'classifier'): if np.issubdtype(type(labels[0]), np.str_): label_encoder = LabelEncoder() label_encoder.fit(labels) labels = label_encoder.transform(labels) y_type = typ...
def test_nested_typechange(conf_scope): cfg = conf_scope({'f': {'a': 10}}) assert (cfg.typechanged == {'f.a': (type('a'), int)})
def image_label(loader, model, threshold=0.9, out_dir=None): out_path = osp.join(out_dir, 'pseudo_label.txt') print('Pseudo Labeling to ', out_path) iter_label = iter(loader['target_label']) with torch.no_grad(): with open(out_path, 'w') as f: for i in range(len(loader['target_label'...
class TFDebertaModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class MultiEdgeGraphPairwiseFormatter(BaseGraphFormatter): def __init__(self, config, name='MultiEdgeGraphPairwiseFormatter'): self.name = name self.disable_tqdm = config.disable_tqdm self.config = config BaseGraphFormatter.__init__(self, config, name) def format(self, item_json,...
class DecentralizedDistributedMixin(): def _get_advantages_distributed(self, rollouts: RolloutStorage) -> torch.Tensor: advantages = (rollouts.returns[:(- 1)] - rollouts.value_preds[:(- 1)]) if (not self.use_normalized_advantage): return advantages (mean, var) = distributed_mean_...
def prepare_keys_div2k(folder_path): print('Reading image path list ...') img_path_list = sorted(list(scandir(folder_path, suffix='png', recursive=False))) keys = [img_path.split('.png')[0] for img_path in sorted(img_path_list)] return (img_path_list, keys)
class ReversibleSequence(nn.Module): def __init__(self, blocks, args_route={}): super().__init__() self.args_route = args_route self.blocks = nn.ModuleList([ReversibleBlock(f=f, g=g) for (f, g) in blocks]) def forward(self, x, **kwargs): x = torch.cat([x, x], dim=(- 1)) b...
class ResContextBlock(nn.Module): def __init__(self, in_filters, out_filters, kernel_size=(3, 3, 3), stride=1, indice_key=None): super(ResContextBlock, self).__init__() self.conv1 = conv1x3(in_filters, out_filters, indice_key=(indice_key + 'bef')) self.bn0 = nn.BatchNorm1d(out_filters) ...
class Device(): du = Device_Util() speed_distri = None try: with open('speed_distri.json', 'r') as f: speed_distri = json.load(f) except FileNotFoundError as e: speed_distri = None logger.warn("no user's network speed trace was found, set all communication time to 0.0...
class ESPNet(nn.Module): def __init__(self, in_channels, num_classes): super().__init__() self.input1 = InputProjectionA(1) self.input2 = InputProjectionA(1) initial = 16 config = [32, 128, 256, 256] reps = [2, 2, 3] self.level0 = CBR(in_channels, initial, 7, ...
def get_checkpoint_from_config_class(config_class): checkpoint = None config_source = inspect.getsource(config_class) checkpoints = _re_checkpoint.findall(config_source) for (ckpt_name, ckpt_link) in checkpoints: if ckpt_link.endswith('/'): ckpt_link = ckpt_link[:(- 1)] ckpt_...
def prepare_keys_vimeo90k(folder_path, train_list_path, mode): print('Reading image path list ...') with open(train_list_path, 'r') as fin: train_list = [line.strip() for line in fin] img_path_list = [] keys = [] for line in train_list: (folder, sub_folder) = line.split('/') ...
class TextSampler(Sampler): def __init__(self, lengths, batch_size, n_buckets, shuffle=False): self.lengths = lengths self.batch_size = batch_size self.shuffle = shuffle (self.sizes, self.buckets) = kmeans(x=lengths, k=n_buckets) self.chunks = [max(((size * len(bucket)) // se...
def cal_acc(zeros, ones): accuracy = 0.0 for example in zeros: if (not np.isnan(example[0])): if (example[0] < 0.5): accuracy += 1.0 for example in ones: if (not np.isnan(example[0])): if (example[0] > 0.5): accuracy += 1.0 accuracy...
def dump2json(ofn, data, force=False): if (os.path.exists(ofn) and (not force)): return def default(obj): if isinstance(obj, np.int32): return int(obj) elif isinstance(obj, np.int64): return int(obj) elif isinstance(obj, np.float32): return flo...
class EncoderLayer(nn.Module): def __init__(self, d_model, self_attn, feed_forward=None, use_residual=False, dropout=0.1): super(EncoderLayer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.use_residual = use_residual if use_residual: ...
class RePU(nn.ReLU): def __init__(self, n): super(RePU, self).__init__() self.n = n def forward(self, x: torch.Tensor): return (torch.relu(x) ** self.n)
def main(): args = parse_args() dataset_path = args.dataset_path if (args.out_dir is None): out_dir = osp.join('data', 'loveDA') else: out_dir = args.out_dir print('Making directories...') mmcv.mkdir_or_exist(out_dir) mmcv.mkdir_or_exist(osp.join(out_dir, 'img_dir')) mmcv...
def main(args, logger): logger.info(args) fix_seed_for_reproducability(args.seed) t_start = t.time() (model, optimizer, classifier) = get_model_and_optimizer(args, logger) (inv_list, eqv_list) = get_transform_params(args) trainset = get_dataset(args, mode='train', inv_list=inv_list, eqv_list=eqv...
def reduce_param_groups(params: List[Dict[(str, Any)]]) -> List[Dict[(str, Any)]]: params = _expand_param_groups(params) groups = defaultdict(list) for item in params: cur_params = tuple(((x, y) for (x, y) in item.items() if (x != 'params'))) groups[cur_params].extend(item['params']) ret...
def add_dmc_args(parser): parser.add_argument('--domain_name', type=str, default='fish') parser.add_argument('--task_name', type=str, default='swim') parser.add_argument('--from_pixels', action='store_true', help='Use image observations') parser.add_argument('--height', type=int, default=84) parser....
def dumb_css_parser(data): data += ';' importIndex = data.find('') while (importIndex != (- 1)): data = (data[0:importIndex] + data[(data.find(';', importIndex) + 1):]) importIndex = data.find('') elements = [x.split('{') for x in data.split('}') if ('{' in x.strip())] try: e...