code
stringlengths
101
5.91M
class NoamOpt(): def __init__(self, model_size, factor, warmup, optimizer): self.optimizer = optimizer self._step = 0 self.warmup = warmup self.factor = factor self.model_size = model_size self._rate = 0 def zero_grad(self): self.optimizer.zero_grad() ...
def init_pretrained_weights(key): import os import errno import gdown def _get_torch_home(): ENV_TORCH_HOME = 'TORCH_HOME' ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME' DEFAULT_CACHE_DIR = '~/.cache' torch_home = os.path.expanduser(os.getenv(ENV_TORCH_HOME, os.path.join(os.getenv...
def _random_replay_eval(*, self, source, idx: int, **_kwargs): from returnn.tf.layers.basic import LayerBase assert isinstance(self, LayerBase) idx def _py_func() -> numpy.ndarray: elem = ReturnnLayersBackend._random_journal.get_next(new_out_template=self.output) assert isinstance(elem.o...
class SemimonomialActionVec(Action): def __init__(self, G, V, check=True): if check: from sage.modules.free_module import FreeModule_generic if (not isinstance(G, SemimonomialTransformationGroup)): raise ValueError(('%s is not a semimonomial group' % G)) i...
def calc_matrix_error(act_tiles, pred_tiles, ncol_tiles, nrow_tiles): user_matrix_error = 0.0 for fr in range(len(pred_tiles)): act_tile = act_tiles[fr] pred_tile = pred_tiles[fr] act_prob = np.array([[0.0 for i in range(ncol_tiles)] for j in range(nrow_tiles)]) pred_prob = np.ar...
def _IfExp(t, symbols, inferred_symbols): _dispatch(t.test, symbols, inferred_symbols) type_body = _dispatch(t.body, symbols, inferred_symbols) type_orelse = _dispatch(t.orelse, symbols, inferred_symbols) return dtypes.result_type_of(type_body, type_orelse)
class Policy(): def __init__(self, solver='ECOS'): self._name = None self._solver = solver def name(self): return self._name def scale_factors_array(self, scale_factors, job_ids, m, n): scale_factors_array = np.zeros((m, n)) for i in range(m): for j in ran...
def list_of_dicts__to__dict_of_lists(lst): if (len(lst) == 0): return {} keys = lst[0].keys() output_dict = collections.defaultdict(list) for d in lst: assert set(keys).issubset(set(d.keys())) for k in set(keys): output_dict[k].append(d[k]) return output_dict
def parse_file(args): (abundances_df, density_df, time_of_model, quantities_row) = convert_format(args.input_path) filename = os.path.splitext(os.path.basename(args.input_path))[0] save_fname = '.'.join((filename, 'csv')) resultant_df = pd.concat([density_df, abundances_df], axis=1) resultant_df.col...
class CosineSchedule(BaseSchedule): def __init__(self, timesteps: int, device: Optional[torch.device]=None, s: float=0.008, *args, **kwargs) -> None: self.s = s super().__init__(timesteps, device, *args, **kwargs) def _get_betas(self, timesteps: int) -> Tensor: steps = (timesteps + 1) ...
def tweakval(val, identifier): if (not identifier): raise ValueError('Must provide an identifier for tweakval to work') args = collect_args() for (k, v) in args.items(): stripped = k.replace('-', '_') if (stripped == identifier): log(('replacing %s in %s with %s' % (strip...
def evaluate(model, instances, iterator, device): with torch.no_grad(): model.eval() model.decode_type = 'mst' test_generator = iterator(instances=instances, shuffle=False, num_epochs=1) logger.info('Iterating over dataset') generator_tqdm = Tqdm.tqdm(test_generator, total=it...
class GaussianPolicy(nn.Module): def __init__(self, obs_dim, act_dim, hidden_dim=256, n_hidden=2): super().__init__() self.net = mlp([obs_dim, *([hidden_dim] * n_hidden), act_dim]) self.log_std = nn.Parameter(torch.zeros(act_dim, dtype=torch.float32)) def forward(self, obs): mean...
def test_ufunc_afterward(): assert ((ak.operations.values_astype(ak.highlevel.Array([{'x': 1.1}, {'x': 3.3}]), np.float32)['x'] + 1).to_list() == [2., 4.])
class TestExampleKeyORM(ORMTester): def object(self): return ('bob', 4) def orm(self): return ExampleKeyORM()
def check_exists(path, preserve=DO_PRESERVE_RUNS): if osp.exists(path): print(f'{path} exists') if (not preserve): print(f'removing {path}') shutil.rmtree(path, ignore_errors=True) return True return False
def _destinsrc(src, dst): src = abspath(src) dst = abspath(dst) if (not src.endswith(os.path.sep)): src += os.path.sep if (not dst.endswith(os.path.sep)): dst += os.path.sep return dst.startswith(src)
class BaseBackbone(nn.Module, metaclass=ABCMeta): def __init__(self): super(BaseBackbone, self).__init__() def init_weights(self, pretrained=None): if isinstance(pretrained, str): logger = logging.getLogger() load_checkpoint(self, pretrained, strict=False, logger=logger) ...
def _load_data(name): filename = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'data', name) with np.load(filename) as f: return dict(f.items())
def partial_apply_nontensors(fn, args, **kwargs): source = [('t' if (isinstance(arg, torch.Tensor) or is_iterable_of_tensors(arg)) else 's') for arg in args] def new_fn(*tensors_): tensors = iter(tensors_) return fn(*((args[i] if (s == 's') else next(tensors)) for (i, s) in enumerate(source)), *...
def mix_labels(target, lam, n_classes, label_smoothing=0.1): onehot_target = label_smooth(target, n_classes, label_smoothing) flipped_target = torch.flip(onehot_target, dims=[0]) return ((lam * onehot_target) + ((1 - lam) * flipped_target))
def read_ptb(): sys.stderr.write((('\nReading PTB data from ' + PTB_DATA_DIR) + ' ...\n')) sentences = [] senno = 0 with codecs.open('ptb.sents', 'w', 'utf-8') as ptbsf: for constitfile in os.listdir(PTB_DATA_DIR): reader = BracketParseCorpusReader(PTB_DATA_DIR, constitfile) ...
def propagate_through_equivalence(links_by_name, set_2_nodes, node_2_set): all_expanded_links = {} for (name, links) in links_by_name.iteritems(): set_links = [] for link in links: relation = link[0] (arg1, arg2) = link[2] set1 = node_2_set[arg1] s...
def convert_conv2convws_model(module, process_group=None, channel_last=False): mod = module if isinstance(module, torch.nn.modules.conv._ConvNd): if isinstance(module.bias, torch.Tensor): bias = True else: bias = False mod = Conv2dWS(module.in_channels, module.out...
class EvernoteManagerCreateNote(VirtualFunctionTool): name = 'EvernoteManagerCreateNote' summary = 'Create a new note with a title, content, and optional attachments.' parameters: List[ArgParameter] = [{'name': 'title', 'type': 'string', 'description': 'The title of the note.', 'required': True}, {'name': '...
class EigenDataset(EigenDatasetBase, MatrixDataset): def __init__(self, num_features=20, sparse=True, **kwargs): super().__init__(num_features=num_features, sparse=sparse, **kwargs)
def test_not_captured(capfd): msg = 'Something that should not show up in log' stream = StringIO() with redirect_stdout(stream): m.raw_output(msg) (stdout, stderr) = capfd.readouterr() assert (stdout == msg) assert (stderr == '') assert (stream.getvalue() == '') stream = StringIO...
def main(rag_example_args: 'RagExampleArguments', processing_args: 'ProcessingArguments', index_hnsw_args: 'IndexHnswArguments'): logger.info('Step 1 - Create the dataset') assert os.path.isfile(rag_example_args.csv_path), 'Please provide a valid path to a csv file' dataset = load_dataset('csv', data_files=...
def enum_product_projective_finite_field(X): if is_Scheme(X): if (not is_ProductProjectiveSpaces(X.ambient_space())): raise TypeError('ambient space must be product of projective space over the rational field') X = X(X.base_ring()) elif (not is_ProductProjectiveSpaces(X.codomain().am...
class CartesianProduct_iters(EnumeratedSetFromIterator): def __init__(self, *iters): self.iters = iters self._mrange = xmrange_iter(iters) category = EnumeratedSets() try: category = (category.Finite() if self.is_finite() else category.Infinite()) except ValueErro...
def linear_warmup_decay(learning_rate, warmup_steps, num_train_steps): with F.default_main_program()._lr_schedule_guard(): lr = L.tensor.create_global_var(shape=[1], value=0.0, dtype='float32', persistable=True, name='scheduled_learning_rate') global_step = L.learning_rate_scheduler._decay_step_coun...
def write_to_json_file(file_path, dict): directory = os.path.dirname(file_path) os.makedirs(directory, exist_ok=True) for k in dict.keys(): if isinstance(dict[k], (np.float32, np.float64)): dict[k] = dict[k].item() json_obj = json.dumps(dict) fout = open(file_path, 'w') fout....
_model def gluon_resnet50_v1e(pretrained=False, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['gluon_resnet50_v1e'] model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes, in_chans=in_chans, stem_width=64, stem_type='deep', avg_down=True, **kwargs) model.default_cfg = default...
def setup_distributed(local_rank: int, no_cuda: bool) -> typing.Tuple[(torch.device, int, bool)]: if ((local_rank != (- 1)) and (not no_cuda)): torch.cuda.set_device(local_rank) device: torch.device = torch.device('cuda', local_rank) n_gpu = 1 dist.init_process_group(backend='nccl') ...
def read_image(image_path): msg = '{0} library is not installed. Use "pip install {0}" to install it.' try: import numpy as np except: raise ImportError(msg.format('numpy')) try: from PIL import Image except: raise ImportError(msg.format('pillow')) Image.MAX_IMAGE...
def clean_data_home(data_home: Optional[Union[(str, Path)]]=None): data_home = get_data_home(data_home) for file in listdir(data_home): if isfile(join(data_home, file)): remove(join(data_home, file))
class AutoConfig(object): def __init__(self): raise EnvironmentError('AutoConfig is designed to be instantiated using the `AutoConfig.from_pretrained(pretrained_model_name_or_path)` method.') def for_model(cls, model_type, *args, **kwargs): if ('distilbert' in model_type): return Dis...
def _read(fileid): with open((((MAP_DIR + '/') + fileid) + '.map')) as f: for ln in f: ln = ln.strip() if (ln == ''): continue (fine, coarse) = ln.split('\t') assert (coarse in COARSE_TAGS), 'Unexpected coarse tag: {}'.format(coarse) ...
def execute(bbox: BoundingBox, n5_dir: str=None, group_path: str=None, voxel_size: tuple=None, type: str=None, driver: str='n5'): assert (driver == 'n5') if isinstance(voxel_size, tuple): voxel_size = Cartesian.from_collection(voxel_size) fsstore = zarr.N5FSStore(n5_dir, anon=True) img_zarr = za...
def load_cam_dtu(file, num_depth=0, interval_scale=1.0): cam = np.zeros((2, 4, 4)) words = file.read().split() for i in range(0, 4): for j in range(0, 4): extrinsic_index = (((4 * i) + j) + 1) cam[0][i][j] = words[extrinsic_index] for i in range(0, 3): for j in ra...
def _map_multiprocess(func, iterable, chunksize=1): with closing(ProcessPool()) as pool: return pool.imap_unordered(func, iterable, chunksize)
def buildargs(command): replace = [('<instance>', 'FILECNF'), ('<seed>', 'RANDOMSEED'), ('<tempdir>', '/tmp')] toret = [] args = command.split()[1:] for a in args: for r in replace: a = a.replace(r[0], r[1]) toret.append(a) return toret
def log(spark): return spark.createDataFrame(data=[[0, 0, datetime(2019, 8, 22), 4.0], [0, 2, datetime(2019, 8, 23), 3.0], [0, 1, datetime(2019, 8, 27), 2.0], [1, 3, datetime(2019, 8, 24), 3.0], [1, 0, datetime(2019, 8, 25), 4.0], [2, 1, datetime(2019, 8, 26), 5.0], [2, 0, datetime(2019, 8, 26), 5.0], [2, 2, dateti...
def read(filename, mmap=False): if hasattr(filename, 'read'): fid = filename mmap = False else: fid = open(filename, 'rb') try: (file_size, is_big_endian) = _read_riff_chunk(fid) fmt_chunk_received = False data_chunk_received = False channels = 1 ...
def test_get_visual_block_single_estimator(): est = LogisticRegression(C=10.0) est_html_info = _get_visual_block(est) assert (est_html_info.kind == 'single') assert (est_html_info.estimators == est) assert (est_html_info.names == est.__class__.__name__) assert (est_html_info.name_details == str(...
def BLMatrixMult(LensMatrX, LensMatrY, DriftMatr, DriftMatr0): InitDriftLenseX = matr_prod(LensMatrX, DriftMatr0) tRMSfunX = matr_prod(DriftMatr, InitDriftLenseX) InitDriftLenseY = matr_prod(LensMatrY, DriftMatr0) tRMSfunY = matr_prod(DriftMatr, InitDriftLenseY) return (tRMSfunX, tRMSfunY)
class childnodeTypeSub(supermod.childnodeType): def __init__(self, relation=None, refid=None, edgelabel=None): supermod.childnodeType.__init__(self, relation, refid, edgelabel)
def ed_decode_line(bin_line): sep_idx = bin_line.find(b'=') if (sep_idx <= 0): return (None, None) key = bin_line[:sep_idx].decode('utf8').lower() val = bin_line[(sep_idx + 1):].decode('utf8') if (re.match('^-?[0-9]+$', val) and (key is not 'data')): val = int(val) elif re.match(...
def construct_slurm_args(experiment_name: str, slurm_args: dict): Path('logs').mkdir(exist_ok=True) sbatch_args = f'--output=logs/{experiment_name}_%j.log' for (k, v) in slurm_args.items(): if (k == '_num_gpu'): if (v > 0): sbatch_args = f'{sbatch_args} --gres=gpu:{v}' ...
def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan): xp = array_namespace(x) if is_numpy(xp): return pocketfft_func(x, s=s, axes=axes, norm=norm, overwrite_x=overwrite_x, workers=workers, plan=plan) norm = _validate_fft_args(workers, plan, norm) if hasattr(xp,...
class Minecraft2DmazeProblem(Problem): def __init__(self): super().__init__() self._width = 14 self._height = 14 self._prob = {'AIR': 0.5, 'DIRT': 0.5} self._border_tile = 'DIRT' self._target_path = 20 self._random_probs = True self._reward_weights = {...
def test_detector_tokenizer(): sents = [',', '', '', '', '', ',', ',,,,', '3', ':?', '', ''] d = Detector() d.check_detector_initialized() detector_tokenizer = d.tokenizer for text in sents: print(text) print('deault', detector_tokenizer.tokenize(text, 'default')) print('sear...
class ProtoCLS(nn.Module): def __init__(self, in_dim, out_dim, temp=0.05): super(ProtoCLS, self).__init__() self.fc = nn.Linear(in_dim, out_dim, bias=False) self.tmp = temp self.weight_norm() def forward(self, x): x = F.normalize(x) x = (self.fc(x) / self.tmp) ...
class TwoSourceModel(): def __init__(self, src1_vocab, src2_vocab, tgt_vocab, single, pointer_gen, coverage, diag_loss, load_model, model_file, beam_size, best_val_cer): self.model = dy.ParameterCollection() self.src1_vocab = src1_vocab self.src2_vocab = src2_vocab self.tgt_vocab = t...
def FruchtGraph(): edges = {0: [1, 6, 7], 1: [2, 7], 2: [3, 8], 3: [4, 9], 4: [5, 9], 5: [6, 10], 6: [10], 7: [11], 8: [9, 11], 10: [11]} g = Graph(edges, format='dict_of_lists', name='Frucht graph') g._circle_embedding(range(7), radius=2, angle=(pi / 2)) g._circle_embedding(range(7, 11), radius=1, angl...
(scope='module') def sdec_ref_data_path(tardis_ref_path): return os.path.abspath(os.path.join(tardis_ref_path, 'sdec_ref.h5'))
class LxmertPreTrainedModel(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
class OpenNLPSentenceDetector(object): def __init__(self): init_java() from jnius import autoclass File = autoclass('java.io.File') SentenceModel = autoclass('opennlp.tools.sentdetect.SentenceModel') SentenceDetectorME = autoclass('opennlp.tools.sentdetect.SentenceDetectorME'...
def gumbel_softmax_sample(logits, temperature, dim=1): y = (logits + sample_gumbel(logits.shape, tens_type=type(logits.data))) return F.softmax((y / temperature), dim=dim)
class InfoSubprocVecEnv(ShareVecEnv): def __init__(self, env_fns, spaces=None): self.waiting = False self.closed = False nenvs = len(env_fns) self._mp_ctx = mp.get_context('forkserver') (self.remotes, self.work_remotes) = zip(*[self._mp_ctx.Pipe(duplex=True) for _ in range(ne...
def get_metric(pred_list, topk=10): NDCG = 0.0 HIT = 0.0 MRR = 0.0 for rank in pred_list: MRR += (1.0 / (rank + 1.0)) if (rank < topk): NDCG += (1.0 / np.log2((rank + 2.0))) HIT += 1.0 return ((HIT / len(pred_list)), (NDCG / len(pred_list)), (MRR / len(pred_li...
class CausalLMOutput(ModelOutput): loss: Optional[torch.FloatTensor] = None logits: torch.FloatTensor = None hidden_states: Optional[Tuple[torch.FloatTensor]] = None attentions: Optional[Tuple[torch.FloatTensor]] = None
def sync(src: str, dst: str, debug: bool=typer.Option(False, help='If true, will write debug information to debug directory.'), multipart: bool=typer.Option(cloud_config.get_flag('multipart_enabled'), help='If true, will use multipart uploads.'), confirm: bool=typer.Option(cloud_config.get_flag('autoconfirm'), '--confi...
def gen_plot_from_dict(fn_to_contour, plot_fn, out_base_name, out_dir='results'): d = dict(fig=None, plot_fn=plot_fn) for (n, c) in fn_to_contour.items(): (d['fig'], ax) = add_plot(n, c, **d) gen_plot(out_dir=out_dir, out_base_name=f'{out_base_name}.png')
class ReflexiveModule_tensor(ReflexiveModule_abstract): def tensor_factors(self): tensor_type = self.tensor_type() if (tensor_type == (0, 1)): raise NotImplementedError bmodule = self.base_module() factors = ([bmodule] * tensor_type[0]) dmodule = bmodule.dual() ...
class ProjectivePlaneCurvePoint_finite_field(ProjectivePlaneCurvePoint_field, SchemeMorphism_point_projective_finite_field): pass
def binary_weight_convolution_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, base_axis=1, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0): dy = grad_inputs[0] x0 = inputs[0] raise NotImplementedError('binary_weight_convolution_backward is not implemented.')
def flop_count_operators(model: nn.Module, inputs: list, **kwargs) -> typing.DefaultDict[(str, float)]: return _wrapper_count_operators(model=model, inputs=inputs, mode=FLOPS_MODE, **kwargs)
_driver.jit(device=True) def _get_ob(state_arr, observation_arr, kEnvId, kThisAgentId): state = state_arr[(kEnvId, kThisAgentId)] observation_arr[(kEnvId, kThisAgentId, 0)] = math.cos(state[0]) observation_arr[(kEnvId, kThisAgentId, 1)] = math.sin(state[0]) observation_arr[(kEnvId, kThisAgentId, 2)] = m...
def _create_schema_embeddings(bert_config, schema_embedding_file, dataset_config): if (not tf.io.gfile.exists(FLAGS.schema_embedding_dir)): tf.io.gfile.makedirs(FLAGS.schema_embedding_dir) is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2 schema_emb_run_config = tf.contrib.tpu.RunConfig(m...
class DomainNameCachingService(Service): __auto_root: bool def __init__(self, autoRoot: bool=True): super().__init__() self.__auto_root = autoRoot self.addDependency('Base', False, False) if autoRoot: self.addDependency('DomainNameService', False, False) def _crea...
class EditableCandidate(_InstallRequirementBackedCandidate): is_editable = True def __init__(self, link, template, factory, name=None, version=None): super(EditableCandidate, self).__init__(link=link, source_link=link, ireq=make_install_req_from_editable(link, template), factory=factory, name=name, vers...
class Environment(object): def make(cls, domain, subdomain): if (domain == 'miniwob'): from wge.miniwob.environment import MiniWoBEnvironment return MiniWoBEnvironment(subdomain) elif (domain == 'formwob'): from wge.formwob.environment import FormWoBEnvironment ...
class Seq2VecEncoder(_EncoderBase): def get_input_dim(self) -> int: raise NotImplementedError def get_output_dim(self) -> int: raise NotImplementedError
class BDFormat(Enum): INT8 = 0 FP16 = 1 FP32 = 2 INT16 = 3 INT32 = 4 BFP16 = 5 UNKNOWN = (- 1)
def import_from_path(name): splitted = name.split('.') package_name = '.'.join(splitted[:(- 1)]) cls = splitted[(- 1)] package = importlib.import_module(package_name) imported = getattr(package, cls) return imported
class GraphHandler(object): def __init__(self, model): self.model = model self.saver = tf.train.Saver(max_to_keep=3) self.writer = None def initialize(self, sess): sess.run(tf.global_variables_initializer()) if (cfg.load_model or (cfg.mode != 'train')): self.r...
def register_Ns3LteRrcSapRlcConfig_methods(root_module, cls): cls.add_constructor([]) cls.add_constructor([param('ns3::LteRrcSap::RlcConfig const &', 'arg0')]) cls.add_instance_attribute('choice', 'ns3::LteRrcSap::RlcConfig::direction', is_const=False) return
def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True): if (torch is None): raise RuntimeError('pytorch is not installed') assert (torch.is_tensor(tensor) and (tensor.ndim == 4)) assert (len(mean) == 3) assert (len(std) == 3) num_imgs = tensor.size(0) mean = np.array(mean, d...
class Power2OrZPred(FunPred): sig = (Value,) code = 'isPowerOf2OrZero' type_constraints = _one_int
('/get_block/<blockNumber>', methods=('GET',)) def get_block(blockNumber): web3 = connect_to_geth(app.web3_url, app.consensus) if (blockNumber == 'latest'): blockNumber = web3.eth.getBlock('latest').number block = web3.eth.get_block(int(blockNumber)) resp = Response(json.dumps(dict(block), cls=H...
def _sinkhorn_distance(x, y, d): t0 = time.time() m = ot.sinkhorn2(x, y, d, 0.1, method='sinkhorn') logger.debug(('%8f secs for Sinkhorn dist. \t#source_nbr: %d, #target_nbr: %d' % ((time.time() - t0), len(x), len(y)))) return m
class _ASPPModule(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding, dilation, BatchNorm): super(_ASPPModule, self).__init__() self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=1, padding=padding, dilation=dilation, bias=False) self.bn = Batch...
class Net(nn.Module): def __init__(self, opt): super().__init__() self.sub_mean = ops.MeanShift(255) self.add_mean = ops.MeanShift(255, sign=1) head = [ops.DownBlock(opt.scale), nn.Conv2d((3 * (opt.scale ** 2)), opt.num_channels, 3, 1, 1)] body = list() for _ in range...
def _denominator(t_slice_shape, precision, unroll=1): def fwd(qs, ks): def body(p, qk): (q, k) = qk p += k x = jnp.einsum('...m,...m->...', q, p, precision=precision) return (p, x) p = jnp.zeros(t_slice_shape) (p, R) = lax.scan(body, p, (qs, ks...
class Statistics(): def __init__(self): self.tp = {} self.fp = {} self.tn = {} self.fn = {} self.t0 = [round(t, 2) for t in np.linspace(0, 1, 21)] self.t0[0] = 0.001 self.t0[(- 1)] = 0.999 for t in self.t0: self.tp[t] = 0 self.f...
def get_tree_starting_at(module, edges): vertices_seen = [module] new_edges = [edge for edge in edges if ((edge[0] == module) and (edge[1] != module) and ('__init__.py' not in edge[1]))] tree = [module] while (len(new_edges) > 0): tree.append(new_edges) final_vertices = list({edge[1] for...
class XLNetTokenizer(PreTrainedTokenizer): vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, do_lower_case=False, remove_space=True, keep_accents=False, bos_token='<s...
class EnhancedSet(): def __init__(self, data=None): if data: self.data = set(data) else: self.data = set() def __iter__(self): return self.data.__iter__() def __contains__(self, datum): return (datum in self.data) def __len__(self): return ...
def check_path(path): if (not os.path.exists(path)): os.makedirs(path) print(f'{path} created')
('/accumulate', methods=['POST']) def getUpdateNotification(): print(dir(request)) data = request.get_json() print(data) pload = data['subscriptionId'] subId.append(data['subscriptionId']) print(pload) return 'Done'
class MLPHead(nn.Module): def __init__(self, in_channels, mlp_hidden_size, projection_size): super(MLPHead, self).__init__() self.net = nn.Sequential(nn.Linear(in_channels, mlp_hidden_size), nn.BatchNorm1d(mlp_hidden_size), nn.ReLU(inplace=True), nn.Linear(mlp_hidden_size, projection_size)) def ...
def _make_constant(nodes, predicate): for n in nodes.values(): if predicate(n): for i in n.in_edges: i.remove_output(n) n.args.clear() n.kwargs.clear() n.type = NodeTypes.CONSTANT
def infer_abbr(class_type): if (not inspect.isclass(class_type)): raise TypeError(f'class_type must be a type, but got {type(class_type)}') if hasattr(class_type, '_abbr_'): return class_type._abbr_ if issubclass(class_type, _InstanceNorm): return 'in' elif issubclass(class_type,...
def preprocess_for_train(image, height, width, bbox, fast_mode=True, scope=None): with tf.name_scope(scope, 'distort_image', [image, height, width, bbox]): if (bbox is None): bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) if (image.dtype != tf.float32): ...
class chi_gen(rv_continuous): def _shape_info(self): return [_ShapeInfo('df', False, (0, np.inf), (False, False))] def _rvs(self, df, size=None, random_state=None): return np.sqrt(chi2.rvs(df, size=size, random_state=random_state)) def _pdf(self, x, df): return np.exp(self._logpdf(x,...
def configure_logger(model_args: ModelArguments, training_args: TrainingArguments): logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', handlers=[logging.StreamHandler(sys.stdout)]) logging_level = logging.WARNING if model_args.verbose_logging: ...
def brightness_up_mapping(level, src_img): if (level == 1): factor = 0.5 else: factor = level noisy_factor = ((1 + (factor * 0.2)) + np.random.uniform((- 0.01), 0.01)) return ImageEnhance.Brightness(src_img).enhance(noisy_factor)
class SingleImageDataset(VisionDataset): def __init__(self, root, pairs_file=None, num_images=1000, extensions='.jpg', height=256, Train=True, down_scale=1): self.height = 512 self.width = 1024 self.num_images = num_images assert ((down_scale == 1) or (down_scale == 2)), 'only suppor...
def outmess(line, flag=1): global filepositiontext if (not verbose): return if (not quiet): if flag: sys.stdout.write(filepositiontext) sys.stdout.write(line)