code
stringlengths
101
5.91M
def test_orbit_method_inputAsQuantity(): from galpy import potential from galpy.orbit import Orbit (ro, vo) = (7.0, 210.0) o = Orbit([(10.0 * units.kpc), (((- 20.0) * units.km) / units.s), ((210.0 * units.km) / units.s), (500.0 * units.pc), (((- 12.0) * units.km) / units.s), (45.0 * units.deg)], ro=ro, ...
_REGISTRY.register() def resnet101_ms_l123(pretrained=True, **kwargs): from dassl.modeling.ops import MixStyle model = ResNet(block=Bottleneck, layers=[3, 4, 23, 3], ms_class=MixStyle, ms_layers=['layer1', 'layer2', 'layer3']) if pretrained: init_pretrained_weights(model, model_urls['resnet101']) ...
.parametrize('loader_parameters', [{'path_data': [__data_testing_dir__], 'target_suffix': ['_lesion-manual'], 'extensions': [], 'roi_params': {'suffix': '_seg-manual', 'slice_filter_roi': None}, 'contrast_params': {'contrast_lst': ['T1w', 'T2w']}}]) def test_bids_df_anat(download_data_testing_test_files, loader_paramet...
class CatBoostEvalMetricMSE(object): def get_final_error(self, error, weight): return error def is_max_optimal(self): return False def evaluate(self, approxes, target, weight): assert (len(approxes) == 1) assert (len(target) == len(approxes[0])) preds = np.array(appro...
def mask_reduce_loss(loss, weight=None, reduction='mean', sample_wise=False): if (weight is not None): assert (weight.dim() == loss.dim()) assert ((weight.size(1) == 1) or (weight.size(1) == loss.size(1))) loss = (loss * weight) if ((weight is None) or (reduction == 'sum')): loss...
def run_tracker(tracker_name, tracker_param, run_id=None, dataset_name='otb', sequence=None, debug=0, threads=0, num_gpus=8): dataset = get_dataset(dataset_name) if (sequence is not None): dataset = [dataset[sequence]] trackers = [Tracker(tracker_name, tracker_param, dataset_name, run_id)] run_d...
class Pool(): def __init__(self, size): self.size = size self.data = ([None] * size) self.idx = 0 self.sum_len = 0 self.total = 0 def put(self, x): if (self.total >= self.size): old_x = self.data[self.idx] self.sum_len -= len(old_x[0]) ...
def fcn_resnet50(pretrained=False, progress=True, num_classes=21, aux_loss=None, **kwargs): return _load_model('fcn', 'resnet50', pretrained, progress, num_classes, aux_loss, **kwargs)
class LaTextControl(bc.BaseTextControl): (STC_STYLE_LA_DEFAULT, STC_STYLE_LA_KW, STC_STYLE_LA_IDENTIFIER, STC_STYLE_LA_STRING, STC_STYLE_LA_OPERATOR, STC_STYLE_LA_NUMBER, STC_STYLE_LA_ESCAPE_CHAR, STC_STYLE_LA_ESCAPE_STR, STC_STYLE_LA_ESCAPE_PARAMETER, STC_STYLE_LA_ESCAPE_DESCRIPTION) = range(10) SUBSTITUTION_S...
class UnCLIPTextProjModel(ModelMixin, ConfigMixin): _to_config def __init__(self, *, clip_extra_context_tokens: int=4, clip_embeddings_dim: int=768, time_embed_dim: int, cross_attention_dim): super().__init__() self.learned_classifier_free_guidance_embeddings = nn.Parameter(torch.zeros(clip_embe...
class BaseDeep(pl.LightningModule, _BaseModel): def __init__(self, latent_dimensions: int, encoders=None, optimizer: str='adam', scheduler: Optional[str]=None, lr: float=0.01, extra_optimizer_kwargs: Optional[Dict[(str, Any)]]=None, max_epochs: int=1000, eps=1e-06, *args, **kwargs): super().__init__() ...
def values_from_const(node_def): if (node_def.op != 'Const'): raise ValueError(f'''Can not extract constant value from a node that is not Const. Got: {node_def}''') input_tensor = node_def.attr['value'].tensor tensor_value = tensor_util.MakeNdarray(input_tensor) return tensor_value
def parse_args(): parser = argparse.ArgumentParser(description='Generate symlinks for train and test') parser.add_argument('-d', '--dataset', help='which dataset to process', default='all') parser.add_argument('--root-dir', help='the dir to store train and test symlinks', default='./data/HazeWorld') par...
def main(): parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--train-scp', required=True, help='kaldi train scp file') parser.add_argument('--train-utt2label', required=True, help='train utt2label') parser.add_argument('--validation-scp', required=True, help='ka...
def build_model(cfg, num_classes): if (cfg.MODEL.SETTING == 'video'): model = VNetwork(num_classes, cfg.MODEL.LAST_STRIDE, cfg.MODEL.PRETRAIN_PATH, cfg.MODEL.NECK, cfg.TEST.NECK_FEAT, cfg.MODEL.NAME, cfg.MODEL.PRETRAIN_CHOICE, cfg.MODEL.TEMP, cfg.MODEL.NON_LAYERS, cfg.INPUT.SEQ_LEN) return model ...
def test_caller(path, step_ind, on_val): os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0' config = Config() config.load(path) print() print('Dataset Preparation') print('') dataset = ThreeDMatchDataset(1, load_test=True) dataset.init_test_input_pipeline(config) print('Creating Model') pr...
class SimCLRCifarTransform(transforms.Compose): def __init__(self, train, finetune=False, normalize_stats=None): self.transforms = [] if (train or finetune): self.transforms = [transforms.RandomResizedCrop(32), transforms.RandomHorizontalFlip(p=0.5)] if train: self.tr...
def load_pipeline(config, dataset): name = config.pipeline.lower() mdict = {model.__name__.lower(): model for model in all_models} if (name not in mdict): print('Invalid pipeline. Options are:') for model in all_models: print('\t* {}'.format(model.__name__)) return None ...
def main_worker(gpu, ngpus_per_node, args): args.gpu = gpu if (args.multiprocessing_distributed and (args.gpu != 0)): def print_pass(*args): pass builtins.print = print_pass if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if args.distribu...
def test_repr(): assert ('pybind11_type' in repr(type(UserType))) assert ('UserType' in repr(UserType))
def rla_mobilenetv2_k6(): print('Constructing rla_mobilenetv2_k6......') model = RLA_MobileNetV2(rla_channel=6) return model
def tanh_1(x, mu, sd): xn = ((x - mu) / sd) tanh = torch.tanh(xn) sech2 = (1 - (tanh ** 2)) t = tanh jt = ((1 / sd) * sech2) return (t, jt)
def strip_iterator(graph_def): from neural_compressor.adaptor.tf_utils.util import strip_unused_nodes input_node_names = ['input_ids', 'input_mask', 'segment_ids'] output_node_names = ['loss/Softmax'] with tf.compat.v1.Graph().as_default() as g: input_ids = tf.compat.v1.placeholder(tf.int32, sha...
def __scale_shortside(img, target_width, method=Image.BICUBIC): (ow, oh) = img.size (ss, ls) = (min(ow, oh), max(ow, oh)) width_is_shorter = (ow == ss) if (ss == target_width): return img ls = int(((target_width * ls) / ss)) (nw, nh) = ((ss, ls) if width_is_shorter else (ls, ss)) ret...
def eval(args, val_loader, model, criterion): model.eval() if is_distributed(args.rank): model = model.module losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() device = args.device if args.cuda: torch.cuda.empty_cache() for (data, y) in val_loader: ...
def default_hp_search_backend(): if is_optuna_available(): return 'optuna' elif is_ray_available(): return 'ray'
def getUserStatistics(): cur = getDb().cursor() sql = 'select count(*), DATE(registered) from users group by DATE(registered) order by registered desc limit 30' cur.execute(sql) usersByDate = cur.fetchall() cur.execute('SELECT count(*) from users') total = cur.fetchall()[0][0] today = dateti...
class LinearWarmupCosineAnnealingLR(_LRScheduler): def __init__(self, optimizer: Optimizer, warmup_epochs: int, max_epochs: int, warmup_start_lr: float=0.0, eta_min: float=0.0, last_epoch: int=(- 1)) -> None: self.warmup_epochs = warmup_epochs self.max_epochs = max_epochs self.warmup_start_l...
def load_results(cfg, stage): try: filename = RESULTS_FILE.format(stage=stage) path = (Path(cfg.paths.results) / filename) results = pd.read_csv(path, index_col=0).to_dict() results = {f'{mode}/{k}': v for (mode, sub_dict) in results.items() for (k, v) in sub_dict.items()} re...
def Backbone_ResNet50_in3(): net = resnet50(pretrained=True) div_2 = nn.Sequential(*list(net.children())[:3]) div_4 = nn.Sequential(*list(net.children())[3:5]) div_8 = net.layer2 div_16 = net.layer3 div_32 = net.layer4 return (div_2, div_4, div_8, div_16, div_32)
def _segm_mobilenet(name, backbone_name, num_classes, output_stride, pretrained_backbone): if (output_stride == 8): aspp_dilate = [12, 24, 36] else: aspp_dilate = [6, 12, 18] backbone = mobilenetv2.mobilenet_v2(pretrained=pretrained_backbone, output_stride=output_stride) backbone.low_lev...
def cfg_base(): cfg = {} uuid = '' config_file = os.path.join(os.getcwd(), 'habitat-api/configs/tasks/pointnav_gibson_val.yaml') cfg['eval_kwargs'] = {'exp_path': '/mnt/logdir/keypoints3d_encoding_restart1', 'weights_only_path': None, 'challenge': True, 'debug': False, 'overwrite_configs': True, 'benchm...
def comp_num_seg_out_of_p_sent_beam(_filtered_doc_list, _num_edu, _absas_read_str, abs_as_read_list, map_from_new_to_ori_idx, beam_sz=8): beam = [] if (len(_filtered_doc_list) <= _num_edu): return {'nlabel': _num_edu, 'data': {}, 'best': None} combs = list(range(1, len(_filtered_doc_list))) cur_...
def set_seed(seed=3): os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
def chatglm_tokenize(ctx: ChatGLMContext, prompt: str) -> List[int]: return ctx.pipeline.tokenizer.encode(prompt)
class TransfEncoder(nn.Module): def __init__(self, n_vocab, pretrained=None, model_name='default', d_word_vec=512, d_model=512, len_max_seq=512, n_layer=6, d_inner=2048, slf_attn='multi-head', n_head=8, d_k=64, d_v=64, feat_vocab=None, d_feat_vec=32, layer_attn=False, slf_attn_mask='', dropout=0.1, attn_dropout=0.1...
def resampling_dataset_present(ds): if isinstance(ds, ResamplingDataset): return True if isinstance(ds, ConcatDataset): return any((resampling_dataset_present(d) for d in ds.datasets)) if hasattr(ds, 'dataset'): return resampling_dataset_present(ds.dataset) return False
def trades_loss(model, x_natural, y, optimizer, step_size=0.003, epsilon=0.031, perturb_steps=10, beta=1.0, attack='linf-pgd', label_smoothing=0.1): criterion_ce = SmoothCrossEntropyLoss(reduction='mean', smoothing=label_smoothing) criterion_kl = nn.KLDivLoss(reduction='sum') model.train() track_bn_stat...
def quantize_grad(x, num_bits=None, qparams=None, flatten_dims=_DEFAULT_FLATTEN_GRAD, reduce_dim=0, dequantize=True, signed=False, stochastic=True): return UniformQuantizeGrad().apply(x, num_bits, qparams, flatten_dims, reduce_dim, dequantize, signed, stochastic)
class _TorchNanoModule(_LiteModule): def __init__(self, module, precision_plugin, channels_last) -> None: super().__init__(module, precision_plugin) self.channels_last = channels_last def state_dict(self, *args, **kwargs): if isinstance(self.module, DistributedDataParallel): ...
class RoFormerTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION def __init__(self, vocab_file, do_l...
class ConResidualBlock(nn.Module): def __init__(self, h_dim, c_norm_layer=None, nl_layer=None, use_dropout=False, return_con=False): super(ConResidualBlock, self).__init__() self.return_con = return_con self.c1 = Conv2dBlock(h_dim, h_dim, kernel_size=3, stride=1, padding=1, pad_type='reflect...
def test_digits_cosine_greedi_ln_object(): model = SumRedundancySelection(100, 'cosine', optimizer=GreeDi(optimizer1='lazy', optimizer2='naive', random_state=0)) model.fit(X_digits) assert_array_equal(model.ranking, digits_cosine_greedi_ranking) assert_array_almost_equal(model.gains, digits_cosine_greed...
class FlaxLMSDiscreteScheduler(FlaxSchedulerMixin, ConfigMixin): _compatibles = [e.name for e in FlaxKarrasDiffusionSchedulers] dtype: jnp.dtype def has_state(self): return True _to_config def __init__(self, num_train_timesteps: int=1000, beta_start: float=0.0001, beta_end: float=0.02, beta_...
def require_torch(test_case): if (not is_torch_available()): return unittest.skip('test requires PyTorch')(test_case) else: return test_case
def generate_json(docid, vector): return json.dumps({'id': docid, 'contents': '', 'vector': vector}, ensure_ascii=False)
_model def ese_vovnet39b_evos(pretrained=False, **kwargs): def norm_act_fn(num_features, **nkwargs): return create_norm_act('EvoNormSample', num_features, jit=False, **nkwargs) return _create_vovnet('ese_vovnet39b_evos', pretrained=pretrained, norm_layer=norm_act_fn, **kwargs)
def generate_model(opt): assert (opt.model in ['resnet', 'resnext']) if (opt.model == 'resnet'): assert (opt.model_depth in [10, 18, 34, 50, 101, 152, 200]) from models.resnet import get_fine_tuning_parameters if (opt.model_depth == 10): model = resnet.resnet10(opt=opt) ...
_metaclass(ABCMeta) class SimulatorProcessBase(mp.Process): def __init__(self, idx): super(SimulatorProcessBase, self).__init__() self.idx = int(idx) self.name = u'simulator-{}'.format(self.idx) self.identity = self.name.encode('utf-8') def _build_player(self): pass
class _GateMoudle(nn.Module): def __init__(self): super(_GateMoudle, self).__init__() self.conv1 = nn.Conv2d(131, 64, (3, 3), 1, 1) self.relu = nn.LeakyReLU(0.2, inplace=True) self.conv2 = nn.Conv2d(64, 64, (1, 1), 1, padding=0) for i in self.modules(): if isinsta...
def test(dataset, epoch): ff = open((('recordFATTOld' + str(epoch)) + '.txt'), 'w') count = 0 correct = 0 tp = [] tn = [] fp = [] fn = [] for yi in range(0, 18): tp.append(0) tn.append(0) fp.append(0) fn.append(0) results = [] for (data, label) in ...
def training_loss_2nd_user_task(data, batch_index, model, sess, train_data, is_training): train_loss = 0.0 num_batch = (data.oracle_num_users // setting.batch_size_user) for index in batch_index: (b_target_user, b_k_shot_item, b_second_order_users, b_third_order_items, b_oracle_user_ebd, b_mask_num_...
def test(model, dataloader): model.eval() device = model.device time_start = time.time() batch_time = 0.0 accuracy = 0.0 with torch.no_grad(): for batch in dataloader: batch_start = time.time() premises = batch['premise'].to(device) premises_lengths = ...
class Bert4WSFunction(BaseFunction): def __init__(self): super().__init__() def forward(self, batch=None): (input_ids, attention_mask, segment_ids, label_ids, label_masks) = batch sequence_output = self.bert(input_ids=input_ids, attention_mask=attention_mask)[0] sequence_output =...
class CosineSimilarityAnalysis(): def __init__(self, file_paths): self.file_paths = file_paths def load_scores(self, file_path): with open(file_path, 'r') as file: scores = json.load(file) return scores def calculate_cosine_scores_gpu(self, data1, data2_tensors, vectorize...
class DeResNetBlockBatchNorm(nn.Module): def __init__(self, inplanes, planes, stride=1, output_padding=0, activation='relu'): super(DeResNetBlockBatchNorm, self).__init__() assert (activation in ['relu', 'elu', 'leaky_relu']) self.deconv1 = deconv3x3(inplanes, planes, stride, output_padding)...
def _upgrade_state_dict(state): if ('optimizer_history' not in state): state['optimizer_history'] = [{'criterion_name': 'CrossEntropyCriterion', 'best_loss': state['best_loss']}] state['last_optimizer_state'] = state['optimizer'] del state['optimizer'] del state['best_loss'] if (...
class EntityLabel(): def __init__(self, identifier, index, short_name, verbose_name): self._identifier = identifier self._index = index self._short_name = short_name self._verbose_name = verbose_name def identifier(self): return self._identifier def index(self): ...
class TestBasicSwap(QiskitTestCase): def test_trivial_case(self): coupling = CouplingMap([[0, 1], [0, 2]]) qr = QuantumRegister(3, 'q') circuit = QuantumCircuit(qr) circuit.cx(qr[0], qr[1]) circuit.h(qr[0]) circuit.cx(qr[0], qr[2]) dag = circuit_to_dag(circuit...
def predict_inputs(model: nn.Module, inputs: Tensor) -> Tuple[(Tensor, Tensor, Tensor)]: logits = model(inputs) probabilities = torch.softmax(logits, 1) predictions = logits.argmax(1) return (logits, probabilities, predictions)
('pretrained_mlm') class PretrainedMLM(TokenEmbedder): authorized_missing_keys = ['position_ids$'] def __init__(self, model_name: str, *, max_length: int=None, train_parameters: Union[(bool, str)]=True, arp_injector: Union[(Lazy[ArpInjector], ArpInjector)], on_logits: Union[(bool, str)]=False, eval_mode: bool=F...
def parse_node_str(node_str): node_str = node_str.split(' #')[0] op_groups = node_str.split('), %') for i in range((len(op_groups) - 1)): op_groups[i] += ')' for i in range(1, len(op_groups)): op_groups[i] = ('%' + op_groups[i]) node_dict = {} for op_group in op_groups: (...
class VGG19FeatureExtractor(nn.Module): def __init__(self, layer_names: List[str]=VGG19LAYERS): super().__init__() self.backbone = tv_models.vgg19(pretrained=True) _set_requires_grad_false(self.backbone) self.features = nn.Sequential(*(list(self.backbone.features.children()) + [self....
class RandomRotate90(DualTransform): def __init__(self, axes=(0, 1), always_apply=False, p=0.5): super().__init__(always_apply, p) self.axes = axes def apply(self, img, factor): return np.rot90(img, factor, axes=self.axes) def get_params(self, **data): return {'factor': rando...
def get_launcher_path() -> Path: root = Path('/root/eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/plugins/') return next(root.glob('org.eclipse.equinox.launcher_*.jar'))
def build_frame_selector(cfg: CfgNode): strategy = FrameSelectionStrategy(cfg.STRATEGY) if (strategy == FrameSelectionStrategy.RANDOM_K): frame_selector = RandomKFramesSelector(cfg.NUM_IMAGES) elif (strategy == FrameSelectionStrategy.FIRST_K): frame_selector = FirstKFramesSelector(cfg.NUM_IM...
def custom_vgg(custom_cfg, dataset_history=[], dataset2num_classes={}, network_width_multiplier=1.0, groups=1, shared_layer_info={}, **kwargs): return VGG(make_layers(custom_cfg, network_width_multiplier, batch_norm=True, groups=groups), dataset_history, dataset2num_classes, network_width_multiplier, shared_layer_i...
_grad() def evaluate(model, criterion, valid_loader): model.eval() acc_losses = {} for (i, (x, _)) in enumerate(valid_loader): x = x.to(args.device) output = model(x) (_, diagnostics) = criterion(x, output, model) acc_losses = (Counter(acc_losses) + Counter(diagnostics)) ...
def parseTask(task: list) -> Tuple[(str, str, str)]: api: str = task[0] label: str = task[1] src: str = task[2] return (api, label, src)
_registry('SelfKnowledgeDistillationLoss', 'pytorch') class PyTorchSelfKnowledgeDistillationLossWrapper(object): def __init__(self, param_dict): self.param_dict = param_dict def _param_check(self): param_dict = self.param_dict _params = ['temperature', 'layer_mappings', 'loss_types', 'lo...
def exitTensorMol(): PrintTMTIMER() LOGGER.info('Total Time : %0.5f s', (time.time() - TMSTARTTIME)) LOGGER.info('~ Adios Homeshake ~')
class Time_usage_testing(): def __init__(self): pass def init(self, train): self.start_time = 0 self.start_time_cpu = 0 self.time_sum_cpu = 0 self.time_sum = 0 self.time_count = 0 def start_predict(self, algorithm): self.start_time = time.time() ...
_grad() def convert_dalle_checkpoint(checkpoint_path, pytorch_dump_folder_path, config_path=None, save_checkpoint=True): from dall_e import Encoder encoder = Encoder() if os.path.exists(checkpoint_path): ckpt = torch.load(checkpoint_path) else: ckpt = torch.hub.load_state_dict_from_url(c...
class DataHandler(): base_dataset = None train_transforms = [] common_transforms = [transforms.ToTensor()] class_order = None
def _build_viz_err_obj(err_msg): _type = 'html' figure = _build_error_frame(err_msg) viz_figure = {'type': _type, 'figure': figure} viz_obj = {'name': 'Error', 'overall': viz_figure, 'specific': [], 'selector': {'columns': [], 'data': []}} return viz_obj
class RandomCrop(object): def __init__(self, output_size): if ((type(output_size) != tuple) and (type(output_size) != list)): output_size = (output_size, output_size) self.output_size = output_size def __call__(self, input): img = input if (type(input) == list): ...
def create_transform(input_size, is_training=False, use_prefetcher=False, no_aug=False, scale=None, ratio=None, hflip=0.5, vflip=0.0, color_jitter=0.4, auto_augment=None, interpolation='bilinear', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, re_prob=0.0, re_mode='const', re_count=1, re_num_splits=0, crop_pct=N...
def test_can_access_globals_from_original_scope(): from .enclosed_config_scope import cfg as conf_scope cfg = conf_scope() assert (set(cfg.keys()) == {'answer'}) assert (cfg['answer'] == 42)
class PrefixTransformer(pl.LightningModule): def __init__(self, hparams: argparse.Namespace, num_labels=None, config=None, tokenizer=None, seq2seq_model=None, **config_kwargs): super().__init__() self.save_hyperparameters(hparams) self.step_count = 0 self.output_dir = Path(self.hpara...
class FairseqLRScheduler(object): def __init__(self, args, optimizer): super().__init__() if (not isinstance(optimizer, FairseqOptimizer)): raise ValueError('optimizer must be an instance of FairseqOptimizer') self.args = args self.optimizer = optimizer self.best ...
def set_output_path(context): path_output = copy.deepcopy(context[ConfigKW.PATH_OUTPUT]) if (not Path(path_output).is_dir()): logger.info(f'Creating output path: {path_output}') Path(path_output).mkdir(parents=True) else: logger.info(f'Output path already exists: {path_output}') ...
def _write_data_by_character(examples, output_directory): if (not os.path.exists(output_directory)): os.makedirs(output_directory) for (character_name, sound_bites) in examples.items(): filename = os.path.join(output_directory, (character_name + '.txt')) with open(filename, 'w') as outpu...
def extract_citationIDs(application_identifier, line): words = line.split('\t')[6].split(' ') indices = [i for (i, x) in enumerate(words) if ('sr-cit' in x)] return [((application_identifier + '_') + words[i][(words[i].find('sr-cit') + 6):(words[i].find('sr-cit') + 10)]) for i in indices]
class BaseNStepReturnBuffer(BaseReplayBuffer): def __init__(self, example, size, B, discount=1, n_step_return=1): self.T = T = math.ceil((size / B)) self.B = B self.size = (T * B) self.discount = discount self.n_step_return = n_step_return self.t = 0 self.samp...
def build_failed_report(results, include_warning=True): failed_results = {} for config_name in results: if ('error' in results[config_name]): if (config_name not in failed_results): failed_results[config_name] = {} failed_results[config_name] = {'error': results[c...
def generate_latency_model(agent_count, latency_type='deterministic'): assert (latency_type in ['deterministic', 'no_latency']), 'Please select a correct latency_type' latency_rstate = np.random.RandomState(seed=np.random.randint(low=0, high=(2 ** 32))) pairwise = (agent_count, agent_count) if (latency_...
class BaseAssigner(metaclass=ABCMeta): def assign(self, pred_instances: InstanceData, gt_instances: InstanceData, gt_instances_ignore: Optional[InstanceData]=None, **kwargs):
class FlaxBertPreTrainedModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
class FileBinarizer(): def multiprocess_dataset(cls, input_file: str, dataset_impl: str, binarizer: Binarizer, output_prefix: str, vocab_size=None, num_workers=1) -> BinarizeSummary: final_summary = BinarizeSummary() offsets = find_offsets(input_file, num_workers) (first_chunk, *more_chunks)...
class _ConvBN(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, norm_layer=nn.BatchNorm2d, **kwargs): super(_ConvBN, self).__init__() self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias=...
def _get_graphs(): return [nn.GraphsTuple(nodes=np.array([[1.0], [2.0]]), edges=np.array([[[1.0], [2.0]], [[3.0], [4.0]]]), globals=np.array([1.0]), edge_idx=np.array([[0, 1], [0, 1]])), nn.GraphsTuple(nodes=np.array([[1.0], [2.0]]), edges=np.array([[[1.0], [2.0]], [[3.0], [4.0]]]), globals=np.array([1.0]), edge_id...
class FlaxBertForMaskedLM(): def __init__(self, *args, **kwargs): requires_flax(self) def from_pretrained(self, *args, **kwargs): requires_flax(self)
class MvpModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def main(): args = parse_args() assert (args.out or args.eval or args.format_only or args.show), 'Please specify at least one operation (save/eval/format/show the results) with the argument "--out", "--eval", "--format_only" or "--show"' if (args.eval and args.format_only): raise ValueError('--eval ...
def conv(data, name, filters, kernel=3, stride=1, dilate=1, pad=(- 1), groups=1, no_bias=False, workspace=(- 1)): if (kernel == 1): dilate = 1 if (pad < 0): assert ((kernel % 2) == 1), 'Specify pad for an even kernel size' pad = ((((kernel - 1) * dilate) + 1) // 2) if (workspace < 0)...
def main(): args = parse_args() if (args is None): exit() with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess: gan = UGATIT(sess, args) gan.build_model() show_all_variables() if (args.phase == 'train'): gan.train() print('...
def get_dataset(batch_size, dataset, is_training=True, inception_style=False, use_randaug=True): if is_training: if inception_style: dataset = dataset.repeat((args.epochs + 1)) def _pp(im, y): channels = im.shape[(- 1)] (begin, size, _) = tf.image.samp...
def concat_tensor_list(tensor_list, recurrent=False): if recurrent: return np.array(tensor_list) else: return np.concatenate(tensor_list, axis=0)
def main(): env = gym.make('CartPole-v0') act = deepq.load('cartpole_model.pkl') while True: (obs, done) = (env.reset(), False) episode_rew = 0 while (not done): env.render() (obs, rew, done, _) = env.step(act(obs[None])[0]) episode_rew += rew ...
class Transpose(Module): def __init__(self, perm): super().__init__() self.perm = perm def forward(self, input): assert (input.dim() == len(self.perm)) return input.permute(self.perm) def from_onnx(parameters=None, attributes=None): if (attributes is None): ...