code
stringlengths
101
5.91M
_metaclass(abc.ABCMeta) class InferenceTask(tf.train.SessionRunHook, Configurable): def __init__(self, params): Configurable.__init__(self, params, tf.contrib.learn.ModeKeys.INFER) self._predictions = None def begin(self): self._predictions = graph_utils.get_dict_from_collection('predict...
def resnet_arg_scope(weight_decay=0.0001, batch_norm_decay=0.997, batch_norm_epsilon=1e-05, batch_norm_scale=True): batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': batch_norm_scale, 'updates_collections': tf.GraphKeys.UPDATE_OPS} with slim.arg_scope([slim.conv2d], weights...
def pll_maximum(yHat_2d, y_2d): optimal_tau = ((yHat_2d - y_2d) ** (- 2.0)) return pll(np.array([yHat_2d]), np.array([y_2d]), 1, optimal_tau)
.parametrize('custom_prior', [True, False]) .parametrize('vectorized', [True, False]) .parametrize('pass_dict', [True, False]) def test_sampler_prior(custom_prior, vectorized, pass_dict): if custom_prior: if pass_dict: def prior(x): return dict(a=x[(..., 0)], b=x[(..., 1)]) ...
def _split_a3ms(output_dir): for fname in os.listdir(output_dir): if (not (os.path.splitext(fname)[(- 1)] == '.a3m')): continue fpath = os.path.join(output_dir, fname) with open(fpath, 'r') as fp: a3ms = fp.read() a3ms = a3ms.split('\x00')[:(- 1)] for ...
def create_demo(model): gr.Markdown('### Image to 3D mesh') gr.Markdown('Convert a single 2D image to a 3D mesh') with gr.Row(): image = gr.Image(label='Input Image', type='pil') result = gr.Model3D(label='3d mesh reconstruction', clear_color=[1.0, 1.0, 1.0, 1.0]) checkbox = gr.Checkbox(...
class XLNetForQuestionAnsweringSimple(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, cls_token_at_end=False, cls_token='[CLS]', cls_token_segment_id=1, sep_token='[SEP]', sep_token_extra=False, pad_on_left=False, pad_token=0, pad_token_segment_id=0, pad_token_label_id=(- 100), sequence_a_segment_id=0, mask_padding_with_ze...
class Casiab_sub(BaseVideoDataset): dataset_dir = 'CASIA_pro' def __init__(self, root='data', min_seq_len=8, verbose=True, **kwargs): self.dataset_dir = osp.join(root, self.dataset_dir) self.train_dir = osp.join(self.dataset_dir, 'train_candi') self.gallery_dir = osp.join(self.dataset_di...
def tensorflow_lite_inference(path, model_name, inputs, inputs_astype): filePath = os.path.join(path, model_name) interpreter = tf.compat.v1.lite.Interpreter(filePath) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() ...
def test_A(): num_v = 20 num_e = 50 import random for _ in range(3): g = Graph(num_v) A = torch.zeros((num_v, num_v)) for _ in range(num_e): s = random.randrange(num_v) d = random.randrange(num_v) g.add_edges((s, d)) A[(s, d)] = 1 ...
_model def dm_nfnet_f2(pretrained=False, **kwargs): return _create_normfreenet('dm_nfnet_f2', pretrained=pretrained, **kwargs)
class LeastSquaresNormalize(intnormb.LocationScaleCLIMixin, intnormb.DirectoryNormalizeCLI): def __init__(self, *, norm_value: float=1.0, **kwargs: typing.Any): super().__init__(norm_value=norm_value, **kwargs) self.tissue_memberships: list[mioi.Image] = [] self.standard_tissue_means: (npt.N...
def main(): (cfg, config_file) = parse_args() cfg.freeze() logger.info('{}'.format(cfg)) logger.info('check mode - {}'.format(cfg.mode.mode)) if (not os.path.exists(cfg.train.log_directory)): os.mkdir(cfg.train.log_directory) if (not os.path.exists(os.path.join(cfg.train.log_directory, c...
() def nearest_upsampling(input_layer, kernel, stride, edges=PAD_SAME, name=PROVIDED): assert (len(input_layer.shape) == 4), 'input rank must be 4' kernel = _kernel(kernel) stride = _stride(stride) input_height = input_layer.shape[1] input_width = input_layer.shape[2] depth = input_layer.shape[3...
class TanhPolar(nn.LayerBase): def __init__(self, width, height, angular_offset_deg=270, **kwargs): self.width = width self.height = height (warp_gridx, warp_gridy) = TanhPolar._get_tanh_polar_warp_grids(width, height, angular_offset_deg=angular_offset_deg) (restore_gridx, restore_gr...
class BaseDetector(metaclass=ABCMeta): default_cfg_acorr: dict[(str, Union[(str, float)])] = {'method_derivative': 'sobel', 'sigma_d': 1.0, 'truncation_d': 3.0, 'method_weighting': 'gaussian', 'sigma_w': 1.0, 'truncation_w': 3.0} def __init__(self, cfg, cfg_acorr, cfg_matching, disable_grads=True): chec...
def _unflatten(dico): new_dico = OrderedDict() for (full_k, v) in dico.items(): full_k = full_k.split('.') node = new_dico for k in full_k[:(- 1)]: if (k.startswith('[') and k.endswith(']')): k = int(k[1:(- 1)]) if (k not in node): ...
class QuantizableInceptionD(inception_module.InceptionD): def __init__(self, *args, **kwargs): super(QuantizableInceptionD, self).__init__(*args, conv_block=QuantizableBasicConv2d, **kwargs) self.myop = nn.quantized.FloatFunctional() def forward(self, x): outputs = self._forward(x) ...
def ppo_loss(A, rho, eps=0.2): return (- torch.min((rho * A), (rho.clamp((1 - eps), (1 + eps)) * A)))
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler): output_dir = Path(args.output_dir) epoch_name = str(epoch) if (loss_scaler is not None): checkpoint_paths = [(output_dir / ('checkpoint-%s.pth' % epoch_name))] for checkpoint_path in checkpoint_paths: ...
def plot_arrow_2D(generalized_pose, length=1.0, width=0.5, fc='r', ec='k'): (x, y, theta) = (generalized_pose.x, generalized_pose.y, generalized_pose.theta) plt.arrow(x, y, (length * np.cos(theta)), (length * np.sin(theta)), fc=fc, ec=ec, head_width=width, head_length=width)
def _get_word_ngrams(n, sentences): assert (len(sentences) > 0) assert (n > 0) words = sum(sentences, []) return _get_ngrams(n, words)
def main(): parser = get_parser() args = parser.parse_args() if (len(args.results) != (args.num_spkrs ** 2)): parser.print_help() sys.exit(1) results = {} for r in six.moves.range(1, (args.num_spkrs + 1)): for h in six.moves.range(1, (args.num_spkrs + 1)): idx = (...
def create_reverse_dependency_map(): modules = [str(f.relative_to(PATH_TO_TRANFORMERS)) for f in (Path(PATH_TO_TRANFORMERS) / 'src/transformers').glob('**/*.py')] direct_deps = {m: get_module_dependencies(m) for m in modules} tests = [str(f.relative_to(PATH_TO_TRANFORMERS)) for f in (Path(PATH_TO_TRANFORMER...
class ScheduledOptim(): def __init__(self, optimizer): self._optimizer = optimizer def step_lr(self): self._optimizer.step() def update_lr(self): self._update_learning_rate() def _update_learning_rate(self): for param_group in self._optimizer.param_groups: lr ...
def load_data(train, test, session_key, item_key, time_key, pad_idx=0): items2idx = {} items2idx['<pad>'] = pad_idx idx_cnt = 0 (train_data, idx_cnt) = _load_data(train, items2idx, idx_cnt, pad_idx, session_key, item_key, time_key) print(len(items2idx.keys())) (test_data, idx_cnt) = _load_data(t...
def Split_On_last_letter_Quote_Mark(input_word): new_token = [input_word] if (len(input_word) <= 1): return new_token class_func_name_rule = re.compile(Class_Func_Name) class_func_words = class_func_name_rule.findall(input_word) if (len(class_func_words) > 0): return new_token fu...
_end_docstrings(PIPELINE_INIT_ARGS) class ObjectDetectionPipeline(Pipeline): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if (self.framework == 'tf'): raise ValueError(f'The {self.__class__} is only available in PyTorch.') requires_backends(self, 'vision...
def _cuda_s2_mm(x, y): import s2cnn.utils.cuda as cuda_utils assert (x.is_cuda and (x.dtype == torch.float32)) assert (y.is_cuda and (y.dtype == torch.float32)) assert (y.size(3) == 2) assert (x.size(3) == 2) nbatch = x.size(1) nfeature_in = x.size(2) nfeature_out = y.size(2) assert ...
def sgd_optimizer_fromparams(params, lr, momentum, weight_decay): optimizer = torch.optim.SGD(params, lr=lr, momentum=momentum, weight_decay=weight_decay) return optimizer
class SpaceAdaptiveReceiver(sc.Receiver): def receive_notify(self, solver, message): if ((sc.Signal.TRAIN_PIPE_END in message.keys()) and ((solver.global_step % 1000) == 0)): sc.logger.info('space adaptive sampling...') results = solver.infer_step({'data_evaluate': ['x', 't', 'sdf', ...
def _pad_1x1_to_3x3_tensor(kernel1x1, padding_11=1): if (kernel1x1 is None): return 0 else: return torch.nn.functional.pad(kernel1x1, ([padding_11] * 4))
class AnomalyRotation(): def __init__(self, max_aug, aug_type): self.max_aug = max_aug self.aug_type = aug_type if (aug_type == 'r'): self.target_augs = np.random.choice(range((- 5), (5 + 1)), 2, replace=False) elif (aug_type == 's'): self.target_augs = (0.95,...
class ModulatedDeformConvPack(ModulatedDeformConv): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation=1, groups=1, deformable_groups=1, im2col_step=64, bias=True, lr_mult=0.1): super(ModulatedDeformConvPack, self).__init__(in_channels, out_channels, kernel_size, stride, pa...
class MPNetForMultipleChoice(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def world_size(): if dist.is_initialized(): return dist.get_world_size() else: return 1
_REGISTRY.register() def build_p37_dla_bifpn_backbone(cfg, input_shape: ShapeSpec): bottom_up = dla34(cfg) in_features = cfg.MODEL.FPN.IN_FEATURES assert (cfg.MODEL.BIFPN.NUM_LEVELS == 5) backbone = BiFPN(cfg=cfg, bottom_up=bottom_up, in_features=in_features, out_channels=cfg.MODEL.BIFPN.OUT_CHANNELS, n...
def gen_lemma_rule(form, lemma, allow_copy=False): form = form.lower() previous_case = (- 1) lemma_casing = '' for (i, c) in enumerate(lemma): case = ('' if (c.lower() != c) else '') if (case != previous_case): lemma_casing += '{}{}{}'.format(('' if lemma_casing else ''), cas...
class AudioAddSilenceTransformer(): def __init__(self, startDurationSeconds: float, endDurationSeconds: float): self.startDurationSeconds = startDurationSeconds self.endDurationSeconds = endDurationSeconds def transform(self, audio: Audio): silenceAudioFront = self.generateSilence(self.s...
def get_psp_resnet50_ade(pretrained=False, root='~/.encoding/models', **kwargs): return get_psp('ade20k', 'resnet50', pretrained, root=root, **kwargs)
def subprocess_fn(rank, args, temp_dir): dnnlib.util.Logger(file_name=os.path.join(args.run_dir, 'log.txt'), file_mode='a', should_flush=True) if (args.num_gpus > 1): init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init')) if (os.name == 'nt'): init_method = ('...
class TwoCropsTransform(): def __init__(self, base_transform1, base_transform2): self.base_transform1 = base_transform1 self.base_transform2 = base_transform2 def __call__(self, x): im1 = self.base_transform1(x) im2 = self.base_transform2(x) return [im1, im2]
def predicative(adjective): w = adjective.lower() if (len(w) > 3): for suffix in ('em', 'en', 'er', 'es', 'e'): if w.endswith(suffix): b = w[:max((- len(suffix)), (- (len(w) - 3)))] if b.endswith('bl'): b = (b[:(- 1)] + 'el') ...
def BasicConv3d(in_channels, out_channels, kernel_size, stride, pad, dilation=1): return nn.Sequential(nn.Conv3d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=pad, dilation=dilation, bias=False), nn.BatchNorm3d(out_channels), nn.LeakyReLU(inplace=True, negative_slope=0.2))
def cal_loss(pred, gold, smoothing): gold = gold.contiguous().view((- 1)) pred = pred.contiguous().view((- 1), pred.size((- 1))) if smoothing: eps = 0.1 n_class = pred.size(1) one_hot = torch.zeros_like(pred).scatter(1, gold.view((- 1), 1), 1) one_hot = ((one_hot * (1 - eps))...
class ASPP_Bottleneck(nn.Module): def __init__(self, num_classes): super(ASPP_Bottleneck, self).__init__() self.conv_1x1_1 = nn.Conv2d((4 * 512), 256, kernel_size=1) self.bn_conv_1x1_1 = nn.BatchNorm2d(256) self.conv_3x3_1 = nn.Conv2d((4 * 512), 256, kernel_size=3, stride=1, padding=...
def evaluate_hull(x, hull): if (x < hull[4][0]): hux = ((hull[3][0] * (x - hull[1][0])) + hull[2][0]) indx = 0 else: if (len(hull[5]) == 1): indx = 1 else: indx = 1 while ((indx < len(hull[4])) and (hull[4][indx] < x)): indx = (...
def runner(env, policy_func, load_model_path, timesteps_per_batch, number_trajs, stochastic_policy, save=False, reuse=False): ob_space = env.observation_space ac_space = env.action_space pi = policy_func('pi', ob_space, ac_space, reuse=reuse) U.initialize() U.load_state(load_model_path) obs_list...
def convert_models(onnx_path: str, num_controlnet: int, output_path: str, fp16: bool=False, sd_xl: bool=False): if sd_xl: batch_size = 1 unet_in_channels = 4 unet_sample_size = 64 num_tokens = 77 text_hidden_size = 2048 img_size = 512 text_embeds_shape = ((2 *...
.register('SGD') def build_sgd(cfg, groups): lr = cfg.OPTIMIZER.LR weight_decay = cfg.OPTIMIZER.WEIGHT_DECAY.DECAY momentum = cfg.OPTIMIZER.MOMENTUM return optim.SGD(groups, lr=lr, momentum=momentum, weight_decay=weight_decay)
class MultipleNegativesRankingLoss(nn.Module): def __init__(self, sentence_embedder): super(MultipleNegativesRankingLoss, self).__init__() self.sentence_embedder = sentence_embedder def forward(self, sentence_features: Iterable[Dict[(str, Tensor)]], labels: Tensor): reps = [self.sentence...
class LayoutLMv2ForQuestionAnswering(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
(name='save_mock') def _save_mock(monkeypatch: MonkeyPatch) -> MagicMock: save_mock = MagicMock() monkeypatch.setattr(cache.dataframe_utils, 'save_df', save_mock) return save_mock
class DataSource(): def __init__(self, data, config, tokenizer, label_tokenizer): self.dataset_path = config.dataset_path self.max_uttr_len = config.max_uttr_len self.history_len = config.history_len self.label_tokenizer = label_tokenizer self.tokenizer = tokenizer se...
class FeatureFused(nn.Module): def __init__(self, inter_channels=48, norm_layer=nn.BatchNorm2d): super(FeatureFused, self).__init__() self.conv2 = nn.Sequential(nn.Conv2d(512, inter_channels, 1, bias=False), norm_layer(inter_channels), nn.ReLU(True)) self.conv3 = nn.Sequential(nn.Conv2d(1024...
def test_python_vs_c_linacc_changingacc_xyz_accellsrframe_scalaromegaz_2d(): lp = potential.MiyamotoNagaiPotential(normalize=1.0, a=1.0, b=0.2) dp = potential.DehnenBarPotential(omegab=1.8, rb=0.5, Af=0.03) diskpot = (lp + dp) x0 = [(lambda t: ((((- 0.03) * (t ** 2.0)) / 2.0) - (((0.03 * (t ** 3.0)) / 6...
class Attention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0): super().__init__() self.num_heads = num_heads head_dim = (dim // num_heads) self.scale = (qk_scale or (head_dim ** (- 0.5))) self.qkv = nn.Linear(dim...
def contingency_matrix(labels_true, labels_pred, eps=None, sparse=False): if ((eps is not None) and sparse): raise ValueError("Cannot set 'eps' when sparse=True") (classes, class_idx) = np.unique(labels_true, return_inverse=True) (clusters, cluster_idx) = np.unique(labels_pred, return_inverse=True) ...
def visualize_stn(): with torch.no_grad(): data = next(iter(test_loader))[0].to(device) input_tensor = data.cpu() transformed_input_tensor = model.stn(data).cpu() in_grid = convert_image_np(torchvision.utils.make_grid(input_tensor)) out_grid = convert_image_np(torchvision.uti...
def _decode_record(record, name_to_features): example = tf.parse_single_example(record, name_to_features) for name in list(example.keys()): t = example[name] if (t.dtype == tf.int64): t = tf.cast(t, tf.int32) example[name] = t return example
class SwinForMaskedImageModeling(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class TerminalTablePrinter(object): def __init__(self): self.headers = None self.tabulars = [] def print_tabular(self, new_tabular): if (self.headers is None): self.headers = [x[0] for x in new_tabular] else: assert (len(self.headers) == len(new_tabular)) ...
class RelationGenerator(nn.Module): def __init__(self, vocabs, embed_dim, rel_size, dropout): super(RelationGenerator, self).__init__() self.vocabs = vocabs self.transfer_head = nn.Linear(embed_dim, rel_size) self.transfer_dep = nn.Linear(embed_dim, rel_size) self.proj = nn.L...
def main(): args = parse_args() if (args.seed is None): args.seed = np.random.randint(1, 10000) os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE' assert torch.cuda.is_available(), 'Please ensure codes are executed in cuda.' device = 'cuda' if (args.seed is not None): torch.manual_see...
_model def dla60_res2next(pretrained=None, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['dla60_res2next'] model = DLA(levels=(1, 1, 1, 2, 3, 1), channels=(16, 32, 128, 256, 512, 1024), block=DlaBottle2neck, cardinality=8, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs)...
class TensorFlowEmitter(object): def __init__(self, tab=None): self.tab = (tab or (' ' * 4)) self.prefix = '' def indent(self): self.prefix += self.tab def outdent(self): self.prefix = self.prefix[:(- len(self.tab))] def statement(self, s): return ((self.prefix + ...
def eval_corrupt_wrapper(model, fn_test_corrupt, args_test_corrupt): corruptions = ['clean', 'scale', 'jitter', 'rotate', 'dropout_global', 'dropout_local', 'add_global', 'add_local'] DGCNN_OA = {'clean': 0.448, 'scale': 0.415, 'jitter': 0.284, 'rotate': 0.341, 'dropout_global': 0.326, 'dropout_local': 0.319, '...
_grad() def evaluate(args, model, criterion, postprocessors, dataloader, support_data_loader, base_ds, device, type='all'): model.eval() criterion.eval() support_iter = iter(support_data_loader) all_category_codes_final = [] print('Extracting support category codes...') number_of_supports = 100 ...
_BOX_FEATURE_EXTRACTORS.register('ResNet18Conv5ROIFeatureExtractor') class ResNet18Conv5ROIFeatureExtractor(nn.Module): def __init__(self, config, in_channels): super(ResNet18Conv5ROIFeatureExtractor, self).__init__() resolution = config.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION scales = config.M...
def visualize_prediction(src_kps, prd_kps, src_img, trg_img, vispath, relaxation=2000): src_imsize = src_img.size()[1:][::(- 1)] trg_imsize = trg_img.size()[1:][::(- 1)] img_tps = geometry.ImageTPS(src_kps, prd_kps, src_imsize, trg_imsize, relaxation) wrp_img = ff.to_pil_image(img_tps(unnorm(src_img.cpu...
class TFRegNetYLayer(tf.keras.layers.Layer): def __init__(self, config: RegNetConfig, in_channels: int, out_channels: int, stride: int=1, **kwargs): super().__init__(**kwargs) should_apply_shortcut = ((in_channels != out_channels) or (stride != 1)) groups = max(1, (out_channels // config.gro...
def metric_name_to_print_format(metric_name) -> str: if (metric_name in ['amota', 'amotp', 'motar', 'recall', 'mota', 'motp']): print_format = '%.3f' elif (metric_name in ['tid', 'lgd']): print_format = '%.2f' elif (metric_name in ['faf']): print_format = '%.1f' else: pri...
def get_approximate_min_distance(x: np.ndarray, axis=0): approx_min_dist = np.abs((x_train[(0, axis)] - x_train[(1, axis)])) return approx_min_dist
.parametrize('update,expected', [(None, {}), (['a=5'], {'a': 5}), (['foo.bar=6'], {'foo': {'bar': 6}}), (['a=9', 'b=0'], {'a': 9, 'b': 0}), (["hello='world'"], {'hello': 'world'}), (['hello="world"'], {'hello': 'world'}), (['f=23.5'], {'f': 23.5}), (['n=None'], {'n': None}), (['t=True'], {'t': True}), (['f=False'], {'f...
def compute_scores_and_write_to_csv(target_filepattern, prediction_filepattern, output_filename, scorer, aggregator, delimiter='\n'): target_filenames = _glob(target_filepattern) prediction_filenames = _glob(prediction_filepattern) scores = _compute_scores(target_filenames, prediction_filenames, scorer, del...
def test_get_observations_at(): config = get_config() if (not os.path.exists(config.SIMULATOR.SCENE)): pytest.skip('Please download Habitat test data to data folder.') config.defrost() config.TASK.SENSORS = [] config.SIMULATOR.AGENT_0.SENSORS = ['RGB_SENSOR', 'DEPTH_SENSOR'] config.freez...
def prettyprint(dct): print('{') for (key, val) in dct.items(): print(" '{}':".format(key)) if isinstance(val, str): print(textwrap.indent(val, ' \t')) else: print(textwrap.indent(val.__repr__(), ' \t')) print('}')
def test_digits_two_stage_object(): model = MaxCoverageSelection(100, optimizer=TwoStageGreedy()) model.fit(X_digits) assert_array_equal(model.ranking[:4], digits_ranking[:4]) assert_array_almost_equal(model.gains[:4], digits_gains[:4], 4) assert_array_almost_equal(model.subset, X_digits[model.ranki...
def get_mvdr_vector(psd_s: ComplexTensor, psd_n: ComplexTensor, reference_vector: torch.Tensor, eps: float=1e-15) -> ComplexTensor: C = psd_n.size((- 1)) eye = torch.eye(C, dtype=psd_n.dtype, device=psd_n.device) shape = ([1 for _ in range((psd_n.dim() - 2))] + [C, C]) eye = eye.view(*shape) psd_n +...
def generate_import_column(name, dtype): return {'inputColumn': name, 'inputType': typeConverter(dtype), 'name': name, 'operation': 'COPY'}
def main(): args = parse_args() frames = create_frame_by_matplotlib(args.image_dir) create_gif(frames, args.out)
class TaggingDataset(Dataset): def __init__(self, root: Union[(str, Path)], audio_transform: Callable=None, subset: Optional[str]='training') -> None: super().__init__() self.subset = subset assert ((subset is None) or (subset in ['training', 'validation', 'testing'])), ('When `subset` not N...
def _create_proportional_tensor(axis_weights): axis_sums = [weights.sum() for weights in axis_weights] total_weight = exp((sum((log(axis_sum) for axis_sum in axis_sums)) / len(axis_sums))) axis_percentages = [(weights / axis_sum) for (weights, axis_sum) in zip(axis_weights, axis_sums)] shape = tuple(map...
class BaseDataset(data.Dataset, ABC): def __init__(self, opt): self.opt = opt self.root = opt.dataroot def modify_commandline_options(parser, is_train): return parser def __len__(self): return 0 def __getitem__(self, index): pass
def mkdir_if_missing(dirname): if (not osp.exists(dirname)): try: os.makedirs(dirname) except OSError as e: if (e.errno != errno.EEXIST): raise
def train(train_loader, model, optimizer): model.train() loss_fn = nn.L1Loss() train_loss = [utils.Averager() for _ in range(len(train_loader.dataset.scale_max))] data_norm = config['data_norm'] t = data_norm['inp'] inp_sub = torch.FloatTensor(t['sub']).view(1, (- 1), 1, 1).cuda() inp_div = ...
def eval_func(model): (x_train, y_train, x_test, y_test) = build_dataset() start = time.time() model.compile(metrics=['accuracy'], run_eagerly=False) score = model.evaluate(x_test, y_test) end = time.time() if (test_mode == 'performance'): latency = (end - start) print('Latency: ...
def save_data(my_array, my_file_name, chunks_value): x_hdf = da.from_array(my_array, chunks=chunks_value) x_hdf.to_hdf5(my_file_name, '/x', compression='lzf', shuffle=True) return
_config def model_lifelong_sidetune_double_resnet_taskonomy(): cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'base_class': 'TaskonomyEncoder', 'base_weights_path': '/mnt/models/curvature_encoder.dat', 'base_kwargs': {'eval_only': True, 'train': False, 'normalize_outputs': False}, 'use_bake...
_module() class MaskFormer(SingleStageDetector): 'Implementation of `Per-Pixel Classification is\n NOT All You Need for Semantic Segmentation\n < def __init__(self, backbone: ConfigType, neck: OptConfigType=None, panoptic_head: OptConfigType=None, panoptic_fusion_head: OptConfigType=None, train_cfg: OptCo...
class TestImagePreprocessing(TestCase): def setup_method(self, method): self.resource_path = os.path.join(os.path.split(__file__)[0], '../resources') def test_read_images(self): file_path = os.path.join(self.resource_path, 'cats/') data_shard = bigdl.orca.data.read_images(file_path) ...
def parse_attributes_section(self, section): return self._format_fields('Attributes', self._consume_fields())
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument('--out', help='output result file') parser.add_argument('--json_out', help='...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--data-root', type=str, help='The data root of coco dataset.', default='./data/coco/') parser.add_argument('--out-dir', type=str, help='The output directory of coco semi-supervised annotations.', default='./data/coco/semi_anns/') ...
class OffsetGenerator(): def initialize(cls, n_patch_side, pad_size): grid_1d = torch.linspace((- 1), 1, n_patch_side).to('cuda') if (pad_size > 0): pad_dist = torch.cumsum((grid_1d[(- 1)] - grid_1d[(- 2)]).repeat(pad_size), dim=0) grid_1d = torch.cat([((- 1) - pad_dist).flip...
class SingleSTG(nn.Module): def __init__(self, input_dim, hidden_dim, sigma): super(SingleSTG, self).__init__() self.gate = FeatureSelector(input_dim, sigma) self.to_latent = nn.Sequential(nn.Linear(input_dim, hidden_dim), nn.ReLU(inplace=True), nn.Linear(hidden_dim, hidden_dim)) def for...
(version='2.0') class Quantization(Component): def __init__(self, conf_fname_or_obj=None): super(Quantization, self).__init__() if isinstance(conf_fname_or_obj, QuantConf): self.conf = conf_fname_or_obj elif isinstance(conf_fname_or_obj, Config): self.conf = QuantConf...
class TestAutoRoundLinear(unittest.TestCase): def setUpClass(self): model_name = 'facebook/opt-125m' self.model = AutoModelForCausalLM.from_pretrained(model_name, low_cpu_mem_usage=True, torch_dtype='auto', trust_remote_code=True) self.model = self.model.eval() self.tokenizer = AutoT...
def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), name=None): if (name is not None): bn_name = (name + '_bn') conv_name = (name + '_conv') else: bn_name = None conv_name = None if (K.image_data_format() == 'channels_first'): bn_axis = 1 e...