code
stringlengths
101
5.91M
def replace_example_docstring(example_docstring): def docstring_decorator(fn): func_doc = fn.__doc__ lines = func_doc.split('\n') i = 0 while ((i < len(lines)) and (re.search('^\\s*Examples?:\\s*$', lines[i]) is None)): i += 1 if (i < len(lines)): line...
def add_content_and_label(file_location, output_sentences, output_labels, label): with open(file_location) as file: content = ' '.join(file.readlines()).replace('\n', ' ').replace('\r', '') single_spaced_content = ' '.join(content.split()) output_sentences.write((single_spaced_content + '\n'...
def get_learning_rate_schedules(specs): schedule_specs = specs['LearningRateSchedule'] schedules = [] for schedule_specs in schedule_specs: if (schedule_specs['Type'] == 'Step'): schedules.append(StepLearningRateSchedule(schedule_specs['Initial'], schedule_specs['Interval'], schedule_spe...
class RandAugment(torch.nn.Module): def __init__(self, num_ops: int=2, magnitude: int=9, num_magnitude_bins: int=31, interpolation: InterpolationMode=InterpolationMode.NEAREST, fill: Optional[List[float]]=None) -> None: super().__init__() self.num_ops = num_ops self.magnitude = magnitude ...
def find_first_non_zero_pixel(points, instance_image): points = list(points) coord = points[0] for pixel in points: pixel = list(pixel) pixel[0] = np.clip(pixel[0], 0, (instance_image.shape[1] - 1)) pixel[1] = np.clip(pixel[1], 0, (instance_image.shape[0] - 1)) coord = pixel ...
def sample_and_group_all(xyz, points, use_xyz=True): batch_size = tf.shape(xyz)[0] nsample = xyz.get_shape()[1].value new_xyz = tf.tile(np.array([0, 0, 0], dtype=np.float32).reshape((1, 1, 3)), (batch_size, 1, 1)) idx = tf.tile(np.array(range(nsample), dtype=np.float32).reshape((1, 1, nsample)), (batch_...
_task('cross_lingual_lm') class CrossLingualLMTask(FairseqTask): def add_args(parser): parser.add_argument('data', help='colon separated path to data directories list, will be iterated upon during epochs in round-robin manner') parser.add_argument('--tokens-per-sample', d...
def test_graph_gnm(): (n_v, n_e) = (100, 500) g = graph_Gnm(n_v, n_e) assert (g.num_v == n_v) assert (g.num_e == n_e)
('translate', inputs={'source_imgs': runway.image(description='input image to be translated'), 'Strokes': runway.number(min=100, max=700, default=100, description='number of strokes')}, outputs={'image': runway.image(description='output image containing the translated result')}) def translate(learn, inputs): os.mak...
def perfect_plot(ax, xarr, yarr, label): if (len(xarr) != len(yarr)): ax.plot(xarr[:(- 1)], yarr, label=label) else: ax.plot(xarr, yarr, label=label)
class TestTensorboardXWriter(unittest.TestCase): def test_no_files_created(self) -> None: with tempfile.TemporaryDirectory() as tmp_dir: writer = TensorboardXWriter(tmp_dir) writer.close() self.assertFalse(os.listdir(tmp_dir)) def test_single_write(self) -> None: ...
def attach_head_and_body(root): head = ET.Element('head') body = ET.Element('body') root.append(head) root.append(body) meta1 = ET.Element('meta') meta1.set('name', 'ocr-system') meta1.set('content', 'eperiodica_fulltext') meta2 = ET.Element('meta') meta2.set('name', 'ocr-capabilitie...
class PathBuffer(): def __init__(self, capacity_in_transitions): self._capacity = capacity_in_transitions self._transitions_stored = 0 self._first_idx_of_next_path = 0 self._path_segments = collections.deque() self._buffer = {} def add_path(self, path): for (key, ...
def load_obj_data(filename): v_list = [] vt_list = [] vc_list = [] vn_list = [] f_list = [] fn_list = [] ft_list = [] fp = open(filename, 'r') lines = fp.readlines() fp.close() for line in lines: if (len(line) < 2): continue line_data = line.strip(...
def test_potential_paramunits_1d(): from galpy import potential from galpy.util import conversion (ro, vo) = (10.5, 195.0) pot = potential.KGPotential(amp=1.0, K=((40.0 * units.Msun) / (units.pc ** 2)), F=((0.02 * units.Msun) / (units.pc ** 3)), D=(200 * units.pc), ro=ro, vo=vo) pot_nounits = potent...
class TFRemBertPreTrainedModel(metaclass=DummyObject): _backends = ['tf'] def __init__(self, *args, **kwargs): requires_backends(self, ['tf'])
class DistEvalHook(EvalHook): def after_train_epoch(self, runner): if (not self.every_n_epochs(runner, self.interval)): return current_ckpt_path = osp.join(runner.work_dir, f'epoch_{(runner.epoch + 1)}.pth') json_path = osp.join(runner.work_dir, 'best.json') if (osp.exist...
def test_digits_cosine_lazy_init(): model = SumRedundancySelection(100, 'cosine', optimizer='lazy', initial_subset=digits_cosine_ranking[:5]) model.fit(X_digits) assert_array_equal(model.ranking[:(- 5)], digits_cosine_ranking[5:]) assert_array_almost_equal(model.gains[:(- 5)], digits_cosine_gains[5:], 4...
class Critic(nn.Module): def __init__(self, state_dim, action_dim): super(Critic, self).__init__() self.l1 = nn.Linear(state_dim, 400) self.l2 = nn.Linear((400 + action_dim), 300) self.l3_additional = nn.Linear(300, 300) self.l3 = nn.Linear(300, 1) def forward(self, x, u)...
def get_split_subset(args, ds, split): manual_seed(args.split_seed) indices = randperm(len(ds)) valid_size = round((len(ds) * args.split_ratio)) if (args.dataset == 'cifar10'): if (split == 'train'): ds = Subset(ds, indices[:(- valid_size)]) elif (split == 'val'): ...
class AsyncMultiGPUTrainer(MultiGPUTrainer, SingleCostFeedfreeTrainer, MultiPredictorTowerTrainer): def __init__(self, config, input_queue=None, average_gradient=True, predict_tower=None): if hasattr(config, 'dataset'): self._input_method = QueueInput(config.dataset, input_queue) else: ...
def stanford_pre(path_bf, path_af, path_root='/home/cc', data_name='nyt', flist='before-parse-problems-flist.txt'): files = os.listdir(path_bf) files = [os.path.join(path_bf, f) for f in files] num_flist = multiprocessing.cpu_count() slice = (len(files) // num_flist) for i in range(num_flist): ...
class TestBoxIOU(unittest.TestCase): def test_pairwise_iou(self): boxes1 = torch.tensor([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]]) boxes2 = torch.tensor([[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.5, 1.0], [0.0, 0.0, 1.0, 0.5], [0.0, 0.0, 0.5, 0.5], [0.5, 0.5, 1.0, 1.0], [0.5, 0.5, 1.5, 1.5]]) ex...
def regadv(): filename = sys.argv[1] config = {} config['jobs'] = [] model_list = ['ResNet18'] batch_size = [(512, 32)] for (i, modelname) in enumerate(model_list): job = {} job['eps'] = 0.047 job['alpha'] = 0.01 job['model'] = {} job['model']['name'] = mo...
def unwrap_if_singleton(x): if (isinstance(x, dict) and (len(x) == 1) and ('single_element' in x)): return x['single_element'] return x
def train(train_loader, model, criterion, optimizer, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') top1 = AverageMeter('', ':6.2f') top5 = AverageMeter('', ':6.2f') progress = ProgressMeter(len(train_loade...
def get_post_fmean(blm, X, Psi=None, w=None): if (Psi is None): Psi = blm.lik.linear.basis.get_basis(X) if (w is None): w = get_post_params_mean(blm) return (Psi.dot(w) + blm.lik.linear.bias)
_model def resnet12_wide(pretrained=False, **kwargs): model_args = dict(block=BasicBlock, layers=[1, 1, 1, 2], base_width=(64 * 2), our_ver=True, **kwargs) return _create_resnet('resnet12_wide', pretrained, **model_args)
def run_model_on_fold(name, max_len, embed_size, embed, bulid_fun): max_features = 50000 scores = {} scores.setdefault('fit_time', []) scores.setdefault('score_time', []) scores.setdefault('test_F1', []) scores.setdefault('test_Precision', []) scores.setdefault('test_Recall', []) scores....
class Lossless(RateEstimator): def forward_help(self, z, _, parent=None): (batch_size, z_dim) = z.shape z_hat = z with closing(io.BytesIO()) as f: np.savez_compressed(f, to_numpy(z_hat)) bit_rate = ((f.getbuffer().nbytes * 8) / batch_size) nats_rate = (bit_rat...
class NLIDataset(torch.utils.data.Dataset): def __init__(self, premise, hypothesis, label, memory_key=None, memory_value=None, attention=None): assert (len(premise) == len(hypothesis)) self.premise = premise.astype(np.long) self.hypothesis = hypothesis.astype(np.long) if (label is no...
class MetadataField(Field[DataArray]): def __init__(self, metadata: Any) -> None: self.metadata = metadata def get_padding_lengths(self) -> Dict[(str, int)]: return {} def as_tensor(self, padding_lengths: Dict[(str, int)]) -> DataArray: return self.metadata def empty_field(self) ...
class First_order_chemical_synapse(SynapseModel): def __init__(self, conn, **kwargs): super(First_order_chemical_synapse, self).__init__(conn) from .Connections import FullConnection assert isinstance(conn, FullConnection) self._syn_tau_variables['tau[link]'] = kwargs.get('tau', 2.0)...
class WordSequence(nn.Module): def __init__(self, data): super(WordSequence, self).__init__() print(('build word sequence feature extractor: %s...' % data.word_feature_extractor)) self.gpu = data.HP_gpu self.use_char = data.use_char self.droplstm = nn.Dropout(data.HP_dropout)...
class IMSATHeader(nn.Module): def __init__(self, output_k=10, num_sub_heads=5): super().__init__() self.output_k = output_k self.num_sub_heads = num_sub_heads self.heads = nn.ModuleList([nn.Sequential(nn.Linear(1200, self.output_k), nn.Softmax(dim=1)) for _ in range(self.num_sub_head...
def chunk_list(examples, chunk_size=2, pad_to_divisible=True): n_examples = len(examples) remainder = (n_examples % chunk_size) if (pad_to_divisible and (remainder > 0)): n_pad = (chunk_size - remainder) pad = random.choices(examples, k=n_pad) examples = (examples + pad) n_ex...
def get_arrow_hex_str(batched_data, names): import pyarrow as pa sink = pa.BufferOutputStream() pred_arrow = pa.record_batch(batched_data, names=names) with pa.ipc.new_stream(sink, pred_arrow.schema) as writer: writer.write_batch(pred_arrow) pred_arrow = sink.getvalue().hex() pred_arrow ...
class MetricLogger(object): def __init__(self, delimiter='\t'): self.meters = defaultdict(SmoothedValue) self.delimiter = delimiter def update(self, **kwargs): for (k, v) in kwargs.items(): if (v is None): continue if isinstance(v, torch.Tensor): ...
class ResNetPerfCallback(MainCallback): def before_val_epoch(self, runner): if (runner.config['ipex'] and runner.config['int8'] and runner.config['calibration']): print('running int8 calibration step\n') import intel_extension_for_pytorch as ipex from torch.ao.quantizatio...
def _add_category(context, name: str=None, color: Tuple[float]=None) -> None: if (name in context.scene.categories.keys()): log.warning(f'Skipping duplicate category {name}.') return if (color is None): color = zpy.color.random_color(output_style='frgb') log.info(f'Choosing rando...
class Interpolation(): def interpolate_position(dataframe: NumTrajDF, sampling_rate: float, ip_type: Optional[Text]='linear', class_label_col: Optional[Text]=''): df = dataframe.reset_index() df_chunks = helper._df_split_helper(df) processes = ([None] * len(df_chunks)) manager = mlp....
def sample_vectors(samples, num): (num_samples, device) = (samples.shape[0], samples.device) if (num_samples >= num): indices = torch.randperm(num_samples, device=device)[:num] else: indices = torch.randint(0, num_samples, (num,), device=device) return samples[indices]
def get_figure_properties(fig): return {'figwidth': fig.get_figwidth(), 'figheight': fig.get_figheight(), 'dpi': fig.dpi}
def evaluate(Net, config, load_data, train, test, optim_func): file_name = config['exp_name'] for trial in range(config['num_trials_eval']): csv_name = (((file_name + '_t') + str(trial)) + '.csv') model_name = (((file_name + '_t') + str(trial)) + '.pt') num_epochs = config['num_epochs_ev...
def replaceRule(expr, repls): for (k, m) in repls.items(): expr = expr.replace(k, m, map=False, simultaneous=True, exact=False) return expr
class Walker2dFullObsEnv(mujoco_env.MujocoEnv, utils.EzPickle): def __init__(self): asset_path = os.path.join(os.path.dirname(__file__), 'assets/walker2d.xml') mujoco_env.MujocoEnv.__init__(self, asset_path, 4) utils.EzPickle.__init__(self) def step(self, a): posbefore = self.sim...
class TupleTensorOutputModel(nn.Module): def __init__(self): super().__init__() self.layer_1 = nn.Linear((28 * 28), 12) self.layer_2 = nn.Linear((28 * 28), 12) self.layer_3 = nn.Linear(24, 1) def forward(self, x1, x2): x1 = self.layer_1(x1) x2 = self.layer_2(x2) ...
_criterion('cross_entropy') class CrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): net_output = model(**sample['net_input']) lprobs = model.get_normalized_probs(net_output, log_probs=True)...
def create_dir(dir_path): if (not osp.exists(dir_path)): os.makedirs(dir_path) return dir_path
class SpatialTemporalEnsemble(nn.Module): def __init__(self, is_temporal_ensemble=False): super().__init__() self.is_temporal_ensemble = is_temporal_ensemble def _transform(self, imgs, mode): is_single_image = False if (imgs.ndim == 4): if self.is_temporal_ensemble: ...
class HiLAMParallel(BaseHiGraphModel): def __init__(self, args): super().__init__(args) total_edge_index_list = ((list(self.m2m_edge_index) + list(self.mesh_up_edge_index)) + list(self.mesh_down_edge_index)) total_edge_index = torch.cat(total_edge_index_list, dim=1) self.edge_split_s...
def init_weights(net, init_type='kaiming', scale=1.0, std=0.02): print('initialization method [{:s}]'.format(init_type)) if (init_type == 'normal'): weights_init_normal_ = functools.partial(weights_init_normal, std=std) net.apply(weights_init_normal_) elif (init_type == 'kaiming'): w...
class World(object): def __init__(self, name, args, timeout): self.client = None self.name = name self.args = args self.timeout = timeout self.server_fps = 0.0 self.simulation_time = 0 self.server_clock = pygame.time.Clock() self.world = None s...
class TestGraphMatMulFusion(unittest.TestCase): def setUpClass(self): build_fake_yaml() self.op_wise_sequences = TensorflowQuery(local_config_file=os.path.join(os.path.dirname(neural_compressor.__file__), 'adaptor/tensorflow.yaml')).get_eightbit_patterns() def tearDownClass(self): os.rem...
def reveal_fog_of_war(top_down_map: np.ndarray, current_fog_of_war_mask: np.ndarray, current_point: np.ndarray, current_angle: float, fov: float=90, max_line_len: float=100) -> np.ndarray: fov = np.deg2rad(fov) angles = np.arange(((- fov) / 2), (fov / 2), step=(1.0 / max_line_len), dtype=np.float32) fog_of_...
def save_episode_result(environment, test_result): res_dict = environment.get_final_result() date = environment.day idx = environment.episode_idx test_result.loc[((date + '_') + str(idx))] = [res_dict['pnl'], res_dict['nd_pnl'], res_dict['avg_abs_position'], res_dict['profit_ratio'], res_dict['volume']]
def main(): atheris.Setup(sys.argv, TestOneInput, enable_python_coverage=True) atheris.Fuzz()
def world_info_from_env(): local_rank = 0 for v in ('LOCAL_RANK', 'MPI_LOCALRANKID', 'SLURM_LOCALID', 'OMPI_COMM_WORLD_LOCAL_RANK'): if (v in os.environ): local_rank = int(os.environ[v]) break global_rank = 0 for v in ('RANK', 'PMI_RANK', 'SLURM_PROCID', 'OMPI_COMM_WORLD_...
class SkipProofDatasetCreator(DatasetCreator): def __init__(self, fp): super().__init__(fp) self.seen = set() def process_dp(self, dp): (result, proof_term) = get_skip_proof_datapoint(dp) guard = (lambda : ('PREDICT' in result)) if guard(): if (not ((result, p...
def convert(model, qconfig_mapping): for ((op_name, op_type), qconfig) in qconfig_mapping.items(): if (qconfig.weight_dtype not in FP8_DTYPE): continue module = fetch_module(model, op_name) if (module is None): logger.info(f'{op_name} is not found in model.') ...
def get_sumo_binary(): sumo_binary = 'sumo' if Settings.USE_GUI: if (Settings.SYSTEM == 'Windows'): sumo_binary = 'sumo-gui.exe' elif (Settings.SYSTEM == 'Linux'): sumo_binary = 'sumo-gui' elif (Settings.SYSTEM == 'Windows'): sumo_binary = 'sumo.exe' elif ...
def insert_receptors(path_db, name, receptors, max_cdr3_length=32): labels = set() for quantities in receptors.values(): labels.update(quantities.keys()) labels = sorted(list(labels)) dtype_receptor = ([('tra_vgene', 'S16'), ('tra_cdr3', ('S' + str(max_cdr3_length))), ('tra_jgene', 'S16'), ('trb...
def read_non_scored_words(non_scored_words_file): for line in non_scored_words_file.readlines(): parts = line.split() if (not (len(parts) == 1)): raise RuntimeError('segment_ctm_edits.py: bad line in non-scored-words file {0}: {1}'.format(non_scored_words_file, line)) _global_non...
def _at_least_version(actual_version, required_version): actual = [int(v) for v in actual_version.split('.')] required = [int(v) for v in required_version.split('.')] return (actual >= required)
def conv2d_bn(x, filters, kernel_size, strides=1, padding='same', activation='relu', use_bias=False, name=None): x = Conv2D(filters, kernel_size, strides=strides, padding=padding, use_bias=use_bias, name=name)(x) if (not use_bias): bn_axis = (1 if (K.image_data_format() == 'channels_first') else 3) ...
class LeakyClamp(torch.autograd.Function): def forward(ctx: Any, x: torch.Tensor, min: float, max: float) -> torch.Tensor: ctx.save_for_backward((x.ge(min) * x.le(max))) return torch.clamp(x, min=min, max=max) def backward(ctx: Any, grad_output: torch.Tensor) -> Tuple[(torch.Tensor, None, None)]...
class AvgStatistic(Statistic): decay: bool = False debias: bool = False def new_step(self): (self.val, self.count) = (0.0, 0) def accumulate(self, val): self.count += 1 self.val += self._get_val1(val) def _get_val1(self, val): return val.mean() def _get_val2(self,...
class LinearFilter(nn.Module): def __init__(self, filter_size, filter_initializer, filter_optimizer=None, feature_extractor=None): super().__init__() self.filter_size = filter_size self.filter_initializer = filter_initializer self.filter_optimizer = filter_optimizer self.feat...
class PhotoAIAPIRouter(APIRouter): def __init__(self) -> None: super().__init__() self.chatbot = None def set_chatbot(self, chatbot, use_deepspeed, world_size, host, port) -> None: self.chatbot = chatbot self.use_deepspeed = use_deepspeed self.world_size = world_size ...
class SchedulerBaseTests(unittest.TestCase): def test_save_load_from_different_config(self): obj = SchedulerObject() setattr(diffusers, 'SchedulerObject', SchedulerObject) logger = logging.get_logger('diffusers.configuration_utils') with tempfile.TemporaryDirectory() as tmpdirname: ...
def load_dataset_config(cfg_path): cfg = OmegaConf.load(cfg_path).datasets cfg = cfg[list(cfg.keys())[0]] return cfg
class DummyModel(EztorchBaseModule, ABC): def __init__(self, input_shape: int, transform: Optional[DictConfig]=None) -> None: super().__init__() self.transform = (hydra.utils.instantiate(transform) if (transform is not None) else None) self.save_hyperparameters() input_dim = math.pro...
def flavour_compair(d1, d2): diffs1 = {x: [] for x in 'tp fp fn fl None'.split()} diffs2 = {x: [] for x in 'tp fp fn fl None'.split()} for arc in d1['tp']: if (arc in d2['tp']): diffs1['tp'].append(arc) elif (arc in d2['fp']): diffs1['fp'].append(arc) elif (ar...
class NormsMethods(Generic[T_co], ExtensionMethods): l0: Callable[(..., T_co)] = norms.l0 l1: Callable[(..., T_co)] = norms.l1 l2: Callable[(..., T_co)] = norms.l2 linf: Callable[(..., T_co)] = norms.linf lp: Callable[(..., T_co)] = norms.lp
def gradients_collection(ys, xs, grad_ys=None, **kwargs): return gradients(ys, xs, grad_ys, checkpoints='collection', **kwargs)
class RPNModule(torch.nn.Module): def __init__(self, cfg, in_channels): super(RPNModule, self).__init__() self.cfg = cfg.clone() anchor_generator = make_anchor_generator(cfg) rpn_head = registry.RPN_HEADS[cfg.MODEL.RPN.RPN_HEAD] head = rpn_head(cfg, in_channels, anchor_genera...
def main(): args = parser.parse_args() print(args) if (args.seed is not None): random.seed(args.seed) torch.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed training. This will turn on the CUDNN deterministic setting, which can slow dow...
class TanhTransformedDistribution(tfd.TransformedDistribution): def __init__(self, distribution: tfd.Distribution, validate_args: bool=False): super().__init__(distribution=distribution, bijector=tfb.Tanh(), validate_args=validate_args) def mode(self) -> jnp.ndarray: return self.bijector.forward...
class Cell(nn.Module): def __init__(self, genotype, C_prev_prev, C_prev, C, reduction, reduction_prev): super(Cell, self).__init__() print(C_prev_prev, C_prev, C) if reduction_prev: self.preprocess0 = FactorizedReduce(C_prev_prev, C) else: self.preprocess0 = R...
class TimeLimit(EnvWrapper): def __init__(self, env, duration): super().__init__(env) self._duration = duration self._step = None def step(self, action): assert (self._step is not None), 'Must reset environment.' (obs, reward, done, info) = self.env.step(action) s...
def start_server(args): scorer = Scorer(args) app = web.Application([('/result', ResultHandler, dict(scorer=scorer)), ('/src', SourceHandler, dict(scorer=scorer)), ('/hypo', HypothesisHandler, dict(scorer=scorer)), ('/', EvalSessionHandler, dict(scorer=scorer))], debug=False) app.listen(args.port, max_buffe...
class DatasetSplit(Dataset): def __init__(self, dataset, idxs, Y=None): self.dataset = dataset self.idxs = [int(i) for i in idxs] self.mal = False if (Y is not None): self.mal = True self.mal_Y = Y def __len__(self): return len(self.idxs) def _...
def setup(rank, world_size, port): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = str(port) dist.init_process_group('nccl', rank=rank, world_size=world_size, init_method='env://')
class Txt2ImgIterableBaseDataset(IterableDataset): def __init__(self, num_records=0, valid_ids=None, size=256): super().__init__() self.num_records = num_records self.valid_ids = valid_ids self.sample_ids = valid_ids self.size = size print(f'{self.__class__.__name__} ...
def update(config, args): config['model_dir'] = get_value(config['model_dir'], args.model_dir) config['training_opt']['batch_size'] = get_value(config['training_opt']['batch_size'], args.batch_size) return config
def get_metric(y_true_aspect, y_predict_aspect, y_true_opinion, y_predict_opinion, y_true_sentiment, y_predict_sentiment, mask, train_op): (f_a, f_o) = (0, 0) (true_aspect, true_sentiment) = convert_to_list(y_true_aspect, y_true_sentiment, mask) (predict_aspect, predict_sentiment) = convert_to_list(y_predic...
class KIEDecoderTRIE(nn.Module): def __init__(self, ocr_dict, entity_dict, use_crf=False, ins_lvl_mean=False, d_model=(- 1), lstm_args=None): super(KIEDecoderTRIE, self).__init__() self.debug_mode = False self.ins_lvl_mean = ins_lvl_mean self.ocr_dict = ocr_dict self.rev_ocr_...
class SharedMLP(nn.Sequential): def __init__(self, args: List[int], *, bn: bool=False, activation=nn.ReLU(inplace=True), preact: bool=False, first: bool=False, name: str=''): super().__init__() for i in range((len(args) - 1)): self.add_module((name + 'layer{}'.format(i)), Conv2d(args[i],...
def parse(opt_path, root_path, is_train=True, debug=False): with open(opt_path, mode='r') as f: (Loader, _) = ordered_yaml() opt = yaml.load(f, Loader=Loader) if (debug and (not opt['name'].startswith('debug'))): opt['name'] = ('debug_' + opt['name']) opt['is_train'] = is_train i...
class Model(nn.Module): def __init__(self, nclasses): super().__init__() self.features = [6, 100, 100, nclasses] self.bandwidths = [64, 16, 10] assert (len(self.bandwidths) == (len(self.features) - 1)) sequence = [] grid = s2_equatorial_grid(max_beta=0, n_alpha=(2 * s...
def test_fs_observer_resource_event(dir_obs, sample_run, tmpfile): (basedir, obs) = dir_obs _id = obs.started_event(**sample_run) run_dir = basedir.join(_id) obs.resource_event(tmpfile.name) res_dir = basedir.join('_resources') assert res_dir.exists() assert (len(res_dir.listdir()) == 1) ...
def train(args, trainer, task, epoch_itr): update_freq = (args.update_freq[(epoch_itr.epoch - 1)] if (epoch_itr.epoch <= len(args.update_freq)) else args.update_freq[(- 1)]) itr = epoch_itr.next_epoch_itr(fix_batches_to_gpus=args.fix_batches_to_gpus, shuffle=(epoch_itr.epoch >= args.curriculum)) itr = itera...
def create_oracles_with_ilp(dataname, path_read, path_wt_distributed): process_one_example_with_ilp(path_read, path_wt_distributed, '6b43f5e79b3cdf1c4a6debad958d5d70358f4269', 30, data_name) process_one_example_with_ilp(path_read, path_wt_distributed, 'e1dc607107cc484c4bc1515cfa414a45088d4048', 30, data_name) ...
def data_reader(): data_root = 'data/Casia_maxpy_clean' images_data = [] images_label = [] batch_size = 128 count_value = 0 class_file_list = os.listdir(data_root) for i in tqdm.tqdm(range(len(class_file_list)), ncols=80): images_path = os.listdir(os.path.join(data_root, class_file_l...
class LoadGinConfigOperator(bpy.types.Operator): bl_idname = 'scene.zpy_load_gin_config' bl_label = 'Load gin config from file.' bl_description = 'Load gin config from file.' bl_category = 'ZPY' bl_options = {'REGISTER'} DEFAULT_TEXT_NAME = 'config' def execute(self, context): zpy.bl...
def complete_device(device): if (not torch.cuda.is_available()): return torch.device('cpu') if (type(device) == str): device = torch.device(device) if ((device.type == 'cuda') and (device.index is None)): return torch.device(device.type, torch.cuda.current_device()) return device
class EvolutionStrategyEmitter(EmitterBase): def __init__(self, archive, *, x0, sigma0, ranker='2imp', es='cma_es', es_kwargs=None, selection_rule='filter', restart_rule='no_improvement', bounds=None, batch_size=None, seed=None): EmitterBase.__init__(self, archive, solution_dim=archive.solution_dim, bounds=...
def integer_mixed_cell(dim, nbr, idx, verbose=True): from ast import literal_eval from phcpy.phcpy2c3 import py2c_intcelcon_get_inner_normal as getnormal from phcpy.phcpy2c3 import py2c_intcelcon_mixed_volume as mixvol from phcpy.phcpy2c3 import py2c_intcelcon_number_of_points_in_cell as npts from p...
class MasterServicer(elastic_training_pb2_grpc.MasterServicer): def __init__(self, task_manager, job_manager, speed_monitor: SpeedMonitor, rdzv_managers: Dict[(str, RendezvousManager)], job_metric_collector=None, elastic_ps_service=None, sync_service=None): self._task_manager: TaskManager = task_manager ...
class _UpConv(nn.Module): def __init__(self, in_ch, out_ch, momentum=0.1): super(_UpConv, self).__init__() self.up = nn.Sequential(nn.Upsample(scale_factor=2), nn.Conv2d(in_ch, out_ch, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False), nn.BatchNorm2d(out_ch, momentum=momentum), nn.ReLU(...