code
stringlengths
101
5.91M
def get_args(): parser = argparse.ArgumentParser('Fed-BEiT pre-training', add_help=False) parser.add_argument('--batch_size', default=64, type=int) parser.add_argument('--save_ckpt_freq', default=50, type=int) parser.add_argument('--discrete_vae_weight_path', default='/home/yan/data/SSL-FL/tokenizer_wei...
class Word2VecTraining(): def train(self, data_path, model_name, vector_name, vector_size=100, alpha=0.025, min_alpha=0.0001, sg=0, hs=0, negative=5, ns_exponent=0.75, window=5, min_count=5, max_vocab_size=None, workers=3, epochs=5, sample=0.001, cbow_mean=1, compute_loss=True, callbacks=()): if isinstance(...
def list_results(args): model_name = args.model_name config_name = args.config_name.zfill(2) data_type = args.data_type num_per_page = args.num_per_page data_dir = args.data_dir task = args.task.zfill(2) mem_size = args.mem_size run_id = args.run_id.zfill(2) trial_num = args.trial_nu...
def load_checkpoint_to_cpu(path, arg_overrides=None): try: with open(path, 'rb') as f: state = torch.load(f, map_location=(lambda s, l: default_restore_location(s, 'cpu'))) except (ModuleNotFoundError, ImportError): state = torch.load(path, map_location=(lambda s, l: default_restore_...
def test_mutation_insert_twice_no_success(default_test_case): test_factory = MagicMock(tf.TestFactory) def side_effect(tc, pos): return (- 1) test_factory.insert_random_statement.side_effect = side_effect chromosome = tcc.TestCaseChromosome(default_test_case, test_factory=test_factory) confi...
class sdist(old_sdist): def add_defaults(self): old_sdist.add_defaults(self) dist = self.distribution if dist.has_data_files(): for data in dist.data_files: self.filelist.extend(get_data_files(data)) if dist.has_headers(): headers = [] ...
def register_dataset(mod_name, dset_name, data_cfg=None): register_func = eval(mod_name) register_func.register_with_name_cfg(dset_name, data_cfg)
def probability_variance(sampled_probabilities, mean_probabilities=None): if (mean_probabilities is None): mean_probabilities = np.mean(sampled_probabilities, axis=1) mean_probabilities = np.expand_dims(mean_probabilities, axis=1) return ((sampled_probabilities - mean_probabilities) ** 2).mean(1).su...
class Config(): size = attr.ib(type=str) dataset = attr.ib(type=str) single_resolution = attr.ib(type=int) def two_d_resolution(self): return f'{self.single_resolution}x{self.single_resolution}' def gcs_folder_name(self): return f'convnext_{self.size}_{self.dataset}_{self.single_reso...
def generate_uncertainty_qes(args, question): if (args.method == 'few_shot_cot'): given_prompt = create_input_prompt(args, True) if (args.dataset in ('gsm8k', 'asdiv', 'svamp', 'singleeq', 'addsub', 'multiarith')): uncertainty_record = {'dataset_idx': question['question_idx'], 'variance': float,...
class PPO(NPO): def __init__(self, env_spec, policy, baseline, scope=None, max_path_length=500, discount=0.99, gae_lambda=1, center_adv=True, positive_adv=False, fixed_horizon=False, pg_loss='surrogate_clip', lr_clip_range=0.01, max_kl_step=0.01, optimizer=None, optimizer_args=None, policy_ent_coeff=0.0, use_softpl...
class ValueFunction(nn.Module): def __init__(self, state_dim, hidden_dim=256, n_hidden=2): super().__init__() dims = [state_dim, *([hidden_dim] * n_hidden), 1] self.v = mlp(dims, squeeze_output=True) def forward(self, state): return self.v(state)
def safe_divide(numerator, denominator, name='safe_divide'): return tf.where(math_ops.greater(denominator, 0), math_ops.divide(numerator, denominator), tf.zeros_like(numerator), name=name)
class CorefTest(ModelTestCase): def setUp(self): super(CorefTest, self).setUp() self.set_up_model('tests/fixtures/coref/experiment.json', 'tests/fixtures/data/coref/sample.gold_conll') def test_coref_model_can_train_save_and_load(self): self.ensure_model_can_train_save_and_load(self.para...
def create_pipeline_configuration(DEBUG=False, batch_size=8): config = {'batch_dim': 0, 'depth': 10000, 'basic_blocks': (T5LayerNorm, Linear, Dropout, StatelessEmbedding, Embedding), 'model_inputs': {'attention_mask': {'shape': torch.Size([8, 320]), 'dtype': torch.int64, 'is_batched': True, 'used_by': [0, 8]}, 'dec...
def BaulieuVII_calc(TP, FP, FN, TN): try: n = (((TP + FP) + FN) + TN) return ((FP + FN) / (n + ((TP * (TP - 4)) * (TP - 4)))) except Exception: return 'None'
class SignalToNoiseRatioContrastiveLoss(ContrastiveLoss): def __init__(self, **kwargs): super().__init__(**kwargs) c_f.assert_distance_type(self, SNRDistance) def get_default_distance(self): return SNRDistance()
class Transition(nn.Module): def __init__(self, in_planes, out_planes): super(Transition, self).__init__() self.bn = nn.BatchNorm2d(in_planes) self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=1, bias=False) self.pdelu = PDELU() def forward(self, x): out = self.con...
_numpy_output(positive=True, check_dtype=True) def test_ufunc_log2_u(A: dace.uint32[10]): return np.log2(A)
.pure .gpu .parametrize('bn_impl', ['cuDNN', 'pure']) def test_mbconv(bn_impl, use_cpp_dispatcher): with change_default(donnx.ONNXConv, 'cuDNN'), change_default(donnx.ONNXBatchNormalization, bn_impl): with torch.no_grad(): dace_inputs = torch.rand(8, 32, 224, 224).cuda() torch_inputs...
def simGetStackInt32Value(stackHandle): value = ffi.new('int *') ret = lib.simGetStackInt32Value(stackHandle, value) _check_return(ret) return value[0]
def test_gpu_schedule_scalar_autodetect_2(): def add(a: (dace.float32[(10, 10)] dace.StorageType.GPU_Global), b: dace.float32): return (a + b) sdfg = add.to_sdfg() set_default_schedule_and_storage_types(sdfg, None) for (node, _) in sdfg.all_nodes_recursive(): if isinstance(node, (dace.n...
def last_relevant_time_slice(output, sequence_length): shape = output.get_shape() if (len(shape) == 3): batch_size = tf.shape(output)[0] max_length = tf.shape(output)[1] out_size = int(output.get_shape()[2]) index = ((tf.range(0, batch_size) * max_length) + tf.subtract(sequence_l...
def eval(args): cfg = CommonConfiguration.from_yaml(args.setting) dictionary = CommonConfiguration.from_yaml(cfg.DATASET.DICTIONARY) dictionary = next(dictionary.items())[1] prefix = 'infer' transforms = prepare_transforms_seg() (*dataset_str_parts, dataset_class_str) = cfg.DATASET.CLASS.split('...
def trickledown(array, i, size): if ((level(i) % 2) == 0): trickledownmin(array, i, size) else: trickledownmax(array, i, size)
class LegacyFairseqLRScheduler(FairseqLRScheduler): def __init__(self, args: Namespace, optimizer): if (not isinstance(optimizer, FairseqOptimizer)): raise ValueError('optimizer must be an instance of FairseqOptimizer') self.args = args self.optimizer = optimizer self.bes...
def make_env(env_name, terminates=True, **kwargs): env = None base_env = None env_infos = dict() if (env_name == 'maze'): from lifelong_rl.envs.environments.maze_env import MazeEnv base_env = MazeEnv env_infos['mujoco'] = False elif (env_name == 'half_cheetah'): from ...
def get_trained_data_separated_model(args, id, local_train_loader, local_test_loader, test_loader, base_net=None): torch.backends.cudnn.enabled = False if (base_net is not None): network = copy.deepcopy(base_net) else: network = get_model_from_name(args, idx=id) optimizer = optim.SGD(net...
def test_g2p(): g2p = G2P() char_sent = 'HELLO WORLD' phn_sent = g2p.encode(char_sent) logging.info(phn_sent)
def ParseSynset(canon): if (len(canon) == 0): return None return Synset(canon[0]['synset_name'], canon[0]['synset_definition'])
class TFBertForSequenceClassification(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
def train(train_list, model, criterion, optimizer, epoch): losses = AverageMeter() batch_time = AverageMeter() data_time = AverageMeter() train_loader = torch.utils.data.DataLoader(dataset.listDataset(train_list, shuffle=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize(mea...
class SplitByNode(): def __init__(self, group=None): self.rank = (- 1) self.size = (- 1) try: import torch if ((not torch.distributed.is_available()) or (not torch.distributed.is_initialized())): return except Exception as e: print(...
class DatasetISIC(Dataset): def __init__(self, datapath, fold, transform, split, shot, num=600): self.split = split self.benchmark = 'isic' self.shot = shot self.num = num self.base_path = os.path.join(datapath, 'ISIC') self.categories = ['1', '2', '3'] self.c...
def prepare_student_data(dataset, nb_teachers, save=False): assert input.create_dir_if_needed(FLAGS.train_dir) if (dataset == 'svhn'): (test_data, test_labels) = input.ld_svhn(test_only=True) elif (dataset == 'cifar10'): (test_data, test_labels) = input.ld_cifar10(test_only=True) elif (d...
def example_hin_random(feature_size_by_type=None, nodes_by_type={}, n_isolates_by_type={}, edges_by_type={}): check_isolates = False while (not check_isolates): G = nx.Graph() node_dict = {} for nt in nodes_by_type: nodes = ['{}_{}'.format(nt, ii) for ii in range(nodes_by_typ...
class MyLMHead(torch.nn.Module): def __init__(self, lm_head, mapping): super().__init__() self.my_lm_head = torch.nn.Linear(lm_head.in_features, len(mapping), bias=False) indices = [mapping[i] for i in range(len(mapping))] init_weight = lm_head.state_dict()['weight'][indices] ...
def freeze_BERT_parameters(model: BertForSequenceClassification, verbose: bool=True) -> None: if (not isinstance(model, BertForSequenceClassification)): raise TypeError params_to_freeze = ['bert.embeddings.', 'bert.encoder.layer.0.', 'bert.encoder.layer.1.', 'bert.encoder.layer.2.', 'bert.encoder.layer....
class SingleFileSanitizedNames(SingleFileSnapshotExtension): _write_mode = WriteMode.TEXT _file_extension = 'txt' def get_snapshot_name(cls, *, test_location: 'PyTestLocation', index: 'SnapshotIndex') -> str: original_name = SingleFileSnapshotExtension.get_snapshot_name(test_location=test_location, ...
def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None, color=False, resize=None): with open(index_file_path, 'rb') as index_file: split_lines = [ln.decode().strip().split('\t') for ln in index_file] pair_specs = [sl for sl in split_lines if (len(sl) > 2)] n_pairs = len(pair_specs) ...
def get_slide_prob_label(csv_file): pred_corpus = {} label_corpus = {} slide_id_list = [] with open(csv_file, 'r') as f: reader = csv.reader(f) for row in reader: if (len(row) == 5): slide_id = row[0].split('_')[0] prob_list = [float(row[3]), f...
class FC_Q(nn.Module): def __init__(self, state_dim, num_actions): super(FC_Q, self).__init__() self.l1 = nn.Linear(state_dim, 256) self.l2 = nn.Linear(256, 256) self.l3 = nn.Linear(256, num_actions) def forward(self, state): q = F.relu(self.l1(state)) q = F.relu(...
class ASR(sb.Brain): def compute_forward(self, batch, stage): batch = batch.to(self.device) (wavs, wav_lens) = batch.sig (bos_tokens, _) = batch.tokens_bos if self.hparams.gradient_checkpointing: wavs.requires_grad_() enc_out = torch.utils.checkpoint.checkpoin...
class Decoder(nn.Module): def __init__(self, vocab_size, d_model, N, heads, dropout): super().__init__() self.N = N self.embed = Embedder(vocab_size, d_model) self.pe = PositionalEncoder(d_model, dropout=dropout) self.layers = get_clones(DecoderLayer(d_model, heads, dropout),...
def load_phi_id(phi_id, timeout, output, client, headers, alphabet): file_path = os.path.join(output, '{}.html'.format(phi_id)) path_exists = (FLAGS.local or os.path.exists(file_path)) if path_exists: with open(file_path, 'r') as f: req_text = f.read().strip() else: req_text ...
class LazyOperatorNormInfo(): def __init__(self, A, A_1_norm=None, ell=2, scale=1): self._A = A self._A_1_norm = A_1_norm self._ell = ell self._d = {} self._scale = scale def set_scale(self, scale): self._scale = scale def onenorm(self): if (self._A_1_...
def make_padic_poly(parent, x, version): if (version == 0): return parent(x, construct=True) else: raise ValueError('unknown pickling version')
class XTagger(BaseXTagger): def __call__(self, vocabs, moving_params=None): top_recur = super(XTagger, self).__call__(vocabs, moving_params=moving_params) int_tokens_to_keep = tf.to_int32(self.tokens_to_keep) with tf.variable_scope('MLP'): (tag_mlp, xtag_mlp) = self.MLP(top_recur...
def test_downcast(): x = np.arange(10).astype(np.uint64) with expected_warnings(['Downcasting']): y = img_as_int(x) assert np.allclose(y, x.astype(np.int16)) assert (y.dtype == np.int16), y.dtype
.experimental def test_cat_features_transformer_empty_list(long_log_with_features, short_log_with_features): transformed = get_transformed_features(transformer=CatFeaturesTransformer([]), train=long_log_with_features, test=short_log_with_features) assert (len(transformed.columns) == 4) assert ('timestamp' i...
def do_log_training_loss(iteration, loss, *, lr_scheduler, grad_norm, num_examples, len_contexts, len_answers, logger, train_task, round_progress, epochs, task_progress, timestamp, writer, log_prefix): avg_batch_size = f'avbatch_{num_examples:.0f}_{len_contexts:.0f}_{len_answers:.0f}:' logger.info(f'{timestamp}...
def process(sentence, annotation, use_fine_grained_null=True): def compare(a, b): if (a[0] > b[0]): return 1 elif (a[0] == b[0]): if (a[1] > b[1]): return (- 1) else: return 1 else: return (- 1) def compare2(...
class MethodNotAllowed(HTTPException): code = 405 description = 'The method is not allowed for the requested URL.' def __init__(self, valid_methods=None, description=None): HTTPException.__init__(self, description) self.valid_methods = valid_methods def get_headers(self, environ=None): ...
def parse_config(filename): config = configparser.ConfigParser() config.read(filename) output = {} for section in config.sections(): output[section] = {} for key in config[section]: val_str = str(config[section][key]) if (len(val_str) > 0): val = p...
def validate(passages: Dict[(object, Tuple[(str, str)])], answers: List[List[str]], result_ctx_ids: List[Tuple[(List[object], List[float])]], workers_num: int, match_type: str) -> List[List[bool]]: match_stats = calculate_matches(passages, answers, result_ctx_ids, workers_num, match_type) top_k_hits = match_sta...
def encode_for_summarization(story_lines, summary_lines, tokenizer): story_lines_token_ids = [tokenizer.encode(line) for line in story_lines] story_token_ids = [token for sentence in story_lines_token_ids for token in sentence] summary_lines_token_ids = [tokenizer.encode(line) for line in summary_lines] ...
def _get_feature(model, loaders, device): views_features = defaultdict((lambda : defaultdict(list))) print('extracting features') with torch.no_grad(): for loader in loaders.values(): for (views, labels) in tqdm(loader, ncols=80): outputs = [] for (view_in...
def get_monitor_physical_size(monitor): width_value = ctypes.c_int(0) width = ctypes.pointer(width_value) height_value = ctypes.c_int(0) height = ctypes.pointer(height_value) _glfw.glfwGetMonitorPhysicalSize(monitor, width, height) return (width_value.value, height_value.value)
def KL_divergence(mu1: Tensor, log_var1: Tensor, mu2: Tensor, log_var2: Tensor, reduce_axis: int=(- 1)): log_det = (log_var1 - log_var2) trace_cov = (- log_det).exp() mean_diff = (((mu1 - mu2) ** 2) / log_var1.exp()) return (0.5 * (((trace_cov + mean_diff) + log_det).sum(reduce_axis) - mu1.shape[reduce_...
def taichi_scope(func): (func) def wrapped(*args, **kwargs): assert in_taichi_scope(), f'{func.__name__} cannot be called in Python-scope' return func(*args, **kwargs) return wrapped
class MHCABlock(nn.Module): def __init__(self, dim, num_heads, mlp_ratio=3, drop_path=0.0, qkv_bias=True, qk_scale=None, norm_layer=partial(nn.LayerNorm, eps=1e-06), shared_cpe=None, shared_crpe=None): super().__init__() self.cpe = shared_cpe self.crpe = shared_crpe self.factoratt_cr...
def read_langs(file_name, max_line=None): print('Reading lines from {}'.format(file_name)) (data, context_arr, conv_arr, kb_arr, conv_arr_plain) = ([], [], [], [], []) (node2id, neighbors_info) = ({}, {}) node_cnt = 0 max_resp_len = 0 (total_node_cnt, total_dep_cnt) = (0, 0) with open('data/...
((not have_sympy), 'SymPy not installed') def test_abs(): x = Symbol('x') e1 = abs(sympy.Symbol('x')) e2 = abs(x) assert (sympify(e1) == e2) assert (e1 == e2._sympy_()) e1 = abs((2 * sympy.Symbol('x'))) e2 = (2 * abs(x)) assert (sympify(e1) == e2) assert (e1 == e2._sympy_()) y = ...
def AllCusps(N): N = ZZ(N) if (N <= 0): raise ValueError('N must be positive') c = [] for d in divisors(N): n = num_cusps_of_width(N, d) if (n == 1): c.append(CuspFamily(N, d)) elif (n > 1): for i in range(n): c.append(CuspFamily(N,...
def cnn_large(in_ch, in_dim, num_classes=10): return nn.Sequential(nn.Conv2d(in_ch, 64, 3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(64, 64, 3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(64, 128, 3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(128, 128, 3, stride=1, padding=1), nn.ReLU(), nn.Conv2d(128, 128, 3, stri...
def get_tokens_with_boxes(unnormalized_word_boxes, list_of_words, token_label, tokenizer, pad_token_id=0, pad_token_box=[0, 0, 0, 0], max_seq_len=512, pad_token_class=7): assert (len(unnormalized_word_boxes) == len(list_of_words) == len(token_label)), f'Length of Bounding box: {len(unnormalized_word_boxes)}, words:...
def upload_files(data_root, data_dir, upload_func): for (root, dirs, files) in os.walk(data_dir): prefix = os.path.relpath(root, data_root) for file in files: file_name = ((prefix + '/') + file) filepath = os.path.join(root, file) upload_func(0, file_name, filepat...
def to_device(sample_list: Union[(SampleList, Dict[(str, Any)])], device: device_type='cuda'): if isinstance(sample_list, collections.Mapping): sample_list = convert_batch_to_sample_list(sample_list) if (not isinstance(sample_list, SampleList)): warnings.warn('You are not returning SampleList/Sa...
def main_mlp(): parser = argparse.ArgumentParser(description='GNN baselines on ogbgmol* data with Pytorch Geometrics') parser.add_argument('--device', type=int, default=0, help='which gpu to use if any (default: 0)') parser.add_argument('--num_mlp_layers', type=int, default=6, help='number of mlp layers (de...
class CustomModuleQuantizeHandler(QuantizeHandler): def convert(self, quantizer, node, load_arg, debug=False): assert (node.op == 'call_module') observed_custom_module = quantizer.modules[node.target] if (node.name in quantizer.activation_post_process_map): observed_custom_module...
def save_config_file(ppo_config, env, file_path): task_config = env._task.get_task_params() for task_param in task_config: if (not isinstance(task_config[task_param], str)): task_config[task_param] = str(task_config[task_param]) env_config = env.get_world_params() env.close() con...
def _kl_error_function(x: np.ndarray, range_min: float, range_max: float, n_bins: int=2048, n_bits: int=8) -> np.float32: if (range_max <= range_min): return np.inf (bc, bv) = np.histogram(x, bins=n_bins) if (not _is_range_valid(bv, range_min, range_max)): return np.inf q_bins = uniform_...
class Evaluator(): def initialize(cls): cls.ignore_index = 255 def classify_prediction(cls, pred_mask, batch): gt_mask = batch.get('query_mask') query_ignore_idx = batch.get('query_ignore_idx') if (query_ignore_idx is not None): assert (torch.logical_and(query_ignore_...
def _verify_python3_env(): if PY2: return try: import locale fs_enc = codecs.lookup(locale.getpreferredencoding()).name except Exception: fs_enc = 'ascii' if (fs_enc != 'ascii'): return extra = '' if (os.name == 'posix'): import subprocess ...
class RandomSampler(Sampler[int]): data_source: Sized replacement: bool def __init__(self, data_source: Sized, replacement: bool=False, num_samples: Optional[int]=None, generator=None) -> None: self.data_source = data_source self.replacement = replacement self._num_samples = num_samp...
def compare_spectra(actual, desired): test_helper.assert_quantity_allclose(actual.frequency, desired.frequency) test_helper.assert_quantity_allclose(actual.luminosity, desired.luminosity) if getattr(actual, 'distance', None): test_helper.assert_quantity_allclose(actual.distance, desired.distance)
class WhisperProcessor(ProcessorMixin): feature_extractor_class = 'WhisperFeatureExtractor' tokenizer_class = 'WhisperTokenizer' def __init__(self, feature_extractor, tokenizer): super().__init__(feature_extractor, tokenizer) self.current_processor = self.feature_extractor self._in_t...
class Encoder(nn.Module): def __init__(self, input_size, embedding_size, hidden_size, num_layers, p): super(Encoder, self).__init__() self.dropout = nn.Dropout(p) self.hidden_size = hidden_size self.num_layers = num_layers self.embedding = nn.Embedding(input_size, embedding_s...
def plot_stuff(images, labels, filename): plt.figure(figsize=(7, 7)) for (i, image) in enumerate(images): ax = plt.subplot(3, 3, (i + 1)) plt.imshow(image.numpy().astype('int')) plt.title(int(labels[i])) plt.axis('off') plt.savefig(filename)
def non_sphere_rejection(partitionZ): orientation = Quaternion([0.0, 0.0, 0.0, 0.0]) new_location = np.array([0.0, 0.0, 0.0]) while True: orientation.random_orientation() new_location[2] = np.random.uniform(A, (max_height - A)) acceptance_prob = (non_sphere_GB(new_location, orientati...
def read_sparse_matrix_hdf5(filename, output_format=None): with pt.open_file(filename, mode='r') as fd: out = read_sparse_matrix_from_hdf5(fd, fd.root, output_format) return out
def subsample_dataset(dataset, idxs, absolute=True): mask = np.zeros(len(dataset)).astype('bool') if (absolute == True): mask[idxs] = True else: idxs = set(idxs) mask = np.array([(i in idxs) for i in dataset.uq_idxs]) dataset.data = dataset.data[mask] dataset.targets = np.arr...
class SplineCoupling(tf.keras.Model): def __init__(self, dim_out, settings_dict, **kwargs): super().__init__(**kwargs) self.dim_out = dim_out self.bins = settings_dict['bins'] self.default_domain = settings_dict['default_domain'] self.spline_params_counts = {'left_edge': 1, '...
def main(opts): logger = logging.getLogger(__name__) roidb = combined_roidb_for_training(cfg.TRAIN.DATASETS, cfg.TRAIN.PROPOSAL_FILES) logger.info('{:d} roidb entries'.format(len(roidb))) roi_data_loader = RoIDataLoader(roidb, num_loaders=opts.num_loaders, minibatch_queue_size=opts.minibatch_queue_size,...
def predict_contacts(model, x, y, use_cuda): b = len(x) (x, order) = pack_sequences(x) x = PackedSequence(Variable(x.data), x.batch_sizes) z = model(x) z = unpack_sequences(z, order) logits = [] y_list = [] for i in range(b): zi = z[i] lp = model.predict(zi.unsqueeze(0))....
def tune_config(key, name, tfms_fixed={}, **kwargs): import optuna from optuna.integration import FastAIPruningCallback from optuna.visualization import plot_optimization_history import logging import sys optuna.logging.get_logger('optuna').addHandler(logging.StreamHandler(sys.stdout)) stora...
def _assert_no_error(error, exception_class=None): if (error == 0): return cf_error_string = Security.SecCopyErrorMessageString(error, None) output = _cf_string_to_unicode(cf_error_string) CoreFoundation.CFRelease(cf_error_string) if ((output is None) or (output == u'')): output = (u...
def main(): logger.info('Parsing Spec...') spec = S.parse(toy_spec_str) logger.info('Parsing succeeded') logger.info('Building synthesizer...') synthesizer = Synthesizer(enumerator=SmtEnumerator(spec, depth=3, loc=2), decider=ExampleConstraintDecider(spec=spec, interpreter=ToyInterpreter(), examples...
def match_computation(stats_baseline, key=['gnn', 'dim_inner'], mode='sqrt'): stats = get_stats() if (stats != stats_baseline): while True: if (mode == 'sqrt'): scale = math.sqrt((stats_baseline / stats)) elif (mode == 'linear'): scale = (stats_bas...
def eps(err, is_real): e = RIF((- err), err) if is_real: return e else: return CIF(e, e)
class GrailEntityDisambProblem(): def __init__(self, pid, query, mention, target_id, candidates): self.pid = pid self.qid = pid.split('-')[0] self.query = query self.mention = mention self.target_id = target_id self.candidates = candidates
def get_model(args): print('Loading model...') if ('clip' in args.model): if (args.model == 'clip32B'): clip_variant = 'ViTB32' elif (args.model == 'clip16B'): clip_variant = 'ViTB16' elif (args.model == 'clip336'): clip_variant = 'ViTL14' elif...
def hash_model(data): cmd = np.hstack(data['cad_cmd']) param = np.vstack(data['cad_param']) ext = np.hstack(data['cad_ext']) hash_str = ((((sha256(np.ascontiguousarray(ext).flatten()).hexdigest() + '_') + sha256(np.ascontiguousarray(cmd).flatten()).hexdigest()) + '_') + sha256(np.ascontiguousarray(param...
class normfactor_builder(): is_shared = True def __init__(self, config): self.builder_data = {} self.config = config self.required_parsets = {} def collect(self, thismod, nom): maskval = (True if thismod else False) mask = ([maskval] * len(nom)) return {'mask'...
def set_module(module): def decorator(func): if (module is not None): func.__module__ = module return func return decorator
class VGVQADataset(VQADataset): def __init__(self, vis_processor, text_processor, vis_root, ann_paths): super().__init__(vis_processor, text_processor, vis_root, ann_paths) def __getitem__(self, index): ann = self.annotation[index] image_path = os.path.join(self.vis_root, ann['image']) ...
class Base(object): def __init__(self, db, nnet, func, model=None): super(Base, self).__init__() self._db = db self._nnet = nnet self._func = func if (model is not None): self._nnet.load_pretrained_params(model) self._nnet.cuda() self._nnet.eval_mo...
.script class Match(object): def __init__(self, match_results: torch.Tensor): if (len(match_results.shape) != 1): raise ValueError('match_results should have rank 1') if (match_results.dtype not in (torch.int32, torch.int64)): raise ValueError('match_results should be an int3...
def transform_svhn(augment=False, from_tensor=False, normalize=True): if (not augment): aug = [] else: aug = [transforms.RandomCrop(32, padding=4)] print('Dataset with basic SVHN augmentation') if from_tensor: cast = [] else: cast = [transforms.ToTensor()] if ...
def encode_label(x): x_copy = x.copy(deep=True) unique = sorted(list(set([str(item) for item in x_copy.astype(str).unique()]))) kv = {unique[i]: i for i in range(len(unique))} x_copy = x_copy.map((lambda x: kv[str(x)])) return x_copy