code
stringlengths
101
5.91M
class Pool(): def __init__(self, processes=1): self.processes = processes def _worker_loop(self, func, ip, inputQueue): while True: args = inputQueue.get(block=True, timeout=None) if (args == (- 1)): break p = mp.Process(target=func, args=([ip]...
class SquadDataTrainingArguments(): def __init__(self, *args, **kwargs): requires_pytorch(self)
class TestChoi(ChannelTestCase): def test_init(self): mat4 = (np.eye(4) / 2.0) chan = Choi(mat4) self.assertAllClose(chan.data, mat4) self.assertEqual(chan.dim, (2, 2)) mat8 = (np.eye(8) / 2.0) chan = Choi(mat8, input_dims=4) self.assertAllClose(chan.data, mat...
class wrong_loss(nn.Module): def __init__(self): super(wrong_loss, self).__init__() def forward(self, pred_score, target_score): tar_sum = torch.sum(target_score, dim=1, keepdim=True) tar_sum_is_0 = torch.eq(tar_sum, 0) tar_sum.masked_fill_(tar_sum_is_0, 1e-06) tar = (tar...
_tokenizer('bpe') class SentencePieceBPETokenizer(SentencePieceUnigramTokenizer): MODEL_TYPE = 'bpe'
def find_model_using_name(model_name): model_filename = (('models.' + model_name) + '_model') modellib = importlib.import_module(model_filename) model = None target_model_name = (model_name.replace('_', '') + 'model') for (name, cls) in modellib.__dict__.items(): if ((name.lower() == target_...
class BaseTrainer(): def __init__(self, actor, loaders, optimizer, settings, lr_scheduler=None): self.actor = actor self.optimizer = optimizer self.lr_scheduler = lr_scheduler self.loaders = loaders self.update_settings(settings) self.epoch = 0 self.stats = {}...
def orient_shapes_hwd(data: (list | tuple), slice_axis: int) -> np.ndarray: if (slice_axis == 0): return np.array(data)[[2, 1, 0]] elif (slice_axis == 1): return np.array(data)[[2, 0, 1]] elif (slice_axis == 2): return np.array(data)
def parse_args(): parser = argparse.ArgumentParser(description='Train a music captioning model') parser.add_argument('experiment_id', type=str) parser.add_argument('--metrics', type=bool, default=False) parser.add_argument('--device_num', type=str, default='0') parser.add_argument('--decoding', type...
def filter_kwargs(func): (func) def wrapper(*args, **kwargs): new_kwargs = {k: v for (k, v) in kwargs.items() if (k in ['backend', 'layers', 'models', 'utils'])} return func(*args, **new_kwargs) return wrapper
def get_morgan_bit_fps(data, bits=2048, radius=2): X = [[c for c in AllChem.GetMorganFingerprintAsBitVect(m, radius, nBits=bits).ToBitString()] for m in data] X = pd.DataFrame(X) return X
class TestInstructions(QiskitTestCase): def test_instructions_equal(self): hop1 = Instruction('h', 1, 0, []) hop2 = Instruction('s', 1, 0, []) hop3 = Instruction('h', 1, 0, []) uop1 = Instruction('u', 1, 0, [0.4, 0.5, 0.5]) uop2 = Instruction('u', 1, 0, [0.4, 0.6, 0.5]) ...
_module() class TPSPreprocessor(BasePreprocessor): def __init__(self, num_fiducial=20, img_size=(32, 100), rectified_img_size=(32, 100), num_img_channel=1, init_cfg=None): super().__init__(init_cfg=init_cfg) assert isinstance(num_fiducial, int) assert (num_fiducial > 0) assert isinst...
def train(args, train_dataset, model, tokenizer): if (args.local_rank in [(- 1), 0]): tb_writer = SummaryWriter() args.train_batch_size = (args.per_gpu_train_batch_size * max(1, args.n_gpu)) train_sampler = (RandomSampler(train_dataset) if (args.local_rank == (- 1)) else DistributedSampler(train_dat...
class AdExchangeAgent(ph.Agent): (frozen=True) class AdExchangeView(ph.AgentView): users_info: dict def __init__(self, agent_id: str, publisher_id: str, advertiser_ids: Iterable=tuple(), strategy: str='first'): super().__init__(agent_id) self.publisher_id = publisher_id self....
def get_prefix_allowed_tokens_fn(model, split_token='|', title_trie: Trie=None): return _get_end_to_end_prefix_allowed_tokens_fn((lambda x: model.encode(x).tolist()), (lambda x: model.decode(torch.tensor(x))), model.model.decoder.dictionary.bos(), model.model.decoder.dictionary.pad(), model.model.decoder.dictionary...
def test_starred_assignment_in_middle(): run_cell('a, b, c, d, e = 1, 2, 3, 4, 5') run_cell('x, *star, y = [a, b, c, d, e]') run_cell('a += 1') run_cell('logging.info(x)') assert_detected() run_cell('logging.info(star)') assert_not_detected() run_cell('logging.info(y)') assert_not_de...
class nnUNetTrainerV2(nnUNetTrainer): def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False): super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data, determin...
class FlaxLogitsWarper(metaclass=DummyObject): _backends = ['flax'] def __init__(self, *args, **kwargs): requires_backends(self, ['flax'])
def check_md5_hash(path, md5_hash): computed_md5_hash = hashlib.md5() with open(path, 'rb') as f: for chunk in iter((lambda : f.read(4096)), b''): computed_md5_hash.update(chunk) computed_md5_hash = computed_md5_hash.hexdigest() if (md5_hash != computed_md5_hash): print('MD5 ...
class Superpixels(meta.Augmenter): def __init__(self, p_replace=0, n_segments=100, max_size=128, interpolation='linear', name=None, deterministic=False, random_state=None): super(Superpixels, self).__init__(name=name, deterministic=deterministic, random_state=random_state) self.p_replace = iap.handl...
def load_clip(device): model = CLIPModel.from_pretrained('openai/clip-vit-base-patch32').to(device) processor = CLIPProcessor.from_pretrained('openai/clip-vit-base-patch32') tokenizer = CLIPTokenizer.from_pretrained('openai/clip-vit-base-patch32') return (model, processor, tokenizer)
def ndc_projection(x=0.1, n=1.0, f=50.0): return np.array([[(n / x), 0, 0, 0], [0, (n / (- x)), 0, 0], [0, 0, ((- (f + n)) / (f - n)), ((- ((2 * f) * n)) / (f - n))], [0, 0, (- 1), 0]]).astype(np.float32)
_arg_scope def mobilenet(input_tensor, num_classes=1001, depth_multiplier=1.0, scope='MobilenetV2', conv_defs=None, finegrain_classification_mode=False, min_depth=None, divisible_by=None, activation_fn=None, **kwargs): if (conv_defs is None): conv_defs = V2_DEF if ('multiplier' in kwargs): raise...
class ptb_rum_single_config(object): cell = 'rum' num_steps = 150 learning_rate = 0.002 T_norm = 1.0 num_layers = 1 init_scale = 0.01 max_grad_norm = 1.0 cell_size = 2000 embed_size = 128 max_epoch = 100 max_max_epoch = max_epoch keep_prob = 0.65 zoneout_h = 0.9 l...
class TestTranslation(unittest.TestCase): def setUp(self): logging.disable(logging.CRITICAL) def tearDown(self): logging.disable(logging.NOTSET) def test_fconv(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv') as data_dir: ...
class _Calibrator(object): def __init__(self, dataset: Dataset, results_dir: str, image_shape: Tuple[(int, int)], num_samples: int, theta_dims: int): self.dataset = dataset self.results_dir = results_dir self.image_shape = image_shape self.num_samples = num_samples self.theta...
class TFElectraModel(): def __init__(self, *args, **kwargs): requires_tf(self) def from_pretrained(self, *args, **kwargs): requires_tf(self)
class RetinaPolicy(object): def __init__(self, scale_ranges=[1, 1.1], img_size=[512, 512], translate=[0.1, 0.1], rotation=[(- 20), 20], crop_dims=[480, 480], brightness=None): self.scale_ranges = scale_ranges self.img_size = img_size self.translate = translate self.rotation = rotatio...
def reduce_df(dataframe, num_per_class): df_list = [] for i in range(10): df_list.append(dataframe.iloc[(i * 5000):((i * 5000) + num_per_class)]) df = pd.concat(df_list) return df
def get_model_fn(n_token, cutoffs, train_bin_sizes, eval_bin_sizes): def model_fn(features, labels, mode, params): is_training = (mode == tf.estimator.ModeKeys.TRAIN) batch_size = params['batch_size'] mems = params['cache'] inp = tf.transpose(features['inputs'], [1, 0]) tgt =...
def fix_parentheses(string): stack = list() output_string = '' for i in range(len(string)): if (string[i] == '('): stack.append(i) output_string += string[i] elif (string[i] == ')'): if (len(stack) == 0): pass else: ...
def test_isotropic_eddington_dehnencore_in_nfw_sigmar(): pot = [potential.NFWPotential(amp=2.3, a=1.3)] denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15) dfp = eddingtondf(pot=pot, denspot=denspot) numpy.random.seed(10) samp = dfp.sample(n=1000000) tol = 0.08 check_sigmar_aga...
def print_cfg(blocks): for block in blocks: print(('[%s]' % block['type'])) for (key, value) in block.items(): if (key != 'type'): print(('%s=%s' % (key, value))) print('')
def test_lambda_metric(): env = MockEnv() metric = ph.metrics.LambdaMetric(extract_fn=(lambda env: env.test_property), train_reduce_fn=(lambda values: np.sum(values)), eval_reduce_fn=(lambda values: (np.sum(values) * 2))) values = [] for _ in range(5): env.step() values.append(metric.ext...
class ResUNetBN2F(ResUNet2): NORM_TYPE = 'BN' CHANNELS = [None, 16, 32, 64, 128] TR_CHANNELS = [None, 16, 32, 64, 128]
class Encoder(nn.Module): def __init__(self, cin, cout, size=64, nf=64, activation=nn.Tanh): super(Encoder, self).__init__() extra = int((np.log2(size) - 6)) network = [nn.Conv2d(cin, nf, kernel_size=4, stride=2, padding=1, bias=False), nn.ReLU(inplace=True), nn.Conv2d(nf, (nf * 2), kernel_s...
_lr_scheduler('cosine', dataclass=CosineLRScheduleConfig) class CosineLRSchedule(FairseqLRScheduler): def __init__(self, cfg: CosineLRScheduleConfig, fairseq_optimizer): super().__init__(cfg, fairseq_optimizer) if (isinstance(cfg.lr, Collection) and (len(cfg.lr) > 1)): raise ValueError(f...
def encode_affinity(n_cpu_core=1, n_gpu=0, cpu_reserved=0, contexts_per_gpu=1, gpu_per_run=1, cpu_per_run=1, cpu_per_worker=1, async_sample=False, sample_gpu_per_run=0, optim_sample_share_gpu=False, hyperthread_offset=None, n_socket=None, run_slot=None, alternating=False, set_affinity=True): affinity_code = f'{n_cp...
_task('speech_to_text_wav2vec_triple_dataset') class SpeechToTextTaskWav2VecTripleDataset(LegacyFairseqTask): def add_args(parser): parser.add_argument('data', help='manifest root path') parser.add_argument('--config-yaml', type=str, default='config.yaml', help='Configuration YAML filename (under ma...
class TrainSetTransform(): def __init__(self, aug_mode): self.aug_mode = aug_mode self.transform = None if (aug_mode == 0): t = None elif (aug_mode == 1): t = [RandomRotation(max_theta=5, max_theta2=0, axis=np.array([0, 0, 1])), RandomFlip([0.25, 0.25, 0.0])] ...
def call_output(cmd): print(f'Executing: {cmd}') ret = check_output(cmd, shell=True) print(ret) return ret
class GatherViewer(MjViewer): def __init__(self, env): self.env = env super(GatherViewer, self).__init__() green_ball_model = MjModel(osp.abspath(osp.join(MODEL_DIR, 'green_ball.xml'))) self.green_ball_renderer = EmbeddedViewer() self.green_ball_model = green_ball_model ...
class FunctionGetFetches(object): def __init__(self, inputs, outputs, updates=None, name=None, **session_kwargs): updates = (updates or []) if (not isinstance(inputs, (list, tuple))): raise TypeError('`inputs` to a TensorFlow backend function should be a list or tuple.') if (not ...
def check_balancing_schedule(balancing_schedule): if callable(balancing_schedule): try: return_value = balancing_schedule({}, {}, 0, 0) except Exception as e: e_args = list(e.args) e_args[0] += BALANCING_SCHEDULE_INFO e.args = tuple(e_args) ...
def gen_data_step(decl_file: str, dest: str, rec_limit: int, depth_limit: int, weight_limit: int): lean_cmd = ['lean'] lean_cmd += ['--run'] lean_cmd += ['./src/lean_step.lean'] lean_cmd += list(map(str, [decl_file, dest, rec_limit, depth_limit, weight_limit])) path = Path(dest) stdout_dest = os...
def w2v_pad(protein, maxlen_, victor_size): tokenizer = text.Tokenizer(num_words=10000, lower=False, filters='\u3000') tokenizer.fit_on_texts(protein) protein_ = sequence.pad_sequences(tokenizer.texts_to_sequences(protein), maxlen=maxlen_) word_index = tokenizer.word_index nb_words = len(word_index)...
class Transmission(xmlr.Object): def __init__(self, name=None, joint=None, actuator=None): self.name = name self.joint = joint self.actuator = actuator
def collate_train_baseline(batch): if (batch[0][(- 1)] is not None): return collate_eval(batch) indice = [b[0] for b in batch] image = torch.stack([b[1] for b in batch]) return (indice, image)
def precision(tp, fp) -> float: predicted_positives = (tp + fp) if (predicted_positives <= 0): return 0 return (tp / predicted_positives)
def train_classifier(classifier: nn.Module, save_dir: str, train: List[Annotation], val: List[Annotation], documents: Dict[(str, List[List[int]])], model_pars: dict, class_interner: Dict[(str, int)], attention_optimizer=None, classifier_optimizer=None) -> Tuple[(nn.Module, dict)]: logging.info(f'Beginning training ...
() ('-r', '--results', type=click.Path(exists=True), help='Path of results.') ('-t', '--targets', type=click.Path(exists=True), help='Path of targets.') ('--train-labels', type=click.Path(exists=True), default=None, help='Path of labels for training set.') ('-a', type=click.FLOAT, default=0.55, help='Parameter A for pr...
def parse_args(): parser = argparse.ArgumentParser(description='Train a segmentor') parser.add_argument('config', help='train config file path') parser.add_argument('--fvcore', action='store_true', default=False) parser.add_argument('--shape', type=int, nargs='+', default=[1024, 1024], help='input image...
def script_preset_(model: torch.nn.Module): script_submodules_(model, [nn.Dropout, Attention, GlobalAttention, EvoformerBlock], attempt_trace=False, batch_dims=None)
def build_model(config): module_name = config.pop('name') support_dict = ['DBNet', 'CRNN'] assert (module_name in support_dict) module_class = eval(module_name)(**config) return module_class
def _init_dist_pytorch(backend, **kwargs): rank = int(os.environ['RANK']) num_gpus = torch.cuda.device_count() torch.cuda.set_device((rank % num_gpus)) dist.init_process_group(backend=backend, **kwargs) print(f'init distributed in rank {torch.distributed.get_rank()}')
def test_he_uniform(): from lasagne.init import HeUniform sample = HeUniform().sample((300, 200)) assert ((- 0.1) <= sample.min() < (- 0.09)) assert (0.09 < sample.max() <= 0.1)
def shufflenet(): device = torch.device('cpu') cfg_file = 'tests/configs/shufflenet/shufflenet_v1_3g1x.yaml' cfg.merge_from_file(cfg_file) model = build_recognizer(cfg, device) print(model) cfg_file = 'tests/configs/shufflenet/shufflenet_v2_torchvision.yaml' cfg.merge_from_file(cfg_file) ...
class INSnipClient(SnipClient): def init_optimizer(self): self.optimizer = SGD(self.model.parameters(), lr=INIT_LR, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY) self.optimizer_scheduler = lr_scheduler.StepLR(self.optimizer, step_size=STEP_SIZE, gamma=(0.5 ** (STEP_SIZE / LR_HALF_LIFE))) sel...
def build_compressed_embedding_pkl(name): embeddings = [] weights_dir = os.path.join(experiment_path, str(experiment_id), 'weights') with open(os.path.join(weights_dir, name), 'r') as f: lines = f.readlines() for line in lines: tokens = line.strip().split() v = [float...
class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, stride=8): self.inplanes = 128 super().__init__() self.conv1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False), norm_layer(64), nn.ReLU(inplace=True), nn.Conv2d(64, 64, kernel_size=3, ...
def eebls_gpu_custom(t, y, dy, freqs, q_values, phi_values, ignore_negative_delta_sols=False, freq_batch_size=None, nstreams=5, max_memory=None, functions=None, **kwargs): functions = (functions if (functions is not None) else compile_bls(**kwargs)) block_size = kwargs.get('block_size', _default_block_size) ...
class __FakeLocalTFRunner(): def __init__(*args, **kwargs): raise ImportError('LocalTFRunner requires TensorFlow. To use it, please install TensorFlow.')
_materialize('core') class GELU(ElementWiseUnaryOp): in_dtypes = [(i,) for i in DTYPE_GEN_FLOATS] out_dtypes = [(i,) for i in DTYPE_GEN_FLOATS]
def averagees_average_info(model): stop_epoch_sum = 0.0 stop_acc_sum = 0.0 for suffix in [0, 1, 2, 3, 4, 75, 76, 77, 78, 79]: (stop_epoch, stop_acc) = analysis.get_averagees_stopping_point(model=model, file_suffix=suffix) stop_epoch_sum += stop_epoch stop_acc_sum += stop_acc stop...
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Baseline_Exp1(): state = prototype_state() state['end_sym_utterance'] = '__eot__' state['unk_sym'] = 0 state['eos_sym'] = 1 state['eod_sym'] = (- 1) state['first_speaker_sym'] = (- 1) state['second_speaker_sym'] = (- 1) state['third_speake...
def ReadFileGS(x_axis, tthread, batchInterval, NUM_ITEMS, NUM_ACCESS, key_skewness, overlap_ratio, abort_ratio, txn_length, isCyclic, complexity): (w, h) = (2, len(x_axis)) y = [[] for _ in range(w)] for batchInterval in x_axis: inputEvents = (tthread * batchInterval) op_gs_path = getPathGS(...
class SequentialPostProcessor(object): operations: Sequence[Callable] def __post_init__(self): special_tokens = [] for operation in self.operations: if hasattr(operation, 'special_tokens'): special_tokens.extend(operation.special_tokens) self.special_tokens = ...
class Experiment(): def __init__(self, store_or_uri: Union[(str, Store)], name: str=None, description: str=None, _id: int=None): if (name is None): name = f'#{random.randint(0, 9999)}' if (description is None): description = f'Experiment: {name}' if isinstance(store_o...
def test_call_deps(): run_cell('def f(): return 0, 1, 2, 3') run_cell('a, b, c, d = f()') for sym in ('a', 'b', 'c', 'd'): run_cell(f'assert deps({sym}) == [lift(f)]') run_cell(f'assert users({sym}) == []') run_cell('g = lambda: (0, 1, 2, 3)') run_cell('w, x, y, z = g()') for sym...
class ResnetTester(nn.Module): def __init__(self, model): super(ResnetTester, self).__init__() self.layers = model self.classifier = nn.Linear(((2048 * 7) * 7), 200) def forward(self, input): features_in = self.layers(input) features_in = features_in.view(features_in.shap...
def model2state_dict(file_path): model = torch.load(file_path) if (model['model'] is not None): model_state_dict = model['model'].state_dict() torch.save(model_state_dict, file_path.replace('.pth', 'state_dict.pth')) else: print(type(model)) print(model) print('skip')
def generate_df_pop_by_ags(df): log.info('aggregate (sum) population by AGS') df_pop = df.drop(columns=list((set(df.columns) - set(['ags', 'population_total'])))) df_pop = df_pop.rename(columns={'population_total': 'population'}) df_pop_by_ags = df_pop.groupby('ags').sum() df_pop_by_ags.index = df_p...
class ApplySameTransformInputKeyOnList(ApplySameTransformToKeyOnList): def __init__(self, transform: Module, dim: int=1): super().__init__('input', transform=transform, dim=dim) def __repr__(self): return f'{self.__class__.__name__}(transform={self._transform}, dim={self._dim})'
def get_version(): major_value = ctypes.c_int(0) major = ctypes.pointer(major_value) minor_value = ctypes.c_int(0) minor = ctypes.pointer(minor_value) rev_value = ctypes.c_int(0) rev = ctypes.pointer(rev_value) _glfw.glfwGetVersion(major, minor, rev) return (major_value.value, minor_valu...
class Generator(object): def __init__(self): self.z_dim = 100 self.x_dim = 784 self.name = 'mnist/mlp/g_net' def __call__(self, z): with tf.variable_scope(self.name) as vs: fc = z fc = tcl.fully_connected(fc, 512, weights_initializer=tf.random_normal_initi...
def sentence_tokenizer(sentences): tokenized_sents = nltk.word_tokenize(sentences) return tokenized_sents
.parametrize('dataset_class,model_class,create_submission_f,apply_model', [(T4c22Dataset, DummyArangeNN_eta, create_submission_eta_plain_torch, apply_model_plain), (T4c22GeometricDataset, DummyArangeNN_eta, create_submission_eta_torch_geometric, apply_model_geometric)]) def test_create_submission_eta_city_plain_torch(c...
class MetricGraphPrinter(AbstractBaseLogger): def __init__(self, writer, key='train_loss', graph_name='Train Loss', group_name='metric'): self.key = key self.graph_label = graph_name self.group_name = group_name self.writer = writer def log(self, *args, **kwargs): if (sel...
def iou_boxes_polygons(boxes, polygons, w=0, h=0, xywh=True, ioubp=False): if ((w * h) == 0): p_boxes = [polygon_to_box(p) for p in polygons] region = boxes_region((p_boxes + list(boxes))) w = int((region[2] + 1)) h = int((region[3] + 1)) p_mask = polygons_to_mask(polygons, w, h)...
def _find_rocsolver_config(rocm_install_path): def rocsolver_version_numbers(path): possible_version_files = ['include/rocsolver/rocsolver-version.h', 'rocsolver/include/rocsolver-version.h'] version_file = None for f in possible_version_files: version_file_path = os.path.join(pa...
class P1203Pv(object): _COEFFS = {'u1': 72.61, 'u2': 0.32, 't1': 30.98, 't2': 1.29, 't3': 64.65, 'q1': 4.66, 'q2': (- 0.07), 'q3': 4.06, 'mode0': {'a1': 11.9983519, 'a2': (- 2.), 'a3': 41., 'a4': 0.}, 'mode1': {'a1': 5., 'a2': (- 1.), 'a3': 41.3585049, 'a4': 0, 'c0': (- 0.), 'c1': 0, 'c2': (- 3.), 'c3': 20.4098663}...
def available_classes(cls: type[Registry]) -> list[str]: return list(cls.available_classes().keys())
def postprocess_args(args): ROOTDIR = args.root_dir if (args.dataset == 'touchdown'): ft_file_map = {'resnet18': 'resnet18_view_fts.hdf5', 'vit_clip': 'vit_clip_view_fts.hdf5'} args.img_ft_file = os.path.join(ROOTDIR, 'Touchdown', 'features', ft_file_map[args.features]) args.anno_dir = o...
def get_current_user_path(path_in): if (path_in == ''): return '' from os.path import expanduser path = path_in.split('/') new_path = ((expanduser('~') + '/') + '/'.join(path[3:])) return str(new_path)
def nano(num_processes): def decorator(func): return _Nano_Customized_Training(func, num_processes) return decorator
class NezhaForQuestionAnswering(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def dbscan_with_masked_image(image, eps=0.5, min_samples=3): if (len(image.shape) != 2): raise ValueError('Input image must be grayscale!') masked_points = np.where((image > 0)) if (len(masked_points) > 0): X = np.column_stack(tuple((masked_points[1], masked_points[0]))) if (X.shape[...
def main(opt): model = torch.load(opt['model.model_path']) model.eval() model_opt_file = os.path.join(os.path.dirname(opt['model.model_path']), 'opt.json') with open(model_opt_file, 'r') as f: model_opt = json.load(f) model_opt['model.x_dim'] = map(int, model_opt['model.x_dim'].split(',')) ...
def test_run_with_ignore_embedded_text(): example = EXAMPLES[2] document = load_document(example.path, use_embedded_text=False) pipe = pipeline('document-question-answering', model=CHECKPOINTS['LayoutLMv1']) for qa in example.qa_pairs: resp = pipe(question=qa.question, **document.context, top_k=...
def test_env_instantiation(): env = ArgumentEnv('arg') assert (env.arg == 'arg') assert (env.calls == 1)
((PT_VERSION.release < Version('2.1.0').release), 'Please use PyTroch 2.1.0 or higher version for executor backend') class TestLLMQuantization(unittest.TestCase): def test_qwen(self): tokenizer = AutoTokenizer.from_pretrained('Qwen/Qwen-7B-Chat', trust_remote_code=True) sq_config = SmoothQuantConfig...
def linear_rampup(current, rampup_length=16): if (rampup_length == 0): return 1.0 else: current = np.clip((current / rampup_length), 0.0, 1.0) return float(current)
def create_meter_display(group_dict, ignore_start_with='_'): def prune_dict(dictionary: dict, ignore='_'): for (k, v) in dictionary.copy().items(): if isinstance(v, dict): prune_dict(v, ignore) elif k.startswith(ignore): del dictionary[k] def prune...
class TestTensorParallelOptimization(unittest.TestCase): def tearDown(self): destroy_parallel_group() return super().tearDown() def test_tensor_parallel_optimization(self): _run_tensor_parallel_optimization()
class Trainer(): def __init__(self) -> None: self.task = '' self.note = '' self.ckpt = '' self.dataset = 'ImageNet-LT' self.nb_classes = 1000 self.epochs = 800 self.batch = 256 self.accum_iter = 4 self.device = '0,1,2,3' self.model = 'm...
def create_effects_augmentation_chain(effects, ir_dir_path=None, sample_rate=44100, shuffle=False, parallel=False, parallel_weight_factor=None): fx_list = [] apply_prob = [] for cur_fx in effects: if isinstance(cur_fx, tuple): apply_prob.append(cur_fx[1]) cur_fx = cur_fx[0] ...
class RecurrentTransformerEncoderLayer(Module): def __init__(self, attention, d_model, d_ff=None, dropout=0.1, activation='relu', event_dispatcher=''): super(RecurrentTransformerEncoderLayer, self).__init__() d_ff = (d_ff or (4 * d_model)) self.attention = attention self.linear1 = Li...
def execute(code, stack, pos, storage, mmemory, data, trace, calldepth, debug, read_from_blockchain): op = code[pos]['o'] halt = False executed = True step = code[pos]['id'] if (op not in allops): print(('Unknown operation %s at pos %x' % (op, pos))) return (pos, True) if (allops...
def put_in_middle(str1, str2): n = len(str1) m = len(str2) if (n <= m): return str2 else: start = ((n - m) // 2) return ((str1[:start] + str2) + str1[(start + m):])