code
stringlengths
101
5.91M
def as_dict_handler(obj: Any) -> (dict[(str, Any)] | None): try: return obj.as_dict() except AttributeError: return None
def test_diskdf_sample(): from galpy.df import dehnendf, shudf (ro, vo) = (7.0, 230.0) df = dehnendf(ro=ro, vo=vo) dfnou = dehnendf() dfs = shudf(ro=ro, vo=vo) dfsnou = shudf() numpy.random.seed(1) du = (df.sampledSurfacemassLOS((11.0 * units.deg), n=1, maxd=(10.0 * units.kpc)).to(units....
def l2_norm(input, axis=1): norm = torch.norm(input, 2, axis, True) output = torch.div(input, norm) return output
def face_area(V, F): if (type(V).__module__ == np.__name__): (V, F) = (p2e(V), p2e(F)) A = Xd() igl.doublearea(V, F, A) A = e2p(A).flatten() return A
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(BasicBlock, self).__init__() if (norm_layer is None): norm_layer = nn.BatchNorm2d if ((groups != 1) or (base...
def main(): P = parse_args() P.rank = 0 if torch.cuda.is_available(): torch.cuda.set_device(P.rank) device = torch.device((f'cuda' if torch.cuda.is_available() else 'cpu')) P.world_size = torch.cuda.device_count() P.distributed = (P.world_size > 1) assert (not P.distributed) set_...
def create_cmfd_similarity_branch(img_shape=(256, 256, 3), nb_pools=100, name='simiDet'): img_input = Input(shape=img_shape, name=(name + '_in')) bname = (name + '_cnn') x1 = Conv2D(64, (3, 3), activation='relu', padding='same', name=(bname + '_b1c1'))(img_input) x1 = Conv2D(64, (3, 3), activation='relu...
class Logger(): def __init__(self, *args, **kwargs): from expviz.logger import Logger as ExpvizLogger self.expviz = ExpvizLogger(*args, **kwargs) def write(self, scalar_dict, epoch): for (key, value) in scalar_dict.items(): if isinstance(value, torch.Tensor): ...
def linkcode_resolve(domain, info): if (domain != 'py'): return None if (not info['module']): return None filename = info['module'].replace('.', '/') return '{}/{}.py'.format(repo_url, filename)
_model def res2net50_14w_8s(pretrained=False, **kwargs): model_args = dict(block=Bottle2neck, layers=[3, 4, 6, 3], base_width=14, block_args=dict(scale=8), **kwargs) return _create_res2net('res2net50_14w_8s', pretrained, **model_args)
class LRFinder(LearnerCallback): def __init__(self, learn: Learner, start_lr: float=1e-07, end_lr: float=10, num_it: int=100, stop_div: bool=True): super().__init__(learn) (self.data, self.stop_div) = (learn.data, stop_div) self.sched = Scheduler((start_lr, end_lr), num_it, annealing_exp) ...
class positive_int_or_none(_ParseType): _none def __call__(self, string: str) -> (int | None): return positive_int()(string)
def import_cifar(dataset=10): if (dataset == 10): ((x_train, y_train), (x_test, y_test)) = cifar10.load_data() elif (dataset == 100): ((x_train, y_train), (x_test, y_test)) = cifar100.load_data(label_mode='fine') x_train = x_train.astype('float32') x_test = x_test.astype('float32') (...
class GUITopoSim(Sim): def __init__(self, argv, parser=None): super(GUITopoSim, self).__init__(argv) self.topo_file = ((self.ROOT + '/') + self.args.topology_file) self.ns_file = ((self.ROOT + '/') + self.args.net_settings_file) self.net_desc = self.get_net_desc(self.topo_file, self....
class Data2VecTextForTokenClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def run(model, logdir, batch_size=50, vanilla=False, custom_steps=None, eta=None, n_samples=50000, nplog=None): if vanilla: print(f'Using Vanilla DDPM sampling with {model.num_timesteps} sampling steps.') else: print(f'Using DDIM sampling with {custom_steps} sampling steps and eta={eta}') ts...
def deconv3d_bn_relu(batchNorm, in_planes, out_planes, kernel_size=4, stride=2, padding=1, output_padding=0, bias=True): if batchNorm: return nn.Sequential(nn.ConvTranspose3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, output_padding=output_padding, bias=bias), nn.BatchNo...
def getPosFromFileName(fileName): return (int(fileName.split('/')[(- 1)].split('_')[(- 3)]) > 200)
class CalibCollector(CollectorBase): def __init__(self, include_tensors_kl, include_tensors_minmax, num_bins=8001): self.min_max_dict = {} self.hist_dict = {} self.num_bins = num_bins self.include_tensors_minmax = include_tensors_minmax self.include_tensors_kl = include_tenso...
class MLDG(ERM): def __init__(self, args): super(MLDG, self).__init__(args) self.args = args def update(self, minibatches, opt, sch): num_mb = len(minibatches) objective = 0 opt.zero_grad() for p in self.network.parameters(): if (p.grad is None): ...
def get_analytics_zoo_classpath(): if os.getenv('BIGDL_CLASSPATH'): for path in os.getenv('BIGDL_CLASSPATH').split(':'): if ((not os.path.exists(path)) and (not os.path.exists(path.split('*')[0]))): invalidInputError(False, 'Path {} specified BIGDL_CLASSPATH does not exist.'.form...
def is_prime(n): if ((n % 2) == 0): return False sqrt_n = int(math.floor(math.sqrt(n))) for i in range(3, (sqrt_n + 1), 2): if ((n % i) == 0): return False return True
def run(cfg): seeds = ([cfg.seed] if (cfg.seed is not None) else range(cfg.runs)) if (cfg.gnn.model.name == 'RevGAT'): TRAINER = DGLGNNTrainer else: TRAINER = GNNTrainer all_acc = [] start = time.time() for seed in seeds: cfg.seed = seed trainer = TRAINER(cfg, cfg...
def get_checkpoint_fn(): if deepspeed.checkpointing.is_configured(): checkpoint = deepspeed.checkpointing.checkpoint else: checkpoint = torch.utils.checkpoint.checkpoint return checkpoint
def frozen_bn(model): first_bn = True for (name, m) in model.named_modules(): if isinstance(m, (torch.nn.BatchNorm2d, torch.nn.BatchNorm3d)): if first_bn: first_bn = False print(('Skip frozen first bn layer: ' + name)) continue m.ev...
def cli_register(name: str, description: str=''): def _warpper(command): items = name.split('.') com = neuralchat_commands for item in items: com = com[item] com['_command'] = command if description: com['description'] = description return comm...
def copy_bn_params(module, bn_module, remove_bn=True, verbose=False): with torch.no_grad(): if hasattr(bn_module, 'weight'): module.register_parameter('gamma', nn.Parameter(bn_module.weight.data.clone())) if hasattr(bn_module, 'bias'): module.register_parameter('beta', nn.Par...
.parametrize('space', [Discrete(3), Tuple([Discrete(5), Discrete(10)]), Tuple([Discrete(5), Box(low=np.array([0, 0]), high=np.array([1, 5]))]), Tuple((Discrete(5), Discrete(2), Discrete(2))), MultiDiscrete([2, 2, 100]), Dict({'position': Discrete(5), 'velocity': Box(low=np.array([0, 0]), high=np.array([1, 5]))})]) def ...
def trainfxn(trainer, model, dataloader, criterion, optimizer, lr_scheduler, epoch, args, num_classes, logger, **kwargs): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4f') top1 = AverageMeter('', ':6.2f') if (num_classes >= 5):...
class JTMPN(nn.Module): def __init__(self, hidden_size, depth): super(JTMPN, self).__init__() self.hidden_size = hidden_size self.depth = depth self.W_i = nn.Linear((ATOM_FDIM + BOND_FDIM), hidden_size, bias=False) self.W_h = nn.Linear(hidden_size, hidden_size, bias=False) ...
class ResBlock(nn.Module): def __init__(self, in_channels, out_channels, stride=1): super(ResBlock, self).__init__() self.resize_identity = ((in_channels != out_channels) or (stride != 1)) self.body = PreResBottleneck(in_channels=in_channels, out_channels=out_channels, stride=stride) ...
def PrintModelFree(mfIndi, mbIndi): for i in xrange(len(mfIndi)): if (not np.isnan(mfIndi[i])): print(('[%d]\t%f' % (i, mfIndi[i]))) print('\n')
def init(novel_type, description, request: gr.Request): if (novel_type == ''): novel_type = ('Science Fiction' if ('en' == lang_opt) else '') global _CACHE cookie = request.headers['cookie'] cookie = cookie.split('; _gat_gtag')[0] init_paragraphs = get_init(text=init_prompt(novel_type, descr...
_module class CityscapesDataset(CocoDataset): CLASSES = ('person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle') def _filter_imgs(self, min_size=32): valid_inds = [] ids_with_ann = set((_['image_id'] for _ in self.coco.anns.values())) for (i, img_info) in enumerate(se...
def main(): parser = argparse.ArgumentParser(description='ReID Baseline Inference') parser.add_argument('--config_file', default='./configs/debug.yml', help='path to config file', type=str) parser.add_argument('opts', help='Modify config options using the command-line', default=None, nargs=argparse.REMAINDE...
class ParticleNetWrapper(torch.nn.Module): def __init__(self, **kwargs) -> None: super().__init__() self.mod = ParticleNet(**kwargs) def forward(self, points, features, lorentz_vectors, mask): return self.mod(points, features, mask)
class MetadataCache(Cache): def source(cls, url): print('Getting metadata from source') browser = Browser(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'random_downloads')) browser.get(url) print('URL gotten') metadata = cls.metadata_from_result_page(browser) ...
class AddSubNode(ExprNode): def __init__(self, left=None, right=None, parse_info=None, raw_text=None, op='+-'): super().__init__(IRNodeType.AddSub, parse_info=parse_info, raw_text=raw_text) self.left = left self.right = right self.op = op def split_node(self): add_node = ...
def certificate(domain=LOCALHOST, country=None, state=None, city=None, company=None, contact=None, signed=True, **kwargs): s = subprocess.PIPE p = ('openssl', 'genrsa', ('%s' % kwargs.get('encryption', 2048))) p = subprocess.Popen(p, stdin=s, stdout=s, stderr=s) k = (kwargs.get('key') or p.communicate()...
def dice(input, target, ignore_index=None): smooth = 1.0 iflat = input.clone().view((- 1)) tflat = target.clone().view((- 1)) if (ignore_index is not None): mask = (tflat == ignore_index) tflat[mask] = 0 iflat[mask] = 0 intersection = (iflat * tflat).sum() return (((2.0 *...
class SubsetSum(BinaryProblem): def __init__(self, C: int, W: list): super(SubsetSum, self).__init__() self.C = C self.W = W self.number_of_bits = len(self.W) self.number_of_objectives = 2 self.number_of_variables = 1 self.number_of_constraints = 0 sel...
def make_image(tensor): return tensor.detach().clamp_(min=(- 1), max=1).add(1).div_(2).mul(255).type(torch.uint8).permute(0, 2, 3, 1).to('cpu').numpy()
def main(argv): epochs = FLAGS.epochs batch_size = FLAGS.batch_size gru_units = (FLAGS.model_size * FLAGS.model_size_scale) emb_dim = FLAGS.emb_dim max_seq = FLAGS.max_seq patience = FLAGS.patience l2 = FLAGS.l2 lr = FLAGS.lr with open((FLAGS.input + 'train.pkl'), 'rb') as f: ...
def get_datamodule(datamodule): datamodule = datamodule.lower() if (datamodule == 'cifar10'): return Cifar10DataModule if (datamodule == 'cifar100'): return Cifar100DataModule elif (datamodule == 'mnist'): return MnistDataModule elif (datamodule == 'imagenet'): return...
class ReadWork(): def __init__(self, read_done_condition, key, read_done_flag, cache_lock, cache): self.read_done_condition = read_done_condition self.key = key self.read_done_flag = read_done_flag self.cache_lock = cache_lock self.cache = cache def wait(self): wi...
def main(): app = QtGui.QApplication(sys.argv) tool = CityscapesViewer() sys.exit(app.exec_())
class MLPCategoricalActor(Actor): def __init__(self, obs_dim, act_dim, hidden_sizes, activation): super().__init__() self.logits_net = mlp((([obs_dim] + list(hidden_sizes)) + [act_dim]), activation) def _distribution(self, obs): logits = self.logits_net(obs) return Categorical(lo...
_operation def div(a: torch.Tensor, b: torch.Tensor): if is_real(b): if (b.dim() >= a.dim()): raise ValueError('Incorrect dimensions.') return div_cplx_real(a, b) return div_cplx_real(mult_conj(a, b), abs_sqr(b))
def test_bytes(doc): assert (m.bytes_from_string().decode() == 'foo') assert (m.bytes_from_str().decode() == 'bar') assert (doc(m.bytes_from_str) == 'bytes_from_str() -> {}'.format(('bytes' if (sys.version_info[0] == 3) else 'str')))
class AlbertPreTrainedModel(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def get_coco_api_from_dataset(dataset): for _ in range(10): if isinstance(dataset, torch.utils.data.Subset): dataset = dataset.dataset if isinstance(dataset, LvisDetectionBase): return dataset.lvis if isinstance(dataset, (torchvision.datasets.CocoDetection, CustomCocoDetection)):...
def features_dataset_resizer(features_dataset_class: Type[BaseFeaturesDataset], resize_factor: float): old_get = features_dataset_class.get_features def resizer_get(*args): features = old_get(*args) new_features = copy.deepcopy(features) new_features['skeletons'] *= resize_factor ...
class MobileNetV2(nn.Module): def __init__(self, channels, init_block_channels, final_block_channels, in_channels=3, in_size=(224, 224), num_classes=1000): super(MobileNetV2, self).__init__() self.in_size = in_size self.num_classes = num_classes self.features = nn.Sequential() ...
def penalties(module, reduction='sum'): for (_, penalty) in named_penalties(module, reduction=reduction): (yield penalty)
def load_model_base(self, model_path: str, from_pretrained_kwargs: dict): revision = from_pretrained_kwargs.get('revision', 'main') print('Customized bigdl-llm loader') tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=self.use_fast_tokenizer, revision=revision) from bigdl.llm.transformers ...
class p_z(nn.Module): def __init__(self, output_shape, input_shape): super().__init__() (nc_y_in, nc_u_in) = (input_shape[0][0], input_shape[1][0]) nc_out = (2 * output_shape[0]) self.y_nn = nn.Sequential(DenselyEncoder(in_channels=nc_y_in, out_channels=(nc_out // 2), growth_rate=32,...
def run_daemon(bpf): signal.signal(signal.SIGTERM, remove_rt) signal.signal(signal.SIGINT, remove_rt) for (laddr, gaddr) in LOCAL_GLOBAL_MAP.items(): _ = (lambda x: socket.inet_pton(socket.AF_INET6, x)) logger.info('{}:{}'.format(laddr, gaddr)) bpf['link_local_table'][ip_str_to_ct(la...
class GumbelBatchedGenerator(): def __init__(self, seed=None): if isinstance(seed, random.Random): self.rng = seed else: self.rng = random.Random(seed) def __call__(self): return (- math.log((- math.log(self.rng.random()))))
def import_models(models_dir, namespace): for file in os.listdir(models_dir): path = os.path.join(models_dir, file) if ((not file.startswith('_')) and (not file.startswith('.')) and (file.endswith('.py') or os.path.isdir(path))): model_name = (file[:file.find('.py')] if file.endswith('.p...
def get_valid_mask(mask: np.ndarray): if (mask.ndim == 3): mask_pil = Image.fromarray(mask).convert('L') mask = np.array(mask_pil) if (mask.max() == 255): mask = (mask / 255) return mask
def test_squeeze_and_excitation_block_2d(): N = 10 C = 128 reduction = 16 data = torch.randn(N, C, 7, 7) model = SqueezeAndExcitationBlock2D(in_channels=C, reduction=reduction) print(model) outputs = model(data) print(outputs.shape) assert (outputs.shape == (N, C, 7, 7))
class FilterResponseNorm2d(FilterResponseNormNd): def __init__(self, num_features, eps=1e-06, learnable_eps=False): super(FilterResponseNorm2d, self).__init__(4, num_features, eps=eps, learnable_eps=learnable_eps)
def Ranger(sync_period=6, slow_step_size=0.5, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, weight_decay=0.0, amsgrad=False, sma_threshold=5.0, total_steps=0, warmup_proportion=0.1, min_lr=0.0, name='Ranger'): inner = RectifiedAdam(learning_rate, beta_1, beta_2, epsilon, weight_decay, amsgrad, sma_t...
class DoubleNode(ExprNode): def __init__(self, parse_info=None, raw_text=None): super().__init__(IRNodeType.Double, parse_info=parse_info, raw_text=raw_text) self.value = None
def test_fcm_normalization_nont1w_cli(image: pathlib.Path, mask: pathlib.Path) -> None: args = f'{image} -tm {mask} -mo t2'.split() retval = fcm_main(args) assert (retval == 0)
def dobldobl_ismember(wsys, gpts, dim, point, evatol=1e-06, memtol=1e-06, verbose=True, tasks=0): from phcpy.interface import store_dobldobl_witness_set from phcpy.phcpy2c3 import py2c_witset_dobldobl_ismember as membtest store_dobldobl_witness_set(len(wsys), dim, wsys, gpts) nbc = len(point) nvr = ...
class FlattenMlp(Mlp): def forward(self, *inputs, **kwargs): flat_inputs = torch.cat(inputs, dim=1) return super().forward(flat_inputs, **kwargs)
class ContextNet(AcousticModel): def __init__(self, num_features: int, num_classes: int, kernel_size: int=3, num_blocks: int=6, num_layers: int=5, conv_out_channels: List[int]=[*([256] * 2), *([512] * 3), 640], subsampling_layers: List[int]=[1, 3], alpha: float=1.5, dropout: int=0.1): super().__init__() ...
class ObservationModel(nn.Module): def __init__(self, num_ensemble, dim_x, dim_z): super(ObservationModel, self).__init__() self.num_ensemble = num_ensemble self.dim_x = dim_x self.dim_z = dim_z self.linear1 = torch.nn.Linear(self.dim_x, 64) self.linear2 = torch.nn.Li...
def _get_module_macs(module): s = module.__macs__ for child in module.children(): s += _get_module_macs(child) return s
class Grayscale(object): def __call__(self, img): gs = img.clone() gs[0].mul_(0.299).add_(0.587, gs[1]).add_(0.114, gs[2]) gs[1].copy_(gs[0]) gs[2].copy_(gs[0]) return gs
class sampler(Sampler): def __init__(self, train_size, batch_size): self.num_data = train_size self.num_per_batch = int((train_size / batch_size)) self.batch_size = batch_size self.range = torch.arange(0, batch_size).view(1, batch_size).long() self.leftover_flag = False ...
_sentencepiece class M2M100TokenizationTest(TokenizerTesterMixin, unittest.TestCase): tokenizer_class = M2M100Tokenizer test_rust_tokenizer = False test_seq2seq = False test_sentencepiece = True def setUp(self): super().setUp() vocab = ['</s>', '<unk>', 'This', 'is', 'a', 't', 'est',...
class chamfer_3DFunction(Function): def forward(ctx, xyz1, xyz2): (batchsize, n, _) = xyz1.size() (_, m, _) = xyz2.size() device = xyz1.device dist1 = torch.zeros(batchsize, n) dist2 = torch.zeros(batchsize, m) idx1 = torch.zeros(batchsize, n).type(torch.IntTensor) ...
def fdmobilenet_wd2_cub(num_classes=200, **kwargs): return get_mobilenet(num_classes=num_classes, version='fd', width_scale=0.5, model_name='fdmobilenet_wd2_cub', **kwargs)
def _get_log_dir(exec_func_name): cwd = pathlib.Path.cwd() return str(cwd.joinpath('data', 'local', 'benchmarks', exec_func_name))
def load_fountain_dataset(): rgbd_images = [] fountain_rgbd_dataset = o3d.data.SampleFountainRGBDImages() for i in range(len(fountain_rgbd_dataset.depth_paths)): depth = o3d.io.read_image(fountain_rgbd_dataset.depth_paths[i]) color = o3d.io.read_image(fountain_rgbd_dataset.color_paths[i]) ...
class PostProcessor(abc.ABC): def __init__(self, tokenizer, ignore_pad_token_for_loss): self.tokenizer = tokenizer self.ignore_pad_token_for_loss = ignore_pad_token_for_loss def process(self, preds, labels, data_info=None): if isinstance(preds, tuple): preds = preds[0] ...
class WavLMForAudioFrameClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class PSMDispProcessor(nn.Module): def __init__(self, max_disp=192): super().__init__() self.disp_processor = FasterSoftArgmin(max_disp=max_disp, start_disp=0, dilation=1, alpha=1.0, normalize=True) def forward(self, inputs): cost1 = inputs['cost1'] cost2 = inputs['cost2'] ...
def stat_coef_diff(X, X_tilde, y, method='lasso_cv', n_splits=5, n_jobs=1, n_lambdas=10, n_iter=1000, group_reg=0.001, l1_reg=0.001, joblib_verbose=0, return_coef=False, solver='liblinear', seed=0): n_features = X.shape[1] X_ko = np.column_stack([X, X_tilde]) lambda_max = (np.max(np.dot(X_ko.T, y)) / (2 * n...
class ResNetV2(nn.Module): def __init__(self, layers, channels=(256, 512, 1024, 2048), num_classes=1000, in_chans=3, global_pool='avg', output_stride=32, width_factor=1, stem_chs=64, stem_type='', avg_down=False, preact=True, act_layer=nn.ReLU, conv_layer=StdConv2d, norm_layer=partial(GroupNormAct, num_groups=32), ...
class CLIPVisionCfg(): layers: Union[(Tuple[(int, int, int, int)], int)] width: int head_width: int image_size: int mlp_ratio: float patch_size: int = None timm_model_name: str = None timm_model_pretrained: bool = None timm_pool: str = None timm_proj: str = None
class Host(): def __init__(self, ID, IPS, RAM, Disk, Bw, Latency, Powermodel, Environment): self.id = ID self.ipsCap = IPS self.ramCap = RAM self.diskCap = Disk self.bwCap = Bw self.latency = Latency self.powermodel = Powermodel self.powermodel.allocHo...
class ClassAssocationRule(): id = 0 def __init__(self, antecedent, consequent, support, confidence): self.antecedent = antecedent self.consequent = consequent self.support = support self.confidence = confidence self.rulelen = (len(antecedent) + 1) self.rid = Class...
def add_prefix(inputs, prefix): outputs = dict() for (name, value) in inputs.items(): outputs[f'{prefix}.{name}'] = value return outputs
def get_symbol_edges(node: Union[(str, ast.AST)]) -> List[Tuple[(Union[(str, ast.AST)], ast.AST)]]: if isinstance(node, str): node = ast.parse(node).body[0] return GetSymbolEdges()(node)
def retrieve_data_cfg(config_path, skip_type): cfg = Config.fromfile(config_path) train_data_cfg = cfg.data.train if hasattr(train_data_cfg, 'pipeline'): train_data_cfg['pipeline'] = [x for x in train_data_cfg.pipeline if (x['type'] not in skip_type)] else: train_data_cfg['dataset']['pip...
def get_dataframes_model(all_results, datasets, model_name, divide=False): dataset_keys = list(all_results.keys()) if divide: df_avg_self = pd.DataFrame() df_avg_mt = pd.DataFrame() else: df_avg = {} for average in (['avg'] + list(languages.keys())): df_avg[averag...
class VGGLoss_ESRGAN(nn.Module): def __init__(self): super().__init__() vgg19_model = models.vgg19(pretrained=True) self.vgg19_54 = nn.Sequential(*list(vgg19_model.features.children())[:35]) self.criterion = nn.L1Loss() def forward(self, real, fake): return self.criterion...
def submit_training(**kws): dims = (N_CLUSTERS, kws['dim_l1'], kws['dim__adj'], kws['dim__v']) scenario_key = (kws['aid'], kws['cid']) model_key = (kws['model_type'], kws['spill_v2adj'], kws['ov'], kws['sampling_id']) if ((scenario_key, model_key) in kws['gathered']): history = None else: ...
class ActionRepeat(object): def __init__(self, env, amount): self._env = env self._amount = amount def __getattr__(self, name): return getattr(self._env, name) def step(self, action): done = False total_reward = 0 current_step = 0 while ((current_step ...
def load_embedding(VOCAB, path, embedding_dim=300): with open(path) as f: weights = np.random.rand(VOCAB.get_vocab_size(), embedding_dim) counter = 0 for line in f.readlines(): try: line = line.strip().split() v = list(map(float, line[1:])) ...
def lanczos_generalized(operator, metric_operator=None, metric_inv_operator=None, num_eigenthings=10, which='LM', max_steps=20, tol=1e-06, num_lanczos_vectors=None, init_vec=None, use_gpu=False): if isinstance(operator.size, int): size = operator.size else: size = operator.size[0] shape = (s...
def train_data_loader(config, batch_size): train_dataset = DataSetMap[config.get('dataset', 'LinearDataset')](size=config.get('data_size', 1000), nested_input=config.get('nested_input', False)) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size) return train_loader
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, last=False): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) se...
class FINNExampleOverlay(Overlay): def __init__(self, bitfile_name, platform, io_shape_dict, batch_size=1, fclk_mhz=100.0, device=None, download=True, runtime_weight_dir='runtime_weights/'): super().__init__(bitfile_name, download=download, device=device) self.runtime_weight_dir = runtime_weight_dir...
def mean_absolute_error(y_true, y_pred): result = mean(abs((y_true - y_pred)), axis=1) return result
_module() class CascadeRCNN(TwoStageDetector): 'Implementation of `Cascade R-CNN: Delving into High Quality Object\n Detection < def __init__(self, backbone: ConfigType, neck: OptConfigType=None, rpn_head: OptConfigType=None, roi_head: OptConfigType=None, train_cfg: OptConfigType=None, test_cfg: OptConfigTyp...
class BackendPytorchNative(backend.Backend): def __init__(self): super(BackendPytorchNative, self).__init__() self.sess = None self.model = None self.device = ('cuda:0' if torch.cuda.is_available() else 'cpu') def version(self): return torch.__version__ def name(self)...