code
stringlengths
101
5.91M
def run(): parser = argparse.ArgumentParser(description='Checks all dependencies are found and are correct versions', usage='circlator progcheck') parser.add_argument('--debug', action='store_true', help='Debug mode with very verbose output') options = parser.parse_args() versions.get_all_versions(sys.s...
_properties class CodeNode(Node): label = Property(dtype=str, desc='Name of the CodeNode') location = DictProperty(key_type=str, value_type=dace.symbolic.pystr_to_symbolic, desc='Full storage location identifier (e.g., rank, GPU ID)') environments = SetProperty(str, desc='Environments required by CMake to b...
def get_best_encoding(stream): rv = (getattr(stream, 'encoding', None) or sys.getdefaultencoding()) if is_ascii_encoding(rv): return 'utf-8' return rv
class RoCBertForMaskedLM(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class AspuruGuzikAutoEncoder(SeqToSeq): def __init__(self, num_tokens, max_output_length, embedding_dimension=196, filter_sizes=[9, 9, 10], kernel_sizes=[9, 9, 11], decoder_dimension=488, **kwargs): if (len(filter_sizes) != len(kernel_sizes)): raise ValueError('Must have same number of layers an...
class SPPParameter(message.Message): __metaclass__ = reflection.GeneratedProtocolMessageType DESCRIPTOR = _SPPPARAMETER
class SawyerFaucetCloseV2Policy(Policy): _fully_parsed def _parse_obs(obs): return {'hand_pos': obs[:3], 'faucet_pos': obs[3:6], 'unused_info': obs[6:]} def get_action(self, obs): o_d = self._parse_obs(obs) action = Action({'delta_pos': np.arange(3), 'grab_effort': 3}) action...
class FiniteInductiveValuation(InductiveValuation, DiscreteValuation): def __init__(self, parent, phi): InductiveValuation.__init__(self, parent, phi) DiscreteValuation.__init__(self, parent) def extensions(self, other): from sage.categories.function_fields import FunctionFields ...
class InstanceNormalization(keras.layers.Layer): def __init__(self, epsilon=1e-05): super(InstanceNormalization, self).__init__() self.epsilon = epsilon def build(self, input_shape): self.scale = self.add_weight(name='scale', shape=input_shape[(- 1):], initializer=tf.random_normal_initia...
def is_torch_bf16_available(): if (not is_torch_available()): return False import torch if ((not torch.cuda.is_available()) or (torch.version.cuda is None)): return False if (torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8): return False if (int(torch....
def test_method_get_teacher_forced_logits_for_encoder_decoder_model(): transformers = pytest.importorskip('transformers') name = 'hf-internal-testing/tiny-random-BartModel' tokenizer = transformers.AutoTokenizer.from_pretrained(name) model = transformers.AutoModelForSeq2SeqLM.from_pretrained(name) w...
def find_all_links(file_paths): links = [] for path in file_paths: links += scan_code_for_links(path) return [link for link in links if (link != S3_BUCKET_PREFIX)]
def SetTensorBoundShapes(meta_net_def, tensor_bound_shapes): meta_net_def.tensorBoundShapes.CopyFrom(tensor_bound_shapes)
class DatasetTemplates(): TEMPLATES_KEY = 'templates' DATASET_KEY = 'dataset' SUBSET_KEY = 'subset' TEMPLATE_FILENAME = 'templates.yaml' def __init__(self, dataset_name: str, subset_name: str=None): self.dataset_name: str = dataset_name self.subset_name: str = subset_name sel...
def local_initializer(sess, var_list, print_option=False): if print_option: print('Initialize specific variables') sess.run(tf.variables_initializer(var_list))
def check_all_models_are_auto_configured(): check_missing_backends() modules = get_model_modules() all_auto_models = get_all_auto_configured_models() failures = [] for module in modules: new_failures = check_models_are_auto_configured(module, all_auto_models) if (new_failures is not ...
.parametrize('patchset_file', ['patchset_bad_duplicate_patch_name.json', 'patchset_bad_duplicate_patch_values.json', 'patchset_bad_wrong_values_multiplicity.json']) def test_patchset_bad(datadir, patchset_file): with open(datadir.joinpath(patchset_file), encoding='utf-8') as patch_file: patchsetspec = json....
def run_analysis(_): dataset = FLAGS.dataset model = FLAGS.model thresholding = FLAGS.thresholding split = FLAGS.split threshold = FLAGS.threshold no_concord = FLAGS.no_concord no_r2 = FLAGS.no_r2 out_path = FLAGS.out_path fold_num = FLAGS.fold_num hyper_parameters = FLAGS.hyper_...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--model_type', default=None, type=str, required=True) parser.add_argument('--base_model', default=None, type=str, required=True) parser.add_argument('--lora_model', default='', type=str, help='If None, perform inference on the base mode...
def get_updated_inputs(inputs, **kwargs): features = inputs._asdict() for (k, v) in kwargs.items(): features[k] = v return features_to_inputs(features)
class LatentProductModel(object): def __init__(self, user_size, item_size, size, num_layers, batch_size, learning_rate, learning_rate_decay_factor, user_attributes=None, item_attributes=None, item_ind2logit_ind=None, logit_ind2item_ind=None, loss_function='ce', GPU=None, logit_size_test=None, nonlinear=None, dropou...
def Accuracy(log_probabilities, targets, length=None): if (length is not None): mask = length_to_mask((length * targets.shape[1]), max_len=targets.shape[1]).bool() if (len(targets.shape) == 3): mask = mask.unsqueeze(2).repeat(1, 1, targets.shape[2]) padded_pred = log_probabilities.ar...
def f(x): tmp = x.copy() if (len(tmp.shape) == 2): tmp = tmp.reshape(tmp.shape[0], *X[0].shape) preprocess_input(tmp) return model(tmp)
def test_vector_fixed_set(): pset = paramsets.constrained_by_poisson(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, auxdata=[0, 0, 0, 0, 0], factors=[1, 1, 1, 1, 1]) pset.suggested_fixed = True assert (pset.suggested_...
def parse_args(): parser = argparse.ArgumentParser(description='Train keypoints network') parser.add_argument('--cfg', help='experiment configure file name', required=True, type=str) parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed'...
class ValueIdBreakpoint(Breakpoint): type = 'value-id' pattern = re.compile('^%[0-9]+') def should_stop(self, tdb: TdbCmdBackend) -> bool: index = tdb.get_plugin(FinalMlirIndexPlugin) if (not index.enabled): return False mlir = index.get_mlir_by_point(tdb.cmd_point) ...
class BatchNormalizationFoldingOppositeModifierInner(FunctionModifier, BatchNormBase): def __init__(self, channel_last=False): super(BatchNormalizationFoldingOppositeModifierInner, self).__init__() self._channel_last = channel_last def modify(self, f, inputs): outputs = f.outputs[0] ...
_utils.test() def test_ndrange_start_greater_than_end(): def ndrange_test(i1: ti.i32, i2: ti.i32, j1: ti.i32, j2: ti.i32) -> ti.i32: n: ti.i32 = 0 for (i, j) in ti.ndrange((i1, i2), (j1, j2)): n += 1 return n assert (ndrange_test(0, 10, 0, 20) == 200) assert (ndrange_test...
def freeze(mod, preserved_attrs: Optional[List[str]]=None): if (not isinstance(mod, ScriptModule)): raise RuntimeError("Freezing expects a ScriptModule as input. Please use torch.jit.script or torch.jit.trace to script your 'nn.Module'.") if mod.training: raise RuntimeError('Freezing is currentl...
class CrystalOfTableaux_E7(CrystalOfTableaux): def module_generator(self, shape): if (len(shape) != 1): raise NotImplementedError('only implemented for single row shapes') return self(*([self.letters.highest_weight_vector()] * shape[0]))
def test_ce_loss(): with pytest.raises(AssertionError): CELoss(ignore_index='ignore') with pytest.raises(AssertionError): CELoss(reduction=1) with pytest.raises(AssertionError): CELoss(reduction='avg') ce_loss = CELoss(ignore_index=0) outputs = torch.rand(1, 10, 37) targe...
class Fuzzer(object): __metaclass__ = ABCMeta def run(self): pass def start(self): pass def pause(self): pass def resume(self): pass def stop(self): pass
def get_loader_from_returnn_dataset(dataset: Dataset, mp_manager: torch.multiprocessing.Manager) -> DataLoader: epoch_mp_shared = mp_manager.Value('i', 0) epoch_mp_shared.value = 1 reset_callback = returnn_dataset_wrapper.ReturnnDatasetResetMpSharedEpochCallback(dataset=dataset, epoch_mp_shared=epoch_mp_sha...
def fhtoffset(dln, mu, initial=0.0, bias=0.0): (lnkr, q) = (initial, bias) xp = (((mu + 1) + q) / 2) xm = (((mu + 1) - q) / 2) y = (np.pi / (2 * dln)) zp = loggamma((xp + (1j * y))) zm = loggamma((xm + (1j * y))) arg = (((LN_2 - lnkr) / dln) + ((zp.imag + zm.imag) / np.pi)) return (lnkr ...
def test(): np_array = np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]) one = ak.Array(np_array) np_array[1] = 999 assert (to_list(one) == [0.0, 999, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]) two = copy.copy(one) np_array[3] = 123 assert (to_list(two) == [0.0, 999, 2.2, 123, 4.4, ...
class DPMSolverSampler(object): def __init__(self, model, **kwargs): super().__init__() self.model = model to_torch = (lambda x: x.clone().detach().to(torch.float32).to(model.device)) self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod)) def register_buffer(self,...
def lgb_f1_loss_multiclass(preds: np.ndarray, train_data: lgb.Dataset, clip: float=1e-05) -> Tuple[(np.ndarray, np.ndarray)]: y_true = train_data.get_label().astype(np.int32) preds = preds.reshape((y_true.shape[0], (- 1)), order='F') preds = np.clip(softmax_ax1(preds), clip, (1 - clip)) y_ohe = np.zeros...
class Generalized_RCNN(nn.Module): def __init__(self, is_train=True): super().__init__() if (not is_train): self.Norm = ops.AffineChannel2d(3) self.Norm.weight.data = torch.from_numpy((1.0 / np.array(cfg.PIXEL_STDS))).float() self.Norm.bias.data = torch.from_numpy...
class MongoKeyValueStore(KeyValueStore): _BATCH_SIZE: int = 8 _REQUEST_KEY = 'request' _RESPONSE_KEY = 'response' def __init__(self, uri: str, collection_name: str): self._mongodb_client: MongoClient = MongoClient(uri) self._database = self._mongodb_client.get_default_database() ...
class PAU(torch.nn.Module): __constants__ = ['num_parameters'] num_parameters: int def __init__(self, num_parameters: int=10, init: float=1.0) -> None: self.num_parameters = num_parameters super(PAU, self).__init__() self.weight = Parameter(torch.Tensor(num_parameters).fill_(init)) ...
class EmergencyDispatchSystemSearchIncidents(VirtualFunctionTool): name = 'EmergencyDispatchSystemSearchIncidents' summary = 'Search for incidents based on a specified location and incident type.' parameters: List[ArgParameter] = [{'name': 'location', 'type': 'string', 'description': 'The location to search...
() def test_memory_challenge_c(memory_management_agent: Agent, patched_api_requestor: MockerFixture, monkeypatch: pytest.MonkeyPatch, level_to_run: int, challenge_name: str) -> None: silly_phrases = ['The purple elephant danced on a rainbow while eating a taco', 'The sneaky toaster stole my socks and ran away to Ha...
def get_human_object_recognition_categories(): return sorted(['knife', 'keyboard', 'elephant', 'bicycle', 'airplane', 'clock', 'oven', 'chair', 'bear', 'boat', 'cat', 'bottle', 'truck', 'car', 'bird', 'dog'])
def default_config_dict(name=None, parent_name=None, local_path=None): import warnings warnings.warn(('Use Configuration(%r,%r,top_path=%r) instead of deprecated default_config_dict(%r,%r,%r)' % (name, parent_name, local_path, name, parent_name, local_path)), stacklevel=2) c = Configuration(name, parent_nam...
def CalculateHarary(mol): Distance = np.array(Chem.GetDistanceMatrix(mol), 'd') X = (1.0 / Distance[(Distance != 0)]) res = ((1.0 / 2) * X.sum()) if (res == 0): res = MINVALUE return np.log10(res)
def main(args=None): args = parse_args(args=args) utils.set_random_seed(args['seed']) logger.info('Running parser in {} mode'.format(args['mode'])) if (args['mode'] == 'train'): train(args) else: evaluate(args)
def test(sim_time=1.5, qc_atten=1e-05): network_config = 'star_network.json' network_topo = RouterNetTopo(network_config) set_parameters(network_topo, sim_time, qc_atten) start_node_name = 'router1' end_node_name = 'router2' node1 = node2 = None for router in network_topo.get_nodes_by_type(R...
def resnet50_atrous(pretrained=True, os=16, **kwargs): return _resnet(arch='resnet50', block=Bottleneck, layers=[3, 4, 6, 3], atrous=[1, 2, 1], os=os, pretrained=pretrained, progress=True)
def test_minimize_multiple_constraints(): def func(x): return np.array([(((25 - (0.2 * x[0])) - (0.4 * x[1])) - (0.33 * x[2]))]) def func1(x): return np.array([x[1]]) def func2(x): return np.array([x[2]]) cons = ({'type': 'ineq', 'fun': func}, {'type': 'ineq', 'fun': func1}, {'ty...
class AdamW(Optimizer): def __init__(self, params: Iterable, lr: float=0.001, betas: Tuple[(float, float)]=(0.9, 0.999), eps: float=1e-06, weight_decay: float=0.0, correct_bias: bool=True) -> None: if (lr < 0.0): raise ValueError('Invalid learning rate: {} - should be >= 0.0'.format(lr)) ...
def train(model, optimizer, loader, epoch): batch_time = AverageMeter() data_time = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() losses = AverageMeter() end = time.perf_counter() model.train() criterion = nn.CrossEntropyLoss().cuda() for (iter_epoch, (inp, target)) in e...
def set_linecache(filename, source): import linecache linecache.cache[filename] = (None, None, [(line + '\n') for line in source.splitlines()], filename)
class Bottleneck(nn.Module): expansion = 4 def __init__(self, inplanes, planes, norm_type='batch', stride=1, downsample=None): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False) self.bn1 = normalization(planes, norm_type) self.c...
def ufunc_add_where(A: dace.int32[10], B: dace.int32[10], W: dace.bool_[10]): return np.add(A, B, where=W)
.box(RecordViewType) def box_RecordView(recordviewtype, viewval, c): RecordView_obj = c.pyapi.unserialize(c.pyapi.serialize_object(RecordView)) proxyin = c.context.make_helper(c.builder, recordviewtype, viewval) arrayview_obj = box_ArrayView(recordviewtype.arrayviewtype, proxyin.arrayview, c) at_obj = c...
def show_ann(coco, img, ann_info): plt.imshow(mmcv.bgr2rgb(img)) plt.axis('off') coco.showAnns(ann_info) plt.show()
_arg_scope def separable_conv2d_same(inputs, num_outputs, kernel_size, depth_multiplier, stride, rate=1, use_explicit_padding=True, regularize_depthwise=False, scope=None, **kwargs): def _separable_conv2d(padding): return slim.separable_conv2d(inputs, num_outputs, kernel_size, depth_multiplier=depth_multipl...
class AnnealingTemperature(object): def __init__(self, init_tau=1.0, base_tau=0.5, anneal_rate=0.001, N=500): self.init_tau = init_tau self.base_tau = base_tau self.anneal_rate = anneal_rate self.N = N self._tau = init_tau self._step = 0 def step(self): se...
class GPT2Partitioner(PartitioningTask): def __init__(self, args) -> None: super().__init__(args) self.tokenizer = GPT2Tokenizer.from_pretrained(args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=(args.cache_dir if args.cache_dir else None)) if (args.block_size <= 0): ...
class BipartiteEdgePredLayer(Layer): def __init__(self, input_dim1, input_dim2, placeholders, dropout=False, act=tf.nn.sigmoid, loss_fn='xent', neg_sample_weights=1.0, bias=False, bilinear_weights=False, **kwargs): super(BipartiteEdgePredLayer, self).__init__(**kwargs) self.input_dim1 = input_dim1 ...
def register_Ns3ApplicationContainer_methods(root_module, cls): cls.add_constructor([param('ns3::ApplicationContainer const &', 'arg0')]) cls.add_constructor([]) cls.add_constructor([param('ns3::Ptr< ns3::Application >', 'application')]) cls.add_constructor([param('std::string', 'name')]) cls.add_me...
def attn_post_proc(attn_res, inter_hn=None, wd=0.0, keep_prob=1.0, residual_keep_prob=1.0, is_train=None, activation='relu', sparse_opt=False, scope=None, **kwargs): with tf.variable_scope((scope or 'attn_res')): assert ('mask' in kwargs) if sparse_opt: (x1, reverse_spec) = masked_dense2...
class TextDataset(Dataset): def __init__(self, paths, vocab, logger, max_lengths=200): self.logger = logger self.vocab = vocab self.max_lengths = max_lengths self.data = self.make_dataset(paths, vocab, logger, (max_lengths - 1)) def make_dataset(paths, vocab, logger, max_lengths)...
class TqdmFile(object): dummy_file = None def __init__(self, dummy_file): self.dummy_file = dummy_file def write(self, x): if (len(x.rstrip()) > 0): tqdm.write(x, file=self.dummy_file)
def _dict_flatten(d: Dict[(Any, Any)]) -> Tuple[(List[Any], Context)]: return (list(d.values()), list(d.keys()))
def tokenize(expression: str) -> TokenGenerator: cursor = 0 def is_eol() -> bool: return (cursor == len(expression)) def current_symbol() -> str: return expression[cursor] def move() -> None: nonlocal cursor cursor += 1 def move_until(predicate: Callable[([], bool)]) ...
def dispatch(fn_name): try: return dispatcher[fn_name] except KeyError: print(('Undefined value function `%s' % fn_name)) exit(1)
def get_core_subclass_dict(superclass): return {k: v for (k, v) in get_core_subclass_list(superclass)}
class ResizeShortestEdge(): def __init__(self, short_edge_length: List[int], max_size: int=sys.maxsize): self.interp_method = 'bilinear' self.max_size = max_size self.short_edge_length = short_edge_length def __call__(self, imgs: List[torch.Tensor]): img_augs = [] for img...
def bar_custom(current, total, width=80): print(('Downloading: %d%% [%d / %d] Ks' % (((current / total) * 100), (current / 1000), (total / 1000))), end='\r')
def adjust_length_to_model(length, max_sequence_length): if ((length < 0) and (max_sequence_length > 0)): length = max_sequence_length elif (0 < max_sequence_length < length): length = max_sequence_length elif (length < 0): length = MAX_LENGTH return length
class BNReLU2d(torch.nn.Sequential): def __init__(self, batch_norm, relu): assert ((type(batch_norm) == BatchNorm2d) and (type(relu) == ReLU)), 'Incorrect types for input modules{}{}'.format(type(batch_norm), type(relu)) super(BNReLU2d, self).__init__(batch_norm, relu)
class AnthropicClient(CachingClient): MAX_COMPLETION_LENGTH: int = 8192 ADDITIONAL_TOKENS: int = 5 PROMPT_ANSWER_START: str = 'The answer is ' def __init__(self, tokenizer: Tokenizer, tokenizer_name: str, cache_config: CacheConfig, api_key: Optional[str]=None): super().__init__(cache_config=cach...
_utils.test(require=ti.extension.bls) def test_scatter_1d(): _test_bls_stencil(1, 128, bs=32, stencil=((1,), (0,)), scatter=True)
.parametrize('evaluation_policy_pscore_cascade, evaluation_policy_action_dist, q_hat, description', invalid_input_of_create_estimator_inputs) def test_meta_create_estimator_inputs_using_invalid_input_data(evaluation_policy_pscore_cascade, evaluation_policy_action_dist, q_hat, description: str, synthetic_slate_bandit_fe...
def get_bleu(in_sent, target_sent): bleu = sacrebleu.corpus_bleu([in_sent], [[target_sent]]) out = ' '.join(map(str, (([bleu.score, bleu.sys_len, bleu.ref_len] + bleu.counts) + bleu.totals))) return out
def save_checkpoint(cfg, model, epoch, optimizer=None, scheduler=None, additioanl_dict=None, is_best=False, post_fix='ckpt_latest', save_name=None): if (save_name is None): save_name = cfg.run_name current_ckpt_name = f'{save_name}_{post_fix}.pth' current_pretrained_path = os.path.join(cfg.ckpt_dir,...
def main(inp_dir, oup_dir, map_fn): for (inp_split, oup_split) in [('train', 'train'), ('dev', 'valid'), ('test', 'test')]: n = 0 with open(os.path.join(inp_dir, f'{inp_split}.json')) as fj: with open(os.path.join(oup_dir, f'{oup_split}.text'), 'w') as ftext, open(os.path.join(oup_dir, f...
class clean(_clean): def run(self): self.execute(_clean_bins, (), msg='Cleaning binary files and headers') self.execute(_clean_native_build, (), msg='Cleaning native build') _clean.run(self)
def write(filename, rows, mode='w'): with open(filename, mode) as csvfile: writer = csv.writer(csvfile, delimiter=',') if (type(rows[0]) is tuple): writer.writerows(rows) else: writer.writerow(rows)
class TestSequeneceGenerator(TestSequenceGeneratorBase): def setUp(self): (self.tgt_dict, self.w1, self.w2, src_tokens, src_lengths, self.model) = test_utils.sequence_generator_setup() self.sample = {'net_input': {'src_tokens': src_tokens, 'src_lengths': src_lengths}} def test_with_normalization...
class upConv3D(nn.Module): def __init__(self, in_ch, out_ch, kernel_size, stride, padding, upmode='transpose', batchnorm=False): super().__init__() self.upmode = upmode if (self.upmode == 'transpose'): self.upconv = nn.ModuleList([nn.ConvTranspose3d(in_ch, out_ch, kernel_size=ker...
def visualize_images(images: List[Any], size: Optional[Tuple[(int, int)]]=(224, 224), *args, **kwargs): try: import matplotlib.pyplot as plt except ImportError: print(('Visualization tools require matplotlib. ' + 'Install using pip install matplotlib.')) raise transform_list = [] ...
def _from_sgf(sgf: str): indexes = 'abcdefghijklmnopqrs' infos = sgf.split(';') game_info = infos[1] game_record = infos[2:] size = 19 if (game_info.find('SZ') != (- 1)): sz = game_info[(game_info.find('SZ') + 3):(game_info.find('SZ') + 5)] if (sz[1] == ']'): sz = sz[...
def generate(): RecLayer._create_rnn_cells_dict() layer_names = sorted(list(RecLayer._rnn_cells_dict.keys())) rst_file = open('layer_reference/units.rst', 'w') rst_file.write(header_text) for layer_name in layer_names: unit_class = RecLayer.get_rnn_cell_class(layer_name) if (issubcla...
class CombineLosses(nn.Module): def __init__(self, loss_weights: list, loss_instances: list): super(CombineLosses, self).__init__() self.loss_weights = loss_weights self.loss_instances = nn.ModuleList(loss_instances) def forward(self, pred_score, gt_score): loss = torch.tensor(0,...
def register_Ns3CallbackImpl__Void_Ns3LrWpanMacState_Ns3LrWpanMacState_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_Ns3Empty_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::CallbackImpl< void, ns3::LrWpanMacState, ns3::LrWpanMacState, ns3::empty, ns3::empty, ns3::emp...
class SpeakerVerificationDataLoader(DataLoader): def __init__(self, dataset, speakers_per_batch, utterances_per_speaker, sampler=None, batch_sampler=None, num_workers=0, pin_memory=False, timeout=0, worker_init_fn=None): self.utterances_per_speaker = utterances_per_speaker super().__init__(dataset=d...
.script def call_rpc_torchscript_with_record_function(dst_worker_name: str, block: str) -> Tensor: fut = rpc.rpc_async(dst_worker_name, script_add_ones_with_record_function, (torch.tensor(1), block)) return fut.wait()
class _ctypes(object): def __init__(self, array, ptr=None): self._arr = array if ctypes: self._ctypes = ctypes self._data = _get_void_ptr(array) assert (self._data.value == ptr) else: self._ctypes = _missing_ctypes() self._data = se...
def load_checkpoint(args, trainer, **passthrough_args): if (args.distributed_rank == 0): os.makedirs(args.save_dir, exist_ok=True) if (args.restore_file == 'checkpoint_last.pt'): checkpoint_path = os.path.join(args.save_dir, 'checkpoint_last.pt') else: checkpoint_path = args.restore_...
class TestTokenize(unittest.TestCase): def test_simple(self): s = 'select * from foo;' stream = lexer.tokenize(s) self.assert_(isinstance(stream, types.GeneratorType)) tokens = list(stream) self.assertEqual(len(tokens), 8) self.assertEqual(len(tokens[0]), 2) s...
def getScoreUnigram(candidate, gold): (scoring, bestMatch) = ({}, {}) maxScore = 0 maxLabel = '' for goldLabel in gold: goldKey = str(goldLabel) scoring[goldKey] = {} for candidateLabel in candidate: candidateKey = str(candidateLabel) scoring[goldKey][cand...
def overapproximate(expr): if isinstance(expr, list): return [overapproximate(elem) for elem in expr] return _overapproximate(expr)
def test_potsdam(): test_dataset = PotsdamDataset(pipeline=[], img_dir=osp.join(osp.dirname(__file__), '../data/pseudo_potsdam_dataset/img_dir'), ann_dir=osp.join(osp.dirname(__file__), '../data/pseudo_potsdam_dataset/ann_dir')) assert (len(test_dataset) == 1)
class MergePlan(AddRows, MergeRows): def __init__(self, log_level=Log.info): self.ServerId = '' self.LogLevel = log_level def __set_serverId(self, serverId): self.ServerId = serverId '\n Public methods\n ' def merge_plans(self, leader_plan, worker_plans): _leader_pl...
class AttentionDecoderTest(tf.test.TestCase, DecoderTests): def setUp(self): tf.test.TestCase.setUp(self) tf.logging.set_verbosity(tf.logging.INFO) DecoderTests.__init__(self) self.attention_dim = 64 self.input_seq_len = 10 def create_decoder(self, helper, mode): ...
def _add_entity_variations(utterances, entity_variations, entity_value): utterances[entity_value] = entity_value for variation in entity_variations[entity_value]: if variation: utterances[variation] = entity_value return utterances
class ScopedConstructor(): def __init__(self, c, ctx): self.c = c self.ctx = ctx def __del__(self): if (self.ctx.ref() is not None): Z3_del_constructor(self.ctx.ref(), self.c)
def create_session(agent_path): agent_components = AgentsClient.parse_agent_path(agent_path) location_id = agent_components['location'] if (location_id != 'global'): api_endpoint = f'{location_id}-dialogflow.googleapis.com:443' client_options = {'api_endpoint': api_endpoint} session_clie...