code
stringlengths
101
5.91M
def remove_skip_api(code: str) -> str: bad_codes = ['tf.test.main()', 'tf.compat.v1.test.main()', 'disable_eager_execution()', 'disable_v2_behavior', 'InteractiveSession', 'exit()'] for bad_code in bad_codes: code = code.replace(bad_code, '') return code
def set_gpu_idx(): gpu_idx = os.environ.get('GPU') if (gpu_idx is None): logging.warning('GPU not found in environment variable, setting manually as -1') gpu_idx = (- 1) else: gpu_idx = int(gpu_idx) return gpu_idx
def load_model(opt='gptq'): if ('pt' == opt): return load_pt_model() elif ('gptq' == opt): return load_gptq_model() else: raise Exception('not supported opt: {}'.format(opt))
class PIDParam(): kP: float kI: float kD: float antiwindup: tuple[(float, float)] = ((- 1), 1) setpoint_minmax: tuple[(float, float)] = ((- 1), 1) output_minmax: tuple[(float, float)] = ((- 1), 1) def __post_init__(self): assert (self.antiwindup[0] < self.antiwindup[1]) asser...
def get_caller_name(): caller_frame = inspect.stack()[2][0] caller_method = caller_frame.f_code.co_name try: caller_class = caller_frame.f_locals['self'].__class__.__name__ return f'{caller_class}.{caller_method}' except KeyError: return caller_method
def solve(input, pbar): records = [input] last_step = {} f = {} forbidden = {} forbidden[input] = [] for i in range(args.trycnt): try: p = numpy.zeros_like(records, dtype='float64') if (i < ((1 / 2) * args.trycnt)): if (len(records) > 1): ...
class CplxLinearGaussian(GaussianMixin, CplxLinear): def __init__(self, in_features, out_features, bias=True): super().__init__(in_features, out_features, bias=bias) self.log_sigma2 = torch.nn.Parameter(torch.Tensor(*self.weight.shape)) self.reset_variational_parameters() def forward(sel...
def main(): args = parse_args() if (args is None): exit() gan = DCShadowNet(args) gan.build_model() if (args.phase == 'test'): gan.test() print(' [*] Test finished!')
def image_to_input_collated(output_size, dtype=np.float32): def _thunk(obs_space): def runner(x): assert (x.shape[2] == x.shape[1]), 'Input image must be square, of the form: N,H,W,C' if isinstance(x, torch.Tensor): x = torch.cuda.FloatTensor(x.cuda()) els...
def mock_transform(return_value, arg_list): def mock(arg): arg_list.append(arg) return return_value return mock
def batch_norm(x, train_mode, scope='batch_norm'): return tf.contrib.layers.batch_norm(x, epsilon=1e-05, center=True, scale=True, scope=scope, is_training=train_mode)
class L2Problem(): def __call__(self, x: TensorList) -> TensorList: raise NotImplementedError def ip_input(self, a, b): return sum((a.view((- 1)) b.view((- 1)))) def ip_output(self, a, b): return sum((a.view((- 1)) b.view((- 1)))) def M1(self, x): return x def M2(se...
class RandomAgent(AbstractAgent): name = 'random' def __init__(self, env, *args, **kwargs): super(RandomAgent, self).__init__(*args, **kwargs) self.env = env def fit(self, num_iter): num_iter = 10000 for _ in xrange(num_iter): cmd = self.env.action_space.sample() ...
def text_standardize(text): text = text.replace('', '-') text = text.replace('', '-') text = text.replace('', '-') text = text.replace('...', '...') text = text.replace(' ', "'") text = re.sub('(-+|~+|!+|"+|;+|\\?+|\\++|,+|\\)+|\\(+|\\\\+|\\/+|\\*+|\\[+|\\]+|}+|{+|\\|+|_+)', ' \\1 ', text) t...
def main(cl_args): classifier_type = cl_args.classifier_type classifier_weight_path = cl_args.classifier_weight_path patch_size = int(cl_args.patch_size) stride_classifier = int(cl_args.stride_classifier) stride_thresholding = int(cl_args.stride_thresholding) img_path = cl_args.img_path pred...
class MSDScaleBlock(nn.Module): def __init__(self, in_channels_prev, in_channels, out_channels, use_bottleneck, bottleneck_factor_prev, bottleneck_factor): super(MSDScaleBlock, self).__init__() assert (out_channels > in_channels) assert ((out_channels % 2) == 0) inc_channels = (out_c...
class LeakyReLU(KerasLayer): def __init__(self, alpha=0.01, input_shape=None, **kwargs): super(LeakyReLU, self).__init__(None, float(alpha), (list(input_shape) if input_shape else None), **kwargs)
def main(base_model_name, weights_file, image_source, predictions_file, img_format='jpg'): if os.path.isfile(image_source): (image_dir, samples) = image_file_to_json(image_source) else: image_dir = image_source samples = image_dir_to_json(image_dir, img_type='jpg') nima = Nima(base_m...
class CountOps(AnalysisPass): def run(self, dag): self.property_set['count_ops'] = dag.count_ops()
class unetUp(nn.Module): def __init__(self, in_size, out_size, is_deconv, n_concat=2): super(unetUp, self).__init__() self.conv = unetConv2((out_size * 2), out_size, False) if is_deconv: self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=4, stride=2, padding=1) e...
class TFHubertForCTC(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def diapreresnet56_cifar100(num_classes=100, **kwargs): return get_diapreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name='diapreresnet56_cifar100', **kwargs)
class PConvModule(nn.Module): def __init__(self, in_channels=256, out_channels=256, kernel_size=[3, 3, 3], dilation=[1, 1, 1], groups=[1, 1, 1], iBN=False, part_deform=False): super(PConvModule, self).__init__() self.iBN = iBN self.Pconv = nn.ModuleList() self.Pconv.append(sepc_conv(...
class TestPytorchModel(unittest.TestCase): framework = 'pytorch' model = torchvision.models.quantization.resnet18() lpot_model = MODELS['pytorch'](model) def test_Model(self): model = torchvision.models.quantization.resnet18() inc_model = INCModel(model) self.assertTrue(isinstanc...
def collect_data(args): if args.launch: time.sleep(5) rospy.init_node('ctp_data_collection_runner') q0 = GetHomeJointSpace() rospy.loginfo('Making world...') world = CostarWorld(robot_config=UR5_C_MODEL_CONFIG) rospy.loginfo('Aggregating TF data...') tf_buffer = tf2.Buffer(rospy.Dura...
class DeepLabV3(nn.Module): def __init__(self, num_classes, num_layers): super(DeepLabV3, self).__init__() self.num_classes = num_classes layers = num_layers if (layers == 18): self.resnet = ResNet18_OS16() self.aspp = ASPP(num_classes=self.num_classes) ...
class WrapperPotential(Potential): def __init__(self, amp=1.0, pot=None, ro=None, vo=None, _init=None, **kwargs): if (not _init): return None Potential.__init__(self, amp=amp, ro=ro, vo=vo) self._pot = pot self.isNonAxi = _isNonAxi(self._pot) assert physical_compa...
def run_sequence(seq: Sequence, tracker: Tracker, debug=False, num_gpu=8): try: worker_name = multiprocessing.current_process().name worker_id = (int(worker_name[(worker_name.find('-') + 1):]) - 1) gpu_id = (worker_id % num_gpu) torch.cuda.set_device(gpu_id) except: pass ...
def get_filepath(dataset, architecture, seed, step, layer, folder=False): if folder: return os.path.join(EMBEDDING_PATH, dataset, architecture, str(seed), str(step), str(layer)) else: return os.path.join(EMBEDDING_PATH, dataset, architecture, str(seed), str(step), str(layer), 'rep.npy')
class NewAttention(nn.Module): def __init__(self, enc_dim: int, dec_dim: int, attn_type='dot'): super(NewAttention, self).__init__() self.enc_dim = enc_dim self.dec_dim = dec_dim self.attn_type = attn_type self._relu = nn.ReLU() if (self.attn_type == 'general'): ...
class CLIPVisionConfig(PretrainedConfig): model_type = 'clip_vision_model' def __init__(self, hidden_size=768, intermediate_size=3072, num_hidden_layers=12, num_attention_heads=12, image_size=224, patch_size=32, hidden_act='quick_gelu', layer_norm_eps=1e-05, dropout=0.0, attention_dropout=0.0, initializer_range...
class BNILoss(_Loss): def __init__(self, init_noise_sigma, bucket_centers, bucket_weights): super(BNILoss, self).__init__() self.noise_sigma = torch.nn.Parameter(torch.tensor(init_noise_sigma, device='cuda')) self.bucket_centers = torch.tensor(bucket_centers).cuda() self.bucket_weigh...
class Discriminator_cifar32(nn.Module): def __init__(self, optimizer, optimizer_name, lr, betas): super().__init__() m_g = 4 ch = 512 self.projection = nn.utils.weight_norm(nn.Conv2d(3, 1, kernel_size=4, stride=1, padding=2, bias=False), name='weight') self.projection.weight_...
def save_model(args, epoch, model, model_without_ddp, optimizer, loss_scaler, model_ema=None): output_dir = Path(args.output_dir) epoch_name = str(epoch) checkpoint_paths = [(output_dir / ('checkpoint-%s.pth' % epoch_name))] for checkpoint_path in checkpoint_paths: to_save = {'model': model_with...
class SolveRestrictedGameIncreasingTimeToSolve(SolveRestrictedGame): def __init__(self, scenario: NXDOScenario, dont_solve_first_n_nxdo_iters: int, increase_multiplier: float, starting_episodes: int=None, starting_steps: int=None, required_fields: Union[(List[str], None)]=None): self.scenario = scenario ...
def vgg11_bn(config, **kwargs): if config.pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg['A'], batch_norm=True, norm_type=config.norm_type), **kwargs) if config.pretrained: model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn']), strict=False) return mode...
class SupConCELoss(nn.Module): def __init__(self, weights, alpha=0.5, device='cuda:0', temperature=0.06): super().__init__() self.supcon = SupConLoss(temperature=temperature, device=device) self.ce = nn.CrossEntropyLoss(weight=weights) self.alpha = alpha def forward(self, project...
def set_homotopy_continuation_parameter(idx, val): from phcpy.phcpy2c3 import py2c_padcon_set_homotopy_continuation_parameter return py2c_padcon_set_homotopy_continuation_parameter(idx, val)
def cal_formal_charge(atomic_symbol, bonds) -> int: if (atomic_symbol == 'N'): if (sum((j for (i, j) in bonds)) == 4): return 1 return 0
class RNNLMModelTrainer(tf.Module): def __init__(self, model: RNNLMModel, config): super().__init__() self.model = model self.learning_rate = tf.Variable(0.001, dtype=tf.float32, trainable=False) self.optimizer = tf.optimizers.SGD(learning_rate=self.learning_rate) self.max_gr...
_module(name='Kaiming') class KaimingInit(BaseInit): def __init__(self, a=0, mode='fan_out', nonlinearity='relu', distribution='normal', **kwargs): super().__init__(**kwargs) self.a = a self.mode = mode self.nonlinearity = nonlinearity self.distribution = distribution def...
def alltoall(inputs, per_rank_split_lengths): global myreq (N, E) = inputs[0].size() a2ai = All2AllInfo() a2ai.lS = len(inputs) a2ai.gSS = per_rank_split_lengths (a2ai.lN, a2ai.gNS) = get_split_lengths(N) a2ai.E = E a2ai.N = N a2ai.S = (sum(per_rank_split_lengths) if per_rank_split_l...
(inducing_variables.MultioutputInducingVariables, TensorLike, TensorLike) def _linear_multioutput(Z: inducing_variables.MultioutputInducingVariables, u: TensorLike, f: TensorLike, *, L: TensorLike=None, diag: TensorLike=None, basis: AbstractBasis=None, multioutput_axis: int='default', **kwargs): assert (tuple(u.sha...
def parse_args(): parser = argparse.ArgumentParser(description='Train a segmentor') parser.add_argument('config', help='train config file path') parser.add_argument('--work-dir', help='the dir to save logs and models') parser.add_argument('--load-from', help='the checkpoint file to load weights from') ...
def create_sub_dirs(opt, sub_dirs): for sub_dir in sub_dirs: dir_path = os.path.join(opt.expr_dir, sub_dir) if (not os.path.exists(dir_path)): os.makedirs(dir_path) setattr(opt, sub_dir, dir_path)
class Downsample_module(nn.Module): def __init__(self, block, num_blocks, num_steps=4, num_units=4, has_skip=False, norm_cfg=dict(type='BN'), in_channels=64, expand_times=26): norm_cfg = cp.deepcopy(norm_cfg) super().__init__() self.has_skip = has_skip self.in_channels = in_channels ...
class CaptureLogger(): def __init__(self, logger): self.logger = logger self.io = StringIO() self.sh = logging.StreamHandler(self.io) self.out = '' def __enter__(self): self.logger.addHandler(self.sh) return self def __exit__(self, *exc): self.logger.r...
_model def regnetx_080(pretrained=False, **kwargs): return _regnet('regnetx_080', pretrained, **kwargs)
def get_suffix(phone): if (len(phone) < 3): print('{}: invalid phone {} (please check if the phone is position-dependent)'.format(sys.argv[0], phone), file=sys.stderr) sys.exit(1) return phone[(- 2):]
class MyLightningModule(pl.LightningModule): def __init__(self): super().__init__() self.model = resnet18(pretrained=True) num_ftrs = self.model.fc.in_features self.model.fc = torch.nn.Linear(num_ftrs, 37) self.criterion = torch.nn.CrossEntropyLoss() def forward(self, x):...
class Priority(Enum): HIGHEST = 0 VERY_HIGH = 10 HIGH = 30 ABOVE_NORMAL = 40 NORMAL = 50 BELOW_NORMAL = 60 LOW = 70 VERY_LOW = 90 LOWEST = 100
class manifold_cluster_generator(N2D.UmapGMM): def __init__(self, manifold_class, manifold_args, cluster_class, cluster_args): self.manifold_in_embedding = manifold_class(**manifold_args) self.cluster_manifold = cluster_class(**cluster_args) proba = getattr(self.cluster_manifold, 'predict_pr...
def launch_training(c, desc, outdir, dry_run): dnnlib.util.Logger(should_flush=True) prev_run_dirs = [] if os.path.isdir(outdir): prev_run_dirs = [x for x in os.listdir(outdir) if os.path.isdir(os.path.join(outdir, x))] matching_dirs = [re.fullmatch(('\\d{5}' + f'-{desc}'), x) for x in prev_run_...
def get_overfitting_coefficient(eigenlearnabilities, n, mults): return (n / (n - ((eigenlearnabilities ** 2) * mults).sum()))
def clean_jhu_interventions(data_dir=oj('..', '..', 'raw', 'jhu_interventions'), out_dir='.'): df = load_jhu_interventions(data_dir=data_dir) remap = {'FIPS': 'countyFIPS', 'AREA_NAME': 'County Name', 'STATE': 'State Name'} df = df.rename(columns=remap) df['countyFIPS'] = df['countyFIPS'].astype(str).st...
class Florence(Instance, ABC): def __init__(self): super(Florence, self).__init__() self.dst = '/scratch/NFC/OnFlame/FLORENCE/' self.src = '/scratch/NFC/MICC_Florence/' def get_min_det_score(self): return 0.85 def get_images(self): images = {} for actor in sor...
class Local(Optimizer): def __init__(self, named_params, lr=required): (self.param_names, params) = zip(*named_params) if ((lr is not required) and (lr < 0.0)): raise ValueError('Invalid learning rate: {}'.format(lr)) defaults = dict(lr=lr) super(Local, self).__init__(par...
def test_yolov3_neck(): with pytest.raises(AssertionError): YOLOV3Neck(num_scales=3, in_channels=[16, 8, 4], out_channels=[8, 4]) with pytest.raises(AssertionError): neck = YOLOV3Neck(num_scales=3, in_channels=[16, 8, 4], out_channels=[8, 4, 2]) feats = (torch.rand(1, 4, 16, 16), torch.r...
class Logger(keras.callbacks.Callback): def __init__(self, log_dir=None, num_epochs=None): super(Logger, self).__init__() self.log_dir = log_dir self.num_epochs = num_epochs def on_train_begin(self, logs={}): self.i = 0 self.t0 = time.time() self.x = [] se...
class Cnn10_kw(nn.Module): def __init__(self, config): super(Cnn10_kw, self).__init__() self.bn0 = nn.BatchNorm2d(64) sr = config.wav.sr window_size = config.wav.window_size hop_length = config.wav.hop_length mel_bins = config.wav.mel_bins fmin = config.wav.fm...
def waymo_data_prep(root_path, split, nsweeps=1): waymo_ds.create_waymo_infos(root_path, split=split, nsweeps=nsweeps) if (split == 'train'): create_groundtruth_database('WAYMO', root_path, (Path(root_path) / 'infos_train_{:02d}sweeps_filter_zero_gt.pkl'.format(nsweeps)), used_classes=['VEHICLE', 'CYCLI...
def calc_flops(model, img_size=224): with torch.no_grad(): x = torch.randn(1, 3, img_size, img_size).cuda() fca1 = FlopCountAnalysis(model, x) print('backbone:', (fca1.total(module_name='backbone') / .0)) try: print('text_encoder:', (fca1.total(module_name='text_encoder')...
def transform(df, val): train_df = df.fillna(value=val) train_df['prior_question_had_explanation'] = train_df['prior_question_had_explanation'].astype(int) return train_df
def train(args, model, train_loader, optimizer, epoch): model.train() for (batch_idx, (data, target)) in enumerate(train_loader): (data, target) = (data.cuda(), target.cuda()) optimizer.zero_grad() loss = F.cross_entropy(model(data), target) loss.backward() optimizer.step...
def process_single_fragment(cfg, color_files, depth_files, frag_id, n_frags, intrinsic_path, out_folder): import open3d as o3d o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Error) n_frames = len(color_files) intrinsic = read_intrinsic(intrinsic_path, cfg.width, cfg.height) volume = o3d....
def get_learning_rate(): if FLAGS.fine_tune_checkpoint: return 0.0001 else: return 0.045
def use_gpu(opt): return ((hasattr(opt, 'gpu_ranks') and (len(opt.gpu_ranks) > 0)) or (hasattr(opt, 'gpu') and (opt.gpu > (- 1))))
def _group_checkpoint_keys(keys: List[str]) -> Dict[(str, List[str])]: groups = defaultdict(list) for key in keys: pos = key.rfind('.') if (pos >= 0): (head, tail) = (key[:pos], [key[(pos + 1):]]) else: (head, tail) = (key, []) groups[head].extend(tail) ...
def get_box_proposal(fs_serv, img_path): from show_boxes import show_detsB_boxes q_dets_p = fs_serv.get_box_proposal(img_path) image_basename = os.path.basename(img_path) save_file_path = os.path.join(disp_folder, 'box_prop_{0}'.format(image_basename)) img = cv2.cvtColor(cv2.imread(img_path, (cv2.IM...
class MaxAndSkipEnv(gym.Wrapper): def __init__(self, env, skip=4): gym.Wrapper.__init__(self, env) self._obs_buffer = np.zeros(((2,) + env.observation_space.shape), dtype=np.uint8) self._skip = skip def step(self, action): total_reward = 0.0 done = None for i in r...
def get_transform(opt): transform_list = [] if (opt.resize_or_crop == 'resize_and_crop'): osize = [opt.loadSizeX, opt.loadSizeY] transform_list.append(transforms.Scale(osize, Image.BICUBIC)) transform_list.append(transforms.RandomCrop(opt.fineSize)) elif (opt.resize_or_crop == 'crop'...
def l_resnet101(pretrained=False, **kwargs): model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: L.load_pretrained_params(model, model_url=model_urls['resnet101']) return model
def _get_default_kv_variable_store(): store = ops.get_collection(_VARSTORE_KEY) if store: return store[0] store = _KvVariableStore() ops.add_to_collection(_VARSTORE_KEY, store) return store
def get_scores(ftrain, ftest, food, labelstrain, args): if (args.clusters == 1): return get_scores_one_cluster(ftrain, ftest, food) else: if (args.training_mode == 'SupCE'): print('Using data labels as cluster since model is cross-entropy') ypred = labelstrain els...
def process_folder(q, static_frames, test_scenes, data_dir, output_dir, stride=1): while True: if q.empty(): break folder = q.get() if (folder in static_frames.keys()): static_ids = static_frames[folder] else: static_ids = [] scene = folder...
class GlobalPool(nn.Module): def __init__(self, cfg): super(GlobalPool, self).__init__() self.cfg = cfg self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.maxpool = nn.AdaptiveMaxPool2d((1, 1)) self.exp_pool = ExpPool() self.pcampool = PcamPool() self.linear_poo...
def setup_args(): description = 'Collect codec metrics.' parser = argparse.ArgumentParser(description=description) subparsers = parser.add_subparsers(dest='codec', help='Select codec') subparsers.required = True return (parser, subparsers)
def get_result_batch(exp_name_list, res, res_name): res_list = [] for exp_name in exp_name_list: (cur_res_mean, cur_res_std) = get_result(exp_name, res, res_name) res_list.append([cur_res_mean, cur_res_std]) return res_list
def get_start_time(line_iterable, year): start_datetime = None for line in line_iterable: line = line.strip() if (line.find('Solving') != (- 1)): start_datetime = extract_datetime_from_line(line, year) break return start_datetime
_model def bat_resnext26ts(pretrained=False, **kwargs): return _create_byobnet('bat_resnext26ts', pretrained=pretrained, **kwargs)
class AntNavPrimeEnv(AntEnv): def __init__(self, max_path_length, goal_range=15.0, num_goal_steps=50, **kwargs): self.max_path_length = max_path_length self.goal_range = goal_range self.num_goal_steps = num_goal_steps self.cur_goal = np.random.uniform((- self.goal_range), self.goal_r...
def extract_acc_from_summary_path(summary_path): with open(summary_path, 'r') as f: summary = json.load(f) acc_dict = {} for s in summary: (box_a, box_b) = (s['box1'], s['pred_box1']) center_a = np.array([box_a['center_x'], box_a['center_y'], box_a['center_z']]) center_b = np...
class DebertaV2Tokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_...
def feed_dict(train): global x, y_, keep_prob if (train or FLAGS.fake_data): (xs, ys) = mnist.train.next_batch(100, fake_data=FLAGS.fake_data) k = FLAGS.dropout else: (xs, ys) = (mnist.test.images, mnist.test.labels) k = 1.0 return {x: xs, y_: ys, keep_prob: k}
def mocked_simulator_binaries(): with patch.object(path, 'exists', return_value=True, autospec=True), patch.object(path, 'getsize', return_value=1000, autospec=True): (yield)
class TensorflowCriterions(object): def __init__(self): self.criterions = {} self.criterions.update(TENSORFLOW_CRITERIONS)
def makeplot_qual(eval_path, robot): experiments = {} if (plt_cfg['ql'] == 2): global ax plt.figure(robot) ax = plt.axes(projection='3d') for p in os.listdir(eval_path): filepath = (eval_path + p) planner = p.replace('.csv', '') title = ((robot + '_') + planne...
class TestTransactionDB(unittest.TestCase): def test_init(self): rows1 = [[1, 1, 0, 0], [1, 1, 0, 1], [0, 0, 1, 1], [0, 1, 0, 1]] header1 = ['A', 'B', 'C', 'Y'] transDB1 = TransactionDB(rows1, header1, unique_transactions=False) transaction1 = Transaction([1, 1, 0], 'ABC', Item('Y', ...
class MultiCategory(ItemBase): def __init__(self, data, obj, raw): (self.data, self.obj, self.raw) = (data, obj, raw) def __str__(self): return ';'.join([str(o) for o in self.obj]) def __hash__(self): return hash(str(self))
def test_logreg_l1_sparse_data(): rng = np.random.RandomState(42) n_samples = 50 (X, y) = make_classification(n_samples=n_samples, n_features=20, random_state=0) X_noise = rng.normal(scale=0.1, size=(n_samples, 3)) X_constant = np.zeros(shape=(n_samples, 2)) X = np.concatenate((X, X_noise, X_con...
.skipif((not torch.cuda.is_available()), reason='requires CUDA support') def test_nms_bev(): np_boxes = np.array([[6.0, 3.0, 8.0, 7.0, 2.0], [3.0, 6.0, 9.0, 11.0, 1.0], [3.0, 7.0, 10.0, 12.0, 1.0], [1.0, 4.0, 13.0, 7.0, 3.0]], dtype=np.float32) np_scores = np.array([0.6, 0.9, 0.7, 0.2], dtype=np.float32) np...
class FCN8(EvalOnlyModel): def __init__(self, img_channels=3, normalize_outputs=False, **kwargs): super(FCN8, self).__init__(**kwargs) self.conv1 = _make_layer(img_channels, 64, kernel_size=8, stride=4, padding=2) self.conv2 = _make_layer(64, 128, kernel_size=3, stride=2, padding=1) ...
def test_save_and_load_dict(): wide = Wide(np.unique(X_wide).shape[0], 1) tabmlp = TabMlp(mlp_hidden_dims=[32, 16], column_idx={k: v for (v, k) in enumerate(colnames)}, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):]) model1 = WideDeep(wide=deepcopy(wide), deeptabular=deepcopy(tabmlp)) tra...
def _laplace(x, sigma: Union[(int, float)]=2): return (np.exp(((- abs(x)) / sigma)) / (2.0 * sigma))
class Cell(nn.Module): def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev): super(Cell, self).__init__() self.reduction = reduction if reduction_prev: self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False) else: ...
def cifar10(): return collect_download_configs((lambda : datasets.CIFAR10(ROOT, download=True)), name='CIFAR10')
def get_all_supported_ops(ops_file_path: str): with open(ops_file_path, 'r') as f: lines = f.readlines() skip_in_kws = [] name_2_op_params = {} for line in lines: splitted = line.split('`') if (len(splitted) <= 2): print(f'skipped: {line}') continue ...
def vgg11_bn(**kwargs): model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs) return model
def sqrt(x, epsilon): approx = (x / 2) while (abs((x - approx)) > epsilon): approx = (0.5 * (approx + (x / approx))) return approx
def abs_batch_size_fn(new, count): (src, tgt) = (new[0], new[1]) global max_n_sents, max_n_tokens, max_size if (count == 1): max_size = 0 max_n_sents = 0 max_n_tokens = 0 max_n_sents = max(max_n_sents, len(tgt)) max_size = max(max_size, max_n_sents) src_elements = (count ...