code
stringlengths
101
5.91M
class DavisConfig(Config): TARGET_DATASET = 'test-dev' SAVE_PATH = 'out' DATA_PATH = 'data' json_path = '../prepare/mask_rcnn_result' minDetScore = 0.05 ov_threshold = 0.6
class BaseModel(nn.Module, metaclass=ABCMeta): def init_weights(self): def forward_train(self, imgs, labels): def forward_test(self, imgs): def forward(self, imgs, labels, test_mode, **kwargs): if test_mode: return self.forward_test(imgs, **kwargs) return self.forward_train(i...
class LogisticTS(BaseLogisticPolicy): policy_name: str = 'logistic_ts' def __post_init__(self) -> None: super().__post_init__() def select_action(self, context: np.ndarray) -> np.ndarray: theta = np.array([model.predict_proba_with_sampling(context) for model in self.model_list]).flatten() ...
class DirectiveToken(Token): id = '<directive>' def __init__(self, name, value, start_mark, end_mark): self.name = name self.value = value self.start_mark = start_mark self.end_mark = end_mark
class DataPrefetcher(): def __init__(self, dataset): self.dataset = dataset self.stream = torch.cuda.Stream() self.preload() def preload(self): try: self.next_input = next(self.dataset) except StopIteration: self.next_input = None retur...
class _MkldnnConvNd(torch.jit.ScriptModule): __constants__ = ['stride', 'padding', 'dilation', 'groups'] def __init__(self, dense_module): super(_MkldnnConvNd, self).__init__() self.stride = dense_module.stride self.padding = dense_module.padding self.dilation = dense_module.dila...
class ASR(sb.core.Brain): def compute_forward(self, batch, stage): batch = batch.to(self.device) (wavs, wav_lens) = batch.sig feats = self.modules.wav2vec2(wavs, wav_lens) x = self.modules.enc(feats) logits = self.modules.output_lin(x) p_ctc = self.hparams.log_softmax...
def visualize_errors(frames, predictions, targets, fp_mistakes, fn_mistakes): (scenes, scene_preds) = ([], []) (_, ih, iw, _) = frames.shape for mistakes in [fp_mistakes, fn_mistakes]: for (start, end) in mistakes: idx = int((start + ((end - start) // 2))) scene = frames[max(...
class SubNode(NumBinopNode): def compute_c_result_type(self, type1, type2): if ((type1.is_ptr or type1.is_array) and (type2.is_int or type2.is_enum)): return type1 elif ((type1.is_ptr or type1.is_array) and (type2.is_ptr or type2.is_array)): return PyrexTypes.c_ptrdiff_t_type...
def test_has_path_no_path(): proxy = tt.ObjectProxy([1]) proxy.count(1) assert (tt.UsageTraceNode.from_proxy(proxy).find_path(('count', 'foobar')) is None)
def load_tf_weights_in_xxx(model, config, tf_checkpoint_path): try: import re import numpy as np import tensorflow as tf except ImportError: logger.error('Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see for installation instructions.') ...
def evaluate(dataset, predictions, k, no_f1=False): count = 0 f1 = exact_match = total = 0 ranks = {} for article in dataset: for paragraph in article['paragraphs']: for qa in paragraph['qas']: total += 1 if (qa['id'] not in predictions): ...
def test_metric_evaluate_y_pred_none(): metrics = create_metric_list(k, revenue) for metric in metrics: with pytest.raises(TypeError): metric.evaluate(y_true, None)
def filter_text(transcription: str, dataset='train', acronyms=None, acronyms_noi=None): dataset = dataset.strip().lower() if (dataset == 'train'): transcription = re.sub('\\[SILENCE\\]', '', transcription, flags=re.IGNORECASE) transcription = re.sub('<.*?>', '', transcription) transcript...
class Adamax(Optimizer): def __init__(self, params, lr=0.002, betas=(0.9, 0.999), eps=1e-08, weight_decay=0): if (not (0.0 <= lr)): raise ValueError('Invalid learning rate: {}'.format(lr)) if (not (0.0 <= eps)): raise ValueError('Invalid epsilon value: {}'.format(eps)) ...
def verify(verifier, prover): commitment = prover.commit() challenge = verifier.send_challenge(commitment) response = prover.compute_response(challenge) return verifier.verify(response)
def get_learning_rate(optimizer): for group in optimizer.param_groups: if ('lr' in group): return group['lr']
class CanineForMultipleChoice(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def test_ic_neck(): neck = ICNeck(in_channels=(4, 16, 16), out_channels=8, norm_cfg=dict(type='SyncBN'), align_corners=False) assert _conv_has_norm(neck, sync_bn=True) inputs = [torch.randn(1, 4, 32, 64), torch.randn(1, 16, 16, 32), torch.randn(1, 16, 8, 16)] neck = ICNeck(in_channels=(4, 16, 16), out_c...
class LanguageAccept(Accept): def _value_matches(self, value, item): return ((item == '*') or (_normalize_lang(value) == _normalize_lang(item))) def best_match(self, matches, default=None): result = super(LanguageAccept, self).best_match(matches) if (result is not None): retu...
def _gen_swizzles(cls): KEYGROUP_SET = ['xyzw', 'rgba', 'stpq'] cls._swizzle_to_keygroup = {} cls._keygroup_to_checker = {} def make_valid_attribs_checker(key_group): def check(instance, pattern): valid_attribs = set(key_group[:instance.n]) pattern_set = set(pattern) ...
def enable_calibration(model): logger.info('Enabling Calibration') for (name, module) in model.named_modules(): if name.endswith('_quantizer'): if (module._calibrator is not None): module.disable_quant() module.enable_calib() else: ...
def short_repr(x, n=64): x_repr = repr(x) if isinstance(x_repr, bytes_type): try: x_repr = text_type(x_repr, 'utf-8') except UnicodeDecodeError: x_repr = text_type(x_repr, 'latin1') if (len(x_repr) > n): x_repr = ((x_repr[:(n // 2)] + '...') + x_repr[(len(x_re...
def test_inclusive_policy_negative_examples_3(digraph, features_1d, labels): policy = InclusivePolicy(digraph, features_1d, labels) ground_truth = [True, True, False, False, False, False, True, True] result = policy.negative_examples('2.1') assert_array_equal(ground_truth, result)
.parametrize('task_name', [tn for tn in ((all_tasks - julia_tasks) - noref_tasks)]) def test_reference_posterior_exists(task_name): task = get_task(task_name) reference_samples = task.get_reference_posterior_samples(num_observation=1) assert hasattr(reference_samples, 'shape') assert (len(reference_samp...
def get_verifytype(html): if ('icon_pf_approve_co' in html): return 2 elif ('icon_pf_approve' in html): return 1 else: return 0
def mask_adj_out(adj, max_distance, coordinates, return_xarray=False): n_nodes = adj.shape[0] assert (n_nodes == adj.shape[1]), 'Adjacency matrix must be #Nodes x #Nodes' tmp = xa.DataArray(adj, dims=('x1', 'cord'), coords={'x1': range(n_nodes), 'cord': coordinates}) new_adj = np.zeros((n_nodes, n_nodes...
def generator_loss(loss_func, fake): fake_loss = 0 if loss_func.__contains__('wgan'): fake_loss = (- tf.reduce_mean(fake)) if (loss_func == 'lsgan'): fake_loss = tf.reduce_mean(tf.squared_difference(fake, 1.0)) if ((loss_func == 'gan') or (loss_func == 'dragan')): fake_loss = tf....
class MoEModelOutputWithPastAndCrossAttentions(ModelOutput): last_hidden_state: torch.FloatTensor = None past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None cross_attentions: ...
def init_classifier(dataset): d = data.to_dataset(dataset) if (dataset == 'mnist'): return lenet.LeNet5() elif (dataset in ('svhn', 'fashion')): return resnet.ResNet(d.nc, d.ny) else: return linear.MLP(d.nx, d.ny)
def is_valid_total_length(index, date_to_sent_mapping, all_sent_dates, timeline_properties): selected_date = all_sent_dates[index] if ((selected_date < timeline_properties.start) or (selected_date > timeline_properties.end)): return False return (sum([len(sents) for sents in date_to_sent_mapping.val...
def syncMain(): zConf = Zeroconf() bleRelay = BLERelay() browser = ServiceBrowser(zConf, '_ble_relay_recv._tcp.local.', bleRelay) DBG('Looking for ble relay receivers', logLevel=LogLevel.DEBUG) input('Cancel with CTRL-D')
def ShenfunFile(name, T, backend='hdf5', mode='r', mesh='quadrature', **kw): if (backend.lower() == 'hdf5'): return HDF5File((name + '.h5'), domain=[np.squeeze(d) for d in T.mesh(kind=mesh)], mode=mode, **kw) assert (kw.get('forward_output', False) is False), 'NetCDF4 cannot store complex arrays, use HD...
class Schedule_Autofz(Schedule_Base): def __init__(self, fuzzers, prep_time=300, focus_time=300, diff_threshold=10): super().__init__(fuzzers=fuzzers, prep_time=prep_time, focus_time=focus_time) self.name = f'Autofz_{prep_time}_{focus_time}_AIMD_DT{diff_threshold}' self.policy_bitmap = polic...
def register_Ns3MeshWifiInterfaceMacPlugin_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::MeshWifiInterfaceMacPlugin const &', 'arg0')]) cls.add_method('AssignStreams', 'int64_t', [param('int64_t', 'stream')], is_pure_virtual=True, is_virtual=True) cls.add_method('Re...
class TestUnitImpulse(object): def test_no_index(self): assert_array_equal(waveforms.unit_impulse(7), [1, 0, 0, 0, 0, 0, 0]) assert_array_equal(waveforms.unit_impulse((3, 3)), [[1, 0, 0], [0, 0, 0], [0, 0, 0]]) def test_index(self): assert_array_equal(waveforms.unit_impulse(10, 3), [0, 0...
def train(args, net, env): with tf.Session() as sess: tf.global_variables_initializer().run() saver = tf.train.Saver(tf.global_variables(), max_to_keep=5) if (len(args.ckpt_name) > 0): saver.restore(sess, os.path.join(args.save_dir, args.ckpt_name)) shift = sess.run(net.s...
def _dispatch(tree, symbols, inferred_symbols): try: tree = iter(tree) for t in tree: _dispatch(t, symbols, inferred_symbols) except TypeError: current_module = sys.modules[__name__] meth = getattr(current_module, ('_' + tree.__class__.__name__)) return meth(t...
def _print_alignment(alignment, a, b, empty_symbol='<eps>', separator=' ; ', file=sys.stdout): a_padded = [] b_padded = [] ops_padded = [] for (op, i, j) in alignment: op_string = str(op) a_string = (str(a[i]) if (i is not None) else empty_symbol) b_string = (str(b[j]) if (j is n...
_model_architecture('transformer_lm', 'transformer_lm_gpt2_small') def transformer_lm_gpt2_small(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_layers = getattr(args, 'decoder_layers', 24) ar...
class FNetTokenizerFast(PreTrainedTokenizerFast): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES model_input_names = ['input_ids', 'token_type_ids'] slow_tokenizer_class = FNetTokenizer ...
class Linear(object): def __init__(self, input_size, output_size, weight_init=Uniform(), name='', biases=True): self.W = theano.shared(weight_init((input_size, output_size)), name=('%s_W' % name)) self.b = None self.params = [self.W] if biases: self.b = theano.shared(weig...
def test_python_iterator_in_cpp(): t = (1, 2, 3) assert (m.object_to_list(t) == [1, 2, 3]) assert (m.object_to_list(iter(t)) == [1, 2, 3]) assert (m.iterator_to_list(iter(t)) == [1, 2, 3]) with pytest.raises(TypeError) as excinfo: m.object_to_list(1) assert ('object is not iterable' in s...
def process_mat(mat): videos = mat['Tags'][0] result = [] for video_mat in videos: video_mat = video_mat[0] video_data = process_video_mat(video_mat) result.append(video_data) return result
class DIV2KJPEG(DIV2KSR): def __init__(self, phase, opt): self.quality = opt.quality super().__init__(phase, opt) def get_subdir(self): dir_HQ = 'DIV2K_train_HR' dir_LQ = 'DIV2K_train_JPEG/{}'.format(self.quality) return (dir_HQ, dir_LQ)
class GradedModularFormElement(ModuleElement): def __init__(self, parent, forms_datum): forms_dictionary = {} if isinstance(forms_datum, dict): for (k, f) in forms_datum.items(): if isinstance(k, (int, Integer)): k = ZZ(k) if (k == ...
class eSEModule(nn.Module): def __init__(self, channel, reduction=4): super(eSEModule, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Conv2d(channel, channel, kernel_size=1, padding=0) self.hsigmoid = Hsigmoid() def forward(self, x): input = x ...
def load_model(model_path=''): model = get_concat_2levelmel_model() if torch.cuda.is_available(): model.cuda() return model
def register_Ns3GlobalRouteManager_methods(root_module, cls): cls.add_method('AllocateRouterId', 'uint32_t', [], is_static=True) cls.add_method('DeleteGlobalRoutes', 'void', [], is_static=True) cls.add_method('BuildGlobalRoutingDatabase', 'void', [], is_static=True) cls.add_method('InitializeRoutes', 'v...
.parametrize('fname, ctx, func_name', list_ctx_and_func_name2([('reset_nan', 'ResetNaN'), ('reset_inf', 'ResetInf')])) .parametrize('val', [0, (- 1)]) .parametrize('seed', [313]) def test_reset_nan_reset_inf_forward_backward(seed, val, fname, ctx, func_name): from nbla_test_utils import function_tester np_fun =...
def evaluate(args, model: PreTrainedModel, tokenizer: PreTrainedTokenizer, prefix='') -> Dict: eval_output_dir = args.output_dir eval_dataset = load_and_cache_examples(args, tokenizer, evaluate=True) if (args.local_rank in [(- 1), 0]): os.makedirs(eval_output_dir, exist_ok=True) args.eval_batch_...
class Null(nn.Module): def __init__(self): super(Null, self).__init__() def forward(self, x): return x
class RandomLightPendulum(ModifiablePendulumEnv): def __init__(self): super(RandomLightPendulum, self).__init__() self.mass = uniform_exclude_inner(self.np_random.uniform, self.EXTREME_LOWER_MASS, self.EXTREME_UPPER_MASS, self.RANDOM_LOWER_MASS, self.RANDOM_UPPER_MASS) def reset(self, new=True):...
def center_plus_four_crops(img: Tensor, size: List[int], margin_h: int, margin_w: int) -> Tuple[(Tensor, Tensor, Tensor, Tensor, Tensor)]: if isinstance(size, numbers.Number): size = (int(size), int(size)) elif (isinstance(size, (tuple, list)) and (len(size) == 1)): size = (size[0], size[0]) ...
def test_base_encoder(): encoder = BaseEncoder() encoder.init_weights() encoder.train() feat = torch.randn(1, 256, 4, 40) out_enc = encoder(feat) assert (out_enc.shape == torch.Size([1, 256, 4, 40]))
def setup_logger(name, save_dir, prefix='', timestamp=True): logger = logging.getLogger(name) logger.setLevel(logging.INFO) ch = logging.StreamHandler(stream=sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s') ch.setFormatter(for...
def buildCorpus(body_file, summ_file, w_exp=False): logger.debug(('building corpus [body file]: %s' % body_file)) logger.debug(('building corpus [summ file]: %s' % summ_file)) corpus = [] body_corpus = loadFile(body_file) summ_corpus = loadFile(summ_file) for curr_filename in body_corpus: ...
def GetKCoreNodes_PNEANet(Graph, CoreIdSzV): return _snap.GetKCoreNodes_PNEANet(Graph, CoreIdSzV)
class Data(QtCore.QObject): data_updated = QtCore.pyqtSignal() def __init__(self, data={}): QtCore.QObject.__init__(self) self.data = data def notify_update(self): self.data_updated.emit() def __getitem__(self, key): return self.data.__getitem__(key) def __setitem__(s...
class CohomologyRAAG(CombinatorialFreeModule): def __init__(self, R, A): if (R not in Fields()): raise NotImplementedError('only implemented with coefficients in a field') self._group = A names = tuple([('e' + name[1:]) for name in A.variable_names()]) from sage.graphs.in...
class MLP(nn.Module): def __init__(self, n_input, n_output, hidden_neurons=(512,), dropout_rate=0.1): super(MLP, self).__init__() n_neurons = (((n_input,) + hidden_neurons) + (n_output,)) self.layers = nn.ModuleList() for i in range((len(n_neurons) - 1)): self.layers.appe...
def prefetch_test(opt): os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpus_str Dataset = dataset_factory[opt.dataset] opt = opts().update_dataset_info_and_set_heads(opt, Dataset) print(opt) Logger(opt) Detector = detector_factory[opt.task] split = ('val' if (not opt.trainval) else 'test') dat...
.parametrize('observation_shape', [(100,)]) .parametrize('hidden_units', [[256, 256]]) .parametrize('batch_size', [32]) .parametrize('use_batch_norm', [False, True]) .parametrize('dropout_rate', [None, 0.2]) .parametrize('activation', [torch.nn.ReLU()]) def test_vector_encoder(observation_shape: Sequence[int], hidden_u...
class TransformerEncoder(Module): __constants__ = ['norm'] def __init__(self, encoder_layer, num_layers, norm=None): super(TransformerEncoder, self).__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self,...
def generate_xdmf(h5filename, periodic=True, order='visit'): import h5py f = h5py.File(h5filename, 'a') keys = [] f.visit(keys.append) assert (order.lower() in ('paraview', 'visit')) datasets = {2: {}, 3: {}} for key in keys: if (f[key.split('/')[0]].attrs['rank'] > 0): c...
def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--predictions', required=True, help='Path to predictions file.') parser.add_argument('--track', choices=['default', 'xlingual'], default='default', help='default track or xlingual track. For xlingual, we need to use a different tokeni...
class IdentificationClassificationFeatures(): def __init__(self, input_ids, attention_mask, token_type_ids, cls_index, p_mask, example_index, unique_id, paragraph_len, token_is_max_context, tokens, token_to_orig_map, span_to_orig_map, class_label, span_labels, valid_span_missing_in_context, data_id: str=None, encod...
def print_all_problematic_outputs_between_partitions(graph: Graph, edge_weight_function): problems = [] valid_state = True for n in graph.nodes: if (n.value_type in {type(None), list, tuple, dict, set, int, bool, float, str, slice, torch.Size, torch.dtype}): for o in n.out_edges: ...
def process_spec_file(spec_name, num_bins: int, upper_limit: int, spec_dir: Path): spec_file = (spec_dir / f'{spec_name}.json') loaded_json = json.load(open(spec_file, 'r')) if (loaded_json.get('output_tbl') is None): return None mz = loaded_json['output_tbl']['formula_mass_no_adduct'] inten...
def convert_shuffle(base_input_path, base_output_path, short_name): if (not zipfile.is_zipfile(base_input_path)): raise FileNotFoundError(('Expected %s to be the zipfile with AQMAR in it' % base_input_path)) with zipfile.ZipFile(base_input_path) as zin: namelist = zin.namelist() annotati...
class TestCounterOps(TestCase): def test_stats_ops(self): workspace.RunOperatorOnce(core.CreateOperator('StatRegistryExport', [], ['prev_k', 'prev_v', 'prev_ts'])) previous_keys = workspace.FetchBlob('prev_k') existing = len(previous_keys) prefix = '/'.join([__name__, 'TestCounterOps...
def _get_build_directory(name, verbose): root_extensions_directory = os.environ.get('TORCH_EXTENSIONS_DIR') if (root_extensions_directory is None): root_extensions_directory = os.path.join(tempfile.gettempdir(), 'torch_extensions') if verbose: print('Using {} as PyTorch extensions root...'.f...
def _pickle_RecognizableSeriesSpace(coefficients, indices, category): return RecognizableSeriesSpace(coefficients, indices=indices, category=category)
def load_from_wv_format(filename): with open(filename) as f: l = f.readline().split() (total_num, embedding_size) = (int(l[0]), int(l[1])) res = np.zeros((total_num, embedding_size), dtype=float) ls = map((lambda x: x.strip().split()), f.readlines()) for line in ls: ...
class EarlyStopping(): def __init__(self, min_max='min', tolerance=20, min_delta=1e-09): self.tolerance = tolerance self.min_delta = min_delta self.min_max = min_max self.counter = 0 self.early_stop = False def min_stopping(self, valid_loss, best_valid_loss): if (...
def z_score(x, axis=0): x = np.array(x).astype(float) xr = np.rollaxis(x, axis=axis) xr -= np.mean(x, axis=axis) xr /= np.std(x, axis=axis) return x
class EndStateElimination(transformation.MultiStateTransformation): end_state = transformation.PatternNode(SDFGState) def expressions(cls): return [sdutil.node_path_graph(cls.end_state)] def can_be_applied(self, graph, expr_index, sdfg, permissive=False): state = self.end_state out_e...
def main(): args = parse_args() benchmarks = [ALL_BENCHMARKS[name]() for name in args.benchmarks] for bench in benchmarks: bench.run() for bench in benchmarks: bench.display()
def test_join_items_left_outer_deep(join_items): (left_items, right_items) = join_items joined = pyhf.workspace._join_items('left outer', left_items, right_items, key='name', deep_merge_key='deep') assert (next((k['deep'] for k in joined if (k['name'] == 'common'))) == [{'name': 1}, {'name': 2}])
def _sample_line(real, fake): shape = ([real.size(0)] + ([1] * (real.dim() - 1))) alpha = torch.rand(shape, device=real.device) sample = (real + (alpha * (fake - real))) return sample
class T5EncoderModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
.parametrize('temperature', [0.0, 0.5, 1.0, 2.0]) def test_self_adversarial_negative_sampling(temperature): labels = np.array([1, 0, (- 2), 0, 1], dtype=np.int32) logit_scores = np.array([1.2, (- 2.3), 0.0, 4.5, (- 0.67)], dtype=np.float32) scores = expit(logit_scores) loss_func = SelfAdversarialNegativ...
def load_optim(model_optim_dict, load_dir): checkpoint_dir = os.path.join('checkpoints/', load_dir) print('LOAD_OPTIM: NOT YET LOADING ANY MOMENTUM PARAMS') if (not os.path.exists(checkpoint_dir)): print("...ain't no full checkpoint here!") else: ckpt_names = os.listdir(checkpoint_dir) ...
class PreprocessingConfig(): defaults: List[Any] = field(default_factory=(lambda : DEFAULTS)) hydra: Dict[(str, Any)] = field(default_factory=(lambda : {'run': {'dir': './runs/preprocessing/${now:%m-%d}/dataset-${dataset.name}'}})) seed: int = 21 dry_run: bool = False dataset: DatasetConfig = MISSIN...
class Bottleneck(nn.Module): def __init__(self, in_channels, out_channels, dropout_prob=0.0, downsample=False, asymmetric_ksize=None, dilation=1, use_prelu=True): super().__init__() bt_channels = (out_channels // 4) self.downsample = downsample self.channels_to_pad = (out_channels - ...
def init(args): load_config_file_to_args(args) check_and_update_generation_args(args) if (not args.src_locale): args.src_locale = args.eval_src_languages if (not args.tgt_locale): args.tgt_locale = args.eval_tgt_languages set_seed(args) devices = get_devices() device = device...
class CenterCrop(DauphinTransform): def __init__(self, size, name=None, prob=1.0, level=0): self.size = size self.transform_func = transforms.CenterCrop(self.size) super().__init__(name, prob, level) def transform(self, pil_img, label, **kwargs): return (self.transform_func(pil_i...
def storage_from_cache(cls, key): storage_ref = shared_cache.get(key) if (storage_ref is None): return None return cls._new_with_weak_ptr(storage_ref.cdata)
def normalization(x): return [((float(i) - min(x)) / float(((max(x) - min(x)) + zero_bit))) for i in x]
def try_ann_to_type(ann, loc): if (ann is None): return TensorType.get() if (inspect.isclass(ann) and issubclass(ann, torch.Tensor)): return TensorType.get() if is_tuple(ann): return TupleType([try_ann_to_type(a, loc) for a in ann.__args__]) if is_list(ann): elem_type = t...
def type_ref_to_reflection_dict(type_ref): if type_ref.is_primitive_type(): return ('{ kind: "primitive", type: %s, typeStr: "%s" }' % (type_ref.reflection_constructor, type_ref.name)) else: return ('{ kind: "struct", type: %s, typeStr: "%s" }' % (type_ref.reflection_constructor, type_ref.name))
def noisystudent_loader(): model = timm.create_model('tf_efficientnet_l2_ns', pretrained=False) load_model_state_dict(model, 'efficientnet-l2-noisystudent') return model
def get_bag_of_keywords(cmd): cmd = clean_anonymize_command(cmd) tokens = cmd.strip().split() tokens = [x for x in tokens if (VAR_STR not in x)] return tokens
def token_switching(encoding, prob): for (i, token) in enumerate(encoding['input_ids'][0]): if (token not in [0, 1, 2, 3, 4]): if (np.random.uniform(0, 1) < prob): encoding['input_ids'][0][i] = np.random.choice(np.arange(5, tokenizer.vocab_size), 1)[0] return encoding
def get_inv_cdf_fns(cdfs: DataFrame) -> Iterable[Callable[([Array], Array)]]: def inv_cdf_factory(cdfs_df: DataFrame, key: str) -> Callable[([Array], Array)]: series = pd.Series(cdfs_df[key].index.values, index=cdfs[key].values) index = series.index def repaid_probs_fn(query_probs: Array) ->...
def cross_entropy(input_, target): input_ = input_.view(input_.size(0), (- 1)) loss = (- (target * torch.log(torch.clamp(input_, min=epsilon, max=1))).sum((- 1))) return loss.mean()
class GatHIVNet(HIVNet): def __init__(self, hidden_dim, num_graph_layers, in_feat_drop, residual, readout='mean', activation=nn.ReLU, heads=8, gat_dropout=0.0, gat_version=1): self.heads = heads self.gat_dropout = gat_dropout assert (gat_version in [1, 2]) self.gat_version = gat_vers...
def main(args, config): utils.init_distributed_mode(args) device = torch.device(args.device) seed = (args.seed + utils.get_rank()) torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True print('Creating dataset') datasets = [create_dataset('pretrain', co...
def get_stupid_embedder(config): cm = config.model cmu = cm.utterance_embedder glove_embeddings = GloveEmbeddings(cmu.vocab_size, cmu.glove_dim) token_embedder = TokenEmbedder(glove_embeddings, trainable=cmu.trainable) if (cmu.type == 'average'): utterance_embedder = AverageUtteranceEmbedder...
def is_blocked_key(key): if (key in {'updated', ''}): return True if (('image' in key) or ('caption' in key)): return True return False