code
stringlengths
101
5.91M
def normalize(policy_id, score): key = (policy_id + '-v0') min_score = infos.REF_MIN_SCORE[key] max_score = infos.REF_MAX_SCORE[key] return ((score - min_score) / (max_score - min_score))
def _update_model_res_skip(old_model, new_model): for idx in range(0, len(new_model.WN)): wavenet = new_model.WN[idx] n_channels = wavenet.n_channels n_layers = wavenet.n_layers wavenet.res_skip_layers = torch.nn.ModuleList() for i in range(0, n_layers): if (i < (...
class MyModel(object): def Start(self): ns.core.Simulator.Schedule(ns.core.Seconds(10.0), self.HandleEvent, ns.core.Simulator.Now().GetSeconds()) def HandleEvent(self, value): print('Member method received event at', ns.core.Simulator.Now().GetSeconds(), 's started at', value, 's')
def gen_grad_ens(x, logits, y): adv_loss = K.categorical_crossentropy(logits[0], y, from_logits=True) if (len(logits) >= 1): for i in range(1, len(logits)): adv_loss += K.categorical_crossentropy(logits[i], y, from_logits=True) grad = K.gradients(adv_loss, [x])[0] return (adv_loss, g...
def return_diving48(): root_data = 'Diving48/frames' filename_imglist_train = 'Diving48/train_videofolder.txt' filename_imglist_val = 'Diving48/val_videofolder.txt' prefix = '{:05d}.jpg' return (filename_imglist_train, filename_imglist_val, root_data, prefix)
def method_impl(name, declarations, is_python_method, module): for declaration in declarations: declaration['python_arglists'] = make_python_arglists(declaration, is_python_method) pycname = get_pycname(name) method_header = ['HANDLE_TH_ERRORS'] method_header += emit_namedtuple_typedefs(declarat...
def default_setup(cfg, args): output_dir = cfg.OUTPUT_DIR if (comm.is_main_process() and output_dir): PathManager.mkdirs(output_dir) rank = comm.get_rank() logger = setup_logger(output_dir, distributed_rank=rank) logger.info('Rank of current process: {}. World size: {}'.format(rank, comm.get...
def spawn(cmd, *args): argv = ([cmd] + list(args)) pid = None args_str = ' '.join(argv) try: pid = os.spawnlp(os.P_NOWAIT, cmd, *argv) children[pid] = {'pid': pid, 'cmd': argv} except Exception as inst: print(f"'{args_str}': {str(inst)}") print(f"spawned pid {pid} of npro...
class GammaAugmentor(Augmentor): def __init__(self, gamma_range=((- 0.1), 0.1)): self.gamma_range = gamma_range def apply_after_resize(self, tensors, factor=None): with tf.name_scope('gamma_augmentor'): img = tensors[DataKeys.IMAGES] if (factor is None): f...
class GlobalConsistencyError(ConfusionMatrixMetric): def __init__(self, metric: str='GCOERR'): super().__init__(metric) def calculate(self): tp = self.confusion_matrix.tp tn = self.confusion_matrix.tn fp = self.confusion_matrix.fp fn = self.confusion_matrix.fn if ...
def get_dataset(args): if (args.dataset == 'cifar10'): transform_train = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))]) transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0....
class ROIMaskHead(torch.nn.Module): def __init__(self, cfg, in_channels): super(ROIMaskHead, self).__init__() self.cfg = cfg.clone() self.feature_extractor = make_roi_mask_feature_extractor(cfg, in_channels) self.predictor = make_roi_mask_predictor(cfg, self.feature_extractor.out_cha...
class FeatureFusion3dce(nn.Module): def __init__(self): super(FeatureFusion3dce, self).__init__() self.num_slice = cfg.INPUT.NUM_SLICES self.num_image = cfg.INPUT.NUM_IMAGES_3DCE self.out_dim = cfg.MODEL.BACKBONE.OUT_CHANNELS self.in_dim = cfg.runtime_info.backbone_ft_dim ...
def pesq_nb(predicted, target, sampling_frequency=8000): g = torch.manual_seed(1) nb_pesq = PerceptualEvaluationSpeechQuality(sampling_frequency, 'nb') return nb_pesq(predicted, target)
def draw_image_embedding_with_batch_to_tensor(batch): if (('image_embedding' not in batch) or (batch['image_embedding'] is None)): return (- torch.ones_like(batch['image'])) elif ('image' in batch['image_embedding']): return batch['image_embedding']['image'] else: return (- torch.one...
class LockedValue(object): def __init__(self, value): self.lock = threading.Lock() self._value = value def _get_value(self): self.lock.acquire() try: return self._value finally: self.lock.release() def _set_value(self, value): self.lock...
class ClassifierTeacherLoss(object): def __init__(self, teacher_model): self.teacher = teacher_model def __call__(self, inputs, targets): logits = self.teacher(inputs) loss = F.cross_entropy(logits, targets) return (loss, logits)
def get_model(framework, text_type, text_rep, arch='transformer', frontend='cnn', mix_type='cf', audio_rep='mel'): save_dir = f'../mtr/{framework}/exp/{arch}_{frontend}_{mix_type}_{audio_rep}/{text_type}_{text_rep}' config = OmegaConf.load(os.path.join(save_dir, 'hparams.yaml')) audio_preprocessr = TFRep(sa...
def move_pre_birth(patient: RawPatient) -> Optional[RawPatient]: birth_date = None for event in patient.events: if (event.concept_id == OMOP_BIRTH): birth_date = event.start if (birth_date is None): return None new_events = [] for event in patient.events: if (even...
class HPUXFCompiler(FCompiler): compiler_type = 'hpux' description = 'HP Fortran 90 Compiler' version_pattern = 'HP F90 (?P<version>[^\\s*,]*)' executables = {'version_cmd': ['f90', '+version'], 'compiler_f77': ['f90'], 'compiler_fix': ['f90'], 'compiler_f90': ['f90'], 'linker_so': ['ld', '-b'], 'archiv...
class MapTilingTuner(cutout_tuner.CutoutTuner): def __init__(self, sdfg: dace.SDFG, measurement: dtypes.InstrumentationType=dtypes.InstrumentationType.Timer) -> None: super().__init__(task='MapTiling', sdfg=sdfg) self.instrument = measurement def cutouts(self) -> Generator[(Tuple[(dace.SDFG, str...
.parametrize('directed', [True, False]) .parametrize('tree_func', [breadth_first_tree, depth_first_tree]) def test_int64_indices(tree_func, directed): g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2)) assert (g.indices.dtype == np.int64) tree = tree_func(g, 0, directed=directed) a...
_lr_scheduler('polynomial_decay') class PolynomialDecaySchedule(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) args.warmup_updates = (getattr(args, 'warmup_updates', 0) or 0) self.lr = args.lr[0] if (args.warmup_updates > 0): s...
class _coo_base(_data_matrix, _minmax_mixin): _format = 'coo' def __init__(self, arg1, shape=None, dtype=None, copy=False): _data_matrix.__init__(self) is_array = isinstance(self, sparray) if isinstance(arg1, tuple): if isshape(arg1, allow_1d=is_array): self._...
def add_graph_arguments(parser): parser.add_argument('--num-items', type=int, default=10, help='Maximum number of items in each KB') parser.add_argument('--entity-hist-len', type=int, default=2, help='Number of most recent utterances to consider when updating entity node embeddings') parser.add_argument('--...
class VitAttention(SequenceModule): def d_output(self): return self.dim def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, packed_linear=True, linear_cfg=None, **kwargs): super().__init__() self.dim = dim self.num_heads = num_heads head_dim...
class TransitiveGroup(PermutationGroup_unique): def __init__(self, d, n): self._d = d = Integer(d) self._n = n = Integer(n) if (d < 0): raise ValueError('degree d must not be negative') max_n = TransitiveGroups(d).cardinality() if ((n > max_n) or (n <= 0)): ...
def register_Ns3QueueDisc_methods(root_module, cls): cls.add_constructor([]) cls.add_method('AddInternalQueue', 'void', [param('ns3::Ptr< ns3::Queue< ns3::QueueDiscItem > >', 'queue')]) cls.add_method('AddPacketFilter', 'void', [param('ns3::Ptr< ns3::PacketFilter >', 'filter')]) cls.add_method('AddQueue...
(scope='function') def ray_session_fixture(): if (not ray.is_initialized()): ray.init(memory=, object_store_memory=, ignore_reinit_error=True, log_to_driver=False, include_webui=False) (yield) if ray.is_initialized(): ray.shutdown()
def generate_plot_points(f, xrange, plot_points=5, adaptive_tolerance=0.01, adaptive_recursion=5, randomize=True, initial_points=None, *, excluded=False, imaginary_tolerance=1e-08): from sage.plot.misc import setup_for_eval_on_grid (f, ranges) = setup_for_eval_on_grid(f, [xrange], plot_points, imaginary_toleran...
def _final_estimator_has(attr): def check(self): getattr(self._final_estimator, attr) return True return check
def sample_neighs(G, nodes, sample_num=None, self_loop=False, shuffle=True): _sample = np.random.choice neighs = [list(G[int(node)]) for node in nodes] if sample_num: if self_loop: sample_num -= 1 samp_neighs = [(list(_sample(neigh, sample_num, replace=False)) if (len(neigh) >= s...
def head_forward(inputs, in_index, embed_layers, fuse_layer, align_corners): x = inputs (n, _, h, w) = x[(- 1)].shape os_size = x[0].size()[2:] _c = {} for i in in_index: _c[i] = embed_layers[str(i)](x[i]) if (_c[i].dim() == 3): _c[i] = _c[i].permute(0, 2, 1).contiguous()...
def spec_to_float32(spec): spec32 = [] for (name, dtype) in spec: if (dtype == float64): dtype32 = float32 elif isinstance(dtype, numba.core.types.npytypes.Array): if (dtype.dtype == float64): dtype32 = dtype.copy(dtype=float32) else: ...
class Precision(object): def __init__(self, n=21, max_accuracy=2): self.max_accuracy = max_accuracy self.Xaxis = np.linspace(0, self.max_accuracy, n) self.reset() def reset(self): self.accuracies = [] def add_accuracy(self, val, index=None): self.accuracies.append(val...
class FlaxVisionEncoderDecoderModel(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def test_RegularArray_RecordArray_NumpyArray(): a = ak.contents.regulararray.RegularArray(ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]))], ['nest']), 3) assert (a.to_typetracer().form == a.to_typetracer(forget_length=True).form) assert i...
def GetPseudoAAC1(ProteinSequence, lamda=30, weight=0.05, AAP=[_Hydrophobicity, _hydrophilicity]): rightpart = 0.0 for i in range(lamda): rightpart = (rightpart + GetSequenceOrderCorrelationFactor(ProteinSequence, (i + 1), AAP)) AAC = GetAAComposition(ProteinSequence) result = {} temp = (1 +...
class CommonRemoteModuleTest(RpcAgentTestFixture): def world_size(self): return 2 def _create_remote_module_iter(remote_device, modes=None): if (modes is None): modes = ModuleCreationMode.__members__.values() args = (1,) kwargs = dict(first_kwarg=2) if (Module...
def _check_decreasing_hecke_factorization(t): if (not isinstance(t, DecreasingHeckeFactorization)): if (not isinstance(t, (tuple, list))): raise ValueError('t should be a list or tuple') for factor in t: if (not isinstance(factor, (tuple, list))): raise ValueE...
class GenerativeDecoder(nn.Module): def __init__(self, config, vocabulary): super().__init__() self.config = config self.word_embed = nn.Embedding(len(vocabulary), config['word_embedding_size'], padding_idx=vocabulary.PAD_INDEX) self.answer_rnn = nn.LSTM(config['word_embedding_size']...
class BuildModelJob(GenericJob): def __init__(self, problem): self.type = 'buildmodel' GenericJob.__init__(self, problem) self.add_call_Back(self.print_result) def run(self): print(('Process [%s]: buildmodel running %s' % (os.getpid(), self.problem_name)), file=sys.stderr) ...
def log_pytorch_version_info(): import torch logger.info('Pytorch version: %s', torch.__version__)
def test_resplit_no_keep_tokens(pipeline): tokens = [['I', "can't", 'believe', 'it'], ["I can't", 'sleep']] doc = resplit_mwt(tokens, pipeline, keep_tokens=False) assert (len(doc.sentences) == 2) assert (len(doc.sentences[0].tokens) == 4) assert (len(doc.sentences[0].tokens[1].words) == 2) asser...
def inconsistent_user_full_pandas_dataset(): events = pd.DataFrame({'user_id': [0, 0, 1, 1, 1, 3], 'item_id': [0, 1, 0, 2, 3, 1], 'timestamp': [0, 1, 2, 3, 4, 5], 'rating': [1.1, 1.2, 1.3, 2, 3, 4]}) users = pd.DataFrame({'user_id': [0, 1, 2], 'gender': [0, 1, 0]}) items = pd.DataFrame({'item_id': [0, 1, 2,...
def create_dict_dataloader(X, Y, split, **kwargs): ds = DictDataset.from_tensors(torch.FloatTensor(X), torch.LongTensor(Y), split) return DictDataLoader(ds, **kwargs)
class EncodingBytes(bytes): def __new__(self, value): assert isinstance(value, bytes) return bytes.__new__(self, value.lower()) def __init__(self, value): self._position = (- 1) def __iter__(self): return self def __next__(self): p = self._position = (self._positi...
def test_gcn_lstm_model_input_output(): (fx, fy, a) = get_timeseries_graph_data() gcn_lstm_model = GCN_LSTM(seq_len=fx.shape[(- 1)], adj=a, gc_layer_sizes=[8, 8, 16], gc_activations=['relu', 'relu', 'relu'], lstm_layer_sizes=[8, 16, 32], lstm_activations=['tanh']) (x_input, x_output) = gcn_lstm_model.in_out...
class Metrics(): def calculate_metrics_mm(self, output, gt_item): valid_mask = (gt_item > 0.1) output_mm = (1000.0 * output[valid_mask]) gt_mm = (1000.0 * gt_item[valid_mask]) diff = np.abs((output_mm - gt_mm)) mse = np.mean(np.power(diff, 2)) rmse = np.sqrt(mse) ...
def griffin_lim(magnitudes, stft_fn, n_iters=30): angles = np.angle(np.exp(((2j * np.pi) * np.random.rand(*magnitudes.size())))) angles = angles.astype(np.float32) angles = torch.autograd.Variable(torch.from_numpy(angles)) signal = stft_fn.inverse(magnitudes, angles).squeeze(1) for i in range(n_iter...
def test_add_constructor(provide_callables_from_fixtures_modules, default_test_case): generic_constructor = gao.GenericConstructor(owner=default_test_case.test_cluster.type_system.to_type_info(provide_callables_from_fixtures_modules['Basket']), inferred_signature=InferredSignature(signature=Signature(parameters=[Pa...
class LabelCooccurrenceGraphBuilder(GraphBuilderBase): def __init__(self, weighted=None, include_self_edges=None, normalize_self_edges=None): super(LabelCooccurrenceGraphBuilder, self).__init__() if (weighted not in [True, False]): raise ValueError('Weighted needs to be a boolean') ...
class COCODataset(torchvision.datasets.coco.CocoDetection): def __init__(self, ann_file, root, remove_images_without_annotations, ann_types, transforms=None): super(COCODataset, self).__init__(root, ann_file) self.ids = sorted(self.ids) if remove_images_without_annotations: ids =...
def get_version() -> str: path = (Path(__file__).resolve().parents[2] / 'pyproject.toml') pyproject = toml.loads(open(str(path)).read()) return cast(str, pyproject['tool']['poetry']['version'])
class ImageDataset(Dataset): def __init__(self, root_dir, split, data_transform=None, forward_context=0, back_context=0, strides=(1,), depth_type=None, **kwargs): super().__init__() assert ((depth_type is None) or (depth_type == '')), 'ImageDataset currently does not support depth types' ass...
class Lexicon(): def __init__(self, filename): print('Loading lexicon', filename, file=log.v4) lex_file = open(filename, 'rb') if filename.endswith('.gz'): lex_file = gzip.GzipFile(fileobj=lex_file) self.phoneme_list = [] self.phonemes = {} self.lemmas = {...
def create_pipeline_configuration(DEBUG=False, batch_size=32): config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (CrossEntropyLoss, T5Block, T5LayerNorm, StatelessEmbedding, Linear, Dropout), 'model_inputs': {'attention_mask': {'shape': torch.Size([32, 1, 1, 384]), 'dtype': torch.float32, 'is_batched': True...
def test_timeout_non_int_fails(): parser = _get_command_line_parser(['valid-detector'], [], []) assert_raises(SystemExit, parser.parse_args, ['run', 'ex1', 'valid-detector', '--timeout', 'string'])
def _read_mat_binary(fd): header = fd.read(3).decode() if header.startswith('CM'): return _read_compressed_mat(fd, header) elif (header == 'FM '): sample_size = 4 elif (header == 'DM '): sample_size = 8 else: raise UnknownMatrixHeader(("The header contained '%s'" % he...
_optimizer('nag') class FairseqNAG(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = NAG(params, **self.optimizer_config) def add_args(parser): parser.add_argument('--momentum', default=0.99, type=float, metavar='M', help='momentum factor') ...
class FuncDefNode(StatNode, BlockNode): py_func = None needs_closure = False needs_outer_scope = False pymethdef_required = False is_generator = False is_generator_body = False is_async_def = False modifiers = [] has_fused_arguments = False star_arg = None starstar_arg = None...
_module() class DeepFashionDataset(CocoDataset): CLASSES = ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', 'bag', 'neckwear', 'headwear', 'eyeglass', 'belt', 'footwear', 'hair', 'skin', 'face')
def isend(tensor, dst): assert (torch.distributed.deprecated._initialized == _INITIALIZED_PG), 'collective only supported in process-group mode' return _DistributedRequest(torch._C._dist_isend(tensor, dst))
class SkipSubset(data.Dataset): def __init__(self, dataset, n=2): self.dataset = dataset assert (n >= 1) self.indices = np.arange(len(dataset))[::n] def __getitem__(self, idx): return self.dataset[self.indices[idx]] def __len__(self): return len(self.indices) def ...
def main(): fruits = cv2.imread('fruits.jpg', cv2.IMREAD_COLOR) frame = np.zeros(fruits.shape, np.uint8) low_threshold = [50] high_threshold = [150] use_canny = [False] settings = EnhancedWindow(10, 50, 270, 180, 'Settings') cvui.init(WINDOW_NAME) while True: if use_canny[0]: ...
def test_unknown_data(testdir): testdir.make_test('\()\(max_examples=1)\ndef test_(case):\n pass\n ', **as_param({'name': 'status', 'in': 'unknown', 'required': True, 'type': 'string'}), validate_schema=False) testdir.run_and_assert(passed=1)
def get_gold_standard_arc_seq(history_fn_list, model_space, metric_name_dict, with_skip_connection, with_input_blocks, num_input_blocks): model_gen = get_model_space_generator(model_space, with_skip_connection=with_skip_connection, with_input_blocks=with_input_blocks, num_input_blocks=num_input_blocks) df = rea...
def dual_quaternion_mul(A, B, input): dim = (input.size(1) // 2) (C, D) = torch.split(input, [dim, dim], dim=1) A_hamilton = make_quaternion_mul(A) B_hamilton = make_quaternion_mul(B) AC = torch.mm(C, A_hamilton) AD = torch.mm(D, A_hamilton) BC = torch.mm(C, B_hamilton) AD_plus_BC = (AD ...
def diracnet18(pretrained=False): model = DiracNet(18) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['diracnet18'])) return model
class RewardMLP(MLP): def compute_reward(self, X): predits = (- tf.log((1.0 - self.output))) Y_p = self._predict(predits, X) return Y_p def compute_score(self, X): logits = self.output_layer.get_logits_for(L.get_output(self.layers[(- 2)])) Y_p = self._predict(logits, X) ...
def find_all_linear_names(peft_model, int4=False, int8=False): cls = torch.nn.Linear if (int4 or int8): import bitsandbytes as bnb if int4: cls = bnb.nn.Linear4bit elif int8: cls = bnb.nn.Linear8bitLt lora_module_names = set() for (name, module) in peft_mo...
def main(hdf_file): extractor = extr.PadDataExtractor((2, 2, 2), extr.DataExtractor(categories=(defs.KEY_IMAGES,))) transform = tfm.Permute(permutation=(3, 0, 1, 2), entries=(defs.KEY_IMAGES,)) indexing_strategy = extr.PatchWiseIndexing(patch_shape=(32, 32, 32)) dataset = extr.PymiaDatasource(hdf_file, ...
(Output('forecasting-select-file', 'options'), Output('forecasting-select-target', 'value'), Output('forecasting-select-features', 'value'), Output('forecasting-select-exog', 'value'), Input('forecasting-select-file-parent', 'n_clicks'), Input('forecasting-select-file', 'value'), [State('forecasting-select-target', 'va...
.parametrize('metric', [['minkowski', 0.], ['mahalanobis', 0.]]) def test_deskl(metric): (pool_classifiers, X_dsel, y_dsel, X_test, y_test) = setup_classifiers() technique = DESKL(pool_classifiers, knn_metric=metric[0]) technique.fit(X_dsel, y_dsel) assert np.isclose(technique.score(X_test, y_test), met...
def test_learn_nse_different_proba_sizes(): m = 250 stream = RandomTreeGenerator(tree_random_state=7, sample_random_state=8, n_classes=2) dt = DecisionTreeClassifier(random_state=7) classifier = LearnPPNSEClassifier(base_estimator=dt, window_size=250) (X, y) = stream.next_sample(m) classifier.pa...
class TransformTwice(): def __init__(self, transform): self.transform = transform def __call__(self, inp): out1 = self.transform(inp) out2 = self.transform(inp) return (out1, out2)
def make_dataset(path, impl, fix_lua_indexing=False, dictionary=None): if ((impl == 'raw') and IndexedRawTextDataset.exists(path)): assert (dictionary is not None) return IndexedRawTextDataset(path, dictionary) elif ((impl == 'lazy') and IndexedDataset.exists(path)): return IndexedDatase...
class TrainingRunViewer(gtd.ml.training_run_viewer.TrainingRunViewer): def __init__(self): runs = MiniWoBTrainingRuns(check_commit=False) super(TrainingRunViewer, self).__init__(runs) metadata = (lambda keys: JSONSelector('metadata.txt', keys)) self.add('name', run_name) self...
def add_del_statements(statements: List[str]) -> Iterator[str]: new_statements = [statements[(- 1)]] variable_name_matcher = re.compile('t_[0-9]+|x[0-9]+') inplace_arithmetic_matcher = re.compile('\\d \\S=') alive = set(variable_name_matcher.findall(statements[(- 1)])) for s in reversed(statements[:...
class Restormer(nn.Module): def __init__(self, inp_channels=3, out_channels=3, dim=48, num_blocks=[4, 6, 6, 8], num_refinement_blocks=4, heads=[1, 2, 4, 8], ffn_expansion_factor=2.66, bias=False, LayerNorm_type='WithBias', dual_pixel_task=False): super(Restormer, self).__init__() self.patch_embed = ...
class ImageNetDataset(Dataset): def __init__(self, imagenet_dir, transform=None): super().__init__() self.imagenet_dir = imagenet_dir self.transform = transform self.dataset = ImageFolder(self.imagenet_dir, transform=self.transform) def __len__(self): return 1000 def ...
def random_bivariate_plateau_kernel(kernel_size, sigma_x_range, sigma_y_range, rotation_range, beta_range, noise_range=None, is_isotropic=True): assert ((kernel_size % 2) == 1), 'Kernel size must be an odd number.' assert (sigma_x_range[0] <= sigma_x_range[1]), 'Wrong sigma_x_range.' sigma_x = np.random.uni...
def main_worker(gpu, ngpus_per_node, args): args.gpu = gpu if (args.gpu is not None): print('Use GPU: {} for training'.format(args.gpu)) if (args.multiprocessing_distributed and (args.gpu != 0)): def print_pass(*args): pass builtins.print = print_pass if ((args.dist_u...
def inverse_laplace(ex, s, t, algorithm='maxima'): if (not isinstance(ex, Expression)): ex = SR(ex) if (algorithm == 'maxima'): return ex.parent()(ex._maxima_().ilt(var(s), var(t))) elif (algorithm == 'sympy'): (ex_sy, s, t) = (expr._sympy_() for expr in (ex, s, t)) from symp...
_builder('coco_caption') class COCOCapBuilder(BaseDatasetBuilder): train_dataset_cls = COCOCapDataset eval_dataset_cls = COCOCapEvalDataset DATASET_CONFIG_DICT = {'default': 'configs/datasets/coco/defaults_cap.yaml'}
def gen_model_input_sdm(train_set, user_profile, seq_short_max_len, seq_prefer_max_len): train_uid = np.array([line[0] for line in train_set]) train_iid = np.array([line[1] for line in train_set]) train_label = np.array([line[2] for line in train_set]) short_train_seq = [line[3] for line in train_set] ...
def run_experiment_lite(stub_method_call=None, batch_tasks=None, exp_prefix='experiment', exp_name=None, log_dir=None, script='scripts/run_experiment_lite.py', python_command='python', mode='local', dry=False, docker_image=None, aws_config=None, env=None, variant=None, use_gpu=False, sync_s3_pkl=False, sync_log_on_term...
def _augment_gain(audio, low=0.75, high=1.25): g = random.uniform(low, high) return (audio * g)
class RandomCrop(object): def __init__(self, size, padding=0): self.size = tuple(size) self.padding = padding def __call__(self, img, mask): if (self.padding > 0): img = ImageOps.expand(img, border=self.padding, fill=0) mask = ImageOps.expand(mask, border=self.pad...
def plot_gp(x: torch.Tensor, model: gpytorch.models.GP, num_samples: int, ax: mpl.axes.Axes) -> None: with torch.no_grad(), gpytorch.settings.fast_pred_var(): pred = model(x) mean = pred.mean.numpy() error = (2 * pred.stddev.numpy()) true_values = objective(None, x, None)[0].numpy() ...
def RunAndExtractTestList(args=None): p = gtest_test_utils.Subprocess(([COMMAND] + (args or [])), env=environ) tests_run = [] test_case = '' test = '' for line in p.output.split('\n'): match = TEST_CASE_REGEX.match(line) if (match is not None): test_case = match.group(1) ...
def inference_main(meta_files, ckpt, config, id, **kwargs): import warnings sweetdebug(use_telegram_if_cache_exists=False) warnings.filterwarnings(action='ignore') config = OmegaConf.load(config) wrapper = TransformerWrapper(config) wrapper = wrapper.load_from_checkpoint(ckpt, config=config).cud...
def get_device_details(devices_type): global devices global dpdk_drivers dev = {} dev_lines = subprocess.check_output(['lspci', '-Dvmmnnk']).splitlines() for dev_line in dev_lines: if (not dev_line): if device_type_match(dev, devices_type): if ('Driver' in dev.key...
class Discovery(BaseTest): def __init__(self, calculator: BaseCalculator, poinull: POI): super().__init__(calculator, poinull) def result(self, printlevel: int=1) -> tuple[(float, float)]: (pnull, _) = self.calculator.pvalue(self.poinull, onesideddiscovery=True) pnull = pnull[0] ...
class GroupNorm(nn.Module): ngroups: int = 32 def __call__(self, x): input_shape = x.shape group_shape = (x.shape[:(- 1)] + (self.ngroups, (x.shape[(- 1)] // self.ngroups))) x = x.reshape(group_shape) x = standardize(x, axis=[1, 2, 4], eps=1e-05) x = x.reshape(input_shape...
class AcuteKidneyInjuryLabValueLabeler(InpatientLabValueLabeler): original_expanded_omop_concept_ids = [, 3020564, 3035090, 3022243, 3019397, 3040495, 3016723]
class ToTensor(object): def __call__(self, sample): result = {} for key in sample.keys(): if isinstance(sample[key], np.ndarray): if (key == 'image'): image = sample[key].transpose((2, 0, 1)) image = torch.from_numpy(image) ...
def _check_fp_args(a, b): if z3_debug(): _z3_assert((is_fp(a) or is_fp(b)), 'First or second argument must be a Z3 floating-point expression')
def container_construct_op_name(container_cls): container_str = {dict: 'Dict', list: 'List', tuple: 'Tuple', set: 'Set', slice: 'Slice'}[container_cls] return f'prim::{container_str}Construct'
class SchellingAgent(Agent): def __init__(self, pos, model, agent_type, homophily): super().__init__(pos, model) self.pos = pos self.type = agent_type self.homophily = homophily def step(self): similar = 0 for neighbor in self.model.grid.neighbor_iter(self.pos): ...