code
stringlengths
101
5.91M
def simple_total_photo_ion_coefficients(simple_index_nlte_ion): simple_photo_ion_coefficients = [0., 0.] return pd.DataFrame(simple_photo_ion_coefficients, index=simple_index_nlte_ion)
def is_torch_bf16_available(): warnings.warn("The util is_torch_bf16_available is deprecated, please use is_torch_bf16_gpu_available or is_torch_bf16_cpu_available instead according to whether it's used with cpu or gpu", FutureWarning) return is_torch_bf16_gpu_available()
def dummy_forward_monkeypatch(module: _torch.nn.Module) -> _MonkeyPatchBase: def encapsulator(fmodule: _MonkeyPatchBase, module: _torch.nn.Module) -> None: params = list(module.parameters()) buffer_sync(module, fmodule, None) fmodule.update_params(params) fmodule = make_functional(module...
class DihedralGroup(UniqueRepresentation, Parent): def __init__(self, n=5): assert (n >= 2) Parent.__init__(self, category=FiniteCoxeterGroups()) self.n = n def _repr_(self): return ('The %s-th dihedral group of order %s' % (self.n, (2 * self.n))) def __contains__(self, x): ...
def test_copy(): x = np.array([1], dtype=np.float64) y = img_as_float(x) z = img_as_float(x, force_copy=True) assert (y is x) assert (z is not x)
class _ApproximateKernel(gpflow.kernels.Kernel): def __init__(self, feature_functions: tf.keras.layers.Layer, feature_coefficients: TensorType): self._feature_functions = feature_functions self._feature_coefficients = feature_coefficients def K(self, X: TensorType, X2: Optional[TensorType]=None)...
def get_glosary_info(): res = {} for wf in get_wf_fields(): res[wf.glossary_name] = (wf.__doc__, wf().find_units_label()) return res
class TestCLI(SnipsTest): fixture_dir = (TEST_PATH / 'cli_fixture') def setUp(self): super(TestCLI, self).setUp() if (not self.fixture_dir.exists()): self.fixture_dir.mkdir() dataset_stream = io.StringIO(u'\n---\ntype: intent\nname: MakeTea\nutterances:\n - make me a [bevera...
def psnr(img1, img2): mse = np.mean(((img1 - img2) ** 2)) if (mse == 0): return 100 PIXEL_MAX = np.max(img2) return (20 * log10((PIXEL_MAX / sqrt(mse))))
def _has_sufficient_memory(device, size): if device.startswith('cuda'): return (torch.cuda.is_available() and (torch.cuda.get_device_properties(0).total_memory >= size)) if (device == 'xla'): raise unittest.SkipTest('TODO: Memory availability checks for XLA?') if (device != 'cpu'): r...
def mi(x, y, k=3, base=2): assert (len(x) == len(y)), 'Lists should have same length' assert (k <= (len(x) - 1)), 'Set k smaller than num. samples - 1' (x, y) = flatten(*to_np_array(x, y)) intens = 1e-10 x = [list((p + (intens * nr.rand(len(x[0]))))) for p in x] y = [list((p + (intens * nr.rand(...
def simulator(theta, l1=0.5, l2=0.5, l3=1.0, **kwargs): x1 = (l1 * np.sin(theta[1])) x1 += (l2 * np.sin((theta[1] + theta[2]))) x1 += ((l3 * np.sin(((theta[1] + theta[2]) + theta[3]))) + theta[0]) x2 = (l1 * np.cos(theta[1])) x2 += (l2 * np.cos((theta[1] + theta[2]))) x2 += (l3 * np.cos(((theta[...
class AmazonPostReview(VirtualFunctionTool): name = 'AmazonPostReview' summary = 'Post a review for a previous product that was purchased.' parameters: List[ArgParameter] = [{'name': 'product_id', 'type': 'string', 'description': 'The unique identifier of the product.', 'required': True}, {'name': 'review',...
def _hc(k, cs, rho, omega): return ((((cs / sin(omega)) * (rho ** k)) * sin((omega * (k + 1)))) * greater(k, (- 1)))
def create_dummy_files(backend_specific_objects=None): if (backend_specific_objects is None): backend_specific_objects = read_init() dummy_files = {} for (backend, objects) in backend_specific_objects.items(): backend_name = (('[' + ', '.join((f'"{b}"' for b in backend.split('_and_')))) + ']...
def _resnet(arch: str, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], pretrained: bool, progress: bool, **kwargs: Any) -> ResNet: model = ResNet(block, layers, **kwargs) if pretrained: sys.exit('No pre-trained model is allowed here!') return model
class BidirectionalGRU(nn.Module): def __init__(self, rnn_dim, hidden_size, dropout, batch_first): super(BidirectionalGRU, self).__init__() self.BiGRU = nn.GRU(input_size=rnn_dim, hidden_size=hidden_size, num_layers=1, batch_first=batch_first, bidirectional=True) self.layer_norm = nn.LayerNo...
class WFRadiationMeshNvx(RadiationField): glossary_name = 'params/Mesh/nvx' def __init__(self, wf): super(WFRadiationMeshNvx, self).__init__(wf) self.attributes.update({'units': '-', 'limits': '[2:LONG_MAX]', 'alias': ''}) def value(self): return self._wf._srwl_wf.mesh.nvx def va...
class SeparableConv2DBNFoldingTest(BaseBatchNormalizationFolding): def __init__(self, unit_test): super().__init__(unit_test, linear_layer=layers.SeparableConv2D) def create_networks(self): inputs = layers.Input(shape=self.get_input_shapes()[0][1:]) x = self.linear_layer(1, 3, padding='s...
def roll_buffer(buffer, *args, **kwargs): return Buffer(torch.roll(buffer.states, *args, **kwargs), torch.roll(buffer.actions, *args, **kwargs), torch.roll(buffer.rewards, *args, **kwargs), torch.roll(buffer.dones, *args, **kwargs))
_test() def test_kernels_inside_component_1(): def kernels_inside_component_1(x: dace.float32[8], y: dace.float32[8], v: dace.float32[8], w: dace.float32[8], z: dace.float32[8], t: dace.float32[8], alpha: dace.float32, beta: dace.float32): tmp1 = (x + y) tmp2 = (v + w) tmp3 = (tmp1 + tmp2) ...
def test_bubbles_from_slic(): out = t2c.bubbles_from_slic((1 - data_ball), n_segments=200) assert (out[(rad, rad, rad)] == data_ball[(rad, rad, rad)])
class ConfigListOfType(): _type = None def __init__(self, iterable: Iterable=None): self._values = [] if (iterable is None): iterable = [] for value in iterable: self._values.append(self._type(value)) def __len__(self) -> int: return len(self._values) ...
def vis_num_instance(cat_obj_count): total_instances_per_image = np.sum(cat_obj_count, axis=0) plot_hist(total_instances_per_image, bins=((max(total_instances_per_image) - min(total_instances_per_image)) + 1), save_path='vis_fig/instance_dist_hist.pdf')
def test_solo(): n_latent = 5 adata = synthetic_iid() SCVI.setup_anndata(adata) model = SCVI(adata, n_latent=n_latent) model.train(1, check_val_every_n_epoch=1, train_size=0.5) solo = SOLO.from_scvi_model(model) solo.train(1, check_val_every_n_epoch=1, train_size=0.9) assert ('validation...
def grad(outputs: _TensorOrTensors, inputs: _TensorOrTensors, grad_outputs: Optional[_TensorOrTensors]=None, retain_graph: Optional[bool]=None, create_graph: bool=False, only_inputs: bool=True, allow_unused: bool=False) -> Tuple[(torch.Tensor, ...)]: outputs = ((outputs,) if isinstance(outputs, torch.Tensor) else t...
class InstallHeaders(Command): description = 'install C/C++ header files' user_options = [('install-dir=', 'd', 'directory to install header files to'), ('force', 'f', 'force installation (overwrite existing files)')] boolean_options = ['force'] def initialize_options(self): self.install_dir = N...
class FeedbackBlock(nn.Module): def __init__(self, mid_channels, num_blocks, upscale_factor, padding=2, prelu_init=0.2): super().__init__() stride = upscale_factor kernel_size = (upscale_factor + 4) self.num_blocks = num_blocks self.need_reset = True self.last_hidden ...
class QuantizeRecordingToTrainingModifier(FunctionModifier): class SimulatedQNN(object): def __init__(self, functions_ranks, modifier=None, config=None): self._config = config self._modifier = modifier self._map_input_scale_zeropoint = defaultdict(list) self.f...
class AppGroup(click.Group): def command(self, *args, **kwargs): wrap_for_ctx = kwargs.pop('with_appcontext', True) def decorator(f): if wrap_for_ctx: f = with_appcontext(f) return click.Group.command(self, *args, **kwargs)(f) return decorator def ...
def objective(trial): (model_type, cfg_model, cfg_training) = train_line_parser() cfg_model['dilation_rate'] = trial.suggest_int('dl', 1, 3) cfg_model['kernel'] = (3 + (2 * trial.suggest_int('k', 0, 2))) cfg_model['memroy_kernel'] = (3 + (2 * trial.suggest_int('mk', 0, 2))) if (not cfg_training['off...
def class_process(dir_path, dst_dir_path, class_name): class_path = os.path.join(dir_path, class_name) if (not os.path.isdir(class_path)): return dst_class_path = os.path.join(dst_dir_path, class_name) if (not os.path.exists(dst_class_path)): os.mkdir(dst_class_path) for file_name in...
def test_predict_proba_test_data(): (train, test) = load_toy_cancer() _bk = Background(modes=train.modes) _dn = BoostedRDNClassifier(background=_bk, target='cancer', n_estimators=5) _dn.fit(train) assert_array_almost_equal(_dn.predict_proba(test), np.array([0.74, 0.74, 0.74, 0.25, 0.25]), decimal=2)
def single_naive(file, prediction_horizon_list, interval_multiplier): data = pd.read_csv(file) train_flag = data['train_flag'].to_numpy() training_index = sorted(np.argwhere((train_flag == 1)).reshape([(- 1)])) testing_index = sorted(np.argwhere((train_flag == 0)).reshape([(- 1)])) testing_data = da...
def load_hparam(filename): stream = open(filename, 'r') docs = yaml.load_all(stream, Loader=yaml.Loader) hparam_dict = dict() for doc in docs: for (k, v) in doc.items(): hparam_dict[k] = v return hparam_dict
def opt_config_to_gpt2_config(opt_config: OPTConfig) -> GPT2Config: assert (opt_config.layerdrop == 0.0) assert opt_config.layer_norm_elementwise_affine word_embed_proj_dim = (None if (opt_config.word_embed_proj_dim == opt_config.hidden_size) else opt_config.word_embed_proj_dim) return GPT2Config(vocab_...
class ConstituencyClassifier(BaseClassifier): def __init__(self, tree_embedding, labels, args): super(ConstituencyClassifier, self).__init__() self.labels = labels self.config = SimpleNamespace(fc_shapes=args.fc_shapes, dropout=args.dropout, num_classes=len(labels), constituency_backprop=arg...
('Correlation') def _CorrelationGrad(op, in_grad, in_grad1, in_grad2): (grad0, grad1) = _correlation_module.correlation_grad(in_grad, op.inputs[0], op.inputs[1], op.outputs[1], op.outputs[2], kernel_size=op.get_attr('kernel_size'), max_displacement=op.get_attr('max_displacement'), pad=op.get_attr('pad'), stride_1=o...
class QAMetric(Metric): def __call__(self, output_dict: Dict[(str, torch.Tensor)], metadata_list: List[Dict]): raise NotImplementedError
class TestExtract(object): def setup_method(self): self.cases = [csr_matrix([[1, 2]]), csr_matrix([[1, 0]]), csr_matrix([[0, 0]]), csr_matrix([[1], [2]]), csr_matrix([[1], [0]]), csr_matrix([[0], [0]]), csr_matrix([[1, 2], [3, 4]]), csr_matrix([[0, 1], [0, 0]]), csr_matrix([[0, 0], [1, 0]]), csr_matrix([[0,...
class PosedCameraTest(CamTestMixin, TestCase): def element(cls) -> sf.PosedCamera: return sf.PosedCamera(pose=sf.Pose3(R=sf.Rot3.from_yaw_pitch_roll(0.0, (np.pi / 2.0), 0.0), t=sf.V3(0, 0, 100)), calibration=sf.LinearCameraCal(focal_length=(440, 400), principal_point=(320, 240)), image_size=(640, 480)) ...
def predict_type_embed_task(types_embed_array: np.array, types_embed_labels: np.array, type_space_labels: np.array, pred_task_idx: tuple, indexed_knn: AnnoyIndex, k: int) -> List[dict]: def find_pred_task(i: int): if (i < pred_task_idx[0]): return 'Parameter' elif (i < pred_task_idx[1]):...
def color_jitter(color_jitter, mean, std, data=None, target=None, s=0.25, p=0.2): if (not (data is None)): if (data.shape[1] == 3): if (color_jitter > p): if isinstance(s, dict): seq = nn.Sequential(kornia.augmentation.ColorJitter(**s)) else: ...
class ShuffleLayer(nn.Module): def __init__(self, groups): super(ShuffleLayer, self).__init__() self.groups = groups def forward(self, x): (batchsize, num_channels, height, width) = x.size() channels_per_group = (num_channels // self.groups) x = x.view(batchsize, self.gro...
class Fusions(serial.SerializedTestCase): (scale=st.floats(0.0001, 100.0), zp=st.integers((- 128), 128), size=st.integers(1, 100000), rand_seed=st.integers(0, 65534)) (deadline=None) def Skip_test_tanhquantize(self, scale, zp, size, rand_seed): np.random.seed(rand_seed) workspace.ResetWorksp...
class Ratkowsky01(Benchmark): def __init__(self, dimensions=4): Benchmark.__init__(self, dimensions) self._bounds = list(zip([0.0, 1.0, 0.0, 0.1], [1000, 20.0, 3.0, 6.0])) self.global_optimum = [[, 5., 0., 1.]] self.fglob = 8786.404908 self.a = asarray([16.08, 33.83, 65.8, 97...
def count_meta_edges(G, p_v): partition_vector = to_np_arr(p_v) edge_cut_counts = defaultdict(int) edge_cut_capacities = defaultdict(float) for (u, part_id) in enumerate(partition_vector): for v in G.successors(u): if (partition_vector[v] != part_id): print('({}, {})'...
def save_weights(filename, data): with h5py.File(filename, 'w') as file: file.create_dataset('weights', shape=data.shape, data=data, compression='gzip', compression_opts=9)
def test_record_struct_1(): text = 'struct[{"1": int64[parameters={"xkcd": [11, 12, 13]}]}, parameters={"wonky": ["bla", 1, 2]}]' parsedtype = ak.types.from_datashape(text, highlevel=False) assert isinstance(parsedtype, ak.types.RecordType) assert (str(parsedtype) == text)
def masked_cross_entropy(logits, target, length): if USE_CUDA: length = Variable(torch.LongTensor(length)).cuda() else: length = Variable(torch.LongTensor(length)) logits_flat = logits.view((- 1), logits.size((- 1))) log_probs_flat = functional.log_softmax(logits_flat, dim=1) target_...
class Regression(Repository, CalcRegression): def __init__(self, base_dir='.', log_level=Log.error): self.ServerId = '' self.Level = 0 self.set_base_dir(base_dir) self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId '\n Handle self...
def get_post_state(sdfg: SDFG, state: SDFGState): for s in sdfg.all_sdfgs_recursive(): for post_state in s.states(): if (('post_' + str(state)) == str(post_state)): return post_state return None
def build_parser(line): parser = optparse.OptionParser(add_help_option=False) option_factories = (SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ) for option_factory in option_factories: option = option_factory() parser.add_option(option) def parser_exit(self, msg): msg = ('Invalid req...
class JobExecutorInSeriesBlocking(ExecutorBase): def __init__(self, n_workers: int, verbose=False): super().__init__(n_workers, verbose=verbose) self._creation_time = time.time() def run_until_n_free(self, n_desired_free_workers) -> None: while (self.n_free_workers < n_desired_free_worke...
class LeakyReLU(Module): def __init__(self, negative_slope=0.01, inplace=False): super(LeakyReLU, self).__init__() self.negative_slope = negative_slope self.inplace = inplace def forward(self, input): return F.leaky_relu(input, self.negative_slope, self.inplace) def extra_rep...
class CPDataset(data.Dataset): def __init__(self, opt): super(CPDataset, self).__init__() self.opt = opt self.root = opt.dataroot self.datamode = opt.datamode self.stage = opt.stage self.data_list = opt.data_list self.fine_height = opt.fine_height self...
class ExpandPure(ExpandTransformation): environments = [] def expansion(node, parent_state, parent_sdfg): (inp_tensor, out_tensor) = node.validate(parent_sdfg, parent_state) sdfg = dace.SDFG(f'{node.label}_sdfg') (_, inp_arr) = sdfg.add_array('_inp_tensor', inp_tensor.shape, inp_tensor.d...
def convert_openai_whisper_to_tfms(checkpoint_path, pytorch_dump_folder_path): if ('.pt' not in checkpoint_path): original_checkpoint = _download(_MODELS[checkpoint_path]) else: original_checkpoint = torch.load(checkpoint_path, map_location='cpu') dimensions = original_checkpoint['dims'] ...
def main(): parser = argparse.ArgumentParser() parser.add_argument('command', nargs='?', type=str, choices=['view', 'export'], help='view: view the images in the lmdb database interactively.\nexport: Export the images in the lmdb databases to a folder. The images are grouped in subfolders determinted by the pre...
def test_listtype_numpytype_categorical(): t = ListType(NumpyType('int32'), {'__categorical__': True}) assert (str(parser.parse(str(t))) == str(t))
class Entropy(_CrossEntropy): def __init__(self): super(Entropy, self).__init__(sumit=True) def forward(self, p): return super(Entropy, self).forward(p, p)
def idx_to_onehot(idx, num_elements): onehot = np.zeros(num_elements, dtype=np.float32) onehot[idx] = 1.0 return onehot
class FunctionFieldMorphism_rational(FunctionFieldMorphism): def __init__(self, parent, im_gen, base_morphism): FunctionFieldMorphism.__init__(self, parent, im_gen, base_morphism) def _call_(self, x): a = x.element() if (self._base_morphism is None): return a.subs({a.parent()...
class BinnedDataset(Dataset): def __init__(self, df, data_dir, num_bins, num_workers=0, upper_limit=1500, form_dir_name: str='subform_50', use_ray=False, **kwargs): self.df = df self.num_bins = num_bins self.num_workers = num_workers self.upper_limit = upper_limit self.bins =...
class TicTacToeGame(Game): def __init__(self, n=3): self.n = n def getInitBoard(self): b = Board(self.n) return np.array(b.pieces) def getBoardSize(self): return (self.n, self.n) def getActionSize(self): return ((self.n * self.n) + 1) def getNextState(self, bo...
class UninitializedTensorMixin(): _allowed_methods = [torch.Tensor.__hash__, torch.Tensor.size, torch.Tensor.copy_, torch.Tensor.is_floating_point, torch.Tensor.half, torch.Tensor.float, torch.Tensor.double, torch.Tensor.char, torch.Tensor.short, torch.Tensor.int, torch.Tensor.long, torch.Tensor.cuda, torch.Tensor....
def register_Ns3FixedRssLossModel_methods(root_module, cls): cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True) cls.add_constructor([]) cls.add_method('SetRss', 'void', [param('double', 'rss')]) cls.add_method('DoCalcRxPower', 'double', [param('double', 'txPowerDbm'), param('ns3::Ptr< ns3::M...
class PartitionRngStasher(): def __init__(self, device=torch.device('cpu')): self.device = device self.state = {} self.devices = ([self.device] if (self.device.type == 'cuda') else []) def stash_rng_state(self, micro_batch_index): cpu_rng_state = torch.get_rng_state() if ...
def set_lora_diag(model, diag: torch.Tensor): for _module in model.modules(): if (_module.__class__.__name__ in ['LoraInjectedLinear', 'LoraInjectedConv2d', 'LoraInjectedConv3d']): _module.set_selector_from_diag(diag)
_utils.test() def test_ptr_scalar(): a = ti.field(dtype=ti.f32, shape=()) def func(t: ti.f32): b = ti.static(a) c = ti.static(b) b[None] = (b[None] * t) c[None] = (a[None] + t) for (x, y) in zip(range((- 5), 5), range((- 4), 4)): a[None] = x func(y) as...
.parametrize('ctx, func_name', ctxs) .parametrize('seed', [313, 999]) def test_gelu_double_backward(seed, ctx, func_name): from nbla_test_utils import backward_function_tester rng = np.random.RandomState(seed) inputs = [rng.randn(2, 3, 4).astype(np.float32)] backward_function_tester(rng, F.gelu, inputs,...
def tot() -> operations.GraphOfOperations: operations_graph = operations.GraphOfOperations() operations_graph.append_operation(operations.Generate(1, 20)) operations_graph.append_operation(operations.Score(1, False, utils.num_errors)) keep_best_1 = operations.KeepBestN(1, False) operations_graph.app...
def draw_circle(image, circle, offset=(0, 0), color=(0, 0, 255), thickness=1): center = round_vector((np.array(circle.center) + offset)) cv2.circle(image, center, circle.radius, color, thickness=thickness)
def start_memory_tracing(modules_to_trace: Optional[Union[(str, Iterable[str])]]=None, modules_not_to_trace: Optional[Union[(str, Iterable[str])]]=None, events_to_trace: str='line', gpus_to_trace: Optional[List[int]]=None) -> MemoryTrace: if is_psutil_available(): process = psutil.Process(os.getpid()) e...
def get_answer(solution: Optional[str]) -> Optional[str]: if (solution is None): return None last_boxed = last_boxed_only_string(solution) if (last_boxed is None): return None answer = remove_boxed(last_boxed) if (answer is None): return None return answer
class LightTorsoHopper(RoboschoolXMLModifierMixin, ModifiableRoboschoolHopper): def __init__(self): self.density = 500 with self.modify_xml('hopper.xml') as tree: for elem in tree.iterfind('worldbody/body/geom'): elem.set('density', str(self.density)) RoboschoolFo...
def test_rsl_prims_balltree(): (labels, tree) = robust_single_linkage(X, 0.4, algorithm='prims_balltree') n_clusters_1 = (len(set(labels)) - int(((- 1) in labels))) assert (n_clusters_1 == n_clusters) labels = RobustSingleLinkage(algorithm='prims_balltree').fit(X).labels_ n_clusters_2 = (len(set(lab...
def load_checkpoint(fpath: str): if (fpath is None): raise ValueError('File path is None') if (not osp.exists(fpath)): raise FileNotFoundError('File is not found at "{}"'.format(fpath)) map_location = (None if torch.cuda.is_available() else 'cpu') try: checkpoint = torch.load(fpa...
def _create_pretrained_emb_from_txt(vocab_file, embed_file, num_trainable_tokens=3, dtype=tf.float32, scope=None): (vocab, _) = vocab_utils.load_vocab(vocab_file) trainable_tokens = vocab[:num_trainable_tokens] utils.print_out(('# Using pretrained embedding: %s.' % embed_file)) utils.print_out(' with t...
def obj_fpr(result, reference, connectivity=1): (_, _, _, n_obj_reference, mapping) = __distinct_binary_object_correspondences(reference, result, connectivity) return ((n_obj_reference - len(mapping)) / float(n_obj_reference))
class TensorInfo(): def __init__(self): self.tensor_id = (- 1) self.shape = None self.dtype = DataType.UNKNOWN self.is_const = False self.gaddr = (- 1) self.gsize = 0 self.loffset = (- 1) self.nslice = 0 self.hslice = 0 self.l2addr = 0 ...
def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None, method='highs-ds', callback=None, maxiter=None, disp=False, presolve=True, time_limit=None, dual_feasibility_tolerance=None, primal_feasibility_tolerance=None, simplex_dual_edge_weight_strategy=None, **unknown_options): pass
def fill_gaps2(values): searchval = [0, 255] searchval2 = [255, 0] idx = np.array(np.where(((values[:(- 1)] == searchval[0]) & (values[1:] == searchval[1])))) idx2 = (np.array(np.where(((values[:(- 1)] == searchval[0]) & (values[1:] == searchval[1])))) + 1) new = (idx.tolist() + idx2.tolist()) n...
def create_sdfg_from_fortran_file(source_string: str): parser = pf().create(std='f2008') reader = ffr(source_string) ast = parser(reader) tables = SymbolTable own_ast = ast_components.InternalFortranAst(ast, tables) program = own_ast.create_ast(ast) functions_and_subroutines_builder = ast_tr...
class SSIterator(object): def __init__(self, rng, batch_size, session_file=None, rank_file=None, dtype='int32', can_fit=False, queue_size=100, cache_size=100, shuffle=True, use_infinite_loop=True, max_len=1000): args = locals() args.pop('self') self.__dict__.update(args) self.has_ran...
def common_forward(info, forward_func): batch_size = 1 class ForwardConfig(): pass class Args(): pass args = Args() config = ForwardConfig if hasattr(info, 'global_config'): config.global_config = info.global_config config.executors = info.executors.values() confi...
def load_trees(filename, pipeline): try: raw_text = load_without_asterisks(filename, 'utf-8') except UnicodeDecodeError: raw_text = load_without_asterisks(filename, 'latin-1') trees = tree_reader.read_trees(''.join(raw_text), broken_ok=True) filtered_trees = [] for tree in trees: ...
class TestSpglib(unittest.TestCase): def setUp(self): self._filenames = [] self._ref_filenames = [] self._spgnum_ref = [] for d in dirnames: dirname = os.path.join(data_dir, 'data', d) refdirname = os.path.join(data_dir, 'ref', d) filenames = os.li...
def get_model_url(data, name): return join(WEB_ROOT, data.name, '{}-{}.pth'.format(name, data.model_hash[name]))
def test_cc_head(): head = CCHead(in_channels=16, channels=8, num_classes=19) assert (len(head.convs) == 2) assert hasattr(head, 'cca') if (not torch.cuda.is_available()): pytest.skip('CCHead requires CUDA') inputs = [torch.randn(1, 16, 23, 23)] (head, inputs) = to_cuda(head, inputs) ...
def collate_fn_checker(): dataBatch = list() inpLens = [10, 8, 7, 10] trgtLens = [4, 6, 7, 10] for i in range(len(inpLens)): audInp = torch.from_numpy(np.random.rand((4 * inpLens[i]), args['AUDIO_FEATURE_SIZE'])) vidInp = torch.from_numpy(np.random.rand(inpLens[i], args['TX_NUM_FEATURES'...
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(AverageMeter) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): count = 1 if isinstance(v, torch.Tensor): if (v.numel() == ...
def _get_nan(*data): data = [np.asarray(item) for item in data] try: dtype = np.result_type(*data, np.half) except DTypePromotionError: return np.array(np.nan, dtype=np.float64)[()] return np.array(np.nan, dtype=dtype)[()]
class Metric(ABC): def __init__(self, **kwargs) -> None: super().__init__() self._kwargs = kwargs self.prefix = os.path.splitext(os.path.basename(inspect.getfile(self.__class__)))[0] self.requires_decoded = False def __call__(self, id_to_pred, id_to_labels, is_decoded=False): ...
class EquivarianceWidget(): def __init__(self, viz): self.viz = viz self.xlate = dnnlib.EasyDict(x=0, y=0, anim=False, round=False, speed=0.01) self.xlate_def = dnnlib.EasyDict(self.xlate) self.rotate = dnnlib.EasyDict(val=0, anim=False, speed=0.005) self.rotate_def = dnnlib....
class GloVe(Vectors): def __init__(self, path: str, encoding=None, **kwargs): if os.path.exists(f'{path}.pt'): (itos, vectors) = self.load_from_cache(path) else: (itos, vectors) = _load_from_file(path, encoding) self.save_to_cache(path, itos, vectors) supe...
def test_highlevel_datetime64_ArrayBuilder(): builder = ak.highlevel.ArrayBuilder() dt = np.datetime64('2020-03-27T10:41:12', '25us') dt1 = np.datetime64('2020-03-27T10:41', '15s') dt2 = np.datetime64('2020-05') builder.datetime(dt1) builder.datetime('2020-03-27T10:41:11') builder.datetime(d...
def _calc_tgt(src: int, die) -> int: return (((src >= 24) * (jnp.int32(die) - 1)) + ((src < 24) * jnp.int32(_from_board(src, die))))
def convert_spans_into_sequence_of_tags(tag_matrix: List[str], max_span_width: int, sentence_length: int) -> List[int]: tag_sequence = ['O' for _ in range(sentence_length)] for end_idx in range(sentence_length): for diff in range(max_span_width): if (diff > end_idx): break ...
def get_layer_dtype(layer): if layer.in_tensors: return layer.in_tensors[0].dtype.name if layer.out_tensors: return layer.out_tensors[0].dtype.name return None