code
stringlengths
101
5.91M
class DiscreteMITrainHook(TrainerHook): def learnable_modules(self) -> List[nn.Module]: return [self._projector] def __init__(self, *, name, model: nn.Module, feature_name: str, weight: float=1.0, num_clusters=20, num_subheads=5, padding=None) -> None: super().__init__(hook_name=name) as...
class ParameterStore(type): def __getitem__(cls, key: str): global parameters return parameters[key] def __setitem__(cls, key, value): global parameters parameters[key] = value
def distributed_init(args): if (args.distributed_world_size == 1): raise ValueError('Cannot initialize distributed with distributed_world_size=1') if ((args.ddp_backend == 'no_c10d') or (not c10d_status.has_c10d)): args.ddp_backend = 'no_c10d' _use_c10d[0] = False print('| distribute...
def _generate_cplex(df: pd.DataFrame, category: str, k: int=3, target_column: str='CV3', timelimit: int=10) -> pd.DataFrame: if (not sf.util.CPLEX_AVAILABLE): raise errors.SolverNotFoundError('CPLEX solver not found.') import cvxpy as cp unique_sites = df['site'].unique() unique_labels = df[cate...
class AugMix(object): def __init__(self, prob=0.5, aug_prob_coeff=0.1, mixture_width=3, mixture_depth=1, aug_severity=1): self.prob = prob self.aug_prob_coeff = aug_prob_coeff self.mixture_width = mixture_width self.mixture_depth = mixture_depth self.aug_severity = aug_severi...
def save_results(f): default_path = f'results_{util.timestamp()}.npz' result_path = (FLAGS.result_path if FLAGS.result_path else default_path) if (not os.path.isabs(result_path)): result_path = os.path.join(FLAGS.logdir, result_path) ordered_indices = np.argsort(f.image_path) util.ensure_pat...
class lossfun(torch.nn.Module): def __init__(self): super(lossfun, self).__init__() def forward(self, gt, oup): loss = F.l1_loss(oup, gt) return loss
def _get_fake_filepaths(): log_dir = '/fake/directory' checkpoint_dir_name = 'checkpoints' checkpoint_dir = os.path.join(log_dir, checkpoint_dir_name) return (log_dir, checkpoint_dir_name, checkpoint_dir)
def get_args(): parser = argparse.ArgumentParser(description='Download the model provided by mmflow and convert the model state dict which can be loaded in SCFlow project') parser.add_argument('--model_url', type=str) args = parser.parse_args() return args
def save_pickle(filename, obj): with open(str(filename), 'wb') as f: pickle.dump(obj, f) logging.info('Saved: %s', filename)
def mock_process(client_id, data_train, data_test, target='localhost:8980'): init_fl_context(client_id, target) df_train = pd.read_csv(os.path.join(resource_path, data_train)) fgboost_regression = FGBoostRegression() if ('SalePrice' in df_train): df_x = df_train.drop('SalePrice', 1) df_y...
def fairness(l): a = (1 / (np.mean(l) - (scipy.stats.hmean(l) + 0.001))) if a: return a return 0
def _subproc_worker(pipe, parent_pipe, env_fn_wrapper, obs_bufs, obs_shapes, obs_dtypes, keys): def _write_obs(maybe_dict_obs): flatdict = obs_to_dict(maybe_dict_obs) for k in keys: dst = obs_bufs[k].get_obj() dst_np = np.frombuffer(dst, dtype=obs_dtypes[k]).reshape(obs_shape...
class Annotation(ABC): def __init__(self, ontology=None): if (ontology is not None): assert isinstance(ontology, Ontology), 'Invalid ontology!' self._ontology = ontology def ontology(self): return self._ontology def load(cls, annotation_file, ontology): def save(self,...
def convert_excel_to_csv(file_name: str) -> str: new_file = (file_name + '.csv') excel_data = pd.read_excel(file_name) excel_data.to_csv(new_file, index=False) return new_file
def voc_eval_with_return(result_file, dataset, iou_thr=0.5, logger='print', only_ap=True): det_results = mmcv.load(result_file) annotations = [dataset.get_ann_info(i) for i in range(len(dataset))] if (hasattr(dataset, 'year') and (dataset.year == 2007)): dataset_name = 'voc07' else: data...
def override_kwargs(block_kwargs, model_kwargs): out_kwargs = (block_kwargs if (block_kwargs is not None) else model_kwargs) return (out_kwargs or {})
def get_args(): checkpoint_path = '/home/qwt/code/IMFNet-main/pretrain/3DMatch/3DMatch.pth' parser = argparse.ArgumentParser() parser.add_argument('--use-cuda', action='store_true', default=True, help='Use NVIDIA GPU acceleration') parser.add_argument('--checkpoint', default=checkpoint_path, help='Model...
_torch class MaskFormerSwinModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ((MaskFormerSwinModel, MaskFormerSwinBackbone) if is_torch_available() else ()) pipeline_model_mapping = ({'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}) fx_compat...
class VQADataset(BaseDataset): def __init__(self, vis_processor, text_processor, vis_root, ann_paths): super().__init__(vis_processor, text_processor, vis_root, ann_paths) def collater(self, samples): (image_list, question_list, answer_list, weight_list) = ([], [], [], []) num_answers = ...
def gen_CNN(channels, conv=tf.keras.layers.Conv1D, use_bias=True, activation=tf.keras.layers.ReLU, batch_norm=False): layers = [] for i in range((len(channels) - 1)): (in_size, out_size) = channels[i:(i + 2)] layers.append(conv(out_size, 1, use_bias=use_bias, data_format='channels_first')) ...
class BasicBlock(BaseModule): expansion = 1 def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, plugins=None, init_cfg=None): super(BasicBlock, self).__init__(init_cfg) assert (dcn is None)...
def main_worker(gpu, ngpus_per_node, config): try: seed = (config.seed if (('seed' in config) and config.seed) else 43) fix_random_seed(seed) config.gpu = gpu model = build_model(config) model = load_ckpt(config, model) model = parallelize(config, model) total...
def check_finish(all_model_dict, result_file): tested_cfgs = [] with open(result_file, 'r+') as f: for line in f: line = json.loads(line) tested_cfgs.append(line['cfg']) is_finish = True for cfg in sorted(all_model_dict.keys()): if (cfg not in tested_cfgs): ...
def download_dataset(dataset, basedir, envfile, force_download): info = datasets[dataset] datadir = os.path.join(basedir, dataset) if force_download: if os.path.exists(datadir): print(f'Removing existing dir {datadir}') shutil.rmtree(datadir) for (subdir, flist) in info.i...
def load_leaf_data(file_path): with open(file_path) as json_file: data = json.load(json_file) to_ret = data['user_data'] data = None return to_ret
def check_norm_state(modules, train_state): for mod in modules: if isinstance(mod, _BatchNorm): if (mod.training != train_state): return False return True
class OpenBuddyAdapter(BaseAdapter): def match(self, model_path: str): return ('openbuddy' in model_path) def load_model(self, model_path: str, from_pretrained_kwargs: dict): if ('-bf16' in model_path): from_pretrained_kwargs['torch_dtype'] = torch.bfloat16 warnings.warn(...
def extract_features_from_path(components_list, statistics_list, sample_rate, path): try: wave = Waveform(path=path, sample_rate=sample_rate) feats = extract_features_from_waveform(components_list, statistics_list, wave) return feats except Exception as extraction_exception: prin...
def _translateX(img, magnitude): return img.transform(img.size, Image.AFFINE, (1, 0, ((magnitude * img.size[0]) * random.choice([(- 1), 1])), 0, 1, 0), fillcolor=fillcolor)
def test_branching_2(): run_cell('y = 7') run_cell('x = y + 3') run_cell('\n if False:\n b = 5\n else:\n y = 9\n ') run_cell('logging.info(x)') assert_detected('x depends on stale y')
def GW_distance(X, Y, p, q, lamda=0.5, iteration=5, OT_iteration=20, **kwargs): Cs = cos_batch_torch(X, X).float().cuda() Ct = cos_batch_torch(Y, Y).float().cuda() bs = Cs.size(0) m = Ct.size(2) n = Cs.size(2) (T, Cst) = GW_torch_batch(Cs, Ct, bs, n, m, p, q, beta=lamda, iteration=iteration, OT_...
class InputMetadata(): def __init__(self, seq_groups: List[Tuple[(List[int], SamplingParams)]], seq_data: Dict[(int, SequenceData)], prompt_lens: List[int], context_lens: torch.Tensor, max_context_len: int, sliding_window: Optional[int]=None) -> None: self.seq_groups = seq_groups self.seq_data = seq...
def save_mod(model, mod_path): print('Save to {}'.format(mod_path)) tf.saved_model.save(model, mod_path)
def predictive_index(pred, true): n = len(pred) (ws, cs) = ([], []) for i in range(n): for j in range((i + 1), n): w = abs((true[j] - true[i])) c = (- 1) if (((pred[j] - pred[i]) * (true[j] - true[i])) > 0): c = 1 elif ((true[j] - true[...
def set_quad_double_start_solutions(nvr, sols, vrblvl=0): if (vrblvl > 0): print('in set_quad_double_start_solutions, with nvr :', nvr) print('the solutions :') for (idx, sol) in enumerate(sols): print('Solution', idx, ':') print(sol) set_quad_double_solutions(nvr...
class ResNet(nn.Module): def __init__(self, block, layers, nchannels, nfilters, nclasses=1000): self.inplanes = nfilters super(ResNet, self).__init__() self.conv1 = nn.Conv2d(nchannels, nfilters, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(nfilters) ...
def get_global_norm(arrays): ctx = arrays[0].context total_norm = nd.add_n(*[nd.dot(x, x).as_in_context(ctx) for x in (arr.reshape(((- 1),)) for arr in arrays)]) total_norm = nd.sqrt(total_norm).asscalar() return total_norm
_REGISTRY.register() def resnet101(pretrained=True, **kwargs): model = ResNet(block=Bottleneck, layers=[3, 4, 23, 3]) if pretrained: init_pretrained_weights(model, model_urls['resnet101']) return model
class TestMeters(unittest.TestCase): def testAverageValueMeter(self): m = meter.AverageValueMeter() for i in range(1, 10): m.add(i) (mean, std) = m.value() self.assertEqual(mean, 5.0) m.reset() (mean, std) = m.value() self.assertTrue(np.isnan(mean)...
def simxSetObjectIntParameter(clientID, objectHandle, parameterID, parameterValue, operationMode): return c_SetObjectIntParameter(clientID, objectHandle, parameterID, parameterValue, operationMode)
class LLMConnection(): def __init__(self, config, exec_query): self.conn = config.llm_connection self.model = config.model self.context_size = config.context_size self.exec_query = exec_query def exec_query(self, query): return self.exec_query(self.model, self.context_siz...
def osnet_x1_0_ms234_a0d1(num_classes=1000, pretrained=True, loss='softmax', **kwargs): model = OSNet(num_classes, blocks=[OSBlock, OSBlock, OSBlock], layers=[2, 2, 2], channels=[64, 256, 384, 512], loss=loss, mixstyle_layers=['conv2', 'conv3', 'conv4'], mixstyle_alpha=0.1, **kwargs) if pretrained: init...
class Using(Node): def __init__(self, start, end, names): Node.__init__(self, start, end) self.names = names def __str__(self): return self._StringHelper(self.__class__.__name__, str(self.names))
def quad_double_cascade_step(dim, embsys, esols, tasks=0): from phcpy.phcpy2c3 import py2c_copy_quaddobl_container_to_start_system from phcpy.phcpy2c3 import py2c_copy_quaddobl_container_to_start_solutions from phcpy.phcpy2c3 import py2c_quaddobl_cascade_homotopy from phcpy.phcpy2c3 import py2c_solve_by...
_task('multilingual_translation') class MultilingualTranslationTask(FairseqTask): def add_args(parser): parser.add_argument('data', metavar='DIR', help='path to data directory') parser.add_argument('--lang-pairs', default=None, metavar='PAIRS', help='comma-separated list of language pairs (in traini...
class AdjustSaturation(object): def __init__(self, saturation): self.saturation = saturation def __call__(self, img, mask): assert (img.size == mask.size) return (tf.adjust_saturation(img, random.uniform((1 - self.saturation), (1 + self.saturation))), mask)
def main(args): for file in os.listdir(osp.join(args.data_dir, args.dataset)): cudnn.deterministic = False cudnn.benchmark = True model = resmap.create(args.arch, ibn_type=args.ibn, final_layer=args.final_layer, neck=args.neck).cuda() num_features = model.num_features feamap_...
def dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None, dtype=None, parallel_iterations=None, swap_memory=False, time_major=False, scope=None): assert (not time_major) flat_inputs = flatten(inputs, 2) flat_len = (None if (sequence_length is None) else tf.cast(flatten(sequence_length, 0), 'in...
class SparseMultiheadAttention(MultiheadAttention): def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0.0, bias=True, add_bias_kv=False, add_zero_attn=False, self_attention=False, encoder_decoder_attention=False, stride=32, expressivity=8, is_bidirectional=True): super().__init__(embed_...
def scatter_plot(viz, title, x): if (title in VISDOMWINDOWS): window = VISDOMWINDOWS[title] viz.scatter(X=x, win=window, update='replace', opts={'title': title}) else: window = viz.scatter(X=x, opts={'title': title}) VISDOMWINDOWS[title] = window
def _Resnet(x, num_units, num_filters, bottle_neck, momentum=0.9, eps=1e-05, use_global_stats=False, bn_data=True, strides=(1, 2, 2, 2), dilates=(1, 1, 1, 1), name=None, lr_mult=1, reuse=None): name = ('' if (name is None) else name) x = ResStemV1(x, num_filters[0], momentum, eps, use_global_stats, bn_data, nam...
def generate_segment_latex(sentence, segment): segment_type = segment[0] if (segment_type == 'M'): return generate_match(sentence, segment) elif (segment_type == 'O'): return generate_overlap(sentence, segment) elif (segment_type == 'G'): return generate_gold_left(sentence, segme...
.parametrize('inp,out', [([], []), (['O', 'O', 'O'], [None, None, None]), (['O', 'B-ORG', 'O'], [None, 'ORG', None]), (['O', 'B-ORG', 'B-ORG'], [None, 'ORG', 'ORG']), (['O', 'B-PERSON', 'I-PERSON'], [None, 'PERSON', 'PERSON']), (['B-A', 'O', 'B-T'], ['A', None, 'T'])]) def test_get_etypes(inp, out): assert (get_ety...
def CWT(lenth, data): scale = np.arange(1, lenth) (cwtmatr, freqs) = pywt.cwt(data, scale, 'mexh') return cwtmatr
def output_padding_shape(h_in, conv_out, padding, kernel_size, stride): return tuple((output_padding(h_in[i], conv_out[i], padding, kernel_size, stride) for i in range(len(h_in))))
def _draw_space(space, batch=None): for s in space.shapes: if (not (hasattr(s, 'ignore_draw') and s.ignore_draw)): _draw_shape(s, batch)
_grad() def compare_planes(pred_planes, gt_planes): pred_planes = torch.tensor(np.array(pred_planes), dtype=torch.float32) pred_offsets = (torch.norm(pred_planes, p=2, dim=1) + 1e-05) pred_norms = pred_planes.div(pred_offsets.view((- 1), 1).expand_as(pred_planes)) gt_planes = torch.tensor(np.array(gt_pl...
('span_f1_dist') class SpanF1Measure(Metric): def __init__(self) -> None: self._true_positives: Dict[(str, int)] = defaultdict(int) self._false_positives: Dict[(str, int)] = defaultdict(int) self._false_negatives: Dict[(str, int)] = defaultdict(int) self.training_finished = False ...
class AbstractOptimizer(ABC): support_parallel_opt = False support_constraint = False support_multi_objective = False support_combinatorial = False support_contextual = False def __init__(self, space: DesignSpace) -> None: self.space = space def suggest(self, n_suggestions=1, fix_inp...
def test_fetch_metadata_function_with_querry(tmpdir): root = tmpdir.strpath run_test_experiment(exp_name='experiment 1 alpha', exp_id='1234', root_dir=root) run_test_experiment(exp_name='experiment 2 beta', exp_id='5678', root_dir=root) run_test_experiment(exp_name='experiment 3 alpha beta', exp_id='999...
class PIP(): def __init__(self, tile, index): self.tile = tile self.index = index self.data = tile.get_pip_data(index) def src_wire(self): return Wire(self.tile, self.data.from_wire) def dst_wire(self): return Wire(self.tile, self.data.to_wire) def is_route_thru(s...
def write_csv_timeseries(df, path, float_format=None): df = df.copy() df.index = df.index.strftime('%Y-%m-%dT%H:%M:%S%z') df.index.name = 'time_iso8601' log.info('write time series data to CSV file %s -- df:\n%s', path, df) with open(path, 'wb') as f: f.write(df.to_csv(float_format=float_for...
class Credentials(): def __init__(self, username: str, password: str): self.username = username self.password = password
def loss_D_fn(P, D, options, images, gen_images): assert (images.size(0) == gen_images.size(0)) gen_images = gen_images.detach() N = images.size(0) all_images = torch.cat([images, gen_images], dim=0) d_all = D(P.augment_fn(all_images)) (d_real, d_gen) = (d_all[:N], d_all[N:]) if (options['lo...
class ControlledGDEFunc(GDEFunc): def __init__(self, gnn: nn.Module): super().__init__(gnn) self.nfe = 0 def forward(self, t, x): self.nfe += 1 x = torch.cat([x, self.h0], 1) x = self.gnn(x) return x
class _DiverseCFV2SchemaConstants(): DATA_INTERFACE = 'data_interface' MODEL_TYPE = 'model_type' DESIRED_CLASS = 'desired_class' DESIRED_RANGE = 'desired_range' FEATURE_NAMES_INCLUDING_TARGET = 'feature_names_including_target' FEATURE_NAMES = 'feature_names' TEST_INSTANCE_LIST = 'test_instan...
class GraspSamplerVAE(GraspSampler): def __init__(self, model_scale, pointnet_radius=0.02, pointnet_nclusters=128, latent_size=2, device='cpu'): super(GraspSamplerVAE, self).__init__(latent_size, device) self.create_encoder(model_scale, pointnet_radius, pointnet_nclusters) self.create_decode...
def _cache_spectrogram(labeled_spectrogram: CachedLabeledSpectrogram) -> None: labeled_spectrogram.z_normalized_transposed_spectrogram()
(derivate=True, coderize=True) _loss def knowledge_distillation_kl_div_loss(pred, soft_label, T, detach_target=True): assert (pred.size() == soft_label.size()) target = F.softmax((soft_label / T), dim=1) if detach_target: target = target.detach() kd_loss = (F.kl_div(F.log_softmax((pred / T), dim...
def main(): args = parse_args() logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) device = (torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')) if (args.seed is not None): set_seed(args....
def get_imdb(file_path): imdb = [{'dataset_name': 'gqa'}] questions = json.load(open(file_path, 'r')) print('Processing file {}'.format(file_path)) for (qid, item) in tqdm.tqdm(questions.items()): entry = {'image_name': (item['imageId'] + 'jpg'), 'image_id': item['imageId'], 'question_id': qid, ...
class ClusterNet6cTwoHead(VGGNet): cfg = [(64, 1), ('M', None), (128, 1), ('M', None), (256, 1), ('M', None), (512, 1)] def __init__(self, num_channel: int=3, input_size: int=64, output_k_A: int=10, output_k_B: int=10, num_sub_heads: int=5, semisup: bool=False, batchnorm_track: bool=True): super(Cluster...
def sample_1hot(batch_size, num_classes, device='cuda'): return torch.randint(low=0, high=num_classes, size=(batch_size,), device=device, dtype=torch.int64, requires_grad=False)
class Demo(data.Dataset): def __init__(self, args, train=False): self.args = args self.name = 'Demo' self.scale = args.scale self.idx_scale = 0 self.train = False self.benchmark = False self.filelist = [] for f in os.listdir(args.dir_demo): ...
def get_geo_loss(gt_geo, pred_geo): (d1_gt, d2_gt, d3_gt, d4_gt, angle_gt) = torch.split(gt_geo, 1, 1) (d1_pred, d2_pred, d3_pred, d4_pred, angle_pred) = torch.split(pred_geo, 1, 1) area_gt = ((d1_gt + d2_gt) * (d3_gt + d4_gt)) area_pred = ((d1_pred + d2_pred) * (d3_pred + d4_pred)) w_union = (torch...
class SpatialAttentionBlock(nn.Module): def __init__(self, in_channels): super(SpatialAttentionBlock, self).__init__() self.query = nn.Sequential(nn.Conv2d(in_channels, (in_channels // 8), kernel_size=(1, 3), padding=(0, 1)), nn.BatchNorm2d((in_channels // 8)), nn.ReLU(inplace=True)) self.ke...
def get_raw2scannet_label_map(): lines = [line.rstrip() for line in open('scannet-labels.combined.tsv')] lines = lines[1:] raw2scannet = {} for i in range(len(lines)): label_classes_set = set(g_label_names) elements = lines[i].split('\t') raw_name = elements[0] nyu40_name...
def make_mask(folders_to_convert, split_to_convert, data_dir, save_dir, n_dataloader_workers=4, batch_size=64): if ((folders_to_convert is None) and (split_to_convert is not None)): split_to_convert = eval(split_to_convert) logger.info(f'Converting from split {split_to_convert}') folders_to_...
def test_inheritance_init(msg): class Python(m.Pet): def __init__(self): pass with pytest.raises(TypeError) as exc_info: Python() expected = 'm.class_.Pet.__init__() must be called when overriding __init__' assert (msg(exc_info.value) == expected) class RabbitHamster(m.Ra...
class CodeGenMatlab(CodeGen): def __init__(self): super().__init__(ParserTypeEnum.MATLAB) def init_type(self, type_walker, func_name): super().init_type(type_walker, func_name) self.new_id_prefix = '' self.post_str = '' def get_dim_check_str(self): check_list = [] ...
def main(): all_examples = [] for path in [args.train_path, args.valid_path, args.test_path]: assert os.path.exists(path) print('Process {}...'.format(path)) if (args.task.lower() == 'wn18rr'): all_examples += preprocess_wn18rr(path) elif (args.task.lower() == 'fb15k2...
def convert_id_to_task_name(task_id: int): startswith = ('Task%03.0d' % task_id) if (preprocessing_output_dir is not None): candidates_preprocessed = subdirs(preprocessing_output_dir, prefix=startswith, join=False) else: candidates_preprocessed = [] if (nnUNet_raw_data is not None): ...
class DependencyInjection(): alignSentencesIntoTextCalculator: AlignSentencesIntoTextCalculator textNormalizer: TextNormalizer audioStatisticComponent: AudioStatisticComponent textStatisticComponent: TextStatisticComponent phoneticSentenceToSymbolSentenceConverter: PhoneticSentenceToSymbolSentenceCo...
class PairAggregator(SequenceAttributionAggregator): aggregator_name = 'pair' aggregator_family = 'pair' default_fn = (lambda x, y: (y - x)) def pre_aggregate_hook(cls, attr: 'FeatureAttributionSequenceOutput', paired_attr: 'FeatureAttributionSequenceOutput', **kwargs): super().pre_aggregate_hoo...
class MaskedBertConfig(PretrainedConfig): model_type = 'masked_bert' def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_s...
def shift(carry: MoveCarry) -> MoveUpdate: return MoveUpdate(target=carry.origin, origin=0, additional_reward=0.0, target_idx=carry.target_idx, origin_idx=(carry.origin_idx + 1))
def drn_d_40(BatchNorm, pretrained=True): model = DRN(BasicBlock, [1, 1, 3, 4, 6, 3, 2, 2], arch='D', BatchNorm=BatchNorm) if pretrained: pretrained = model_zoo.load_url(model_urls['drn-d-40']) del pretrained['fc.weight'] del pretrained['fc.bias'] model.load_state_dict(pretrained...
class ResNet_locate(nn.Module): def __init__(self, block, layers): super(ResNet_locate, self).__init__() self.resnet = ResNet(block, layers) self.in_planes = 512 self.out_planes = [512, 256, 256, 128] self.ppms_pre = nn.Conv2d(2048, self.in_planes, 1, 1, bias=False) (...
def preprocess(method, args): base_path = args['base_path'] origin_folder = args['origin_folder'] core_folder = args.get('core_folder', None) node_file = args['node_file'] walk_pair_folder = args['walk_pair_folder'] node_freq_folder = args['node_freq_folder'] file_sep = args['file_sep'] ...
def init_seed(seed=1, use_cuda=False): np.random.seed(seed) torch.manual_seed(seed) if use_cuda: torch.cuda.manual_seed(seed)
def shuffle_pc(file, output_path): mesh = pymesh.load_mesh(file) vertices = copy.deepcopy(mesh.vertices) permutation = np.random.permutation(len(vertices)) vertices = vertices[permutation] new_mesh = pymesh.meshio.form_mesh(vertices, mesh.faces) new_mesh.add_attribute('vertex_nx') new_mesh.s...
def test_write(policy, X): simulator = (lambda x: 1.0) ACTIONS = np.array([0, 1], np.int32) policy.write(ACTIONS, np.apply_along_axis(simulator, 1, X[ACTIONS])) numpy.testing.assert_array_equal(ACTIONS, policy.history.chosen_actions[:len(ACTIONS)]) assert ((len(X) - len(ACTIONS)) == len(policy.actio...
def _gen_efficientnet(variant, channel_multiplier=1.0, depth_multiplier=1.0, pretrained=False, **kwargs): arch_def = [['ds_r1_k3_s1_e1_c16_se0.25'], ['ir_r2_k3_s2_e6_c24_se0.25'], ['ir_r2_k5_s2_e6_c40_se0.25'], ['ir_r3_k3_s2_e6_c80_se0.25'], ['ir_r3_k5_s1_e6_c112_se0.25'], ['ir_r4_k5_s2_e6_c192_se0.25'], ['ir_r1_k3...
def __scale_width_then_half(img, target_width): (ow, oh) = img.size if (ow == target_width): return img w = target_width h = int(((target_width * oh) / ow)) img = img.resize((w, h), Image.BICUBIC) top = np.random.randint(0, int((h / 2))) left = np.random.randint(0, int((w / 2))) ...
def process_text(text, dic, r, grams): X = lil_matrix((len(text), len(dic))) for (i, l) in enumerate(text): tokens = tokenize(l, grams) indexes = [] for t in tokens: try: indexes += [dic[t]] except KeyError: pass indexes = l...
def get_checkpoint_url(config_path): name = config_path.replace('.yaml', '') if (config_path in _ModelZooUrls.CONFIG_PATH_TO_URL_SUFFIX): suffix = _ModelZooUrls.CONFIG_PATH_TO_URL_SUFFIX[config_path] return (((_ModelZooUrls.S3_PREFIX + name) + '/') + suffix) raise RuntimeError('{} not availa...
class State(): board: Board step_count: chex.Numeric flat_mine_locations: chex.Array key: chex.PRNGKey
class BNN(object): def __init__(self, dim_input, dim_output, dim_hidden, num_layers, is_bnn=True): self.dim_input = dim_input self.dim_output = dim_output self.dim_hidden = dim_hidden self.num_layers = num_layers self.is_bnn = is_bnn def construct_network_weights(self, sc...
def test_beit_layer_decay_optimizer_constructor(): backbone = ToyBEiT() model = PseudoDataParallel(ToySegmentor(backbone)) optimizer_cfg = dict(type='AdamW', lr=1, betas=(0.9, 0.999), weight_decay=0.05) paramwise_cfg = dict(layer_decay_rate=2, num_layers=3) optim_constructor = LayerDecayOptimizerCon...