code
stringlengths
101
5.91M
class FreeModule_submodule_with_basis_pid(FreeModule_generic_pid): def __init__(self, ambient, basis, check=True, echelonize=False, echelonized_basis=None, already_echelonized=False, category=None): if (not isinstance(ambient, FreeModule_ambient_pid)): raise TypeError(('ambient (=%s) must be amb...
def test_load_arff_from_gzip_file_error_parser(): err_msg = "Unknown parser: 'xxx'. Should be 'liac-arff' or 'pandas'" with pytest.raises(ValueError, match=err_msg): load_arff_from_gzip_file('xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx')
def create_instance_layout(state) -> html.Div: if (state.instances is not None): figure = plot_one_instance(state.instances, state.get_display_instance('local')) return html.Div(id='info_card', children=[html.B('Query Instance'), html.Hr(), html.Center(id='instance_table', children=figure)]) els...
def gen_restore_seq_with_ratio(device, cl_setting, abbrs, lm_model, ratio, use_gt=False, with_token=True, tr_perc=None, setting_idx=1, **kwargs): root_dir = kwargs.get('root_dir', '/Users/stan') print(f'ROOT={root_dir}') print(f'DEVICE={device}') tmpl = 'if [ ! -f "{}" ] ; then \n CUDA_VISIBLE_DEVICES=$...
class StepParamScheduler(ParamScheduler): def __init__(self, num_updates: Union[(int, float)], values: List[float]) -> None: if (num_updates <= 0): raise ValueError('Number of updates must be larger than 0') if (not (isinstance(values, Sequence) and (len(values) > 0))): raise...
def get_global_knowledge(args): global_knowledge = '' if (args.shared_knowledge_file is not None): with open(args.shared_knowledge_file, 'r') as f: global_knowledge = f.read() global_knowledge = knowledge_parser(global_knowledge) return global_knowledge
class DeHazeDatasetFromFolderTest(data.Dataset): def __init__(self, image_dir, nFrames, upscale_factor, file_list, other_dataset, future_frame, transform=None): super(DeHazeDatasetFromFolderTest, self).__init__() self.nFrames = nFrames self.upscale_factor = upscale_factor self.transf...
class LayerNorm(nn.Module): def __init__(self, size, eps=1e-06): super(LayerNorm, self).__init__() self.eps = eps self.a_2 = nn.Parameter(torch.ones(size)) self.b_2 = nn.Parameter(torch.zeros(size)) def forward(self, x): mean = x.mean((- 1), keepdim=True) std = x....
.parametrize('ctx, solver_name', ctxs) .parametrize('decay', [0.0001]) .parametrize('lr', [0.1, 0.001]) .parametrize('momentum', [0.9, 0.5]) .parametrize('coefficient', [0.001]) .parametrize('eps', [1e-08]) .parametrize('seed', [313]) def test_lars(seed, lr, momentum, coefficient, decay, eps, ctx, solver_name): rng...
def instance_builder(toposort: List[BaseNode], wrapper: Callable=None) -> Dict[(BaseNode, Layer)]: nodes_dict = dict() for n in toposort: if (not n.reuse): keras_node = node_builder(n) if (wrapper is not None): keras_node = wrapper(n, keras_node) nodes...
class BeatREMI(BaseEventREMI): def __init__(self, is_bar, bar, position, start_time, duration): super().__init__('beat', bar, position) self.is_bar = is_bar self.start_time = start_time self.duration = duration self.segment_tag = None def __repr__(self): return '[...
class AbsoluteValue(Function): node_type = 'goos.function.abs' def __init__(self, fun: Function) -> None: super().__init__(fun) def eval(self, input_vals: List[goos.NumericFlow]) -> goos.NumericFlow: val = copy.deepcopy(input_vals[0]) val.array = np.abs(val.array) return val ...
class AutoTokenizer(): def __init__(self): raise EnvironmentError('AutoTokenizer is designed to be instantiated using the `AutoTokenizer.from_pretrained(pretrained_model_name_or_path)` method.') _list_option_in_docstrings(TOKENIZER_MAPPING_NAMES) def from_pretrained(cls, pretrained_model_name_or_pat...
def main(): for (filt, st, nt) in itertools.product(('none', 'contains-hole'), ('cov-xent', 'cov-examples'), (10, 20, 40, 80)): steps = list(range(100, 2600, 100)) args = "{{filt: '{filt}', st: '{st}', nt: {nt}}}".format(filt=filt, st=st, nt=nt) logdir = os.path.join('logdirs/-hs-allmatches-...
class Conv1DWithMasking(Conv1D): def __init__(self, **kwargs): self.supports_masking = True super(Conv1DWithMasking, self).__init__(**kwargs) def compute_mask(self, x, mask): return mask
class CartoonGAN(object): def __init__(self, sess, args): self.model_name = 'CartoonGAN' self.sess = sess self.checkpoint_dir = args.checkpoint_dir self.result_dir = args.result_dir self.log_dir = args.log_dir self.dataset_name = args.dataset self.augment_flag...
def assert_and_infer_cfg(cache_urls=True, make_immutable=True): if (__C.MODEL.RPN_ONLY or __C.MODEL.FASTER_RCNN): __C.RPN.RPN_ON = True if (__C.RPN.RPN_ON or __C.RETINANET.RETINANET_ON): __C.TEST.PRECOMPUTED_PROPOSALS = False if cache_urls: cache_cfg_urls() if make_immutable: ...
def TAGMUtil_ConnectCmtyVV(CmtyVV, CIDSzPrV, NIDMemPrV, Rnd): return _snap.TAGMUtil_ConnectCmtyVV(CmtyVV, CIDSzPrV, NIDMemPrV, Rnd)
class SequencialIterator(object): def __init__(self, files): self.files = files types = map((lambda x: x['text_type']), files) self.preprocessor = Preprocessing(types) def __iter__(self): for f in self.files: max_sentences = f['max_sentences'] file = open_...
class Parameter(): seed: int use_ema: bool ema_decay: float max_epochs: int tensorboard_dir: str RANK: int
def run(argv=None): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() group.add_argument('-s', '--shared', action='store_true', help='create a shared lock') group.add_argument('-x', '--exclusive', action='store_true', help='create an exclusive lock (the ...
def test_case86(): url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert') headers = {'Content-Type': 'application/json', 'Accept': 'application/ld+json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'} r = requests.post(url, data=json.dumps(ld_data.upsertCommand), headers=headers) url = (disco...
def resnet101v6(pthfile, device=None): if (device is None): if torch.cuda.is_available(): warnings.warn('device not defined in resnet101v6, assigning to first CUDA visible device.') device = torch.device('cuda') else: device = torch.device('cpu') model = ResNe...
def recalculate_moving_avgs(flow, train_loader, device): with torch.no_grad(): flow.eval() print('Recalculating moving averages for batch norm layers.') flow.start_averaging() for (h, x) in train_loader: if (device is not None): h = h.to(device, non_blocki...
def main(): filter_r = regex.compile("[^\\p{L}\\p{N}\\p{M}\\' \\-]") for line in sys.stdin: line = line.strip() line = filter_r.sub(' ', line) line = ' '.join(line.split()) print(line)
def init_property_of_dataset(): global gold_heads, gold_tails, gold_relations global candidate_heads, candidate_tails global train_link, aux_link trace('load train') for line in open(args.train_file): items = line.strip().split('\t') items = list(map(int, items)) (h, r, t) = ...
def test_scimodel_keras_optimizers(variable_x, variable_y, functional_fx, functional_gx): xs = [variable_x, variable_y] ys = [functional_fx, functional_gx] assert isinstance(sn.SciModel(xs, ys, 'mse', tf_optimizers.Adam()), sn.SciModel) assert isinstance(sn.SciModel(xs, ys, 'mse', tf_optimizers.RMSprop(...
_method class HeckeSubmodule(module.HeckeModule_free_module): def __init__(self, ambient, submodule, dual_free_module=None, check=True): from . import ambient_module if (not isinstance(ambient, ambient_module.AmbientHeckeModule)): raise TypeError('ambient must be an ambient Hecke module'...
.parametrize('family', 'CLUQJ') def test_constant_inner(family): D = FunctionSpace(6, family, alpha=1, beta=2) for quad in quads[D.family()]: q = inner(1, Array(D, buffer=(x ** 2))) assert (abs((q - (2 / 3))) < 1e-08)
class GNN(torch.nn.Module): def __init__(self, num_tasks=1, num_layers=5, emb_dim=300, gnn_type='gin', virtual_node=True, residual=False, drop_ratio=0, JK='last', graph_pooling='sum'): super(GNN, self).__init__() self.num_layers = num_layers self.drop_ratio = drop_ratio self.JK = JK ...
def _bench(args): rng = np.random.RandomState(412) (m, M) = ((- 1), 1) B = args.batch_size G0 = args.grid_size_base gf = args.growth_factor T0 = args.table_size_base L = args.n_levels D = args.feature_size query_data = (m + (rng.rand(B, 3) * (M - m))) query = nn.Variable.from_num...
def get_parent_sentence(doc, char_start, char_end): offsets = [s.abs_char_offsets[0] for s in doc.sentences] for i in range((len(offsets) - 1)): if ((char_start >= offsets[i]) and (char_end <= offsets[(i + 1)])): return doc.sentences[i] return doc.sentences[(i + 1)]
def svd(A, eps_or_k, rand=True): from scipy.sparse.linalg import LinearOperator real = _is_real(A) if isinstance(A, np.ndarray): if (eps_or_k < 1): eps = eps_or_k if rand: if real: (U, V, S) = backend.iddp_asvd(eps, A) else:...
def parse_if_range_header(value): if (not value): return IfRange() date = parse_date(value) if (date is not None): return IfRange(date=date) return IfRange(unquote_etag(value)[0])
class Result(): outputs: torch.Tensor loss: torch.Tensor batch_dim = 0 def plot(self) -> Dict[(str, Any)]: return {} def batch_size(self) -> int: return self.outputs.shape[self.batch_dim] def merge(l: List, batch_weights: Optional[List[float]]=None): if (len(l) == 1): ...
class DauphinTransform(object): def __init__(self, name=None, prob=1.0, level=0): self.name = (name if (name is not None) else type(self).__name__) self.prob = prob assert (0 <= level <= 1.0), 'Invalid level, level must be in [0, 1.0].' self.level = level def transform(self, text...
def conv3x3(in_planes, out_planes, stride=1, atrous=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=(1 * atrous), dilation=atrous, bias=False)
class SimModelTestCase(unittest.TestCase): def test_w2v_sim_batch(self): model_name = 'w2v-light-tencent-chinese' print(model_name) m = Similarity(model_name, similarity_type=SimilarityType.COSINE, embedding_type=EmbeddingType.WORD2VEC) test_path = os.path.join(pwd_path, '../examples...
def write_model_card(hf_model_name: str, repo_root=DEFAULT_REPO, save_dir=Path('marian_converted'), dry_run=False, extra_metadata={}) -> str: import pandas as pd hf_model_name = remove_prefix(hf_model_name, ORG_NAME) opus_name: str = convert_hf_name_to_opus_name(hf_model_name) if (repo_root not in ('OPU...
def test_fails_on_negative_limit(): parser = _get_command_line_parser(['DemoDetector'], [], []) assert_raises(SystemExit, parser.parse_args, ['publish', 'ex2', 'DemoDetector', '-s', 'site', '--limit', '-1'])
def find_thres(cm, percentage): n = (int((len(cm) * (1.0 - percentage))) - 1) con = sorted(get_neighboring_connectivity(cm)) return con[n]
def slice_data_grad_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, start=None, stop=None, step=None): gdx = grad_inputs[0] gdy = F.slice(gdx, start, stop, step) return gdy
def prepare_data(config, model, test_run): batch_size = config.get('batch_size', 1024) num_workers = config.get('num_workers', default_workers) dataset = data.get_dataset_by_name(config['data'])(sampling_rate=100, component_order='ZNE', dimension_order='NCW', cache='full') restrict_to_phase = config.get...
def p_simple_statement(s, first_statement=0): if (s.sy == 'global'): node = p_global_statement(s) elif (s.sy == 'nonlocal'): node = p_nonlocal_statement(s) elif (s.sy == 'print'): node = p_print_statement(s) elif (s.sy == 'exec'): node = p_exec_statement(s) elif (s.sy...
def t5_3b_tied_lmheads_512_4_8p_bw12_async_squad1_pipedream(): return dict(model_type='t5_stateless', model_name_or_path='t5-3b', do_lower_case=False, output_past=False, output_attentions=False, output_hidden_states=False, do_resize_token_embedding=True, explicitly_set_dict={'output_only': True, 'output_attentions'...
def add_prefix(name, prefix=None, split='.'): if (prefix is not None): return '{}{}{}'.format(prefix, split, name) else: return name
def dictConvert(inDict): key_list = list(inDict.keys()) out = {} for t in key_list: D = inDict[t].split('_') out.update({t: [D[0], int((100 * float(D[1]))), int((100 * float(D[2]))), D[3]]}) return out
def has_onnx(model_type): config_mapping = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING if (model_type not in config_mapping): return False config = config_mapping[model_type] config_module = config.__module__ module = transformers_module for part in config_module.sp...
def _reload_instrumentation_loader(coverage_metrics: set[config.CoverageMetric], dynamic_constant_provider: (DynamicConstantProvider | None), tracer: ExecutionTracer): module_name = config.configuration.module_name module = importlib.import_module(module_name) tracer.current_thread_identifier = threading.cu...
class EllipticCurvePoint_finite_field(EllipticCurvePoint_field): def _magma_init_(self, magma): E = self.curve()._magma_init_(magma) (x, y) = self.xy() return ('%s![%s,%s]' % (E, x, y)) def _acted_upon_(self, other, side): k = ZZ(other) E = self.curve() try: ...
def adjust_learning_rate(optimizer, epoch, lr=0.01, step1=30, step2=60, step3=90): if (epoch >= step3): lr = (lr * 0.001) elif (epoch >= step2): lr = (lr * 0.01) elif (epoch >= step1): lr = (lr * 0.1) else: lr = lr for param_group in optimizer.param_groups: pa...
def h_maxima(image, h, footprint=None): if (h > np.ptp(image)): return np.zeros(image.shape, dtype=np.uint8) if (np.issubdtype(type(h), np.floating) and np.issubdtype(image.dtype, np.integer)): if ((h % 1) != 0): warn('possible precision loss converting image to floating point. To si...
def test_exclusive_policy_negative_examples_1(digraph, features_1d, labels): policy = ExclusivePolicy(digraph, features_1d, labels) ground_truth = [False, False, True, True, True, True, True, True] result = policy.negative_examples('1') assert_array_equal(ground_truth, result)
.parametrize('name, location, exists', (('X-Key', 'header', True), ('X-Key2', 'header', False), ('X-Key', 'cookie', False), ('X-Key', 'query', False), ('key', 'query', True), ('bla', 'body', False), ('body', 'body', True), ('unknown', 'unknown', False))) def test_get_parameter(empty_open_api_3_schema, name, location, e...
def clear_class_registry(): torch._C._jit_clear_class_registry() torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore() torch.jit._state._clear_class_state()
class TileDescription(): def __init__(self, threadblock_shape, stages, warp_count, math_instruction, min_compute, max_compute, cluster_shape=[1, 1, 1]): self.threadblock_shape = threadblock_shape self.stages = stages self.warp_count = warp_count self.math_instruction = math_instructi...
def test__minimize_assertions(): config.configuration.test_case_output.assertion_generation = config.AssertionGenerator.CHECKED_MINIMIZING result = MagicMock() with mock.patch.object(result, 'accept') as result_accept_mock: gen._minimize_assertions(result) result_accept_mock.assert_called_on...
def order_sim(im, s): YmX = (s.unsqueeze(1).expand(s.size(0), im.size(0), s.size(1)) - im.unsqueeze(0).expand(s.size(0), im.size(0), s.size(1))) score = (- YmX.clamp(min=0).pow(2).sum(2).sqrt().t()) return score
def main(): (x, y) = Reals('x y') soft_constraints = [(x > 2), (x < 1), (x < 0), Or(((x + y) > 0), (y < 0)), Or((y >= 0), (x >= 0)), Or((y < 0), (x < 0)), Or((y > 0), (x < 0))] hard_constraints = BoolVal(True) solver = MSSSolver(hard_constraints, soft_constraints) for lits in enumerate_sets(solver):...
class AudioPlayer(): def __init__(self, wav): self.p = pyaudio.PyAudio() self.pos = 0 self.stream = None self._open(wav) def callback(self, in_data, frame_count, time_info, status): data = self.wf.readframes(frame_count) self.pos += frame_count return (dat...
def _configure_logging(args): kwargs = {'format': '%(asctime)s %(levelname)-8s %(message)s', 'datefmt': '%Y-%m-%d %H:%M', 'level': (logging.DEBUG if args.debug else logging.INFO)} if (args.log_file is not None): kwargs['filename'] = args.log_file logging.basicConfig(**kwargs)
def get_sentences_html(doc, language): html_strings = [] nlp = spacy.blank('en') sentences_to_visualize = [] for sentence in doc.sentences: (words, lemmas, heads, deps, tags) = ([], [], [], [], []) if is_right_to_left(language): sent_len = len(sentence.words) for ...
class AllToAllOp(torch.autograd.Function): def forward(ctx, x, output_split_sizes, input_split_sizes, group, async_op): out = torch.empty(((sum(output_split_sizes),) + x.shape[1:]), device=x.device, dtype=x.dtype) ctx.input_shape = x.shape ctx.output_split_sizes = output_split_sizes ...
def getSubsetCore(num_samples, seed, embeddings_file, labels_file, balanced): labels_raw = pd.read_csv(labels_file) labels_raw = labels_raw.astype('int32') labels_raw['btype'] = labels_raw['btype'].values.astype('int8') labels_raw['rtype'] = labels_raw['rtype'].values.astype('int8') btype_targets = ...
def complete_text(prompt, log_file, model, **kwargs): if model.startswith('claude'): completion = complete_text_claude(prompt, stop_sequences=[anthropic.HUMAN_PROMPT, 'Observation:'], log_file=log_file, model=model, **kwargs) elif ('/' in model): completion = complete_text_crfm(prompt, stop_sequ...
def load_audio_input(elem: Dict[(str, Any)], model_cfg=CLAP_MODEL_CFG, enable_fusion=False, target_sr=48000) -> Dict[(str, Any)]: f = elem['file'] (audio_waveform, _) = read_wav(f, target_sr=target_sr) audio_waveform = int16_to_float32(float32_to_int16(audio_waveform)) audio_waveform = torch.from_numpy(...
def get_full_output_dir(output_dir): os.makedirs(output_dir, exist_ok=True) return output_dir
def check_output_types(self, func, ref_outputs, args, kwargs): graph = getattr(func, 'last_graph', None) types = [o.type() for o in graph.outputs()] self.assertTrue((len(types) == 1)) t = types[0] torch._C._jit_assert_is_instance(ref_outputs, t)
def CalculateDistributionSecondaryStr(ProteinSequence): result = CalculateDistribution(ProteinSequence, _SecondaryStr, '_SecondaryStr') return result
def _get_compute_cap(device): caps_str = device.physical_device_desc m = re.search('compute capability: (\\d+).(\\d+)', caps_str) major = m.group(1) minor = m.group(2) return (major, minor)
class LayerNormLinearFn(torch.autograd.Function): _fwd def forward(ctx, x, norm_weight, norm_bias, linear_weight, linear_bias, residual=None, eps=1e-06, prenorm=False, residual_in_fp32=False, is_rms_norm=False): x_shape_og = x.shape x = x.reshape((- 1), x.shape[(- 1)]) if (x.stride((- 1)...
class JasperEncoder(nn.Module): def __init__(self, config: JasperEncoderConfig, device: torch.device) -> None: super(JasperEncoder, self).__init__() self.config = config self.device = device self.layers = nn.ModuleList() self.layers.append(JasperSubBlock(in_channels=self.conf...
(data=st.data()) (deadline=None, suppress_health_check=SUPPRESSED_HEALTH_CHECKS, max_examples=MAX_EXAMPLES) def test_no_unsatisfiable_schemas(data): schema = {'type': 'object', 'required': ['foo']} mutated_schema = data.draw(mutated(schema, {}, location='body', media_type='application/json')) assert (canoni...
class FindNgrams(): def __init__(self, min_count=0, min_pmi=0, language='en'): self.min_count = min_count self.min_pmi = min_pmi self.words = defaultdict(int) (self.ngrams, self.pairs) = (defaultdict(int), defaultdict(int)) self.total = 0.0 self.language = language ...
(base=10) def plot_loglog(funcs, *args, **kwds): return plot(funcs, *args, scale='loglog', **kwds)
def test_z(): circuit = Circuit(1) circuit.z(0) expect = array([[1, 0], [0, (- 1)]]) assert array_equal(expect, circuit.get_unitary_matrix())
class OpenAIGPTForSequenceClassification(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test_synthetic_slate_obtain_batch_bandit_feedback_using_linear_behavior_policy_without_pscore_item_position(): n_unique_action = 80 len_list = 3 dim_context = 2 reward_type = 'binary' random_state = 12345 n_rounds = 100 dataset = SyntheticSlateBanditDataset(n_unique_action=n_unique_actio...
class ResNeSt(nn.Module): def __init__(self, last_stride, block, layers, radix=1, groups=1, bottleneck_width=64, dilated=False, dilation=1, deep_stem=False, stem_width=64, avg_down=False, rectified_conv=False, rectify_avg=False, avd=False, avd_first=False, final_drop=0.0, dropblock_prob=0, last_gamma=False, norm_la...
def main(): args = parse_args() if args.out: out_suffix = args.out.split('.')[(- 1)] assert args.out.endswith('.sh'), f'Expected out file path suffix is .sh, but get .{out_suffix}' assert (args.out or args.run), 'Please specify at least one operation (save/run/ the script) with the argument ...
class AverageMeter(object): def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += (...
def synset2idx(path_to_yaml='data/index_synset.yaml'): with open(path_to_yaml) as f: di2s = yaml.load(f) return dict(((v, k) for (k, v) in di2s.items()))
class MagicPoint(BaseModel): input_spec = {'image': {'shape': [None, None, None, 1], 'type': tf.float32}} required_config_keys = [] default_config = {'data_format': 'channels_first', 'kernel_reg': 0.0, 'grid_size': 8, 'detection_threshold': 0.4, 'homography_adaptation': {'num': 0}, 'nms': 0, 'top_k': 0} ...
def print_mem(info=None): if info: print(info, end=' ') mem_allocated = round((torch.cuda.memory_allocated() / 1048576)) mem_cached = round((torch.cuda.memory_cached() / 1048576)) print(f'Mem allocated: {mem_allocated}MB, Mem cached: {mem_cached}MB')
class ValueFnTests(tf.test.TestCase): def test_label_attention_fn(self): with self.test_session(): mode = tf.estimator.ModeKeys.TRAIN label_embeddings = tf.constant([[0.1, 0.1, 0.1, 0.1], [0.3, 0.3, 0.3, 0.3], [0.5, 0.5, 0.5, 0.5], [10, 10, 10, 10], [1.0, 1.0, 1.0, 1.0]]) ...
def conv_block(input_mat, num_filters, kernel_size, batch_norm): X = Conv2D(num_filters, kernel_size=(kernel_size, kernel_size), strides=(1, 1), padding='same')(input_mat) if batch_norm: X = BatchNormalization()(X) X = Activation('relu')(X) X = Conv2D(num_filters, kernel_size=(kernel_size, kerne...
class TestLinalg(TestCase): exact_dtype = True ((not TEST_NUMPY), 'NumPy not found') ({torch.bfloat16: 0.1}) (*torch.testing.get_all_dtypes()) def test_outer(self, device, dtype): def run_test_case(a, b): if (dtype == torch.bfloat16): a_np = a.to(torch.double).cpu...
class DummyOntology_Generic(): def get_children(self, parent_code: str) -> List[str]: if (parent_code == 'OMOP_CONCEPT_A'): return ['OMOP_CONCEPT_A_CHILD', 'OMOP_CONCEPT_A_CHILD2'] elif (parent_code == 'OMOP_CONCEPT_B'): return ['OMOP_CONCEPT_B_CHILD'] elif (parent_co...
def test_eval_chebyt(): n = np.arange(0, 10000, 7, dtype=np.dtype('long')) x = ((2 * np.random.rand()) - 1) v1 = np.cos((n * np.arccos(x))) v2 = _ufuncs.eval_chebyt(n, x) assert_(np.allclose(v1, v2, rtol=1e-15))
def ref_grad_clip_grad_by_value(x, min_, max_, dy, **kw): dx = dy idx_min = np.where((dy < min_)) idx_max = np.where((dy > max_)) dx[idx_min] = min_[idx_min] dx[idx_max] = max_[idx_max] return dx.flatten()
class TorchSequentialValidationBatch(NamedTuple): query_id: torch.LongTensor padding_mask: torch.BoolTensor features: TensorMap ground_truth: torch.LongTensor train: torch.LongTensor
class MNRParaphraseTrainer(): def __init__(self, args: MNRParaphraseArgs): self.args = args self.base_model = models.Transformer(self.args.model) self.pooler = self._create_pooler() def train(self): model = SentenceTransformer(modules=[self.base_model, self.pooler]) loss ...
_numpy_output(non_zero=True, check_dtype=True) def test_ufunc_tan_u(A: dace.uint32[10]): return np.tan(A)
def _lookup_app_object(name): top = _app_ctx_stack.top if (top is None): raise RuntimeError(_app_ctx_err_msg) return getattr(top, name)
def register_scheduler(key: str, module: Any=None): return register_base(scheduler_dict, key, module)
def build_backbone(in_channels, backbone, output_stride, BatchNorm, Fusion=False): return resnet.ResNet50(in_channels, output_stride, BatchNorm, pretrained=False, Fusion=Fusion)
def get_reduction_schedule(in_array: Array, axes: List[int], use_vectorization=True, use_mini_warps=True, warp_size=32, wide_load_bytes=16): class ReductionSchedule(): grid: List[Size] block: List[Size] sequential: List[Size] shared_mem_size: int in_shape: List[Size] ...
def show_im_bboxes(k, coordinates): im = np.array(Image.open('../images/{}.jpg'.format(k)), dtype=np.uint8) height = im.shape[0] width = im.shape[1] (fig, ax) = plt.subplots(1) ax.imshow(im) colors = ['red', 'yellow', 'black', 'blue', 'orange', 'grey', 'cyan', 'green', 'purple'] for coordina...
class FNetTokenizerFast(metaclass=DummyObject): _backends = ['tokenizers'] def __init__(self, *args, **kwargs): requires_backends(self, ['tokenizers'])
class SSIM(torch.nn.Module): def __init__(self, window_size=11, size_average=True): super(SSIM, self).__init__() self.window_size = window_size self.size_average = size_average self.channel = 1 self.window = create_window(window_size, self.channel) def forward(self, img1,...