code
stringlengths
101
5.91M
def is_definite(self): try: def_str = self.__definiteness_string except AttributeError: self.compute_definiteness() def_str = self.__definiteness_string return ((def_str == 'pos_def') or (def_str == 'neg_def') or (def_str == 'zero'))
class TransRec(object): def __init__(self, emb_size, num_usr, num_item): self.emb_size = emb_size self.item_count = num_item self.user_count = num_usr self.init = self.init = tf.random_uniform_initializer(minval=((- 6) / math.sqrt(self.emb_size)), maxval=(6 / math.sqrt(self.emb_size)...
class LargeCremonaDatabase(MiniCremonaDatabase): _expected_skeleton = _cremonaSkeleton def allbsd(self, N): ret = {} for c in self.__connection__.cursor().execute(('SELECT curve,cp,om,L,' + 'reg,sha FROM t_curve,t_class USING(class) WHERE conductor=?'), (int(N),)): (N, iso, num) = pa...
def test_check_ci_warn(): x = [0, 1, 2, 3, 4, 5] y = [0, (- 1), 2, (- 3), 4, (- 5)] msg = 'interval' with pytest.warns(UserWarning, match=msg): is_increasing = check_increasing(x, y) assert (not is_increasing)
def merge_files(python_files): classes = [] for file in python_files: with open(file, 'r') as f: tree = ast.parse(f.read()) (class_defs, func_defs) = find_classes_and_funcs(tree) for class_def in class_defs: transformer = RewriteName(class_def.name) ...
class AmazonAddToCart(VirtualFunctionTool): name = 'AmazonAddToCart' summary = 'Add a product to the shopping cart.' parameters: List[ArgParameter] = [{'name': 'product_id', 'type': 'string', 'description': 'The unique identifier of the product.', 'required': True}, {'name': 'quantity', 'type': 'integer', '...
class SixConv2DCollapsingTest(BaseConv2DCollapsingTest): def __init__(self, unit_test): super().__init__(unit_test) class Conv2DCollapsingNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1)) s...
def __curve_data_filter__(curve): none_warning = False for c in curve.classes: data_temp = {curve.plot_x_axis: [], curve.plot_y_axis: []} x_data = curve.data[c][curve.plot_x_axis] y_data = curve.data[c][curve.plot_y_axis] for (x, y) in zip(x_data, y_data): if ((x != '...
def test_sort(): data = ak.Array([[7, 5, 7], [], [2], [8, 2]]) assert (to_list(ak.operations.sort(data)) == [[5, 7, 7], [], [2], [2, 8]])
class SchemaAndWordCopyingDecoder(BaseCopyingDecoder): def __init__(self, delimiter=' ', tokens_feature_name='tokens', length_feature_name='length', source_copy_feature_name='source_copy_indices', schema_copy_feature_name='schema_copy_indices', prepend_token=None, append_token=None): super(SchemaAndWordCopy...
class TestRerouteTensor(test_util.TestCase): def test_reroute_tensor(self): net = core.Net('reroute_tensor') net.Conv(['input', 'w', 'b'], 'conv1') net.Relu(['conv1'], 'conv1_relu') new_op = core.CreateOperator('SpatialBN', ['conv1', 'scale', 'bias', 'mean', 'var'], ['conv1_bn', 'mea...
_cache(maxsize=None) def _read_template(template_fn: str) -> CodeTemplate: return CodeTemplate.from_file(template_fn)
class SDPAttention(nn.Module): def __init__(self, dropout=0, causal=False): super(SDPAttention, self).__init__() self.causal = causal self.dropout = nn.Dropout(dropout) self.mask_q = None self.mask_k = None def set_mask_q(self, masked_tq): self.mask_q = masked_tq ...
def lm(batch_size): model = ('LM (batch size %d)' % batch_size) command = 'python main.py --cuda --data %s/wikitext2' command += (' --batch_size %d' % batch_size) working_directory = 'language_modeling' num_steps_arg = '--steps' return JobTemplate(model=model, command=command, working_directory=...
class Q(object): def __init__(self, list_): super(Q, self).__init__() self._list = list_ def __len__(self): return len(self._list) def __getitem__(self, key): return self._list[key] def __eq__(self, other): if isinstance(other, self.__class__): return ...
def gaussian_mlp_policy_tf_ppo_benchmarks(): iterate_experiments(gaussian_mlp_policy, MuJoCo1M_ENV_SET, seeds=_seeds)
def main(dataset_name, task_type, target_size=10000, device='cuda'): examples = get_examples_for_discriminative_construction(dataset_name=dataset_name) para_generator = ParaphraseGenerator(device=device) hallu_generator = HallucinationGenerator(device=device) save_path = f'constructed_data/{dataset_name...
class AdamW(TorchOptimizer): def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.01, amsgrad=False): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('Invalid epsilon value: {...
class Ripple01(Benchmark): def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip(([0.0] * self.N), ([1.0] * self.N))) self.global_optimum = [[0.1 for _ in range(self.N)]] self.fglob = (- 2.2) def fun(self, x, *args): self.nfev += 1...
class FlaskForm(Form): class Meta(DefaultMeta): csrf_class = _FlaskFormCSRF csrf_context = session _property def csrf(self): return current_app.config.get('WTF_CSRF_ENABLED', True) _property def csrf_secret(self): return current_app.config.get(...
class GraphNode(Node): def __init__(self, name: str): self.name: str = name self.node_type: NodeType = NodeType.MEASURED self.center_x: int = (- 1) self.center_y: int = (- 1) self.attributes = {} def get_name(self) -> str: return self.name def get_node_type(se...
class SingleLayerFunctionalLinearModel(torch.nn.Module): def __init__(self): super().__init__() self.linear1 = FunctionalLinear() def forward(self, x): x = self.linear1(x) return x
class JSONWriter(EventWriter): def __init__(self, json_file, window_size=20): self.file_handle = open(json_file, 'a') self.window_size = window_size def write(self, **kwargs): storage = get_event_storage() to_save = {'iteration': (storage.iter + 1)} to_save.update(storage...
class DepTree(): def __init__(self, buff): self._head2deps = defaultdict(list) self._dep2head = dict() self._str = [] for line in buff: dep_idx = int(line[0]) head_idx = int(line[6]) self.head2deps[head_idx].append(dep_idx) self.dep2hea...
def class_prior(complementary_labels): return (np.bincount(complementary_labels) / len(complementary_labels))
def layernorm_pytorch_lstm_creator(**kwargs): (input, hidden, _, module) = lstm_inputs(return_module=True, **kwargs) batch_size = kwargs['miniBatch'] hidden_size = kwargs['hiddenSize'] ln_i = torch.nn.LayerNorm((4 * hidden_size)).cuda() ln_h = torch.nn.LayerNorm((4 * hidden_size)).cuda() ln_c = ...
def _test_predictors(self, predictors, overwrite_cfgs, overwrite_in_channels, hwsize): self.assertGreater(len(predictors), 0) in_channels_default = 64 for (name, builder) in predictors.items(): print('Testing {}...'.format(name)) if (name in overwrite_cfgs): cfg = load_config(ove...
class Decoder(nn.Module): def __init__(self, vocab_size, d_model, N, heads, dropout): super().__init__() self.N = N self.embed = Embedder(vocab_size, d_model) self.pe = PositionalEncoder(d_model, dropout=dropout) self.layers = get_clones(DecoderLayer(d_model, heads, dropout),...
def main(): cfg.merge_from_file(args.config) cur_dir = os.path.dirname(os.path.realpath(__file__)) dataset_root = os.path.join(cur_dir, '../testing_dataset', args.dataset) model = ModelBuilder() model = load_pretrain(model, args.snapshot).cuda().eval() tracker = build_tracker(model) dataset ...
class LocalStack(object): def __init__(self): self._local = Local() def __release_local__(self): self._local.__release_local__() def __ident_func__(self): return self._local.__ident_func__ __ident_func__.setter def __ident_func__(self, value): object.__setattr__(self....
class DatasetTests(unittest.TestCase): def setUpClass(cls): cls.args = {'num_examples': 1000, 'num_clusters': 10, 'num_dims': 2, 'equal_clusters': False, 'min_clust_size': 5} Dataset.global_rng = np.random.RandomState(42) def tearDownClass(cls): Dataset.global_rng = None def test_equ...
def _forward_gravity(receivers, nodes, densities, fields, cell_nodes, kernel_func, constant_factor): n_receivers = receivers.shape[0] n_nodes = nodes.shape[0] n_cells = cell_nodes.shape[0] for i in prange(n_receivers): kernels = np.empty(n_nodes) for j in range(n_nodes): kern...
def TaylorTwographSRG(q): (G, l, v0) = TaylorTwographDescendantSRG(q, clique_partition=True) G.add_vertex(v0) G.seidel_switching(sum(l[:(((q ** 2) + 1) / 2)], [])) G.name('Taylor two-graph SRG') return G
class BEVFusion_lidar(Base3DFusionModel): def __init__(self, C, xbound, ybound, zbound) -> None: super().__init__() f = open('model/bevfusion/lidar-centerpoint-bev128.yaml', 'r') cfg = yaml.safe_load(f) encoders = cfg['model']['encoders'] decoder = cfg['model']['decoder'] ...
_LAYERS.register_module() class HSigmoid(nn.Module): def __init__(self, bias=1.0, divisor=2.0, min_value=0.0, max_value=1.0): super(HSigmoid, self).__init__() self.bias = bias self.divisor = divisor assert (self.divisor != 0) self.min_value = min_value self.max_value ...
class SEGating(nn.Module): def __init__(self, inplanes, reduction=16): super().__init__() self.pool = nn.AdaptiveAvgPool3d(1) self.attn_layer = nn.Sequential(nn.Conv3d(inplanes, inplanes, kernel_size=1, stride=1, bias=True), nn.Sigmoid()) def forward(self, x): out = self.pool(x) ...
class AnalyticalSolver(COPSolver): def solve(self, gradients): if (gradients is None): raise TypeError('Argument: gradients type cannot be None') if (len(gradients) != 2): raise ValueError('Argument: The number of gradients must be equal to 2') if (len(gradients[0]) !...
def tonumpy(data): if isinstance(data, np.ndarray): return data if isinstance(data, t._C._TensorBase): return data.cpu().numpy() if isinstance(data, t.autograd.Variable): return tonumpy(data.data)
def _get_funcs(names, arrays, dtype, lib_name, fmodule, cmodule, fmodule_name, cmodule_name, alias, ilp64=False): funcs = [] unpack = False dtype = _np.dtype(dtype) module1 = (cmodule, cmodule_name) module2 = (fmodule, fmodule_name) if isinstance(names, str): names = (names,) unp...
def out_names(inputs): (question, context) = inputs.split('[SEP]') d = pmodel.tokenizer(question, context) return [pmodel.tokenizer.decode([id]) for id in d['input_ids']]
class FakePolicy(Policy): def compute_action(self, observation, act_mask, evaluate: bool, hidden_state: Any=None, **kwargs): super().compute_action(observation, act_mask, evaluate, hidden_state, **kwargs) return 'checked' def coordinate(self, state, message: Any) -> Any: super().coordina...
def load_examples(path, split, verbose=False): print(f'Split: {split.upper()}') with open(os.path.join(path, 'female_occupations.txt')) as f: female_occupations = [row.lower().strip() for row in f] with open(os.path.join(path, 'male_occupations.txt')) as f: male_occupations = [row.lower().st...
def test_set_get_value(atomic_integer_null): assert (atomic_integer_null.value == 0) atomic_integer_null.value = 23 assert (atomic_integer_null.value == 23)
def configuration_to_dict(handlers): config_dict = defaultdict(dict) for handler in handlers: obj_alias = handler.section_prefix target_obj = handler.target_obj for option in handler.set_options: getter = getattr(target_obj, ('get_%s' % option), None) if (getter i...
_utils.test(require=ti.extension.mesh, demote_no_access_mesh_fors=True) def test_multiple_meshes(): mesh_builder = ti.lang.mesh._TetMesh() mesh_builder.verts.place({'y': ti.i32}) meta = ti.Mesh.load_meta(model_file_path) model1 = mesh_builder.build(meta) model2 = mesh_builder.build(meta) model1....
class TypeConverter(): def tensor_2_numpy_gpu(data): return data.cpu().numpy() def tensor_2_numpy(data): return data.numpy() def image_tensor_2_cv(data): img = TypeConverter.tensor_2_numpy(data) img = (img.transpose([1, 2, 0]) + config['pixel_mean']) img = np.clip(img...
def _sys_git_stat_local_rev(repo, rev): main_path = _main_repo_path(repo) try: out = check_output(['git', '-c', 'log.showsignature=false', 'log', '-n1', '--format=format:%H %cd', ('--date=format:%s' % _DateFormat), rev, '--'], cwd=main_path) except SubprocessError: return (None, None) ou...
def set_quantizer_by_name(model, names, **kwargs): for (name, mod) in model.named_modules(): if (hasattr(mod, '_input_quantizer') or hasattr(mod, '_weight_quantizer')): for n in names: if re.search(n, name): set_quantizers(name, mod, **kwargs) elif nam...
class IMECDecoder(): def __init__(self, medium, block_size=None, n_chunks=None, last_block_size=None, use_header=False, **kwargs): self.use_header = use_header self.medium = medium self.context = kwargs.get('context', None) self.block_size = block_size self.send_block_size_he...
def env_loader(env_name: str, run_number: int, dataset_dir: str, stack_size: int=4, data_percentage: int=10, trajectory_fn: Optional[Callable]=None, shuffle_num_episodes: int=1000, shuffle_num_steps: int=50000, trajectory_length: int=10, **_: Any) -> Tuple[(dm_env.Environment, tf.data.Dataset)]: return (environment...
_model def ese_vovnet19b_slim_dw(pretrained=False, **kwargs): return _vovnet('ese_vovnet19b_slim_dw', pretrained=pretrained, **kwargs)
def test_inlinepp_stateful(): ctr = 11 def stateful(): nonlocal ctr ctr += 1 return ctr def tester(a: dace.float64[3]): a[0] = dace.inline(stateful()) a[1] = dace.inline(stateful()) a[2] = dace.inline((stateful() * 2)) sdfg = tester.to_sdfg() assert _f...
def _eval_op(lhs, op, rhs): try: spec = Specifier(''.join([op.serialize(), rhs])) except InvalidSpecifier: pass else: return spec.contains(lhs) oper = _operators.get(op.serialize()) if (oper is None): raise UndefinedComparison('Undefined {0!r} on {1!r} and {2!r}.'.for...
class GoogleMapGetCurrentLocation(VirtualFunctionTool): name = 'GoogleMapGetCurrentLocation' summary = 'Get the current location of the user.' parameters: List[ArgParameter] = [] returns: List[ArgReturn] = [{'name': 'location_address', 'type': 'string', 'description': "The current location of the user i...
def followstrand(f, factors, x0, x1, y0a, prec=53): if (f.degree() == 1): CF = ComplexField(prec) g = f.change_ring(CF) (x, y) = g.parent().gens() y0 = CF[y](g.subs({x: x0})).roots()[0][0] y1 = CF[y](g.subs({x: x1})).roots()[0][0] res = [(0.0, y0.real(), y0.imag()), (...
class Config(object): NAME = None GPU_COUNT = 1 IMAGES_PER_GPU = 1 STEPS_PER_EPOCH = 1000 VALIDATION_STEPS = 10 BACKBONE = 'resnet101' COMPUTE_BACKBONE_SHAPE = None BACKBONE_STRIDES = [4, 8, 16, 32, 64] FPN_CLASSIF_FC_LAYERS_SIZE = 1024 TOP_DOWN_PYRAMID_SIZE = 256 NUM_CLASSES...
class Generator(nn.Module): def __init__(self, conv_dim=64, c_dim=5, repeat_num=6): super(Generator, self).__init__() layers = [] layers.append(nn.Conv2d((3 + c_dim), conv_dim, kernel_size=7, stride=1, padding=3, bias=False)) layers.append(nn.InstanceNorm2d(conv_dim, affine=True, tra...
def _cf_string_to_unicode(value): value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p)) string = CoreFoundation.CFStringGetCStringPtr(value_as_void_p, CFConst.kCFStringEncodingUTF8) if (string is None): buffer = ctypes.create_string_buffer(1024) result = CoreFoundation.CFStri...
class SimdjsonRepository(): def __init__(self, project_path: str, relative_roots: List[RelativeRoot]): self.project_path = project_path self.relative_roots = relative_roots self.files: Dict[(str, SimdjsonFile)] = {} def validate_free_dependency_files(self): for file in self: ...
def cdist(XA, XB, metric='euclidean', *, out=None, **kwargs): XA = np.asarray(XA) XB = np.asarray(XB) s = XA.shape sB = XB.shape if (len(s) != 2): raise ValueError('XA must be a 2-dimensional array.') if (len(sB) != 2): raise ValueError('XB must be a 2-dimensional array.') if...
def get_dataset(bop_dir, dataset, train=True, incl_param=False, eval_model=False, data_folder='None', data_per_obj=False, train_obj_visible_theshold=0.1): if eval_model: postfix_model = '_eval' else: postfix_model = '' bop_dataset_dir = os.path.join(bop_dir, dataset) target_dir = os.path...
def test_graph_reverse_cuthill_mckee(): A = np.array([[1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 1, 0, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 1, 0], [1, 0, 1, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 1, 0, 1], [0, 0, 0, 1, 0, 0, 1, 0], [0, 1, 0, 0, 0, 1, 0, 1]], dtype=int) graph = csr_matrix(A) perm = rever...
def _act_backward(ctx, x, dx): if (ctx.activation == ACT_LEAKY_RELU): _check(_ext.leaky_relu_backward_cuda, x, dx, ctx.slope) _check(_ext.leaky_relu_cuda, x, (1.0 / ctx.slope)) elif (ctx.activation == ACT_ELU): _check(_ext.elu_backward_cuda, x, dx) _check(_ext.elu_inv_cuda, x) ...
def dice_coeff(prediction, target): mask = np.zeros_like(prediction) mask[(prediction >= 0.5)] = 1 inter = np.sum((mask * target)) union = (np.sum(mask) + np.sum(target)) epsilon = 1e-06 result = np.mean(((2 * inter) / (union + epsilon))) return result
def calc_psnr_and_ssim(img1, img2): img1 = img1.astype(np.float64) img2 = img2.astype(np.float64) psnr = calculate_psnr(img1, img2) ssim = measure.compare_ssim(img1, img2, data_range=255, multichannel=True, win_size=65) return (psnr, ssim)
def select_by_path_component(path_pattern, possible_matches, recursion_index=0): import collections import re if (recursion_index == 0): matches = {p for p in possible_matches if p.startswith(path_pattern)} if matches: return matches split_path_pattern = path_pattern.split('/...
def generate_caption(model, image, use_nucleus_sampling=False, num_beams=3, max_length=40, min_length=5): samples = {'image': image} captions = [] if use_nucleus_sampling: for _ in range(5): caption = model.generate(samples, use_nucleus_sampling=True, max_length=max_length, min_length=mi...
def load_stylegan_decoder(px=1024, dataset='ffhq'): from .StyleGAN.model import G_mapping, G_synthesis ckpt_path = CKPT_PATHS[f'StyleGAN_{px}'] if (px == 64): decoder = nn.Sequential(OrderedDict([('g_mapping', G_mapping()), ('g_synthesis', G_synthesis(dlatent_size=512, resolution=64, blur_filter=Non...
class AdditiveAbelianGroupWrapperElement(addgp.AdditiveAbelianGroupElement): def __init__(self, parent, vector, element=None, check=False): addgp.AdditiveAbelianGroupElement.__init__(self, parent, vector, check) if (element is not None): element = self.parent().universe()(element) ...
def filepath_sent2_chunk(tmpdir): tmpfile = tmpdir.join('STSint.testinput.answers-students.sent2.chunk.txt') tmpfile.write('[ Bulbs A and C ] [ are ] [ still ] [ in closed paths ]\n[ Terminal 1 and the positive terminal ] [ are separated ] [ by the gap ]\n[ Terminal 2 and the positive terminal ] [ are separated...
def normalization_variations(string): from snips_nlu_utils import normalize return {normalize(string)}
def match_similar_filenames(file1, file2): if (file1 == file2): return True return match_by_parts(file1, file2, 'camel-case') return match_by_parts(file1, file2, 'underscore')
def get_device(gpu_id=None): if (gpu_id is None): gpu_str = '' elif isinstance(gpu_id, int): gpu_str = f':{gpu_id}' else: raise TypeError('Input should be int value.') if IS_HIGH_VERSION: if torch.backends.mps.is_available(): return torch.device(('mps' + gpu_s...
def load_datasets(name: str) -> Tuple[(CVDataset, CVDataset, CVDataset)]: datasets_map: Dict[(str, CVDataset)] = {'omniglot': (paddlefsl.datasets.Omniglot(mode='train', image_size=(28, 28)), paddlefsl.datasets.Omniglot(mode='valid', image_size=(28, 28)), paddlefsl.datasets.Omniglot(mode='test', image_size=(28, 28))...
def extract(bagfile, pose_topic, msg_type, out_filename): n = 0 f = open(out_filename, 'w') f.write('# timestamp tx ty tz qx qy qz qw\n') with rosbag.Bag(bagfile, 'r') as bag: for (topic, msg, ts) in bag.read_messages(topics=str(pose_topic)): if (msg_type == 'PoseWithCovarianceStampe...
def likelihood_fun(params, n_obs=50): return RNG.normal(loc=params, size=(n_obs, params.shape[0]))
def oid_challenge_classes(): return ['Footwear', 'Jeans', 'House', 'Tree', 'Woman', 'Man', 'Land vehicle', 'Person', 'Wheel', 'Bus', 'Human face', 'Bird', 'Dress', 'Girl', 'Vehicle', 'Building', 'Cat', 'Car', 'Belt', 'Elephant', 'Dessert', 'Butterfly', 'Train', 'Guitar', 'Poster', 'Book', 'Boy', 'Bee', 'Flower', 'W...
def download_model(name: str) -> str: (model_name, model_type, model_url) = ModelInfo.get_model_info(name) model_path = _create_dirs(model_name) if (model_type == 'single'): model_path = _download_file(model_url, model_path) elif (model_type == 'zip'): model_path = _download_zip_model(mo...
def fit_uniform_dist(xs): n = xs.shape[0] ranges = (np.max(xs, axis=0) - np.min(xs, axis=0)) lower = (np.max(xs, axis=0) - ((ranges * (n + 2)) / n)) upper = (np.min(xs, axis=0) + ((ranges * (n + 2)) / n)) return (lower, upper)
_operation def exp_imag(a: torch.Tensor): a = a.unsqueeze((- 1)) return torch.cat((torch.cos(a), torch.sin(a)), (- 1))
class POWER(): class Data(): def __init__(self, data): self.x = data.astype(np.float32) self.N = self.x.shape[0] def __init__(self): (trn, val, tst) = load_data_normalised() self.trn = self.Data(trn) self.val = self.Data(val) self.tst = self.Data(t...
class PoolFormerEmbeddings(nn.Module): def __init__(self, hidden_size, num_channels, patch_size, stride, padding, norm_layer=None): super().__init__() patch_size = (patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)) stride = (stride if isinstance(st...
class Relabel(pymia_fltr.Filter): def __init__(self, label_changes: typing.Dict[(int, typing.Union[(int, tuple)])]) -> None: super().__init__() self.label_changes = label_changes def execute(self, image: sitk.Image, params: pymia_fltr.FilterParams=None) -> sitk.Image: np_img = sitk.GetAr...
class CamembertForMultipleChoice(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def process_and_save(filename, output_dir): music = process(filename) music.save((output_dir / Path(filename).with_suffix('.json').name)) return music
class AdditionRNNModel(object): def __init__(self, max_digits=15, hidden_size=128, batch_size=4096, invert=True, optimizer_lr=0.001, clipnorm=None, logdir=None): self.max_digits = max_digits self.hidden_size = hidden_size self.batch_size = batch_size self.invert = invert self...
((not torch.cuda.is_available()), 'test requires a GPU') class TestGradientScaling(unittest.TestCase): def setUp(self): self.x = torch.tensor([2.0]).cuda().half() weight = 3.0 bias = 5.0 self.error = 1.0 self.target = torch.tensor([(((self.x * weight) + bias) + self.error)])....
def iterate_training(args, trainer, train_trees, train_sequences, transitions, dev_trees, silver_trees, silver_sequences, foundation_cache, model_save_each_filename, evaluator): model = trainer.model if (args['loss'] == 'cross'): logger.info('Building CrossEntropyLoss(sum)') process_outputs = (l...
_utils.test(arch=archs_support_ndarray_ad, default_fp=ti.f64, require=ti.extension.adstack) def test_mixed_inner_loops(): x = ti.ndarray(dtype=ti.f32, shape=(1,), needs_grad=True) arr = ti.ndarray(dtype=ti.f32, shape=5) loss = ti.ndarray(dtype=ti.f32, shape=(1,), needs_grad=True) def mixed_inner_loops(x...
def _get_generic_omop_transformations() -> Sequence[Callable[([RawPatient], Optional[RawPatient])]]: transforms: Sequence[Callable[([RawPatient], Optional[RawPatient])]] = [remove_nones, delta_encode] return transforms
def local_density(self, p, m): n = self.dim() if (n == 0): raise TypeError("we do not currently handle 0-dim'l forms") Q_local = self.local_normal_form(p) if (n == 1): p_valuation = valuation(Q_local[(0, 0)], p) else: p_valuation = min(valuation(Q_local[(0, 0)], p), valuation...
def test_in_place_wrapper_broadcasting(): array = ak.Array({'x': np.arange(3)}) array['unknown field'] = None assert (array['unknown field'].to_list() == [None, None, None]) assert (ak.operations.fields(array) == ['x', 'unknown field'])
class AutoModelWithLMHead(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def test_totalvi_online_update(save_path): n_latent = 5 adata1 = synthetic_iid() TOTALVI.setup_anndata(adata1, batch_key='batch', protein_expression_obsm_key='protein_expression', protein_names_uns_key='protein_names') model = TOTALVI(adata1, n_latent=n_latent, use_batch_norm='decoder') model.train(...
def destroy_window(window): _glfw.glfwDestroyWindow(window) window_addr = ctypes.cast(ctypes.pointer(window), ctypes.POINTER(ctypes.c_ulong)).contents.value for callback_repository in _callback_repositories: del callback_repository[window_addr]
def add_snippets_to_query(snippets, ignored_entities, query, prob_align=1.0): query_copy = copy.copy(query) sorted_snippets = sorted(snippets, key=(lambda s: len(s.sequence)))[::(- 1)] for snippet in sorted_snippets: ignore = False snippet_seq = snippet.sequence for entity in ignored...
def bbox_overlaps(bboxes1, bboxes2, mode='iou', aligned=False, offset=0): mode_dict = {'iou': 0, 'iof': 1} assert (mode in mode_dict.keys()) mode_flag = mode_dict[mode] assert ((bboxes1.size((- 1)) == 4) or (bboxes1.size(0) == 0)) assert ((bboxes2.size((- 1)) == 4) or (bboxes2.size(0) == 0)) ass...
class TextMetric(object): def __init__(self, text): self.text = text self.k = 0 self.n = 0 def reset(self): pass def value(self): self.n = max(1, self.n) return ((1.0 * self.k) / self.n) def show(self): return ('%.2f' % (1.0 * self.value()))
class Fixed(Masker): def __init__(self): self.shape = (None, 0) self.clustering = np.zeros((0, 4)) def __call__(self, mask, x): return ([x],) def mask_shapes(self, x): return [(0,)]
def sparsity(cl_data_file): class_list = cl_data_file.keys() cl_sparsity = [] for cl in class_list: cl_sparsity.append(np.mean([np.sum((x != 0)) for x in cl_data_file[cl]])) return np.mean(cl_sparsity)