code
stringlengths
101
5.91M
class RoFormerConverter(Converter): def converted(self) -> Tokenizer: from .models.roformer.tokenization_utils import JiebaPreTokenizer vocab = self.original_tokenizer.vocab tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(self.original_tokenizer.unk_token))) strip_accents = Fals...
class Writer(): def __init__(self, width=None, height=None, size=None, greyscale=Default, alpha=False, bitdepth=8, palette=None, transparent=None, background=None, gamma=None, compression=None, interlace=False, planes=None, colormap=None, maxval=None, chunk_limit=(2 ** 20), x_pixels_per_unit=None, y_pixels_per_unit...
def add_T_label(img, label, bbox, draw_bg=True, text_bg_color=(255, 255, 255), text_color=(0, 0, 0)): text_width = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)[0][0] text_height = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)[0][1] x_center = ((bbox[0] + bbox[2]) // 2) y_top = (bbox[1...
def get_word_idx(context, wordss, idx): spanss = get_2d_spans(context, wordss) idx = spanss[idx[0]][idx[1]][0] return idx
def main(argv=None, **kw): from setuptools import setup from setuptools.dist import Distribution class DistributionWithoutHelpCommands(Distribution): common_usage = '' def _show_help(self, *args, **kw): with _patch_usage(): Distribution._show_help(self, *args, **k...
.parametrize('device', ['cpu', 'cuda']) .parametrize('seed', [[[(- 0.5), 0, 0.5], [1, (- 2), 1]], [[3, 0, 1, 2, 0], [0, (- 1), 0]], [2, 3]]) def test_compatibility(device, seed, T=100, D=2): mlpg = diffsptk.MaximumLikelihoodParameterGeneration(T, seed=seed) if U.is_array(seed[0]): opt = ' '.join([('-d '...
.parametrize('indices', [None, [1, 3]]) def test_check_method_params(indices): X = np.random.randn(4, 2) _params = {'list': [1, 2, 3, 4], 'array': np.array([1, 2, 3, 4]), 'sparse-col': sp.csc_matrix([1, 2, 3, 4]).T, 'sparse-row': sp.csc_matrix([1, 2, 3, 4]), 'scalar-int': 1, 'scalar-str': 'xxx', 'None': None} ...
class TwoAlignedDataset(): def initialize(self, opt): assert (opt.isTrain == True) opt1 = opt opt1.phase = opt.phase1 opt1.dataset_model = 'aligned' self.dataset1 = AlignedDataset() self.dataset1.initialize(opt1) opt2 = opt opt2.phase = opt.phase2 ...
def test_pixel_size_setter(): persimgr = PersistenceImager(birth_range=(0, 1), pers_range=(0, 2), pixel_size=1) persimgr.pixel_size = 0.75 np.testing.assert_equal(persimgr.pixel_size, 0.75) np.testing.assert_equal(persimgr._pixel_size, 0.75) np.testing.assert_equal(persimgr.birth_range, ((- 0.25), 1...
def minimal_grid(x, y, tol=1e-06, error_scale=1.0, y_reference=None): import numpy as np from scipy.interpolate import CubicSpline as spline from scipy.signal import find_peaks deg = 3 if (y_reference is None): y_reference = y error_scale = np.asarray(error_scale) if (np.ndim(error_s...
def do_learning(extractor, model, optimizer, loader, k_step, device): model.train() acc_list = [] loss_list = [] for (idx, (img, mask, lbl_1, lbl_2, lbl_1_oh, lbl_2_oh)) in enumerate(loader): if (idx >= k_step): break if (mask.sum() == 0): continue img = i...
class TestConsumeOp(unittest.TestCase): def test_jit_consume_op(self): iters = 6 def foo(x): for i in range(iters): result = torch.ops.operator_benchmark._consume(torch.sum(x)) return result r = torch.jit.trace(foo, torch.rand(2, 2)) graph = st...
def to_float(x, name='ToFloat'): try: return tf.to_float(x, name) except AttributeError: return tf.compat.v1.to_float(x, name)
def test_grad_add_check_numerics_ops(): with make_scope() as session: x = tf.Variable(initial_value=0.0, name='x') session.run(x.initializer) y = (1.0 / x) grad_x = tf.gradients(y, x)[0] print('grad_x:', grad_x.eval()) assert_equal(str(float('-inf')), '-inf') ...
def get_aircraft_datasets(train_transform, test_transform, train_classes=range(60), open_set_classes=range(60, 100), balance_open_set_eval=False, split_train_val=True, seed=0): np.random.seed(seed) train_dataset_whole = FGVCAircraft(root=aircraft_root, transform=train_transform, split='trainval') train_data...
def import_module_error_class(module_name): def decorate(cls): def import_error_init(*args, **kwargs): raise ImportError(f'Please install {module_name} to use {cls.__name__}.') cls.__init__ = MethodType(import_error_init, cls) return cls return decorate
class HybridQA_Dataset(): def __init__(self, config): print('Loading HybridQA ') self.table_dir = config.table_dir self.text_dir = config.text_dir self.table_id_list = [] g = os.walk(self.table_dir) for (_, _, file_list) in g: for file_name in file_list: ...
def generate_ChangePoint(inter_prob, intra_prob, alpha): cps = [15, 30, 60, 75, 90, 105, 135] fname = (((((('ChangePoint_' + str(inter_prob)) + '_') + str(intra_prob)) + '_') + str(alpha)) + '.txt') cps_sizes = [] cps_probs = [] sizes_1 = [250, 250] probs_1 = construct_SBM_block(sizes_1, inter_p...
class DefaultDict(dict): def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value
def _linear_normalize(weights): weights = torch.max(weights, torch.zeros_like(weights)) if (torch.sum(weights) > 1e-08): return (weights / torch.sum(weights)) return torch.zeros_like(weights)
class Trie(): def __init__(self, eos): self.root = TreeNode() self.eos = eos def insert(self, word): cur = self.root for c in word: cur = cur.child[c] def get_next_layer(self, word): cur = self.root for c in word: cur = cur.child.get(c)...
(config_path='../hydra_config', config_name='black_box_opt') def main(config): random.seed(None) log_config = flatten_config(OmegaConf.to_container(config, resolve=True), sep='/') log_config = {'/'.join(('config', key)): val for (key, val) in log_config.items()} wandb.login(host=config.wandb_host) w...
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
class OrderedEnqueuer(SequenceEnqueuer): def __init__(self, sequence, use_multiprocessing=False, shuffle=False): self.sequence = sequence self.use_multiprocessing = use_multiprocessing self.shuffle = shuffle self.workers = 0 self.executor = None self.queue = None ...
(scope='module') def nlp_pipeline(): nlp = stanza.Pipeline(dir=TEST_MODELS_DIR, lang='en') return nlp
class ActionNormWrapper(gym.Wrapper): def __init__(self, env): super().__init__(env) assert isinstance(env.action_space, gym.spaces.Dict), env.action_space ac_space = [] self._low = {} self._high = {} for (k, space) in env.action_space.spaces.items(): if i...
def load_data(): X_df = pd.read_csv(('/projects/leelab2/data/AD_DATA/Nicasia/processed' + '/PCG_normalized/no_covar_correction/MSBB_RNA.tsv'), sep='\t') y_df = pd.read_csv(('/projects/leelab2/data/AD_DATA/Nicasia/processed' + '/samples_neuropath_prenorm/MSBB_RNA.tsv'), sep='\t') X_df = X_df.T X_df.colum...
class NumericTestCase(TorchTestCase): def testNumericBatchNorm(self): a = torch.rand(16, 10) bn = nn.BatchNorm2d(10, momentum=1, eps=1e-05, affine=False) bn.train() a_var1 = Variable(a, requires_grad=True) b_var1 = bn(a_var1) loss1 = b_var1.sum() loss1.backwar...
class TestCharSvm(unittest.TestCase): def test_charsvm(self): with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) run_experiment(predictor_fn=(lambda : CharSvmPredictor()), output_dir=temp_path, n_examples=4, n_trials=1, dataset='gnad10', config=None, n_test_ex...
class Triples(): def __init__(self, ranking, seed=12345): random.seed(seed) self.seed = seed ranking = Ranking.cast(ranking) self.ranking_provenance = ranking.provenance() self.qid2rankings = ranking.todict() def create(self, positives, depth): assert all(((len(x)...
def generate_jsfile(dirpath, name, out_path): tiuProcessor = TIU(dirpath) tiu_instance = tiuProcessor.process_file() gdmaProcessor = DMA(dirpath, 'GDMA') gdma_instances = gdmaProcessor.process_file() sdmaProcessor = DMA(dirpath, 'SDMA') sdma_instances = sdmaProcessor.process_file() cdmaProce...
def _recalculateCenters(y, balancedCluster, k): Centers = [] kAux = 0 while (kAux < k): vectorAux = np.zeros(len(y)) for i in range(0, len(balancedCluster)): if (int(kAux) == int(balancedCluster[i])): for j in range(0, len(y)): vectorAux[j] += ...
def convert_vi_vsfc(paths, dataset_name, *args): in_directory = os.path.join(paths['SENTIMENT_BASE'], 'vietnamese', '_UIT-VSFC') out_directory = paths['SENTIMENT_DATA_DIR'] process_vsfc_vietnamese.main(in_directory, out_directory, dataset_name)
_params({'y_true': ['array-like'], 'y_pred': ['array-like'], 'sample_weight': ['array-like', None]}, prefer_skip_nested_validation=True) def macro_averaged_mean_absolute_error(y_true, y_pred, *, sample_weight=None): (_, y_true, y_pred) = _check_targets(y_true, y_pred) if (sample_weight is not None): sam...
def _get_boolean_value(value): if (value.lower() == TRUE): return True else: return False
def thwart_lemma_3_5(k, n, m, a, b, c, d=0, complement=False, explain_construction=False): from sage.arith.misc import is_prime_power from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF if complement: (a, b, c) = ((n - a), (n - b), (n - c)) if explain_construction: ...
def _called_with_cfg(*args, **kwargs): if (len(args) and isinstance(args[0], _CfgNode)): return True if isinstance(kwargs.pop('cfg', None), _CfgNode): return True return False
def test_wrap_experiment_invalid_options(): prefix = 'wrap_exp_invalid_options' exp_path = pathlib.Path(os.getcwd(), 'data/local', prefix) _hard_rmtree(exp_path) logdir = 'data/local/wrap_exp_invalid_options/test_exp' _experiment(prefix=prefix) def test_exp(ctxt): del ctxt with pytes...
class ProcessContext(): def __init__(self, processes, error_queues): _python_version_check() self.error_queues = error_queues self.processes = processes self.sentinels = {process.sentinel: index for (index, process) in enumerate(processes)} def pids(self): return [int(pro...
def yiq_to_rgb(y, i, q): r = ((y + (0. * i)) + (0. * q)) g = ((y - (0. * i)) - (0. * q)) b = ((y - (1. * i)) + (1. * q)) if (r < 0.0): r = 0.0 if (g < 0.0): g = 0.0 if (b < 0.0): b = 0.0 if (r > 1.0): r = 1.0 if (g > 1.0): g = 1.0 if (b > 1.0):...
def get_project_path(ExpID): full_path = glob.glob(('Experiments/*%s*' % ExpID)) assert (len(full_path) == 1), 'There should be only ONE folder with <ExpID> in its name' return full_path[0]
def to_type(handle: int) -> Object: t = sim.simGetObjectType(handle) if (t == sim.sim_object_shape_type): return Shape(handle) elif (t == sim.sim_object_dummy_type): return Dummy(handle) elif (t == sim.sim_object_path_type): return CartesianPath(handle) elif (t == sim.sim_obj...
class BUDUDrp1mat(SpectralMatrix): def assemble(self, method): (test, trial) = (self.testfunction, self.trialfunction) assert isinstance(test[0], UD) assert isinstance(trial[0], UD) assert (test[0].quad == 'LG') k = np.arange((test[0].N - 1)) d = {0: ((2 * k) + 2)} ...
def main(args=None): args = parse_args(args=args) utils.set_random_seed(args['seed']) logger.info('Running tagger in {} mode'.format(args['mode'])) if (args['mode'] == 'train'): train(args) else: evaluate(args)
(name='random_basis_func_cls', params=[RandomFourierFeatures, RandomFourierFeaturesCosine]) def _random_basis_func_cls_fixture(request): return request.param
def create_model_single_conv2d(input_shape): inputs = Input(shape=input_shape) outputs = Conv2D(2, 3)(inputs) return keras.Model(inputs=inputs, outputs=outputs)
class Registry(Printable): __objects: Dict[(Tuple[(str, str, str)], Registrable)] def __init__(self): self.__objects = {} def register(self, scope: str, type: str, name: str, obj: Registrable) -> Registrable: assert ((scope, type, name) not in self.__objects), 'object with name {} already ex...
.parametrize('valid_index', [[[0, 1]]]) def test_find_lambda_control_star_output(valid_index: List[List[int]]) -> None: assert find_lambda_control_star(r_hat, valid_index, lambdas)
class CC3MDataset(BaseDataset): def __init__(self, *args, split='', **kwargs): assert (split in ['train', 'val', 'test']) self.split = split self.metadata = None self._load_metadata() if (split == 'train'): names = ['cc3m_train'] elif (split == 'val'): ...
def register_Ns3EpcUeNas_methods(root_module, cls): cls.add_constructor([param('ns3::EpcUeNas const &', 'arg0')]) cls.add_constructor([]) cls.add_method('ActivateEpsBearer', 'void', [param('ns3::EpsBearer', 'bearer'), param('ns3::Ptr< ns3::EpcTft >', 'tft')]) cls.add_method('Connect', 'void', []) cl...
class FullyShardedDataParallel(FSDP): def __init__(self, *args, use_sharded_state: bool=False, **kwargs): if (not has_FSDP): raise ImportError('Cannot find FullyShardedDataParallel. Please install fairscale with: pip install fairscale') super().__init__(*args, **kwargs) self.use_...
def get_chinese_rouge_function(rouge_type: str) -> Callable[([str, str], float)]: char_tokenizer = ChineseTokenizer() scorer = rouge_scorer.RougeScorer([rouge_type], use_stemmer=True, tokenizer=char_tokenizer) return partial(rouge_score, scorer=scorer, rouge_type=rouge_type)
def _check_lat_long(val: Any, clean: bool) -> Any: if (val in NULL_VALUES): return ((((None,) * 8) + (0,)) if clean else False) mch = re.match(LAT_LONG_PATTERN, re.sub("''", '"', str(val))) if (not mch): return ((((None,) * 8) + (1,)) if clean else False) if ((not mch.group('deg')) or (n...
def remove_output_labels(s) -> str: label = re.compile('^o+[0-9]+ (=|:) |^ *') lines = s.split('\n') matches = [label.match(l) for l in lines if l] if (not matches): return s n = min(((m.end() - m.start()) for m in matches)) return '\n'.join((l[n:] for l in lines))
class WidthSelFunc(Protocol): def __call__(self, table: Table, attrs: List[str], centers: List[Any], params: Dict[(str, Any)]) -> Query: ...
class DefaultWorker(Worker): def __init__(self, *, seed, max_path_length, worker_number): super().__init__(seed=seed, max_path_length=max_path_length, worker_number=worker_number) self.agent = None self.env = None self._observations = [] self._last_observations = [] s...
def _save(im, fp, filename): try: rawmode = RAWMODE[im.mode] except KeyError: raise OSError(('cannot write mode %s as JPEG' % im.mode)) info = im.encoderinfo dpi = [round(x) for x in info.get('dpi', (0, 0))] quality = info.get('quality', (- 1)) subsampling = info.get('subsampling...
def test(): form = ak.forms.from_dict({'class': 'RecordArray', 'fields': ['muon', 'jet'], 'contents': [{'class': 'ListOffsetArray', 'offsets': 'i64', 'content': {'class': 'RecordArray', 'fields': ['pt', 'eta', 'phi', 'crossref'], 'contents': [{'class': 'NumpyArray', 'primitive': 'int64', 'inner_shape': [], 'paramet...
class SpectralNormalization(tf.keras.layers.Wrapper): def __init__(self, layer, power_iterations=1, **kwargs): super(SpectralNormalization, self).__init__(layer, **kwargs) if (power_iterations <= 0): raise ValueError('`power_iterations` should be greater than zero, got `power_iterations=...
def vgg_a(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_a', fc_conv_padding='VALID', global_pool=False): with tf.variable_scope(scope, 'vgg_a', [inputs]) as sc: end_points_collection = (sc.original_name_scope + '_end_points') with slim.arg_scope(...
class RefBox(): "Ray doesn't dereference ObjectRefs if they're nested in another object. So we use this to take advantage of that.\n ref: ray.ObjectRef
() ('model_path', type=str) ('dataset_name', type=str) ('--im-size', default=None, type=int) ('--multiscale/--singlescale', default=False, is_flag=True) ('--blend/--no-blend', default=True, is_flag=True) ('--window-size', default=None, type=int) ('--window-stride', default=None, type=int) ('--window-batch-size', defaul...
(name='versions') def _versions() -> list[dict[(str, Any)]]: with open(VERSIONS) as f: return json.load(f)
def test_bbox_mask(): cfg = dict(img_shape=(256, 256), max_bbox_shape=100, max_bbox_delta=10, min_margin=10) bbox = random_bbox(**cfg) mask_bbox = bbox2mask(cfg['img_shape'], bbox) assert (mask_bbox.shape == (256, 256, 1)) zero_area = np.sum((mask_bbox == 0).astype(np.uint8)) ones_area = np.sum(...
class KLDivTeacherList(nn.Module): def __init__(self): super(KLDivTeacherList, self).__init__() self.kl = torch.nn.KLDivLoss(reduction='batchmean') def forward(self, scores, labels): loss = self.kl(scores.softmax((- 1)), labels.softmax((- 1))) return loss
def test_NumpyArray(): a = ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3], dtype=np.float64)) assert (a.to_typetracer().form == a.to_typetracer(forget_length=True).form) assert is_unknown_length(a.to_typetracer(forget_length=True).length) b = ak.contents.numpyarray.NumpyArray(np.arange(...
(scope='module') def test_data_xy_dict(test_data_xy): return {'x': test_data_xy[0], 'y': test_data_xy[1]}
def add_bootstrap_config(cfg: CN): _C = cfg _C.BOOTSTRAP_DATASETS = [] _C.BOOTSTRAP_MODEL = CN() _C.BOOTSTRAP_MODEL.WEIGHTS = '' _C.BOOTSTRAP_MODEL.DEVICE = 'cuda'
class SPC(Model): def __init__(self, cfg, emb_dim): super().__init__(name=cfg['name']) cfg['num_inputs'] = emb_dim self.minion = minion_maker(cfg) self.loss = self.minion.loss self.loss_weight = self.minion.loss_weight def forward(self, x, alpha=1, device=None): y...
def get_ann_ids(anno_path): ids = list() for p in anno_path.iterdir(): ids.append(p.name.split('.')[0]) return ids
def matrix_centralizer_cardinalities_length_two(n, q=None, selftranspose=False, invertible=False): if (q is None): q = FractionField(QQ['q']).gen() for tau in SimilarityClassTypes(n): for pair in ext_orbit_centralizers(tau, q=q, selftranspose=selftranspose): (yield (((q ** tau.centra...
def annotate_hop_ids(hop): samples = mongo.get_sample(train=False, limit=limit) count = 0 for doc in samples: (e, p) = doc[hop] e_ids = [] for uri in e: try: e_ids.append(e_index.look_up_by_uri(uri)[0]['_source']['id']) except: ...
class DivisorGroup_curve(DivisorGroup_generic): def _element_constructor_(self, x, check=True, reduce=True): if isinstance(x, Divisor_curve): P = x.parent() if (P is self): return x elif (P == self): return Divisor_curve(x._data, check=Fals...
class VenmoAddMoney(VirtualFunctionTool): name = 'VenmoAddMoney' summary = "Add money to the User's Venmo balance from a linked bank account." parameters: List[ArgParameter] = [{'name': 'amount', 'type': 'number', 'description': 'The amount of money to add, must be positive.', 'required': True}, {'name': 'a...
class ClassGroup(AbelianGroupWithValues_class): Element = FractionalIdealClass def __init__(self, gens_orders, names, number_field, gens, proof=True): AbelianGroupWithValues_class.__init__(self, gens_orders, names, gens, values_group=number_field.ideal_monoid()) self._proof_flag = proof ...
class AttrDict(dict): def __init__(self, init={}): dict.__init__(self, init) def __getitem__(self, name): return super(AttrDict, self).__getitem__(name.lower()) def __setitem__(self, key, value): return super(AttrDict, self).__setitem__(key.lower(), value) __getattr__ = __getitem...
def parse_config(): parser = argparse.ArgumentParser(description='arg parser') parser.add_argument('--cfg_file', type=str, default='cfgs/kitti_models/ptt_best.yaml', help='specify the config for demo') parser.add_argument('--data_path', type=str, default=None, help='specify the point cloud data file or dire...
class HubregtsenEncodingCircuit(EncodingCircuitBase): def __init__(self, num_qubits: int, num_features: int, num_layers: int=1, closed: bool=True, final_encoding=False) -> None: super().__init__(num_qubits, num_features) self.num_layers = num_layers self.closed = closed self.final_en...
def adjust_learning_rate(optimizer, epoch, gammas, schedule): lr = args.learning_rate assert (len(gammas) == len(schedule)), 'length of gammas and schedule should be equal' for (gamma, step) in zip(gammas, schedule): if (epoch >= step): lr = (lr * gamma) else: break ...
def test_mmhash3_bytes(): assert (murmurhash3_32(b'foo', 0) == (- )) assert (murmurhash3_32(b'foo', 42) == (- )) assert (murmurhash3_32(b'foo', 0, positive=True) == ) assert (murmurhash3_32(b'foo', 42, positive=True) == )
class Swish_DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=100): super(Swish_DenseNet, self).__init__() self.growth_rate = growth_rate num_planes = (2 * growth_rate) self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, padding=1, bi...
def short_path(path, cwd=None): if (not isinstance(path, str)): return path if (cwd is None): cwd = os.getcwd() abspath = os.path.abspath(path) relpath = os.path.relpath(path, cwd) if (len(abspath) <= len(relpath)): return abspath return relpath
def test_orthogonal_procrustes_ndim_too_small(): np.random.seed(1234) A = np.random.randn(3) B = np.random.randn(3) assert_raises(ValueError, orthogonal_procrustes, A, B)
def resnet152_csn_ir(**kwargs): model = ResNet(Bottleneck_depthwise_ir, [3, 8, 36, 3], **kwargs) model.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 7, 7), stride=(1, 2, 2), padding=(1, 3, 3), bias=False) return model
(autouse=True) def add_dataset(doctest_namespace): columns = ['query_id', 'item_id', 'timestamp'] data = [(1, 1, '01-01-2020'), (1, 2, '02-01-2020'), (1, 3, '03-01-2020'), (1, 4, '04-01-2020'), (1, 5, '05-01-2020'), (2, 1, '06-01-2020'), (2, 2, '07-01-2020'), (2, 3, '08-01-2020'), (2, 9, '09-01-2020'), (2, 10, ...
class Queue(deque, object): def seeleft(self): if self: return self[0] else: return None
def batch_step(pbar, net, image, optimizers, label, criterion, gamma, gamma_target, gamma_rate, amp_flag, working_device): pbar.update(1) image = image.to(working_device) label = label.to(working_device) prediction = net(image) (correct, total) = common.accuracy_factor(prediction, label) l = cri...
def parse_package(line: str) -> Tuple[(str, Optional[str])]: parts = re.split('(==|>=|<=|>|<)', line) module = parts[0] version = line.replace(module, '') return (module, version)
def build_model(model_opt, opt, fields, checkpoint): print('Building model...') model = onmt.ModelConstructor.make_base_model(model_opt, fields, use_gpu(opt), checkpoint) if (len(opt.gpuid) > 1): print('Multi gpu training: ', opt.gpuid) model = nn.DataParallel(model, device_ids=opt.gpuid, di...
def test_QSDetectorPolarization_set_basis_list(): tl = Timeline() qsdetector = QSDetectorPolarization('qsd', tl) basis_list = [] start_time = 0 frequency = 1000000.0 qsdetector.set_basis_list(basis_list, start_time, frequency) assert ((qsdetector.splitter.basis_list == basis_list) and (qsdet...
class FailedBuilding(Exception): def __init__(self, name, build_command): super(FailedBuilding, self).__init__() self._name = name self._build_command = build_command
def test_sbottom_regionC_1600_850_60(get_json_from_tarfile): sbottom_archive = data_path('pyhf-ins1748602-probability-models.tar.gz') sbottom_regionC_bkgonly_json = get_json_from_tarfile(sbottom_archive, 'RegionC/BkgOnly.json') sbottom_regionC_1600_850_60_patch_json = get_json_from_tarfile(sbottom_archive, ...
.parametrize('task_name', [tn for tn in (all_tasks - julia_tasks)]) def test_obtain_prior_samples_from_task(task_name): task = get_task(task_name) prior = task.get_prior() nsamples = 10 thetas = prior(num_samples=nsamples) assert (thetas.shape[0] == nsamples)
def reset(): for i in range(n_particles): x[i] = [(((ti.random() * 0.2) + 0.3) + (0.1 * (i // group_size))), (((ti.random() * 0.2) + 0.05) + (0.32 * (i // group_size)))] material[i] = (i // group_size) v[i] = [0, 0] F[i] = ti.Matrix([[1, 0], [0, 1]]) Jp[i] = 1 C[i] = ...
def get_transform(opt, params=None, grayscale=False, method=Image.BICUBIC, convert=True): transform_list = [] if grayscale: transform_list.append(transforms.Grayscale(1)) if ('fixsize' in opt.preprocess): transform_list.append(transforms.Resize((opt.crop_size, opt.load_size), method)) if...
def main(_config): _config = copy.deepcopy(_config) pl.seed_everything(_config['seed']) dm = MTDataModule(_config, dist=True) model = AllinoneTransformerSS(_config) exp_name = f"{_config['exp_name']}" os.makedirs(_config['log_dir'], exist_ok=True) checkpoint_callback = pl.callbacks.ModelChec...
def get_amr_match(cur_amr1, cur_amr2, sent_num=1, justinstance=False, justattribute=False, justrelation=False): amr_pair = [] for (i, cur_amr) in ((1, cur_amr1), (2, cur_amr2)): try: amr_pair.append(amr.AMR.parse_AMR_line(cur_amr)) except Exception as e: print(('Error in ...
def test_image_to_tensor(): ori_results = dict(img=np.random.randn(256, 256, 3)) keys = ['img'] to_float32 = False image_to_tensor = ImageToTensor(keys) results = image_to_tensor(ori_results) assert (results['img'].shape == torch.Size([3, 256, 256])) assert isinstance(results['img'], torch.T...
class Object3dCaptionDataset(BaseDataset, __DisplMixin): def __init__(self, **kwargs): super().__init__(kwargs['vis_processor'], kwargs['text_processor'], kwargs['vis_root'], kwargs['ann_paths']) self.modalities = kwargs['modalities'] self.npoints = 8192 self.sample_points_num = self...
.spark def test_refit(fitted_model, log_ucb, log_ucb2): fitted_model.seed = 123 fitted_model.sample = True equality_check = (sparkDataFrameNotEqual if (fitted_model.sample and (fitted_model.seed is None)) else sparkDataFrameEqual) dataset = create_dataset(log_ucb) dataset2 = create_dataset(log_ucb2)...