code
stringlengths
101
5.91M
def main(): parser = argparse.ArgumentParser(description='Prepare SCROLLS predictions') parser.add_argument('--output_dir', type=str, help='Path to output the predictions file', required=True) parser.add_argument('--qmsum_file', type=str, help='The path to the qmsum dataset json file containing predictions'...
class SSHClient(): def __init__(self, ip_address, ssh_credentials): self.ip_address = ip_address self.ssh_credentials = ssh_credentials self.ssh_client = None if ('key_filename' in self.ssh_credentials): fpath = os.path.expanduser(self.ssh_credentials['key_filename']) ...
def _standardize_domains_of_(systems): identical_domains = True for ds in systems: if (ds.domain() != systems[0].domain()): identical_domains = False break over_number_fields = True all_over_QQ = True for ds in systems: if (ds.base_ring() not in NumberFields()...
_builder('webvid2m_caption_instruct') class WebVid2MCapInstructBuilder(BaseDatasetBuilder): train_dataset_cls = WebVideoCaptionInstructDataset DATASET_CONFIG_DICT = {'default': 'configs/datasets/webvid/defaults_cap_instruct.yaml'}
def unflatten_linear_layers(prefix, statedict: StateDict, layer: hnn.Linear, out_dims_first_in_dict: Optional[bool]) -> StateDict: ret_dict: StateDict = {} def _unflatten_linear(layer, prefix): nonlocal out_dims_first_in_dict if (not isinstance(layer, hnn.Linear)): return layer ...
def clone_model(model, input_tensors=None): if isinstance(model, Sequential): return _clone_sequential_model(model, input_tensors=input_tensors) else: return _clone_functional_model(model, input_tensors=input_tensors)
def test_incompatible_shapes_raise_valueerror(): data = [[(3,), (4,)], [(2, 3), (2,)], [(3,), (3,), (4,)], [(1, 3, 4), (2, 3, 3)]] for input_shapes in data: assert_incompatible_shapes_raise(input_shapes) assert_incompatible_shapes_raise(input_shapes[::(- 1)])
def test_divmod(): value = 7 proxy = tt.ObjectProxy(value) assert (divmod(value, 3) == divmod(proxy, 3)) assert (int in tt.UsageTraceNode.from_proxy(proxy).children['__divmod__'].arg_types[0])
def curves_with_j_0_char3(K): if ((not K.is_finite()) or (K.characteristic() != 3)): raise ValueError('field must be finite of characteristic 3') b = None while ((not b) or (not b.trace())): b = K.random_element() if (K.degree() % 2): return [EllipticCurve(K, a4a6) for a4a6 in [[...
class MutualInformation(ConfusionMatrixMetric): def __init__(self, metric: str='MUTINF'): super().__init__(metric) def calculate(self): tp = self.confusion_matrix.tp tn = self.confusion_matrix.tn fp = self.confusion_matrix.fp fn = self.confusion_matrix.fn n = self...
_function def get_cython_cache_dir(): if ('CYTHON_CACHE_DIR' in os.environ): return os.environ['CYTHON_CACHE_DIR'] parent = None if (os.name == 'posix'): if (sys.platform == 'darwin'): parent = os.path.expanduser('~/Library/Caches') else: parent = os.environ.g...
('/list_combiners_data', methods=['POST']) def list_combiners_data(): json_data = request.get_json() combiners = json_data.get('combiners', None) try: response = api.list_combiners_data(combiners) except TypeError as e: return (jsonify({'success': False, 'message': str(e)}), 400) ret...
def create_split_tone_node(node_tree: bpy.types.NodeTree) -> bpy.types.Node: split_tone_node_group = add_split_tone_node_group() node = node_tree.nodes.new(type='CompositorNodeGroup') node.name = 'SplitTone' node.node_tree = split_tone_node_group return node
def posat(context, builder, pos, offset): return builder.add(pos, context.get_constant(numba.intp, offset))
def subst(pattern: List[str], rule_symbol: str, substitute_str: str) -> List[str]: assert (rule_symbol in pattern) indices = [i for (i, x) in enumerate(pattern) if (x == rule_symbol)] new_string = (pattern[:indices[0]] + [substitute_str]) for (i, j) in zip(indices[:(- 1)], indices[1:]): new_stri...
class WFRadiationMeshXMin(RadiationField): glossary_name = 'params/Mesh/xMin' def __init__(self, wf): super(WFRadiationMeshXMin, self).__init__(wf) def value(self): if (self._wf.params.wSpace == 'R-space'): return self._wf._srwl_wf.mesh.xStart else: warnings.w...
class CustomTextDatasetForGenLatentSpace(Dataset): def __init__(self, df, tokenizer, split: str, in_memory: bool=False, train_ratio: float=1, omitted_labels=None, reduced_labels=None, reduced_labels_keep_num=None): self.tokenizer = tokenizer if (split == 'valid'): file_prefix = 'train' ...
def arg_parse(): parser = argparse.ArgumentParser(description='AD-GCL ZINC') parser.add_argument('--dataset', type=str, default='zinc', help='Dataset') parser.add_argument('--full', default=False, action='store_true', help='Flag to use full zinc dataset') parser.add_argument('--model_lr', type=float, de...
def multihead_attention(queries, keys, values, num_units=None, num_heads=1, dropout_keep_prob=1, is_training=True, has_residual=True): if (num_units is None): num_units = queries.get_shape().as_list[(- 1)] Q = tf.layers.dense(queries, num_units, activation=tf.nn.relu) K = tf.layers.dense(keys, num_u...
class LeNet5(nn.Module): def __init__(self, input_channels, imsize, output_dim): super(LeNet5, self).__init__() self.input_channels = input_channels self.imsize = imsize self.output_dim = output_dim assert ((imsize % 2) == 0) self.cnn = nn.Sequential(OrderedDict([('co...
def eval_default_scale_factor(actf, lay): if (actf in ('linear', 'relu')): return 2.0 elif (actf in ('tanh', 'sigmoid')): return (1.0 if (lay > 0) else 1.0) elif (actf in ('sin', 'cos')): return (2.0 if (lay > 0) else 2.0) else: return 1.0
class _data_matrix(spmatrix): def __init__(self): spmatrix.__init__(self) def _get_dtype(self): return self.data.dtype def _set_dtype(self, newtype): self.data.dtype = newtype dtype = property(fget=_get_dtype, fset=_set_dtype) def _deduped_data(self): if hasattr(self,...
def train(net, optimizer, trainloader): net.train() losses = AverageMeter() torch.cuda.empty_cache() loss_all = 0 for (data, labels, _) in tqdm(trainloader): (data, labels) = (data.cuda(), labels.cuda()) optimizer.zero_grad() (embedding, logits) = net(data, True) (_, ...
def rollout(env_name, num_steps=128, use_expert=False, seed=1): env_fn = envs.create_fn(env_name) env = env_fn(batch_size=1, episode_length=(num_steps * 2), auto_reset=False) env.step = jax.jit(env.step) if (not use_expert): parametric_action_distribution = distribution.NormalTanhDistribution(ev...
def test_contains(): proxy = tt.ObjectProxy([42]) assert (42 in proxy) assert (int in tt.UsageTraceNode.from_proxy(proxy).children['__contains__'].arg_types[0])
def construct_beta_hats(opt_beta, sensitivity, eps_list, max_norm): beta_hats = noise_reduc.gen_list(opt_beta, sensitivity, eps_list) for i in range(len(beta_hats)): beta_hats[i] = project.two_norm_project(beta_hats[i], max_norm) return beta_hats
class MyMultiSectionFactory(MultiSectionFactory): def __init__(self, main_file_name, modules): super(MyMultiSectionFactory, self).__init__() self.main_file_name = main_file_name self.main_sink = FileCodeSink(open(main_file_name, 'wt')) self.header_name = 'ns3module.h' header_...
def test_gmm_wrong_descriptor_format_3(): with pytest.raises(DescriptorException): learn_gmm([np.zeros((5, 10)), np.zeros((4, 10, 1))], n_modes=1)
def new(): t_AND = '\\&' t_ANDAND = '\\&\\&' t_ANDEQ = '\\&=' t_BACKSLASH = '\\\\' t_COLON = ':' t_DIV = '\\/' t_DIVEQ = '\\/=' t_DOT = '\\.' t_DOTDIV = '\\./' t_DOTDIVEQ = '\\./=' t_DOTEXP = '\\.\\^' t_DOTMUL = '\\.\\*' t_DOTMULEQ = '\\.\\*=' t_EQ = '=' t_EQE...
def AUROC(open_set_preds, open_set_labels): auroc = roc_auc_score(open_set_labels, open_set_preds) return auroc
def horizontally_flip_bbox(bbox: BoundingBox) -> BoundingBox: return ((1 - (bbox[0] + bbox[2])), bbox[1], bbox[2], bbox[3])
class MatFile5Writer(): def __init__(self, file_stream, do_compression=False, unicode_strings=False, global_vars=None, long_field_names=False, oned_as='row'): self.file_stream = file_stream self.do_compression = do_compression self.unicode_strings = unicode_strings if global_vars: ...
class ClusterGCN(GCN): def __init__(self, layer_sizes, activations, generator, bias=True, dropout=0.0, kernel_initializer='glorot_uniform', kernel_regularizer=None, kernel_constraint=None, bias_initializer='zeros', bias_regularizer=None, bias_constraint=None): warnings.warn('ClusterGCN has been replaced by ...
def test_IndexedArray_RecordArray_NumpyArray(): a = ak.contents.indexedarray.IndexedArray(ak.index.Index(np.array([2, 2, 0, 1, 4, 5, 4])), ak.contents.recordarray.RecordArray([ak.contents.numpyarray.NumpyArray(np.array([1.1, 2.2, 3.3, 4.4, 5.5, 6.6]))], ['nest'])) assert (a.to_typetracer().form == a.form) a...
class AbstractLanguage(Parent): def __init__(self, alphabet=None, category=None): if isinstance(alphabet, (int, Integer)): from sage.sets.integer_range import IntegerRange alphabet = IntegerRange(1, (alphabet + 1)) elif ((alphabet == 'integers') or (alphabet == 'positive inte...
class SimpleModel2(Model): def __init__(self, output_dim=2, hidden_sizes=(4, 4), name=None): super().__init__(name) self._output_dim = output_dim self._hidden_sizes = hidden_sizes def _build(self, obs_input, name=None): del name action = mlp(obs_input, self._output_dim, s...
class Parser(object): def getParser(self): parser = argparse.ArgumentParser() parser.add_argument('--train', action='store_true') parser.add_argument('--infer', action='store_true') parser.add_argument('--verify', action='store_true') parser.add_argument('--word_label', actio...
def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, drop_last=False, pin_memory=True, persistent_workers=True, **kwargs): (rank, world_size) = get_dist_info() if dist: sampler = DistributedSampler(dataset, world_size, rank, shuffle=shuffle) ...
def _group_str(names: List[str]) -> str: lcp = _longest_common_prefix_str(names) rest = [x[len(lcp):] for x in names] rest = (('{' + ','.join(rest)) + '}') ret = (lcp + rest) ret = ret.replace('bn_{beta,running_mean,running_var,gamma}', 'bn_*') ret = ret.replace('bn_beta,bn_running_mean,bn_runni...
def install_lightautoml(): os.system('curl -sSL | ../../bin/python -') os.system('/root/.local/bin/poetry build') os.system('../../bin/pip install ./dist/lightautoml-0.3.7.4-py3-none-any.whl')
def test_custom_record(): behavior = {} behavior[('__numba_typer__', 'Dummy')] = dummy_typer behavior[('__numba_lower__', 'Dummy')] = dummy_lower array = ak.highlevel.Array([{'x': 1.1, 'y': 100}, {'x': 2.2, 'y': 200}, {'x': 3.3, 'y': 300}], behavior=behavior, check_valid=True) array.layout.parameter...
class LatentWidget(): def __init__(self, viz): self.viz = viz self.latent = dnnlib.EasyDict(x=1, y=0, anim=False, speed=0.25) self.latent_def = dnnlib.EasyDict(self.latent) self.step_y = 100 def drag(self, dx, dy): viz = self.viz self.latent.x += ((dx / viz.font_s...
class TestFFTShift(object): def test_definition(self): x = [0, 1, 2, 3, 4, (- 4), (- 3), (- 2), (- 1)] y = [(- 4), (- 3), (- 2), (- 1), 0, 1, 2, 3, 4] assert_array_almost_equal(fft.fftshift(x), y) assert_array_almost_equal(fft.ifftshift(y), x) x = [0, 1, 2, 3, 4, (- 5), (- 4)...
def init_pos(): for (i, j) in ti.ndrange((N + 1), (N + 1)): k = ((i * (N + 1)) + j) pos[k] = (((ti.Vector([i, j]) / N) * 0.25) + ti.Vector([0.45, 0.45])) vel[k] = ti.Vector([0, 0]) for i in range(NF): (ia, ib, ic) = f2v[i] (a, b, c) = (pos[ia], pos[ib], pos[ic]) B...
class Bottleneck(nn.Module): def __init__(self, tensor_shape): super(Bottleneck, self).__init__() (c, h, w) = tensor_shape self.in_shape = tensor_shape self.out_shape = tensor_shape if config.refine_net_use_rnn: rnn_cells = [] for i in range(config.ref...
class CriterionDSN(nn.Module): def __init__(self, ignore_index=255, use_weight=True, reduce=True): super(CriterionDSN, self).__init__() self.ignore_index = ignore_index self.criterion = torch.nn.CrossEntropyLoss(ignore_index=ignore_index, reduce=reduce) if (not reduce): p...
def CremonaRichmondConfiguration(): from sage.graphs.generators.smallgraphs import TutteCoxeterGraph from sage.combinat.designs.incidence_structures import IncidenceStructure g = TutteCoxeterGraph() H = IncidenceStructure([g.neighbors(v) for v in g.bipartite_sets()[0]]) H.relabel() return H
class CComplexBaseTypeNode(CBaseTypeNode): child_attrs = ['base_type', 'declarator'] def analyse(self, env, could_be_name=False): base = self.base_type.analyse(env, could_be_name) (_, type) = self.declarator.analyse(base, env) return type
class TestParser(unittest.TestCase): def test_unlabeled_unweighted(self): self.stub_data_1 = 'stub_1.txt' with open(self.stub_data_1, 'w') as text_file: text_file.write('%stub\n1 3\n4 5\n0 2') adjacency = parse.from_csv(self.stub_data_1) self.assertTrue((adjacency.indices...
def generate_categories(features, definition_df): categories = {} for feature in features: if ('PUMA' in feature): continue coll_definition = definition_df[((definition_df[0] == 'VAL') & (definition_df[1] == feature))] coll_type = coll_definition.iloc[0][2] if (coll_t...
class BaseResponse(object): charset = 'utf-8' default_status = 200 default_mimetype = 'text/plain' implicit_sequence_conversion = True autocorrect_location_header = True automatically_set_content_length = True max_cookie_size = 4093 def __init__(self, response=None, status=None, headers=...
class PoseDataset(Dataset): def __init__(self, pose: Pose): super().__init__() self.points = torch.tensor([p.flatten() for p in np.array(pose.body.data)], dtype=torch.float32) self.confidence = torch.tensor([np.stack([c, c], axis=(- 1)).flatten() for c in np.array(pose.body.confidence)], dty...
.mlir def test_mlir_tasklet_no_entry(): A = dace.ndarray((1,), dace.int32) B = dace.ndarray((1,), dace.int32) C = dace.ndarray((1,), dace.int32) A[:] = 5 B[:] = 2 C[:] = 15 with pytest.raises(SyntaxError): mlir_tasklet_no_entry(A, B, C) with pytest.raises(SyntaxError): ml...
class Logger(): def __init__(self, cfg): self.path = path.join('..', 'experiment', cfg.save, cfg.ablation) if cfg.reset: if path.isdir(self.path): response = input('Do you want to remove the existing directory? [Y/N]: ') is_reset = (response.lower() == 'y'...
def get_envs(variant): from multiworld.core.image_env import ImageEnv from railrl.envs.vae_wrappers import VAEWrappedEnv from railrl.misc.asset_loader import load_local_or_remote_file render = variant.get('render', False) vae_path = variant.get('vae_path', None) reproj_vae_path = variant.get('re...
class NoFilter(FilterBase): def __call__(self): folder_path = (Path(self.root_folder) / self.folder_path) assert folder_path.exists(), f'Folder {folder_path} does not exist' files = sorted(list(folder_path.glob(self.extension))) return files
def test_export_sequence(exportable_test_case, tmp_path): path = (tmp_path / 'generated.py') exporter = export.PyTestChromosomeToAstVisitor() exportable_test_case.accept(exporter) exportable_test_case.accept(exporter) export.save_module_to_file(exporter.to_module(), path) assert (path.read_text(...
class SimpleDicomReader(object): def __init__(self, file): if isinstance(file, str): self._filename = file self._file = open(file, 'rb') else: self._filename = '<unknown file>' self._file = file self._pixel_data_loc = None self.is_impli...
def convert_module_to_f16(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.half() if (l.bias is not None): l.bias.data = l.bias.data.half()
def layer_init(layer, std=np.sqrt(2), bias_const=0.0): torch.nn.init.orthogonal_(layer.weight, std) torch.nn.init.constant_(layer.bias, bias_const) return layer
def GenusSix(): L = ['014', '018', '023', '027', '036', '049', '056', '05b', '07a', '08a', '09b', '125', '126', '137', '139', '147', '15a', '16b', '18b', '19a', '23b', '248', '24a', '258', '269', '279', '2ab', '345', '34b', '35a', '367', '389', '38a', '459', '46a', '46b', '478', '568', '579', '57b', '67a', '689', '...
class MinMaxResize(): def __init__(self, shorter=800, longer=1333): self.min = shorter self.max = longer def __call__(self, x): (w, h) = x.size scale = (self.min / min(w, h)) if (h < w): (newh, neww) = (self.min, (scale * w)) else: (newh, n...
def group_identifier(tlist): def _consume_cycle(tl, i): x = itertools.cycle(((lambda y: (y.match(T.Punctuation, '.') or (y.ttype in (T.Operator, T.Wildcard, T.Name)) or isinstance(y, sql.SquareBrackets))), (lambda y: ((y.ttype in (T.String.Symbol, T.Name, T.Wildcard, T.Literal.String.Single, T.Literal.Numbe...
class TestMLPModel(): .parametrize('input_dim, output_dim, hidden_sizes', [(5, 1, (1,)), (5, 1, (2,)), (5, 2, (3,)), (5, 2, (1, 1)), (5, 3, (2, 2))]) def test_output_values(self, input_dim, output_dim, hidden_sizes): input_val = torch.ones([1, input_dim], dtype=torch.float32) module_with_nonline...
class MetaDictSetting(Setting): def __init__(self, meta_dict: dict, mandatory_fields: list=[]): self.meta_dict = meta_dict self.mandatory_fields = mandatory_fields
def t5_3b_tied_lmheads_64_4_8p_bw12_async_squad1_mpipe(): 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': Fal...
def get_type_line(source): lines = source.split('\n') def strip_comment(line): return line[:(line.index('#') if ('#' in line) else None)] i = 0 while (not _def_end_regex.match(strip_comment(lines[i]))): i += 1 i += 1 type_line = lines[i].strip() if (not type_line.startswith('...
def lift_to_sl2_Ok(N, c, d): k = N.number_field() if (c.is_zero() and d.is_zero()): raise ValueError(('Cannot lift (%s, %s) to an element of Sl2(Ok).' % (c, d))) if (not N.is_coprime(k.ideal(c, d))): raise ValueError(('<%s> + <%s> and the %s are not coprime.' % (c, d, N))) if ((c - 1) in...
class DictAction(Action): def _parse_int_float_bool(val): try: return int(val) except ValueError: pass try: return float(val) except ValueError: pass if (val.lower() in ['true', 'false']): return (True if (val.lower(...
.parametrize('ratio, y, type, err_msg', [(0.5, binary_target, 'clean-sampling', "'clean-sampling' methods do let the user specify the sampling ratio"), (0.1, np.array((([0] * 10) + ([1] * 20))), 'over-sampling', 'remove samples from the minority class while trying to generate new'), (0.1, np.array((([0] * 10) + ([1] * ...
.parametrize('dim_context, action_noise, reward_noise, min_action_value, max_action_value, random_state, err, description', invalid_input_of_init) def test_synthetic_continuous_init_using_invalid_inputs(dim_context, action_noise, reward_noise, min_action_value, max_action_value, random_state, err, description): wit...
def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None): tz = pytz.timezone(zone) if (utcoffset is None): return tz utcoffset = memorized_timedelta(utcoffset) dstoffset = memorized_timedelta(dstoffset) try: return tz._tzinfos[(utcoffset, dstoffset, tzname)] except KeyErr...
def evaluate_interaction_sample(sample, model, max_generation_length, name='', gold_forcing=False, metrics=None, total_num=(- 1), database_username='', database_password='', database_timeout=0, use_predicted_queries=False, write_results=False, use_gpu=False, compute_metrics=False, bool_progressbar=True): prediction...
def get_map(num_classes=16): if (num_classes == 16): map_synthiaId_to_trainId = {3: 0, 4: 1, 2: 2, 21: 3, 5: 4, 7: 5, 15: 6, 9: 7, 6: 8, 1: 9, 10: 10, 17: 11, 8: 12, 19: 13, 12: 14, 11: 15} else: raise NotImplementedError(f'Not yet supported {num_classes} classes') return map_synthiaId_to_tr...
class D(nn.Module): class Maxout(nn.Module): def __init__(self, d_in, d_out, pool_size=5): super().__init__() (self.d_in, self.d_out, self.pool_size) = (d_in, d_out, pool_size) self.lin = nn.Linear(d_in, (d_out * pool_size)) def forward(self, inputs): ...
def load_model_config(config_f): print(config_f) with open(config_f, 'r') as f: config = json.loads(f.read()) print(config) return config
def LF_non(x): rgx = re.compile('(non)[-]*', re.I) is_negated = (rgx.search(get_left_span(x.pain, window=2).text) is not None) return (NEGATIVE if is_negated else ABSTAIN)
class SyntheticProjectCheckout(ProjectCheckout): def __init__(self, name: str, version: str, data_path: str, base_path: str): super().__init__('-synthetic-', join(base_path, name), version) self.name = name self.version = version self.data_path = data_path def exists(self) -> boo...
def _get_data(modality, output_folder_name, in_memory_directory): data = {} if output_folder_name: for filename in os.listdir(output_folder_name): if filename.endswith('.csv'): table_name = Path(filename).stem data_path = os.path.join(output_folder_name, filen...
def add_roi_Xconv1fc_head(model, blob_in, dim_in, spatial_scale): hidden_dim = cfg.FAST_RCNN.CONV_HEAD_DIM roi_size = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION roi_feat = model.RoIFeatureTransform(blob_in, 'roi_feat', blob_rois='rois', method=cfg.FAST_RCNN.ROI_XFORM_METHOD, resolution=roi_size, sampling_ratio=cfg....
def get_elapsed_time(): if (os.name == 'nt'): raise NotImplementedError('cannot use get_elapsed_time() on Windows') return sum(os.times()[:4])
_model def tf_efficientnet_b7_ns(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnet('tf_efficientnet_b7_ns', channel_multiplier=2.0, depth_multiplier=3.1, pretrained=pretrained, **kwargs) return model
class EmissionModel(nn.Module): def __init__(self): super().__init__() self.distribution_function = tdist.normal.Normal def sample(self, means, stds, sampling_temp=1.0): return (self.distribution_function(means, (stds * sampling_temp)).sample() if (sampling_temp > 0) else means) def ...
(scope='module') def source_2bin_2channel_coupledhistosys(): with open('validation/data/2bin_2channel_coupledhisto.json', encoding='utf-8') as read_json: return json.load(read_json)
class IntBlock(nn.Module): def __init__(self, body, shortcut=None): super(IntBlock, self).__init__() self.body = body self.residual_connection = (shortcut is None) if (not self.residual_connection): self.shortcut = shortcut self.post_relu = nn.ReLU(inplace=True) ...
def dataio_prepare(hparams): logging.info('generating datasets...') datasets = load_dataset('text', data_files={'train': hparams['lm_train_data'], 'valid': hparams['lm_valid_data'], 'test': hparams['lm_test_data']}) train_data = sb.dataio.dataset.DynamicItemDataset.from_arrow_dataset(datasets['train']) ...
class TestDeriavtives(TestCase): def setUp(self): self.model = pin.buildSampleModelHumanoidRandom() self.data = self.model.createData() qmax = np.full((self.model.nq, 1), np.pi) self.q = pin.randomConfiguration(self.model, (- qmax), qmax) self.v = np.random.rand(self.model.nv...
def build_processors(processors_config: DictConfig, registry_key: str=None, *args, **kwargs): from mmf.datasets.processors.processors import Processor processor_dict = {} for (processor_key, processor_params) in processors_config.items(): if (not processor_params): continue proce...
def hear_scene_trainvaltest(target_dir: str, cache_dir: str, dataset_root: str, get_path_only: bool=False): target_dir = Path(target_dir) resample_hear_corpus(dataset_root, target_sr=16000) dataset_root = Path(dataset_root) wav_root: Path = (dataset_root / '16000') train_csv = (target_dir / 'train.c...
def basic_blocks(dim, index, layers, pool_size=3, mlp_ratio=4.0, act_layer=nn.GELU, norm_layer=GroupNorm, drop_rate=0.0, drop_path_rate=0.0, use_layer_scale=True, layer_scale_init_value=1e-05): blocks = [] for block_idx in range(layers[index]): block_dpr = ((drop_path_rate * (block_idx + sum(layers[:ind...
def calc_map_mesh(testfile, predfile): with open(testfile, 'r') as ftest, open(predfile, 'r') as fpred: data = [] pred = [] for line in ftest: data.append(line.strip().split('\t')) for line in fpred: pred.append(float(line.strip())) oneq = [] p...
def apply_statistics_correction(transformed_graph: Graph, representative_data_gen: Callable, core_config: CoreConfig, fw_info: FrameworkInfo, fw_impl: FrameworkImplementation, tb_w: TensorboardWriter=None) -> Graph: if core_config.quantization_config.weights_second_moment_correction: transformed_graph = app...
def test(): one = ak.highlevel.Array([[{'x': 1}], [], [{'x': 2}]], with_name='One') two = ak.highlevel.Array([[{'x': 1.1}], [], [{'x': 2.2}]], with_name='Two') assert (str(ak.operations.with_name(ak.operations.concatenate([one, two], axis=1), 'All').type) == '3 * var * All[x: float64]') assert (str(ak.o...
class AdaptiveAggregateAlarms(AggregateAlarms): threshold_class = AdaptiveThreshold def __init__(self, alm_threshold: float=None, abs_score=True, min_alm_in_window: int=2, alm_window_minutes: float=60, alm_suppress_minutes: float=120, bin_sz: int=10, default_hist_gap_thres: float=1.2): super().__init__(...
class consume(): def __init__(self, stream: Deque[T], processing_elements: int=1, condition: Optional[Callable[([], bool)]]=None): self.stream = stream self.pes = processing_elements self.condition = (condition or (lambda : (len(stream) > 0))) def __iter__(self) -> Generator[(T, None, No...
def copy_conllu(tokenizer_dir, mwt_dir, short_name, dataset, particle): input_conllu_tokenizer = f'{tokenizer_dir}/{short_name}.{dataset}.gold.conllu' input_conllu_mwt = f'{mwt_dir}/{short_name}.{dataset}.{particle}.conllu' shutil.copyfile(input_conllu_tokenizer, input_conllu_mwt)
class BackendIPythonCommandline(BackendIPython): def default_preferences(self): from sage.repl.rich_output.preferences import DisplayPreferences return DisplayPreferences(supplemental_plot='never') def _repr_(self): return 'IPython command line' def supported_output(self): re...
def register_Ns3Object_methods(root_module, cls): cls.add_constructor([]) cls.add_method('AggregateObject', 'void', [param('ns3::Ptr< ns3::Object >', 'other')]) cls.add_method('Dispose', 'void', []) cls.add_method('GetAggregateIterator', 'ns3::Object::AggregateIterator', [], is_const=True) cls.add_m...
class FreeGradedModuleMorphism(FPModuleMorphism): def __init__(self, parent, values): from .free_homspace import FreeGradedModuleHomspace if (not isinstance(parent, FreeGradedModuleHomspace)): raise TypeError(('the parent (%s) must be a f.p. free module homset' % parent)) self._f...
def upsample_bilinear(input, size=None, scale_factor=None): warnings.warn('nn.functional.upsample_bilinear is deprecated. Use nn.functional.interpolate instead.') return interpolate(input, size, scale_factor, mode='bilinear', align_corners=True)