code
stringlengths
101
5.91M
def emd_distance(x, y, distance_scaling=1.0): support_size = max(len(x), len(y)) d_mat = toeplitz(range(support_size)).astype(np.float) distance_mat = (d_mat / distance_scaling) x = x.astype(np.float) y = y.astype(np.float) if (len(x) < len(y)): x = np.hstack((x, ([0.0] * (support_size -...
class FullBatchLinkGenerator(FullBatchGenerator): multiplicity = 2 def flow(self, link_ids, targets=None, use_ilocs=False): return super().flow(link_ids, targets, use_ilocs)
def test(cfg, model, question_model, eval_loader, n_unique_close, device, s_opt=None, s_epoch=0): model = model.to(device) question_model = question_model.to(device) utils.create_dir(cfg.TEST.RESULT_DIR) (eval_score, open_score, close_score) = evaluate_classifier(model, question_model, eval_loader, cfg,...
def pushd(target): saved = os.getcwd() os.chdir(target) try: (yield saved) finally: os.chdir(saved)
class ImageFolder(DatasetFolder): def __init__(self, root: str, transform: Optional[Callable]=None, target_transform: Optional[Callable]=None, loader: Callable[([str], Any)]=default_loader, is_valid_file: Optional[Callable[([str], bool)]]=None): super(ImageFolder, self).__init__(root, loader, (IMG_EXTENSION...
def run_explorer_robustness(): problem = flexs.landscapes.rna.registry()['L14_RNA1'] landscape = flexs.landscapes.RNABinding(**problem['params']) wt = problem['starts'][0] def make_explorer(model, ss): return baselines.explorers.DynaPPO(model=model, landscape=landscape, rounds=10, starting_seque...
class DataAnalyzer(): def __init__(self, folder): self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) self.logger.addHandler(dash_logger) self.folder = folder self.df = None def load_data(self, file_name): df = pd.read_csv(os.path.join(se...
class CIFAR100C(Downloader): def __init__(self, corruption=None, severity=0): url = ' base_dir = os.path.dirname(os.path.abspath(__file__)) file_name = os.path.join(base_dir, 'data', 'CIFAR100-C.tar') data_dir = os.path.join(base_dir, 'data', 'CIFAR-100-C') if (not os.path.ex...
class ObjectiveFunWrapper(): def __init__(self, func, maxfun=.0, *args): self.func = func self.args = args self.nfev = 0 self.ngev = 0 self.nhev = 0 self.maxfun = maxfun def fun(self, x): self.nfev += 1 return self.func(x, *self.args)
class ModulatedDeformConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, deform_groups=1, bias=True): super(ModulatedDeformConv2d, self).__init__() self.in_channels = in_channels self.out_channels = out_channels sel...
class SMPKernel(torch.nn.Module): def __init__(self, dim_linear: int, in_channels: int, out_channels: int, n_points: int, radius: float, coord_std: float): super().__init__() self.dim_linear = dim_linear self.in_channels = in_channels self.out_channels = out_channels self.n_p...
def theta_series(self, Max=10, var_str='q', safe_flag=True): try: M = ZZ(Max) except TypeError: M = (- 1) if ((Max not in ['mod_form']) and (not (M >= 0))): raise TypeError('Max = {Max} is not an integer >= 0 or an allowed string') if (Max == 'mod_form'): raise NotImpleme...
def test_plain_decoder(): model = PlainDecoder(512) model.init_weights() model.train() encoder = VGG16(4) img = _demo_inputs() outputs = encoder(img) prediction = model(outputs) assert_tensor_with_shape(prediction, torch.Size([1, 1, 64, 64])) if torch.cuda.is_available(): mod...
def estimate_correlation(input: T.Tensor, output: T.Tensor) -> T.Tensor: xs = T.linalg.norm(input) ys = T.linalg.norm(output) xy = T.linalg.norm((input.T output)) return ((xy / (xs * ys)) ** 2)
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.distribu...
def has_paddle(): _has_paddle = False _env_paddle = os.environ.get('TI_ENABLE_PADDLE', '1') if ((not _env_paddle) or int(_env_paddle)): try: import paddle _has_paddle = True except: pass return _has_paddle
class GraspingRGBDataModule(LightningDataModule): def __init__(self, data: Path, fold: int, n_val: int, bsz: int, preprocess: Callable[([torch.Tensor], torch.Tensor)], pad_resolution: Tuple[(int, int)]=(640, 640), input_resolution: Tuple[(int, int)]=(224, 224), label_scale_factor: float=0.125) -> None: supe...
def _pearson_nxn(df: EDAFrame) -> da.Array: return df.frame.repartition(npartitions=1).map_partitions(partial(pd.DataFrame.corr, method='pearson')).to_dask_array()
def test_old_style_record(): form = {'class': 'RecordArray', 'contents': {'z': {'class': 'NumpyArray', 'primitive': 'int64', 'inner_shape': [], 'parameters': {}, 'form_key': 'node1'}, 'y': {'class': 'NumpyArray', 'primitive': 'int64', 'inner_shape': [], 'parameters': {}, 'form_key': 'node2'}}, 'parameters': {}, 'fo...
class MemUsage(Benchmark): param_names = ['size', 'compressed'] timeout = (4 * 60) unit = 'actual/optimal memory usage ratio' def params(self): return [list(self._get_sizes().keys()), [True, False]] def _get_sizes(self): sizes = {'1M': 1000000.0, '10M': .0, '100M': .0, '300M': .0} ...
class TestJitEnsemble(TestJitSequenceGeneratorBase): ((torch.__version__ < '1.6.0'), 'Targeting OSS scriptability for the 1.6 release') def test_export_ensemble_model(self): model = self.transformer_model ensemble_models = EnsembleModel([model]) torch.jit.script(ensemble_models)
class EgcCifarNet(CifarNet): def __init__(self, hidden_dim, num_graph_layers, residual, readout='mean', activation=nn.ReLU, dropout=0.0, heads=8, bases=8, softmax=False, aggrs=None): assert (aggrs is not None) self.heads = heads self.bases = bases self.softmax = softmax self....
class IdleHost(AppConfig): def run_cmds(self, node: NodeConfig) -> tp.List[str]: return ['sleep infinity']
def batch_frexp(inputs, max_bit=31): shape_of_input = inputs.size() inputs = inputs.view((- 1)) (output_m, output_e) = np.frexp(inputs.cpu().numpy()) tmp_m = [] for m in output_m: int_m_shifted = int(decimal.Decimal((m * (2 ** max_bit))).quantize(decimal.Decimal('1'), rounding=decimal.ROUND_...
def _mutation_type_from_data(n, dig6, compute_if_necessary=True): data = load_data(n) if (compute_if_necessary and (data == {})): from sage.combinat.cluster_algebra_quiver.quiver_mutation_type import save_quiver_data save_quiver_data(n, up_to=False, types='Exceptional', verbose=False) lo...
class TFAutoModelForSemanticSegmentation(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def build_karate_club_graph(): g = dgl.DGLGraph() g.add_nodes(34) edge_list = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (5, 0), (6, 0), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (8, 0), (8, 2), (9, 2), (10, 0), (10, 4), (10, 5), (11, 0), (12, 0), (12, 3), (13, 0), (13, 1), (13, 2), (13,...
def LF_returned(s): rgx = ' returned to ([A-Za-z0-9]+\\s*){1,3}hospital' if re.search(rgx, s.text, re.I): return NO_TRAVEL rgx = 'returned from' return (TRAVEL if re.search(rgx, s.text, re.I) else ABSTAIN)
def test_clear_and_catch_warnings(): my_mod = _get_fresh_mod() assert_equal(getattr(my_mod, '__warningregistry__', {}), {}) with clear_and_catch_warnings(modules=[my_mod]): warnings.simplefilter('ignore') warnings.warn('Some warning') assert_equal(my_mod.__warningregistry__, {}) with...
def scattering_self_energies_kernel(neigh_idx: dc.int32[(NA, NB)], dH: dc.complex128[(NA, NB, N3D, Norb, Norb)], G: dc.complex128[(Nkz, NE, NA, Norb, Norb)], D: dc.complex128[(Nqz, Nw, NA, NB, N3D, N3D)], Sigma: dc.complex128[(Nkz, NE, NA, Norb, Norb)]): for k in range(Nkz): for E in range(NE): ...
_lr_scheduler('reduce_lr_on_plateau') class ReduceLROnPlateau(FairseqLRScheduler): def __init__(self, args, optimizer): super().__init__(args, optimizer) if (len(args.lr) > 1): raise ValueError('Cannot use a fixed learning rate schedule with reduce_lr_on_plateau. Consider --lr-scheduler=...
def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True): (c, lower) = c_and_lower if check_finite: b1 = asarray_chkfinite(b) c = asarray_chkfinite(c) else: b1 = asarray(b) c = asarray(c) if ((c.ndim != 2) or (c.shape[0] != c.shape[1])): raise ValueErro...
def display_subsection(result: SerializedTestResult, color: (str | None)='red') -> None: display_section_name(result.verbose_name, '_', fg=color)
class RandomCrop(object): def __init__(self, size, padding=0): if isinstance(size, numbers.Number): self.size = (int(size), int(size)) else: self.size = size self.padding = padding def __call__(self, img): if (self.padding > 0): img = ImageOps....
class SEG_reg(atomic_reg): OP_NAME = 'SEG' _fields_ = [('cmd_short', ctypes.c_uint64, 1), ('cmd_id', ctypes.c_uint64, 20), ('cmd_id_dep', ctypes.c_uint64, 20), ('tsk_typ', ctypes.c_uint64, 4), ('tsk_eu_typ', ctypes.c_uint64, 5), ('eu_half_en', ctypes.c_uint64, 1), ('tsk_opd_num', ctypes.c_uint64, 2), ('pad_mode...
class Test_CircleModel(unittest.TestCase): def test_When_Constructed_All_Properties_Must_Be_Initialized(self): c1 = CircleModel(100.1, 200.2, 300.3) self.assertAlmostEquals(100.1, c1.X) self.assertAlmostEquals(200.2, c1.Y) self.assertAlmostEquals(300.3, c1.R) def test_String_Repr...
def test_fromstring_bogus(): assert_equal(np.fromstring('1. 2. 3. flop 4.', dtype=float, sep=' '), np.array([1.0, 2.0, 3.0]))
def get_num_layer_for_swin(var_name, num_max_layer, depths): if (var_name in ('cls_token', 'mask_token', 'pos_embed')): return 0 elif var_name.startswith('patch_embed'): return 0 elif var_name.startswith('rel_pos_bias'): return (num_max_layer - 1) elif var_name.startswith('layers...
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): cdict = {'red': [], 'green': [], 'blue': [], 'alpha': []} reg_index = np.linspace(start, stop, 257) shift_index = np.hstack([np.linspace(0.0, midpoint, 128, endpoint=False), np.linspace(midpoint, 1.0, 129, endpoint=True)]) f...
class DALLE3Client(DALLE2Client): DEFAULT_IMAGE_SIZE_STR: str = '1024x1024' VALID_IMAGE_SIZES: List[str] = [DEFAULT_IMAGE_SIZE_STR, '1792x1024', '1024x1792'] def __init__(self, api_key: str, cache_config: CacheConfig, file_cache: FileCache, moderation_api_client: ModerationAPIClient, org_id: Optional[str]=N...
def create(name, *args, **kwargs): if (name not in __factory): raise KeyError('Unknown loss:', name) return __factory[name](*args, **kwargs)
class Generator(nn.Module): def __init__(self, G_ch=64, dim_z=128, bottom_width=4, resolution=128, G_kernel_size=3, G_attn='64', n_classes=1000, num_G_SVs=1, num_G_SV_itrs=1, G_shared=True, shared_dim=0, hier=False, cross_replica=False, mybn=False, G_activation=nn.ReLU(inplace=False), G_lr=5e-05, G_B1=0.0, G_B2=0.9...
class DataLoader(torch.utils.data.DataLoader): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __iter__(self): for batch in super().__iter__(): (yield namedtuple('Batch', [f.name for f in batch.keys()])(*[f.compose(d) for (f, d) in batch.items()]))
def group_indexes_to_spans(indexes, amr): indexes = list(indexes) indexes.sort() spans = [] last_index = None for idx in indexes: if ((last_index is None) or ((idx - last_index) > 2)): spans.append([]) elif ((idx - last_index) == 2): if re.search("(,|'s|of|'|-...
class XLMRobertaForSequenceClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def make_lmdb(mode, data_path, lmdb_path, train_list, batch=5000, compress_level=1): print(f'Create lmdb for {data_path}, save to {lmdb_path}...') if (mode == 'gt'): (h_dst, w_dst) = (256, 448) else: (h_dst, w_dst) = (64, 112) if osp.exists(lmdb_path): print(f'Folder {lmdb_path} ...
def resblock(x_init, channels, use_bias=True, scope='resblock'): with tf.variable_scope(scope): with tf.variable_scope('res1'): x = conv(x_init, channels, kernel=3, stride=1, pad=1, use_bias=use_bias) x = instance_norm(x) x = relu(x) with tf.variable_scope('res2')...
def test_fortran_frontend_twoconnector(): test_string = '\n PROGRAM twoconnector_test\n implicit none\n double precision d(4)\n CALL twoconnector_test_function(d)\n end\n\n SUBROUTINE twoconnector_test_...
def parse_page_transition_routes(page, name_to_display_name): entry_messages = [] transition = {'intent': {}, 'condition': {}, 'fulfillment': {}, 'flow': [], 'page': [], 'entry_messages': []} for (i, transition_to) in enumerate(page.transition_routes): target = '' if transition_to.target_flo...
class PlasmaArray(object): def __init__(self, array): super().__init__() self.array = array self.disable = (array.nbytes < ) self.object_id = None self.path = None self._client = None self._server = None self._server_tmp = None self._plasma = N...
def test_map(doc): d = m.cast_map() assert (d == {'key': 'value'}) d['key2'] = 'value2' assert m.load_map(d) assert (doc(m.cast_map) == 'cast_map() -> Dict[str, str]') assert (doc(m.load_map) == 'load_map(arg0: Dict[str, str]) -> bool')
def test_analyze_for_different_detectors(): img_paths = ['dataset/img1.jpg', 'dataset/img5.jpg', 'dataset/img6.jpg', 'dataset/img8.jpg', 'dataset/img1.jpg', 'dataset/img2.jpg', 'dataset/img1.jpg', 'dataset/img2.jpg', 'dataset/img6.jpg', 'dataset/img6.jpg'] for img_path in img_paths: for detector in dete...
class DIV2KSR(data.BaseDataset): def __init__(self, phase, opt): root = opt.dataset_root self.scale = opt.scale (dir_HQ, dir_LQ) = self.get_subdir() self.HQ_paths = sorted(glob.glob(os.path.join(root, dir_HQ, '*.png'))) self.LQ_paths = sorted(glob.glob(os.path.join(root, dir_...
class GLUEQNLITask(GLUETask): def __init__(self): self._spec = TaskSpecification('QNLI', 'classification', 3, 2, 'GLUE') self._spec.evaluation_metric = self._spec.accuracy def read(self, data_path: str, split: str) -> Iterable[DataExample]: return self.read_data_file(data_path, split, (s...
class StringSourceDescriptor(SourceDescriptor): def __init__(self, name, code): self.name = name self.codelines = [(x + '\n') for x in code.split('\n')] self._cmp_name = name def get_lines(self, encoding=None, error_handling=None): if (not encoding): return self.codel...
def register_Ns3TcpSocketState_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::TcpSocketState const &', 'other')]) cls.add_method('GetCwndInSegments', 'uint32_t', [], is_const=True) cls.add_method('GetSsThreshInSegments', 'uint32_t', [], is_const=True) cls.add_met...
class JSONParser(): _codegen = None _is_host_codegen = False _host_api_required_parameters = {} _host_api_optional_parameters = {} _host_api_supported_routines = set() _modules_codegen_required_parameters = {} _modules_codegen_optional_parameters = {} _modules_codegen_required_input_chan...
def ref_softmax_cross_entropy(x, l, axis): orig_x = x.copy() x = (x - x.max(axis, keepdims=True)) x = (np.exp(x) / np.exp(x).sum(axis, keepdims=True)) x = np.rollaxis(x, axis, x.ndim).reshape((- 1), x.shape[axis]) ll = np.rollaxis(l, axis, x.ndim).flatten() y = (- np.log(np.maximum(x[(np.arange(...
class TableConfig(PretrainedConfig): def __init__(self, vocab_size_or_config_json_file=30522, ent_vocab_size=905139, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_...
class bottleneck(nn.Module): def __init__(self, inplanes, outplanes, stride=1, ptype='preact', bias=False): super(bottleneck, self).__init__() planes = (outplanes // 2) if ((inplanes != outplanes) or (stride != 1)): self.shortcut = nn.Conv2d(inplanes, outplanes, kernel_size=1, st...
def compute_layout_fid(opts, max_real, num_gen): dataset_name = opts.dataset_kwargs['path'].split('/')[(- 3)] detector_pth = ('pretrained/layoutnet_%s.pth.tar' % dataset_name) detector_kwargs = dict(return_features=True) (mu_real, sigma_real) = metric_utils_layout.compute_feature_stats_for_dataset(opts=...
.node class Inv(dace.sdfg.nodes.LibraryNode): implementations = {'OpenBLAS': ExpandInvOpenBLAS, 'MKL': ExpandInvMKL, 'cuSolverDn': ExpandInvCuSolverDn} default_implementation = None overwrite = dace.properties.Property(dtype=bool, default=False) use_getri = dace.properties.Property(dtype=bool, default=T...
def preprocess(Data, dim=256, low=0.1, hi=1.0): for key in Data: Data[key][0] = Data[key][0].reshape(len(Data[key][0]), dim, dim, 1) for (i, img) in enumerate(Data[key][0]): img = (img / 255.0) (minn, maxx) = (np.min(img[(img > 0)]), np.max(img[(img > 0)])) img[(i...
class CustomFrameworkAdapter(FrameworkAdapterPluginInterface): def get_tensor_dict(model, optimizer=None): return {'w': model.weights} def set_tensor_dict(model, tensor_dict, optimizer=None, device='cpu'): model.weights = tensor_dict['w']
def perform_cse(output_exprs: DenseAndSparseOutputTerms, cse_optimizations: T.Union[(T.Literal['basic'], T.Sequence[T.Tuple[(T.Callable, T.Callable)]])]=None) -> T.Tuple[(T_terms, DenseAndSparseOutputTerms)]: flat_output_exprs = [x for storage in (output_exprs.dense + output_exprs.sparse) for x in storage] def ...
('tensorboard-events') ('--c2-dir', type=click.Path(exists=True, file_okay=False), help='Root directory of the Caffe2 run') ('--tf-dir', type=click.Path(writable=True), help='Output path to the logdir used by TensorBoard') def tensorboard_events(c2_dir, tf_dir): np.random.seed(1701) log = logging.getLogger(__na...
def RecordArray_pad_contents(self, length, axis=0): if (axis < 0): raise NotImplementedError else: contents = [] for c in self.contents: contents.append(c.pad(length, axis)) return RecordArray(contents, self.recordlookup, self.length)
def GenerateSM80_SparseTensorOp_16816_fast_math(manifest, cuda_version): if (not CudaToolkitVersionSatisfies(cuda_version, 11, 1)): return layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.RowMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.RowMajor), (LayoutType.Row...
def test_labels(): default_clipid = '64760' dataset = fsd50k.Dataset(TEST_DATA_HOME) clip = dataset.clip(default_clipid) tags = clip.tags assert (tags.labels == ['Electric_guitar', 'Guitar', 'Plucked_string_instrument', 'Musical_instrument', 'Music']) assert np.array_equal(tags.confidence, [1.0,...
class HandEggEnv(ManipulateEnv): def __init__(self, max_step=100, target_position='random', target_rotation='xyz', reward_type='sparse', distance_threshold=0.01, rotation_threshold=0.1): self.num_step = 0 self.max_step = max_step super(HandEggEnv, self).__init__(model_path=MANIPULATE_EGG_XML...
def test_step(x_batch, y_batch): feed_dict = {cnn.input_x: x_batch, cnn.input_y: y_batch, cnn.is_training: False} (loss, preds) = sess.run([cnn.loss, cnn.predictions], feed_dict) time_str = datetime.datetime.now().isoformat() return (preds, loss)
def mk_all_mem_initializer_cpps(): if (not ONLY_MAKEFILES): for c in get_components(): if c.require_mem_initializer(): cnames = [] cnames.extend(c.deps) cnames.append(c.name) mk_mem_initializer_cpp(cnames, c.src_dir)
class DAG(): def __init__(self, arc_seq, num_layers, model_space, input_node, output_node, with_skip_connection=True, with_input_blocks=True): assert all([(not x.is_built) for x in input_node]), 'input_node must not have been built' if (type(output_node) is list): assert all([(not x.is_b...
def _random_gaussian_blur(image, rng, *, kernel_size, padding, sigma_min, sigma_max, apply_prob): (apply_rng, transform_rng) = jax.random.split(rng) def _apply(image): (sigma_rng,) = jax.random.split(transform_rng, 1) sigma = jax.random.uniform(sigma_rng, shape=(), minval=sigma_min, maxval=sigma...
class SkipTo(ParseElementEnhance): def __init__(self, other, include=False, ignore=None, failOn=None): super(SkipTo, self).__init__(other) self.ignoreExpr = ignore self.mayReturnEmpty = True self.mayIndexError = False self.includeMatch = include self.saveAsList = Fals...
class GetAffinityLabelFromIndices(): def __init__(self, indices_from, indices_to): self.indices_from = indices_from self.indices_to = indices_to def __call__(self, segm_map): segm_map_flat = np.reshape(segm_map, (- 1)) segm_label_from = np.expand_dims(segm_map_flat[self.indices_f...
class BridgeTowerPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def _all_reduce(comm, var, division, inplace): comm.all_reduce(var, division=division, inplace=inplace)
def validate(model, data, device): model.eval() (count, correct) = (0, 0) with torch.no_grad(): for batch in tqdm(data, total=len(data)): (question, choices, answer) = [x.to(device) for x in batch] logit = model(question) predict = logit.max(1)[1] corr...
class WFRadiationMeshSliceMin(RadiationField): glossary_name = 'params/Mesh/sliceMin' def __init__(self, wf): super(WFRadiationMeshSliceMin, self).__init__(wf) self.attributes.update({'limits': '[1:LONG_MAX]', 'alias': 'mesh.eFin'}) def value(self): return self._wf._srwl_wf.mesh.eSta...
(scope='class') def modeldef(request, net_name, executor, fuser): set_fuser(fuser, executor) (name, rnn_creator, context) = get_nn_runners(net_name)[0] creator_args = creator_args = {'seqLength': 100, 'numLayers': 1, 'inputSize': 512, 'hiddenSize': 512, 'miniBatch': 64, 'device': 'cuda', 'seed': None} r...
class LFCandidate(): def __init__(self, s_expr, normed_expr, ex=None, f1=None, edist=None): self.s_expr = s_expr self.normed_expr = normed_expr self.ex = ex self.f1 = f1 self.edist = edist def __str__(self): return '{}\n\t->{}\n'.format(self.s_expr, self.normed_ex...
def create_conv2d_pad(in_chs, out_chs, kernel_size, **kwargs): padding = kwargs.pop('padding', '') kwargs.setdefault('bias', False) (padding, is_dynamic) = get_padding_value(padding, kernel_size, **kwargs) if is_dynamic: if is_exportable(): assert (not is_scriptable()) re...
def solarize(image, rng, *, threshold, apply_prob): def _apply(image): return jnp.where((image < threshold), image, (1.0 - image)) return _maybe_apply(_apply, image, rng, apply_prob)
class TrOCRConfig(PretrainedConfig): model_type = 'trocr' keys_to_ignore_at_inference = ['past_key_values'] attribute_map = {'num_attention_heads': 'decoder_attention_heads', 'hidden_size': 'd_model', 'num_hidden_layers': 'decoder_layers'} def __init__(self, vocab_size=50265, d_model=1024, decoder_layer...
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) (form, length, container) = ak.to_buffers(a) for (name, dtype) in form.expected_from...
def read_xml(xml_path, keep_difficult=False): tree = ET.parse(xml_path) root = tree.getroot() size = root.find('size') image_width = int(size.find('width').text) image_height = int(size.find('height').text) bboxes = [] classes = [] for obj in root.findall('object'): label = obj.f...
def project_real_images(network_pkl, dataset_name, data_dir, num_images, num_snapshots): print(('Loading networks from "%s"...' % network_pkl)) (_G, _D, Gs) = pretrained_networks.load_networks(network_pkl) proj = projector.Projector() proj.set_network(Gs) print(('Loading images from "%s"...' % datas...
def create_task_dof_maps(field, cell_tasks, inter_facets, is_overlap=True, use_expand_dofs=False, save_inter_regions=False, output_dir=None): domain = field.domain cmesh = domain.cmesh if use_expand_dofs: id_map = nm.zeros((field.n_nod * field.n_components), dtype=nm.uint32) else: id_map...
def namer_api_name(inplace): if inplace: return 'rename_' else: return 'rename'
def solve(fk): k = ST.wavenumbers(N) if (solver == 'sparse'): A = ADDmat(np.arange(N).astype(np.float)).diags() B = BDDmat(np.arange(N).astype(np.float), quad).diags() fk[0] -= ((((kx ** 2) * pi) / 2.0) * (a + b)) fk[1] -= ((((kx ** 2) * pi) / 4.0) * (a - b)) uk_hat = la....
class TaskEmbeddingWorker(DefaultWorker): def __init__(self, *, seed, max_path_length, worker_number): self._latents = [] self._tasks = [] self._latent_infos = defaultdict(list) (self._z, self._t, self._latent_info) = (None, None, None) super().__init__(seed=seed, max_path_le...
def move_to(var, device): if isinstance(var, dict): return {k: move_to(v, device) for (k, v) in var.items()} elif isinstance(var, list): return [move_to(v, device) for v in var] elif isinstance(var, tuple): return (move_to(v, device) for v in var) return var.to(device)
def style_attr(d): if (not d): return '' return (' style="%s"' % html.escape(css_style_from_dict(d)))
class Policy(torch.nn.Module, abc.ABC): def __init__(self, env_spec, name): super().__init__() self._env_spec = env_spec self._name = name def get_action(self, observation): def get_actions(self, observations): def observation_space(self): return self._env_spec.observatio...
def build_constrained_linear_problem(instance: int=0): obj = PlaneObjective() cons0 = (- SphereObjective(radius=1.0, r0=np.array([0, 0]))) cons1 = (- SphereObjective(radius=1.0, r0=np.array([1, 0]))) param = DirectParam(np.array([0.5, 0.5]), bounds=((- 1), 1)) if (instance == 0): cons_eq = [...
def get_aggregate_list(aggregate_suffix_file, aggregate): assert isinstance(aggregate, list) assert (len(aggregate) > 0) prefix = (aggregate[0] + '_') df_subgroup = pd.read_csv(aggregate_suffix_file, header=0, index_col=0) subgroup_list = list(set(df_subgroup.iloc[:]['Subgroup'])) new_aggregate_...
class CpuLayerType(Enum): CPU_SSD_DETECTION_OUTPUT = 0 CPU_ANAKIN_DETECT_OUTPUT = 1 CPU_RPN = 2 CPU_USER_DEFINED = 3 CPU_ROI_POOLING = 4 CPU_ROIALIGN = 5 CPU_BOXNMS = 6 CPU_YOLO = 7 CPU_CROP_AND_RESIZE = 8 CPU_GATHER = 9 CPU_NON_MAX_SUPPRESSION = 10 CPU_ARGSORT = 11 C...
def get_sql_with_default(sql, schema, in_execution_order): eval_err = False try: ast = get_sql(schema, sql, in_execution_order) except Exception as e: ast = {'except': None, 'from': {'conds': [], 'table_units': []}, 'groupBy': [], 'having': [], 'intersect': None, 'limit': None, 'orderBy': []...
def threshold_and_normalize(args, logger, G, edge_min_aggconf=1000): logger.info('thresholding edges...') G_new = np.zeros((G.shape[0], G.shape[0])) for i in range(G.shape[0]): for j in range(G.shape[0]): if (G[(i, j)] > edge_min_aggconf): G_new[(i, j)] = G[(i, j)] G ...