code
stringlengths
101
5.91M
class TestTwowaySplit(TestCase): def setUp(self): self.n = 40 self.k_test = 10 (self.a, self.b) = twoway_split(self.n, self.k_test) def test_sizes(self): self.assertEqual([len(self.a), len(self.b)], [(40 - 10), 10]) def test_union_is_all(self): union = np.union1d(self...
.parametrize('task_name', [tn for tn in (all_tasks - julia_tasks)]) def test_describe_theta(task_name): task = get_task(task_name) labels = task.get_labels_parameters() assert isinstance(labels, list) assert (len(labels) == task.get_true_parameters(num_observation=1).shape[(- 1)])
def get_morgan_fp_smi(smi: str, nbits: int=2048, radius=3) -> np.ndarray: return get_morgan_fp(Chem.MolFromSmiles(smi), nbits=nbits, radius=radius)
def LF_donor(span): rgx = '\\b(donor)\\b' text = get_left_span(span, span.sentence, window=6).text return (OTHER if re.search(rgx, span.sentence.text.strip(), re.I) else ABSTAIN)
def local_path_from_s3_or_local_path(filename): relative_filename = os.path.join(LOCAL_LOG_DIR, filename) if os.path.isfile(filename): return filename elif os.path.isfile(relative_filename): return relative_filename else: return sync_down(filename)
def _hash_file(fpath, algorithm='sha256', chunk_size=65535): if ((algorithm is 'sha256') or ((algorithm is 'auto') and (len(hash) is 64))): hasher = hashlib.sha256() else: hasher = hashlib.md5() with open(fpath, 'rb') as fpath_file: for chunk in iter((lambda : fpath_file.read(chunk_s...
class Jasper(nn.Module): def __init__(self, num_classes: int, version: str='10x5', device: torch.device='cuda') -> None: super(Jasper, self).__init__() supported_versions = {'10x5': {'encoder_config': Jasper10x5EncoderConfig(num_blocks=10, num_sub_blocks=5), 'decoder_config': JasperDecoderConfig(num...
class LevitPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def convert_weights_to_lp(model: nn.Module, dtype=torch.float16): def _convert_weights(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): l.weight.data = l.weight.data.to(dtype) if (l.bias is not None): l.bias.data = l.bias.data.to(dtype) if isinstance(l...
def my_kde_bandwidth(obj, fac=(1.0 / 5)): return (np.power(obj.n, ((- 1.0) / (obj.d + 4))) * fac)
class TestSummarizationDistillerMultiGPU(TestCasePlus): def setUpClass(cls): return cls _torch_multi_gpu def test_multi_gpu(self): updates = dict(no_teacher=True, freeze_encoder=True, gpus=2, overwrite_output_dir=True, sortish_sampler=True) self._test_distiller_cli_fork(updates, chec...
.parametrize('dt', [ti.i16, ti.u16, ti.u8, ti.i8]) _utils.test(arch=ti.vulkan) def test_arg_short(dt): def foo(a: dt, b: ti.types.ndarray(dtype=dt, ndim=1)): b[0] = a k = ti.ndarray(dt, shape=(1,)) sym_A = ti.graph.Arg(ti.graph.ArgKind.SCALAR, 'mat', dt) sym_B = ti.graph.Arg(ti.graph.ArgKind.NDA...
def main(): parser = argparse.ArgumentParser(description=' Matcha-TTS: A fast TTS architecture with conditional flow matching') parser.add_argument('model', type=str, help='ONNX model to use') parser.add_argument('--vocoder', type=str, default=None, help='Vocoder to use (defaults to None)') parser.add_...
def reset_data() -> None: global data data = {'Num. Workers': [], 'FPS': [], 'Env': [], 'System': [], 'Method': []}
class LR(torch.nn.Module): def __init__(self, opt): super(LR, self).__init__() self.use_cuda = opt.get('use_cuda') self.field_dims = opt['field_dims'] self.linear = FeaturesLinear(self.field_dims) def forward(self, x): score = self.linear.forward(x) return score.s...
def validate_fi_associationid(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(associationid.is_valid) elif isinstance(df, (pd.DataFrame, dd.DataFrame)): if (c...
def get_error_type(result, binary=False): if binary: if (result == True): return 1 else: return 0 if (result == (- 2)): return 0 elif (result == (- 1)): return 1 elif (result == False): return 2 elif (result == True): return 3 ...
def get_xp3_document_iterator(file_path: str) -> Iterator[str]: with open(file_path, 'r') as f: for line in f: json_dict = json.loads(line) (yield json_dict['inputs']) (yield json_dict['targets'])
def check_layers(layers): if (not isinstance(layers[0], Prior)): raise ValueError('first layer must be a Prior') for (i, layer) in enumerate(layers[1:(- 1)]): if (not isinstance(layer, Channel)): raise ValueError(f'intermediate layer i={i} must be a Channel') if isinstance(layers...
def Upsample(tensor, size): name = (tensor.name.split('/')[0] + '_upsample') def bilinear_upsample(x, size): resized = tf.image.resize(images=x, size=size) return resized y = Lambda((lambda x: bilinear_upsample(x, size)), output_shape=size, name=name)(tensor) return y
class ProblemSet(IterableDataset): class Iterator(): def __init__(self, problem_set): self.problem_set = problem_set self.paradigm = problem_set.paradigm self.vocab = problem_set.vocab self.ammo = [] self.magazine = [] self.magazine_siz...
_function_dispatch(_require_fields_dispatcher) def require_fields(array, required_dtype): out = np.empty(array.shape, dtype=required_dtype) assign_fields_by_name(out, array) return out
_binary def atomic_max(x, y): return impl.expr_init(expr.Expr(_ti_core.expr_atomic_max(x.ptr, y.ptr), dbg_info=_ti_core.DebugInfo(stack_info())))
def normalize_question(question: str) -> str: if (question[(- 1)] == '?'): question = question[:(- 1)] return question
def _densenet(arch, growth_rate, block_config, num_init_features, pretrained, progress, **kwargs): return DenseNet(growth_rate, block_config, num_init_features, **kwargs)
def instantiate_from_config(config): if (not ('target' in config)): raise KeyError('Expected key `target` to instantiate.') return get_obj_from_str(config['target'])(**config.get('params', dict()))
def fixmatch_augment_pool(): augs = [(AutoContrast, None, None), (Brightness, 0.9, 0.05), (Color, 0.9, 0.05), (Contrast, 0.9, 0.05), (Equalize, None, None), (Identity, None, None), (Posterize, 4, 4), (Sharpness, 0.9, 0.05), (Solarize, 256, 0)] return augs
def main(argv=None): print('Loading training data..') train_data = load_data(FLAGS.train_prefix) print('Done loading training data..') train(train_data)
def main(): parser = argparse.ArgumentParser(description='OGBN-MAG (MetaPath2Vec)') parser.add_argument('--device', type=int, default=0) parser.add_argument('--embedding_dim', type=int, default=128) parser.add_argument('--walk_length', type=int, default=64) parser.add_argument('--context_size', type...
class DynamicBatchSampler(): def __init__(self, dataset, collator, max_tokens, max_segment_len, max_doc_len=None): self.max_tokens = max_tokens self.dataset = dataset.sort('length', reverse=True) self.collator = collator self.max_segment_len = max_segment_len self.max_doc_len...
class BertTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, ...
class PixelShufflePack(nn.Module): def __init__(self, in_channels, out_channels, scale_factor, upsample_kernel): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.scale_factor = scale_factor self.upsample_kernel = upsample_kernel ...
def FareyMap(p): from sage.combinat.permutation import Permutation from sage.groups.perm_gps.permgroup import PermutationGroup from sage.matrix.constructor import matrix from sage.modules.free_module_element import vector from sage.rings.finite_rings.finite_field_constructor import GF from sage....
def load_url_dist(url, model_dir=None): (rank, world_size) = get_dist_info() rank = int(os.environ.get('LOCAL_RANK', rank)) if (rank == 0): checkpoint = model_zoo.load_url(url, model_dir=model_dir) if (world_size > 1): torch.distributed.barrier() if (rank > 0): checkp...
def get_compile_args(compiler): opts = ['-std=c++11', '-O2', '-DNDEBUG'] if (sys.platform == 'darwin'): opts += ['-stdlib=libc++', '-mmacosx-version-min=10.7'] return opts
def prevent_unsatisfiable_schema(schema: Schema, new_type: str) -> None: drop_not_type_specific_keywords(schema, new_type) if ('not' in schema): drop_not_type_specific_keywords(schema['not'], new_type) if (not schema['not']): del schema['not']
def create_symlinks(target_dir: os.PathLike, symlinks_to_create: List[os.PathLike]): for src_path in symlinks_to_create: trg_path = os.path.join(target_dir, os.path.basename(src_path)) if os.path.islink(src_path): os.symlink(os.readlink(src_path), trg_path) else: prin...
class TestHessianUpdateStrategy(TestCase): def test_hessian_initialization(self): quasi_newton = (BFGS(), SR1()) for qn in quasi_newton: qn.initialize(5, 'hess') B = qn.get_matrix() assert_array_equal(B, np.eye(5)) def test_rosenbrock_with_no_exception(self): ...
class ConvBlock(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding=0, dilation=1, bias=False): super().__init__() self.conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=bias) self.bn = nn.BatchNorm2d(planes) ...
class SparseFeat(namedtuple('SparseFeat', ['name', 'vocabulary_size', 'embedding_dim', 'use_hash', 'vocabulary_path', 'dtype', 'embeddings_initializer', 'embedding_name', 'group_name', 'trainable'])): __slots__ = () def __new__(cls, name, vocabulary_size, embedding_dim=4, use_hash=False, vocabulary_path=None, d...
class ProteinResNetLayerNorm(nn.Module): def __init__(self, config): super().__init__() self.norm = LayerNorm(config.hidden_size) def forward(self, x): return self.norm(x.transpose(1, 2)).transpose(1, 2)
def select_crossover(toolbox, ga_params): if (ga_params['mate_scheme'] == 'cluster'): mate_func = Genotype.xover_cluster elif (ga_params['mate_scheme'] == 'dv'): mate_func = Genotype.xover_genes else: raise ValueError(f"{ga_params['mate_scheme']} is not a valid mutation scheme") ...
class ProphetNetForCausalLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class NllbMoeConfig(PretrainedConfig): model_type = 'nllb-moe' keys_to_ignore_at_inference = ['past_key_values'] attribute_map = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__(self, vocab_size=128112, max_position_embeddings=1024, encoder_layers=12, encoder_ffn...
class RelationType(): def __init__(self, identifier, index, short_name, verbose_name, symmetric=False): self._identifier = identifier self._index = index self._short_name = short_name self._verbose_name = verbose_name self._symmetric = symmetric def identifier(self): ...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = c...
def _remove_existing(trg, is_dir): if os.path.exists(trg): if is_dir: shutil.rmtree(trg) else: os.remove(trg)
def __handle_stream(db, stream, day): if ('transport_info' in stream): if ('remote' in stream['transport_info']): if ('onion' in stream['transport_info']['remote']): return transfer_size_actual = int(stream['byte_info']['payload-bytes-recv']) transfer_size_target = int(st...
class EntityNode(ASTNode): def __init__(self, val, data_type, fields): super().__init__('ENTITY', val, data_type, fields) def textual_form_core(self): return self.val
_model def tf_mixnet_m(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_mixnet_m('tf_mixnet_m', channel_multiplier=1.0, pretrained=pretrained, **kwargs) return model
def test_convert_to_numpy_dataframe_and_series(): X_df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}) y_series = pd.Series([7, 8, 9]) (X_array, y_array) = convert_to_numpy(X_df, y_series) assert isinstance(X_array, np.ndarray) assert isinstance(y_array, np.ndarray) assert np.array_equal(X_arra...
def test_resnet31_ocr_backbone(): with pytest.raises(AssertionError): ResNet31OCR(2.5) with pytest.raises(AssertionError): ResNet31OCR(3, layers=5) with pytest.raises(AssertionError): ResNet31OCR(3, channels=5) model = ResNet31OCR() model.init_weights() model.train() ...
def load_model(helper: PredictHelper, config: PredictionConfig, path_to_model_weights: str) -> Any: return ConstantVelocityHeading(config.seconds, helper)
class Partition15(nn.Module): LAYER_SCOPES = ['T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[21]/ModuleList[layer]/T5LayerSelfAttention[0]/T5LayerNorm[layer_norm]', 'T5ForConditionalGeneration/T5Stack[decoder]/ModuleList[block]/T5Block[21]/ModuleList[layer]/T5LayerSelfAttention[0]/T5Attentio...
def test_signed_scaling_float32(): x = np.array([(- 128), 127], dtype=np.int8) y = img_as_float32(x) assert_equal(y.max(), 1)
class MyTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.testing_class = EnvironmentCPUvsGPU(cpu_env_class=ClassicControlMountainCarEnv, cuda_env_class=CUDAClassicControlMountainCarEnv, env_configs=env_configs, gpu_env_backend='numba', num_envs...
def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None, c1=0.0001, c2=0.9, amax=50, amin=1e-08, xtol=1e-14): _check_c1_c2(c1, c2) if (phi0 is None): phi0 = phi(0.0) if (derphi0 is None): derphi0 = derphi(0.0) if ((old_phi0 is not None) and (derphi0 != 0)): a...
def main(cfg): (dataset, train_loader, test_loader, num_query, num_classes) = make_data_loader(cfg) model = build_model(num_classes, 'base', pretrain_choice=True) model = (torch.nn.DataParallel(model).cuda() if torch.cuda.is_available() else model) loss_func = make_loss() optimizer = make_optimizer(...
def get_results(filename): top3 = get_top3_topics(filename) result = [] for (k, v) in top3: responses = generate_all_responses(k) result.append({'topic': k, 'score': v, 'responses': responses}) return result
def register_Ns3DeviceNameTag_methods(root_module, cls): cls.add_constructor([param('ns3::DeviceNameTag const &', 'arg0')]) cls.add_constructor([]) cls.add_method('Deserialize', 'void', [param('ns3::TagBuffer', 'i')], is_virtual=True) cls.add_method('GetDeviceName', 'std::string', [], is_const=True) ...
def down_resblock(x_init, channels, to_down=True, use_bias=True, sn=False, scope='resblock'): with tf.variable_scope(scope): init_channel = x_init.shape.as_list()[(- 1)] with tf.variable_scope('res1'): x = lrelu(x_init, 0.2) x = conv(x, channels, kernel=3, stride=1, pad=1, pa...
def read_in_run_from_pickle(bm25_file): with open(bm25_file, 'rb') as f: bm25_dict = pickle.load(f) bm25_dict_new = {} for (key, value) in bm25_dict.items(): bm25_dict_new.update({key: {}}) i = 1 for (key2, value2) in value.items(): bm25_dict_new.get(key).update({...
def write_citations(app: Sphinx, citations): from sage.misc.temporary_file import atomic_write outdir = citation_dir(app) with atomic_write((outdir / CITE_FILENAME), binary=True) as f: pickle.dump(citations, f) logger.info(('Saved pickle file: %s' % CITE_FILENAME))
def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
def _named_modules_with_dup(model: nn.Module, prefix: str='') -> Iterable[Tuple[(str, nn.Module)]]: (yield (prefix, model)) for (name, module) in model._modules.items(): if (module is None): continue submodule_prefix = ((prefix + ('.' if prefix else '')) + name) (yield from _...
def modularity(mod_matrix: np.ndarray, communities: list) -> float: C = np.zeros_like(mod_matrix) for community in communities: for (i, j) in combinations(community, 2): C[(i, j)] = 1.0 C[(j, i)] = 1.0 return np.tril(np.multiply(mod_matrix, C), 0).sum()
class TestSamplingPolicy(unittest.TestCase): def test_random_policy(self): policy = RandomPolicy(2, sequence_length=2) n_samples = 100 samples = [policy.generate() for _ in range(n_samples)] a_ct = samples.count([0, 0]) b_ct = samples.count([0, 1]) c_ct = samples.coun...
def test_slice_args(cl): frame = cl.io.Input([NamedVideoStream(cl, 'test1')]) slice_frame = cl.streams.Slice(frame, [cl.partitioner.ranges([[0, 1], [1, 2], [2, 3]])]) test = cl.ops.TestSliceArgs(frame=slice_frame, arg=[SliceList([i for i in range(3)])]) unsliced_frame = cl.streams.Unslice(test) outp...
def _load_orion(pipeline, hyperparameters=None): if (pipeline is None): return Orion() elif isinstance(pipeline, Orion): return pipeline else: hyperparameters = _load_dict(hyperparameters) try: return Orion(pipeline, hyperparameters) except ValueError: ...
class Unit3Dpy(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=(1, 1, 1), stride=(1, 1, 1), activation='relu', padding='SAME', use_bias=False, use_bn=True): super(Unit3Dpy, self).__init__() self.padding = padding self.activation = activation self.use_bn = ...
def should_be_zero(A): a0 = alpha0(A) return ((4 / (9 * (A ** 2))) - ((8 * a0) * ((((a0 ** 2) + (a0 / (2 * A))) + (1 / (16 * (A ** 2)))) - (1 / (4 * A)))))
class IRGAN(RecMixin, BaseRecommenderModel): _charger def __init__(self, data, config, params, *args, **kwargs): self._random = np.random self._params_list = [('_predict_model', 'predict_model', 'predict_model', 'generator', None, None), ('_factors', 'factors', 'factors', 10, None, None), ('_lea...
def test_paramset_unconstrained(): pset = paramsets.unconstrained(name='foo', is_scalar=False, n_parameters=5, inits=[0, 1, 2, 3, 4], bounds=[((- 1), 1), ((- 2), 2), ((- 3), 3), ((- 4), 4)], fixed=False) assert (pset.suggested_init == [0, 1, 2, 3, 4]) assert (pset.suggested_bounds == [((- 1), 1), ((- 2), 2)...
def bn_flops_counter_hook(module, input, output): input = input[0] batch_flops = np.prod(input.shape) if module.affine: batch_flops *= 2 module.__flops__ += int(batch_flops)
class VeRi3kParsingDataset(Dataset): CLASSES = ['background', 'front', 'back', 'roof', 'side'] def __init__(self, image_path, masks_path, augmentation=None, preprocessing=None, subset='trainval'): self.metas = [os.path.splitext(fname)[0] for fname in os.listdir(masks_path)] self.masks_path = Pat...
def test_double_fault_ones_zeros(example_diversity_ones_zeros): (y, y_pred_ones, y_pred_zeros) = example_diversity_ones_zeros df = double_fault(y, y_pred_ones, y_pred_zeros) assert (df == 0.0)
def state_dict_from_pretrained(model_name, device=None, dtype=None): mapped_device = ('cpu' if (dtype not in [torch.float32, None]) else device) is_sharded = False resolved_archive_file = cached_file(model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False) if (resolved_archive_file is None...
def draw_graph(ofolder, idx2lb, g_label, idx, prob): fpath = os.path.join(ofolder, '{}.npz'.format(idx)) ograph_folder = ('graph/' + ofolder.split('/')[(- 1)]) if (not os.path.exists(ograph_folder)): os.makedirs(ograph_folder) color_dict = {1: 'red', 0: 'lightblue'} (vertices, raw_edges) = l...
def gather(x, indices, axis, batch_dims): xshape = x.shape ishape = indices.shape bshape = xshape[:batch_dims] samples = np.prod(bshape).astype(int) x = x.reshape(((samples,) + xshape[batch_dims:])) indices = indices.reshape(((samples,) + ishape[batch_dims:])) y_list = [] for b in range(...
def get_type_str(*args) -> str: types = [] for i in args: if isinstance(i, (int, float, bytes, bytearray)): type_str = str(i.__class__.__name__) elif isinstance(i, np.ndarray): type_str = f'numpy.ndarray[{i.dtype}]' elif isinstance(i, list): inner = ',...
_utils.test() def test_struct_for_huge_offsets(): a = ti.field(dtype=ti.i32) offset = (1024, 2048, 2100, 2200) ti.root.dense(ti.ijkl, 4).place(a, offset=offset) def test(): for (i, j, k, l) in a: a[(i, j, k, l)] = (((i + (j * 10)) + (k * 100)) + (l * 1000)) test() for i in ra...
class FDEM_CrossCheck(unittest.TestCase): if testBH: def test_BH_CrossCheck_jxr(self): self.assertTrue(crossCheckTest(SrcList, 'b', 'h', ['CurrentDensity', 'x', 'r'], verbose=verbose, TOL=TOLEJHB)) def test_BH_CrossCheck_jyr(self): self.assertTrue(crossCheckTest(SrcList, 'b',...
class HoeffdingAdaptiveTreeClassifier(HoeffdingTreeClassifier): _ERROR_WIDTH_THRESHOLD = 300 def __init__(self, max_byte_size=, memory_estimate_period=1000000, grace_period=200, split_criterion='info_gain', split_confidence=1e-07, tie_threshold=0.05, binary_split=False, stop_mem_management=False, remove_poor_at...
def create_result_count(used_seed: int, dataset: Text, arch_config: Dict[(Text, Any)], results: Dict[(Text, Any)], dataloader_dict: Dict[(Text, Any)]) -> ResultsCount: xresult = ResultsCount(dataset, results['net_state_dict'], results['train_acc1es'], results['train_losses'], results['param'], results['flop'], arch...
class LLama2Engine(CausalEngine): config_name: str = 'llama2_engine' def __init__(self, weights_path: Optional[Union[(str, Path)]]=None): super().__init__(model_name='daryl149/llama-2-7b-chat-hf', weights_path=weights_path, trust_remote_code=True) self.tokenizer.pad_token = self.tokenizer.eos_to...
def retrieve_all(db_name): conn = sqlite3.connect(db_name) conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('SELECT * FROM bots order by created_at') data = [] rows = c.fetchall() for row in rows: data.append(list(row)) return data
.skipif((not cpp17), reason='ROOT was compiled without C++17 support') .parametrize('flatlist_as_rvec', [False, True]) def test_ByteMaskedArray_NumpyArray(flatlist_as_rvec): array = ak.contents.ByteMaskedArray(ak.index.Index(np.array([1, 0, 1, 0, 1], np.int8)), ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, ...
def test_extract_entities_from_sentence(): rt = ET.fromstring(SENTENCE_SAMPLE) entities = extract_entities_from_sentence(rt) assert (entities == EXPECTED_ENTITIES['1-p']['1.39-s']) rt = ET.fromstring(EMPTY_SENTENCE) entities = extract_entities_from_sentence(rt) assert (entities == [])
class AbstractDataset(ABC): def __init__(self, config, subset, num_classes): self.summaries = [] self.config = config self.subset = subset self.n_classes = num_classes self.use_bbox_guidance = config.bool('use_bbox_guidance', False) self.use_unsigned_distance_transfor...
def main(): max_cpu = mp.cpu_count() app_path = os.path.dirname(os.path.realpath(__file__)) parser = argparse.ArgumentParser(description='BLASYS -- Approximate Logic Synthesis Using Boolean Matrix Factorization') parser.add_argument('-i', '--input', help='Input verilog file', required=True, dest='input'...
class param(): def __init__(self, config): self.dataset_dir = (get_tc_path() + config['pre_dataset_dir']) self.parametrized_dir = (get_tc_path() + config['pre_output_dir']) self.output_dir = os.path.join(get_tc_path(), config['co_experiment_dir'], config['co_output_dir']) dataset_typ...
def extract_seconds(input_file, output_file): with open(input_file, 'r') as f: lines = f.readlines() log_created_year = get_log_created_year(input_file) start_datetime = get_start_time(lines, log_created_year) assert start_datetime, 'Start time not found' out = open(output_file, 'w') for...
def error(message: str) -> None: if (fenics.MPI.rank(fenics.MPI.comm_world) == 0): _cashocs_logger.error(message) fenics.MPI.barrier(fenics.MPI.comm_world)
class _SigmoidFocalLoss(Function): def forward(ctx, logits, targets, gamma, alpha): ctx.save_for_backward(logits, targets) num_classes = logits.shape[1] ctx.num_classes = num_classes ctx.gamma = gamma ctx.alpha = alpha losses = _C.sigmoid_focalloss_forward(logits, tar...
def get_args(): parser = argparse.ArgumentParser(description='Convert to tfrecords from numpy - Geofacies', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--dataset_path_input', type=str, required=True, default='', help='dataset path (numpy)') parser.add_argument('--dataset_pat...
def optimizer_kwargs(cfg): kwargs = dict(opt=cfg.opt, lr=cfg.lr, weight_decay=cfg.weight_decay, momentum=cfg.momentum) if (getattr(cfg, 'opt_eps', None) is not None): kwargs['eps'] = cfg.opt_eps if (getattr(cfg, 'opt_betas', None) is not None): kwargs['betas'] = cfg.opt_betas if (getattr...
def sigmoid_cross_entropy_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes): dy = grad_inputs[0] x0 = inputs[0] x1 = inputs[1] s0 = F.sigmoid(x0) dx0 = (dy * (s0 - x1)) return (dx0, None)
def sum_interaction_coefficients(n): N = (np.arange((n - 1)) + 2) coeff_dict = {} for K in powerset(N): coeff = 0 for S in powerset(K): if (len(S) == 0): continue num = int(np.math.pow((- 1), (len(S) + 1))) denom = (((len(K) - len(S)) + 1) ...
.parametrize('max_timestep', [3]) .parametrize('embed_dim', [256]) .parametrize('context_size', [10]) .parametrize('batch_size', [32]) def test_global_position_encoding(max_timestep: int, embed_dim: int, context_size: int, batch_size: int) -> None: model = GlobalPositionEncoding(embed_dim, max_timestep, context_siz...
def rescale_l8(img: ee.Image) -> ee.Image: opt = img.select(['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2']) therm = img.select('TEMP1') qa = img.select('pixel_qa') opt = opt.updateMask(opt.gte(0)).clamp(0, 10000) opt = opt.multiply(0.0001) therm = therm.multiply(0.1) scaled = ee.Image.cat...