code
stringlengths
101
5.91M
def main(args): utils.init_distributed_mode(args) print(args) device = torch.device(args.device) seed = (args.seed + utils.get_rank()) torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True model = get_model(args) patch_size = model.encoder.patch_embed.patch_size pri...
class ResnetV2(tf.keras.Model): def __init__(self, num_units=(3, 4, 6, 3), num_outputs=1000, filters_factor=4, strides=(1, 2, 2, 2), **kwargs): super(ResnetV2, self).__init__(**kwargs) num_blocks = len(num_units) num_filters = tuple((((16 * filters_factor) * (2 ** b)) for b in range(num_bloc...
class MixedIterator(object): def __init__(self, files, batch_size=10000): self.files = files self.types = set(map((lambda x: x['text_type']), files)) self.batch_size = batch_size def __iter__(self): iterators = list(map((lambda x: SingleFileBatchIterator(x, self.types, self.batch...
def oneHotVector(num, domain, vector): number_of_options = 6 if (domain != 'train'): idx = domains.index(domain) if (num == 0): vector[(idx * 6):((idx * 6) + 6)] = np.array([1, 0, 0, 0, 0, 0]) elif (num == 1): vector[(idx * 6):((idx * 6) + 6)] = np.array([0, 1, 0,...
def register_Ns3SimpleRefCount__Ns3EventImpl_Ns3Empty_Ns3DefaultDeleter__lt__ns3EventImpl__gt___methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::SimpleRefCount< ns3::EventImpl, ns3::empty, ns3::DefaultDeleter< ns3::EventImpl > > const &', 'o')]) cls.add_method('Cleanup', '...
_numpy_output(non_zero=True, positive=True) def test_augfloordiv(A: dace.int64[(5, 5)], B: dace.int64[(5, 5)]): B //= A return B
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, in_channels=1): self.inplanes = 32 super(ResNet, self).__init__() self.conv1 = nn.Conv2d(in_channels, 32, kernel_size=7, stride=1, padding=3, bias=False) self.bn1 = nn.BatchNorm2d(32) self.relu = nn....
def pop_path_info(environ, charset='utf-8', errors='replace'): path = environ.get('PATH_INFO') if (not path): return None script_name = environ.get('SCRIPT_NAME', '') old_path = path path = path.lstrip('/') if (path != old_path): script_name += ('/' * (len(old_path) - len(path)))...
def three_squares(n): n = ZZ(n) if (n <= 0): if (n == 0): z = ZZ.zero() return (z, z, z) raise ValueError(('%s is not a sum of 3 squares' % n)) if (n.nbits() <= 32): from sage.rings import sum_of_squares return sum_of_squares.three_squares_pyx(n) e...
def test_is_normalized(os_default, os_camera_full, os_structured_full, os_custom_keys_norm): assert os_default.is_normalized() assert os_custom_keys_norm.is_normalized() assert (not os_camera_full.is_normalized()) assert (not os_structured_full.is_normalized())
class SAMG(nn.Module): def __init__(self, in_channels, out_channels, rel_reduction=8, mid_reduction=1): super(SAMG, self).__init__() self.in_channels = in_channels self.out_channels = out_channels if ((in_channels == 3) or (in_channels == 6)): self.rel_channels = 8 ...
.experimental def test_raises_fit(log, user_features, item_features, model): with pytest.raises(ValueError, match='features for .*'): model.fit(log.filter((sf.col('user_idx') != 0)), user_features.filter((sf.col('user_idx') != 1)), item_features)
def split_train_dev_test(data): (g2i, i2g) = ({'m': 0, 'f': 1}, {1: 'f', 0: 'm'}) all_profs = list(set([d['raw_title'].lower() for d in data])) p2i = {p: i for (i, p) in enumerate(sorted(all_profs))} i2p = {i: p for (i, p) in enumerate(sorted(all_profs))} all_data = [] for entry in data: ...
.environment class ONNXRuntimeCUDA(): cmake_minimum_version = None cmake_packages = [] cmake_variables = {} cmake_compile_flags = [] cmake_link_flags = [] cmake_files = [] state_fields = ['OrtMemoryInfo* ort_cuda_mem_info;', 'OrtMemoryInfo* ort_cuda_pinned_mem_info;'] dependencies = [ONN...
def espnet_hubert_base_iter0(*args, refresh=False, **kwargs): url = ' config_url = ' (ckpt, config) = _urls_to_filepaths(url, config_url, refresh=refresh) return espnet_hubert_custom(ckpt, config)
class Tensor(): ID = 0 def __init__(self, shape, name: str=None, ttype='neuron', data=None, dtype: str='float32', is_const=False): self.id = int(Tensor.ID) self.shape = (shape if isinstance(shape, list) else [shape]) self.name = (('BMTensor' + str(self.id)) if (name is None) else name) ...
.experimental .parametrize('batch_size', BATCH_SIZES) def test_actor_get_action(ddpg_actor_param, batch_size): (actor, param) = ddpg_actor_param user_num = param['user_num'] batch_size = min(batch_size, user_num) item_num = param['item_num'] items = torch.tensor(range(item_num)).repeat((batch_size, ...
class FeedForward(nn.Module): def __init__(self, dim, mult=4, dropout=0.0): super().__init__() self.net = nn.Sequential(nn.Linear(dim, ((dim * mult) * 2)), GEGLU(), nn.Dropout(dropout), nn.Linear((dim * mult), dim)) def forward(self, x, **kwargs): return self.net(x)
class DataLoaderTest(object): def __init__(self, data_path, tokenizer, args, cuda=True, batch_size=64): self.cuda = cuda self.batch_size = batch_size self.tokenizer = tokenizer self.max_len = args.max_len self.evi_num = args.evi_num self.threshold = args.threshold ...
_module() class ShikraTextProcess(BaseTextProcessFunc): def __call__(self, conv: Conversation, preprocessor: Dict[(str, Any)], mode: str, **tokenize_kwargs) -> Dict[(str, Any)]: tokenizer = preprocessor['text'] assert isinstance(tokenizer, LlamaTokenizer), 'only work for LlamaTokenizer' _tru...
class ExtractionThread(Thread): def __init__(self, filename, parameters): Thread.__init__(self) self.filename = filename self.parameters = parameters job_semaphore.acquire() def run(self): print(('Processing "%s" ..' % self.filename), file=sys.stderr) try: ...
def load_system(source_dir): pyproject = os.path.join(source_dir, 'pyproject.toml') with open(pyproject) as f: pyproject_data = toml.load(f) return pyproject_data['build-system']
def crop_largest_square(image, aspect_ratio=1): (width, height) = image.size new_width = min(width, int((height * aspect_ratio))) new_height = min(height, int((width / aspect_ratio))) left = ((width - new_width) / 2) top = ((height - new_height) / 2) right = ((width + new_width) / 2) bottom ...
class Logger(): def __init__(self, name, trainer, validators=(), output_prefix=None, encoding='utf-8'): self.name = name self.trainer = trainer self.validators = validators self.output_prefix = output_prefix self.encoding = encoding def log(self, step=0): if ((sel...
_utils.test() def test_assign_ann_over(): def func_ann_over(): my_int = ti.i32 d: my_int = 2 d: ti.f32 = 2.0 with pytest.raises(ti.TaichiCompilationError): func_ann_over()
class TraceNode(Node): def __init__(self, trace, depth=0): super().__init__(x=list(trace), depth=depth, feature_extract_fn=extract_cumul) def expand(self, expansions=None): del expansions counter = ExpansionCounter.get_default() counter.increment() children = [] f...
def exportable_test_case(constructor_mock, function_mock): test_case = dtc.DefaultTestCase(ModuleTestCluster(0)) int_stmt = IntPrimitiveStatement(test_case, 5) constructor_stmt = ConstructorStatement(test_case, constructor_mock, {'y': int_stmt.ret_val}) constructor_stmt.add_assertion(ass.ObjectAssertion...
def _update_playable_dice(playable_dice: Array, played_dice_num: Array, dice: Array, action: Array) -> Array: _n = played_dice_num die_array = jnp.array(([(action % 6)] * 4), dtype=jnp.int32) dice_indices: Array = jnp.array([0, 1, 2, 3], dtype=jnp.int32) def _update_for_diff_dice(die: Array, idx: Array,...
def rundocs(filename=None, raise_on_error=True): from numpy.compat import npy_load_module import doctest if (filename is None): f = sys._getframe(1) filename = f.f_globals['__file__'] name = os.path.splitext(os.path.basename(filename))[0] m = npy_load_module(name, filename) tests...
def last_boxed_only_string(string: str) -> Optional[str]: idx = string.rfind('\\boxed') if (idx < 0): idx = string.rfind('\\fbox') if (idx < 0): return None i = idx right_brace_idx = None num_left_braces_open = 0 while (i < len(string)): if (string[i] == '{'):...
class GroupViTModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def train(train_loader, model, criterion, optimizer, epoch, opt): model.train() batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() end = time.time() for (idx, (images, ta, sa)) in enumerate(train_loader): data_time.update((time.time() - end)) images = ...
def plot_compare(input, output, reduce_x, reduce_y): output_temp = np.repeat(output, reduce_x, axis=0) output_temp = np.repeat(output_temp, reduce_y, axis=1) (fig, (ax1, ax2)) = plt.subplots(1, 2, sharey=True) ax1.imshow(input) ax2.imshow(output_temp) plt.show() plt.clf()
.parametrize('dtype', [ti.f32]) .parametrize('solver_type', ['LLT', 'LU']) _utils.test(arch=ti.cuda) def test_gpu_sparse_solver2(dtype, solver_type): np_dtype = ti.lang.util.to_numpy_type(dtype) n = 10 A = np.random.rand(n, n) A_psd = (np.dot(A, A.transpose()) + np.eye(n)).astype(np_dtype) Abuilder ...
def split_dataset(X, y, img_names, split=0.1): (itr, ival, ite, trs, vals, tes) = ([], [], [], set(), set(), set()) for (i, name) in enumerate(img_names): pid = int(name.split('_')[1]) if (pid in trs): itr.append(i) elif (pid in vals): ival.append(i) elif ...
def p_sizeof(s): pos = s.position() s.next() s.expect('(') if looking_at_expr(s): operand = p_test(s) node = ExprNodes.SizeofVarNode(pos, operand=operand) else: base_type = p_c_base_type(s) declarator = p_c_declarator(s, empty=1) node = ExprNodes.SizeofTypeNod...
class CoerceToPyTypeNode(CoercionNode): type = py_object_type target_type = py_object_type is_temp = 1 def __init__(self, arg, env, type=py_object_type): if (not arg.type.create_to_py_utility_code(env)): error(arg.pos, ("Cannot convert '%s' to Python object" % arg.type)) elif...
_grad() def evaluate(model, dataloader, device): print('Evaluating...') model.eval() metrics = Metrics(dataloader.dataset.n_classes, dataloader.dataset.ignore_label, device) for (images, labels) in tqdm(dataloader): images = images.to(device) labels = labels.to(device) preds = mo...
def main(args): if ((not args.do_train) and (not args.do_valid) and (not args.do_test) and (not args.evaluate_train)): raise ValueError('one of train/val/test mode must be choosed.') if args.init_checkpoint: override_config(args) args.save_path = (('log/%s/%s/%s-%s/%s' % (args.dataset, args....
class MultiGraphics(WithEqualityById, SageObject): def __init__(self, graphics_list): self._glist = [] self._positions = [] for ins in graphics_list: if isinstance(ins, Graphics): self.append(ins) else: if ((not isinstance(ins, (list, t...
def data_cleaning(words): words = words.replace('', '00000000') words = re.sub("[^'A-Za-z0-9oOaAuU]+", ' ', words).upper() words = words.replace("'", ' ') words = words.replace('', ' ') words = words.replace('0000SS0000', '') return words
def test_initialize_example_background_knowledge_1(): (train, _) = load_toy_cancer() _bk = Background(modes=train.modes) assert (_bk.modes == train.modes) assert (not _bk.line_search) assert (not _bk.recursion) _capture = str(_bk) assert ('setParam: nodeSize=2.' in _capture) assert ('set...
def generate_ld_preload(scorep_config): (_, preload, _) = scorep.helper.call(((['scorep-config'] + scorep_config) + ['--preload-libs'])) return preload.strip()
def _maybe_wrap_suffix(suffix, indent, tensor_str): suffix_len = len(suffix) last_line_len = ((len(tensor_str) - tensor_str.rfind('\n')) + 1) if ((suffix_len > 2) and ((last_line_len + suffix_len) > PRINT_OPTS.linewidth)): return ((',\n' + (' ' * indent)) + suffix[2:]) return suffix
def obtain_model(config, extra_path=None): if (config.dataset == 'cifar'): return get_cifar_models(config, extra_path) elif (config.dataset == 'imagenet'): return get_imagenet_models(config) else: raise ValueError('invalid dataset in the model config : {:}'.format(config))
def _determine_cutout_reachability(ct: SDFG, sdfg: SDFG, in_translation: Dict[(Any, Any)], out_translation: Dict[(Any, Any)], state_reach: Dict[(SDFGState, Set[SDFGState])]=None) -> Tuple[(Set[SDFGState], Set[SDFGState])]: if (state_reach is None): original_sdfg_id = out_translation[ct.sdfg_id] stat...
def move_shenzhen(root_folder, destination_root): RE_SEX_AGE = re.compile('(?P<sex>.*al)[e]?[\\s|,]*(?P<age>[0-9]+)[yr]?[s]?') RE_FNAME = re.compile('CHNCXR\\_(?P<idx>[0-9]+)\\_(?P<lbl>[0|1])\\.txt') root_path = Path(root_folder) os.makedirs(destination_root, exist_ok=True) key_words = ['upper', 'lo...
def main(): parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')): (model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: (model_args, data_args,...
def logP_benchmark(target: float) -> GoalDirectedBenchmark: benchmark_name = f'logP (target: {target})' objective = RdkitScoringFunction(descriptor=logP, score_modifier=GaussianModifier(mu=target, sigma=1)) specification = uniform_specification(1, 10, 100) return GoalDirectedBenchmark(name=benchmark_nam...
def spline(x, y, n, yp0, ypn_1): u = np.zeros((n - 1)) y2 = np.zeros(n) if (yp0 > 9.9e+29): y2[0] = 0.0 u[0] = 0.0 else: y2[0] = (- 0.5) u[0] = ((3.0 / (x[1] - x[0])) * (((y[1] - y[0]) / (x[1] - x[0])) - yp0)) for i in range(1, (n - 1)): sig = ((x[i] - x[(i - ...
def get_execution_error_thresh(): try: return float(os.environ['ERROR_THRESH']) except KeyError: return 0.01
.openapi_version('3.0') .operations('create_user', 'get_user', 'update_user') def test_step_override(testdir, app_schema, base_url): testdir.make_test(f''' schema.base_url = "{base_url}" class APIWorkflow(schema.as_state_machine()): def step(self, case, previous=None): raise ValueError("ERROR FOUND!") T...
class TomlTz(tzinfo): def __init__(self, toml_offset): if (toml_offset == 'Z'): self._raw_offset = '+00:00' else: self._raw_offset = toml_offset self._sign = ((- 1) if (self._raw_offset[0] == '-') else 1) self._hours = int(self._raw_offset[1:3]) self._...
def create_train_and_eval_tmp_table(train_select, valid_select, datasource): train_table = create_tmp_table_from_select(train_select, datasource) valid_table = create_tmp_table_from_select(valid_select, datasource) return (train_table, valid_table)
def get_dataloader(net, train_dataset, val_dataset, data_shape, batch_size, num_workers, args): (width, height) = (data_shape, data_shape) batchify_fn = Tuple(*([Stack() for _ in range(6)] + [Pad(axis=0, pad_val=(- 1)) for _ in range(1)])) if args.no_random_shape: train_loader = gluon.data.DataLoade...
class RegNetConvLayer(nn.Module): def __init__(self, in_channels: int, out_channels: int, kernel_size: int=3, stride: int=1, groups: int=1, activation: Optional[str]='relu'): super().__init__() self.convolution = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=(k...
def test_CDF_TT2000_to_UTC_EPOCH16(lib): tt = epoch16 = (ctypes.c_double * 2)((- 1.0), (- 1.0)) res = lib.CDF_TT2000_to_UTC_EPOCH16(tt, epoch16) print('Expect (.0, 1000.0)') print('Actual ({}, {})'.format(epoch16[0], epoch16[1]))
def _maybe_real(A, B, tol=None): if (np.isrealobj(A) and np.iscomplexobj(B)): if (tol is None): tol = {0: (feps * 1000.0), 1: (eps * 1000000.0)}[_array_precision[B.dtype.char]] if np.allclose(B.imag, 0.0, atol=tol): B = B.real return B
_function def barycentric_projection_matrix(n, angle=0): from sage.matrix.constructor import matrix from sage.misc.functional import sqrt n = ZZ(n) if (n == 0): return matrix(QQ, 0, 1) a = (1 / n) b = sqrt((1 - (a ** 2))) result = (b * barycentric_projection_matrix((n - 1))) resu...
def McGeeGraph(embedding=2): from sage.graphs.generators.families import LCFGraph g = LCFGraph(24, [12, 7, (- 7)], 8) g.name('McGee graph') if (embedding == 1): return g elif (embedding == 2): o = [[7, 2, 13, 8, 19, 14, 1, 20], [5, 4, 11, 10, 17, 16, 23, 22], [3, 12, 9, 18, 15, 0, 21...
.register('boe') class BagOfEmbeddingsEncoder(Seq2VecEncoder): def __init__(self, embedding_dim: int, averaged: bool=False) -> None: super(BagOfEmbeddingsEncoder, self).__init__() self._embedding_dim = embedding_dim self._averaged = averaged def get_input_dim(self) -> int: return...
def test_maxpool1d_padding_same(): time_dim = Dim(Tensor('time', [batch_dim], dtype='int32')) in_dim = Dim(7, name='in') extern_data = TensorDict({'data': Tensor('data', [batch_dim, time_dim, in_dim], dtype='float32')}) class _Net(rf.Module): def __call__(self, x: rf.Tensor, *, in_spatial_dim: D...
class PoseEncoderModel(nn.Module): def __init__(self, pose_dims: (int, int)=(137, 2), hidden_dim: int=128, encoder_depth=4, encoder_heads=2, encoder_dim_feedforward=2048, max_seq_size: int=1000, dropout=0.5): super().__init__() self.dropout = nn.Dropout(p=dropout) self.max_seq_size = max_seq...
def translate(language_code: str) -> PerturbationSpec: return PerturbationSpec(class_name='helm.benchmark.augmentations.translate_perturbation.TranslatePerturbation', args={'language_code': language_code})
def re(R_est, R_gt): assert (R_est.shape == R_gt.shape == (3, 3)) error_cos = (0.5 * (np.trace(R_est.dot(np.linalg.inv(R_gt))) - 1.0)) error_cos = min(1.0, max((- 1.0), error_cos)) error = math.acos(error_cos) error = ((180.0 * error) / np.pi) return error
class Scale(Resize): def __init__(self, *args, **kwargs): warnings.warn(('The use of the transforms.Scale transform is deprecated, ' + 'please use transforms.Resize instead.')) super(Scale, self).__init__(*args, **kwargs)
class AdvLoss(nn.Module): def __init__(self): super(AdvLoss, self).__init__() self.criterion = nn.L1Loss(size_average=True) def forward(self, fake_feature, real_feature, v_loss): fm_loss = 0 feat_weights = (10.0 / len(fake_feature)) for i in range((len(fake_feature) - 1))...
def random_image(shape=(128, 128)): img = gaussian_filter(np.random.normal(size=shape), (min(shape) / 20)) img = (img > np.percentile(img, 80)) img = label(img) img[(img > 255)] = ((img[(img > 255)] % 254) + 1) return img
def prepare_librimix(datapath, savepath, n_spks=2, skip_prep=False, librimix_addnoise=False, fs=8000): if skip_prep: return if ('Libri' in datapath): if (n_spks == 2): assert ('Libri2Mix' in datapath), 'Inconsistent number of speakers and datapath' create_libri2mix_csv(da...
.unit .cartographer def test_img_layer_dict_to_str(): min_zoom = 0 max_zoom = 2 name = 'test' layer_dict = dict(directory=(name + '/{z}/{y}/{x}.png'), name=name, min_zoom=min_zoom, max_zoom=(max_zoom + 5), max_native_zoom=max_zoom) actual_str = c.img_layer_dict_to_str(layer_dict) expected_str = ...
_model def seresnet18(pretrained=False, **kwargs): model_args = dict(block=BasicBlock, layers=[2, 2, 2, 2], block_args=dict(attn_layer='se'), **kwargs) return _create_resnet('seresnet18', pretrained, **model_args)
class FunctionSignature(Signature): def __init__(self, id_, return_type, arg_types, arg_pluralities=None, is_symmetric=False, name=None): super(FunctionSignature, self).__init__(id_, return_type, len(arg_types), name=name) self.arg_types = arg_types if (arg_pluralities is None): ...
def write_csv_file(cmds_dict: dict, pmu_profile_info: dict, save_file: str): save_content = [] for k in cmds_dict: cur_core_cmds_list = cmds_dict[k] cmds_count = len(cur_core_cmds_list) pmu_gdma_count = len(pmu_profile_info[k][0]) pmu_tpu_count = len(pmu_profile_info[k][1]) ...
def test_1d_clustering(): np.random.seed(42) n = 50 X = np.concatenate((np.random.normal((- 1), 1.5, (n, 1)), np.random.normal(1, 1.5, (n, 1)))) vis = ncvis.NCVis(n_neighbors=15, M=16, ef_construction=200, d=1, n_init_epochs=20, n_epochs=50, min_dist=0.4, n_threads=(- 1), distance='euclidean', random_se...
def _generating_function_of_integral_points_(polyhedron, indices=None, **kwds): import logging logger = logging.getLogger(__name__) logger.info('using polyhedron %s', polyhedron.Hrepresentation_str(**Hrepresentation_str_options)) if polyhedron.is_empty(): from sage.structure.factorization import...
def mb_return(state, dynamical_model, reward_model, policy, num_steps=1, gamma=1.0, value_function=None, num_samples=1, entropy_reg=0.0, reward_transformer=RewardTransformer(), termination_model=None, reduction='none'): state = repeat_along_dimension(state, number=num_samples, dim=0) trajectory = rollout_model(...
def find_model_using_name(model_name): model_filename = (('models.' + model_name) + '_model') modellib = importlib.import_module(model_filename) model = None target_model_name = (model_name.replace('_', '') + 'model') for (name, cls) in modellib.__dict__.items(): if ((name.lower() == target_...
def register_Ns3UplinkLteGlobalPathlossDatabase_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::UplinkLteGlobalPathlossDatabase const &', 'arg0')]) cls.add_method('UpdatePathloss', 'void', [param('std::string', 'context'), param('ns3::Ptr< ns3::SpectrumPhy const >', 'txPh...
class ScipyOptimizeInterfaceDomain(PythonDomain): name = 'scipy-optimize' def __init__(self, *a, **kw): super().__init__(*a, **kw) self.directives = dict(self.directives) function_directive = self.directives['function'] self.directives['function'] = wrap_mangling_directive(functi...
def check_rule_validity(context_type, rule_parts): valid = False valid_hyperparams = rule_hyperparams[context_type] try: rule_context_ratio = (float(rule_parts[3]) / 4072) except: return False rule_prompt_separator = rule_parts[(- 1)] rule_rule_context_formatting = '_'.join(rule_...
def get_matcher(vgg, opt): matcher = Matcher(opt['what'], 'mse', opt['map_idx']) def hook(module, input, output): matcher(module, output) for layer_name in opt['layers']: vgg._modules[layer_name].register_forward_hook(hook) return matcher
class ParsedRequirement(object): def __init__(self, requirement, is_editable, comes_from, constraint, options=None, line_source=None): self.requirement = requirement self.is_editable = is_editable self.comes_from = comes_from self.options = options self.constraint = constrain...
def test_report_constant(constantdf: pd.DataFrame) -> None: from sys import platform if (platform == 'darwin'): import matplotlib matplotlib.use('PS') create_report(constantdf, mode='basic')
class DaCeMLBackend(base.Backend): def prepare(cls, model, device='CPU', **kwargs): super().prepare(model, device, **kwargs) dace_model = onnx_importer.ONNXModel('backend_model', model, cuda=(device == 'CUDA'), onnx_simplify=False, storage=dtypes.StorageType.Default) return DaCeMLBackendRep(...
def test_mean_reduce_symbolic_shape(): N = dace.symbol('N') def mean_reduce_symbolic_shape(A: dace.float64[(10, N, 3)]): return np.mean(A, axis=((- 2), 0)) X = np.random.normal(scale=10, size=(10, 12, 3)).astype(np.float64) dace_result = mean_reduce_symbolic_shape(A=X) numpy_result = np.mean...
def draw_rect(im, rect, color=(1.0, 1.0, 1.0)): if (im.dtype != np.uint8): raise ValueError('The image must be of type uint8.') im_pil = Image.fromarray(im) draw = ImageDraw.Draw(im_pil) draw.rectangle((rect[0], rect[1], (rect[0] + rect[2]), (rect[1] + rect[3])), outline=tuple([int((c * 255)) fo...
class AutoIterative(AutoFallbackSolver): name = 'ls.auto_iterative' _ls_solvers = [('ls.petsc', {'method': 'cg', 'precond': 'icc'}), ('ls.scipy_iterative', {'method': 'cg'})]
def validate_it_aic(df: Union[(str, pd.Series, dd.Series, pd.DataFrame, dd.DataFrame)], column: str='') -> Union[(bool, pd.Series, pd.DataFrame)]: if isinstance(df, (pd.Series, dd.Series)): return df.apply(aic.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (column != ''): ...
def separated(values, *, limit, stringify, sep): count = len(values) if ((limit is not None) and (count > limit)): values = values[:limit] continuation = (f'{sep}... ({(count - limit)} more)' if (count > limit) else '') else: continuation = '' rendered = sep.join((stringify(x) fo...
class ApiManager(metaclass=Singleton): def __init__(self): self.total_prompt_tokens = 0 self.total_completion_tokens = 0 self.total_cost = 0 self.total_budget = 0 self.models: Optional[list[Model]] = None def reset(self): self.total_prompt_tokens = 0 self....
class VQModel(pl.LightningModule): def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None, remap=None, sane_index_shape=False): super().__init__() self.image_key = image_key self.encoder = Encoder(**...
_connect.numpy.implements('argmin') def _nep_18_impl_argmin(a, axis=None, out=UNSUPPORTED, *, keepdims=False): return argmin(a, axis=axis, keepdims=keepdims)
def register_Ns3DefaultDeleter__Ns3Ipv6Route_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::DefaultDeleter< ns3::Ipv6Route > const &', 'arg0')]) cls.add_method('Delete', 'void', [param('ns3::Ipv6Route *', 'object')], is_static=True) return
def _ell(A, m): if ((len(A.shape) != 2) or (A.shape[0] != A.shape[1])): raise ValueError('expected A to be like a square matrix') choose_2m_m = scipy.special.comb((2 * m), m, exact=True) abs_c_recip = float((choose_2m_m * math.factorial(((2 * m) + 1)))) u = (2 ** (- 53)) A_abs_onenorm = _one...
def enroll_per_utt(test_DB, model): dict_embeddings = {} total_len = len(test_DB) with torch.no_grad(): for i in range(len(test_DB)): tmp_filename = test_DB['filename'][i] (enroll_embedding, _) = get_d_vector(tmp_filename, model) key = os.sep.join(tmp_filename.spl...
class BaseDataset(Dataset): def __init__(self, dataset_path, image_files, labels, transform=None): super(BaseDataset, self).__init__() self.dataset_path = dataset_path self.image_files = image_files self.labels = labels self.transform = transform def __len__(self): ...
class conv1x1(nn.Module): def __init__(self, planes, out_planes=None, stride=1): super(conv1x1, self).__init__() if (config_task.mode == 'series_adapters'): self.conv = nn.Sequential(nn.BatchNorm2d(planes), conv1x1_fonc(planes)) elif (config_task.mode == 'parallel_adapters'): ...
def test_corrupted_flow_args(): base_gen = DummyGenerator([[0]], check_flow_args=True) corr_gen = CorruptedGenerator(base_gen) corr_gen.flow('some', args=1)
def combine_partial_results(partial_results) -> List: records = [] for partial_result in partial_results: records.extend(partial_result) records = list(sorted(records, key=(lambda x: x['id']))) preds = [x['pred'] for x in records] return preds
def run_epochs(model, model_bert, opt, opt_bert, bert_config, tokenizer, path_wikisql, model_path, train_loader, train_table, dev_loader, dev_table, test_loader, test_table, early_stop_ep=None, bool_eval=True, startime_time=None): tepoch = 100 accumulate_gradients = 4 assert bool_eval print(('## Actual ...