code
stringlengths
101
5.91M
class InvertibleModuleWrapper(nn.Module): def __init__(self, fn, keep_input=False, keep_input_inverse=False, num_bwd_passes=1, disable=False, preserve_rng_state=False): super(InvertibleModuleWrapper, self).__init__() self.disable = disable self.keep_input = keep_input self.keep_input...
def main(): data_root = '../datasets/humanml3d' feastures_path = 'in.npy' animation_save_path = 'in.mp4' fps = 20 mean = np.load(pjoin(data_root, 'Mean.npy')) std = np.load(pjoin(data_root, 'Std.npy')) motion = np.load(feastures_path) motion = ((motion * std) + mean) motion_rec = rec...
class Mlp(nn.Module): def __init__(self, hidden_sizes, output_size, input_size, init_w=0.003, hidden_activation=F.relu, output_activation=identity, hidden_init=ptu.fanin_init, b_init_value=0.1, layer_norm=False, layer_norm_kwargs=None): super().__init__() if (layer_norm_kwargs is None): ...
class ProbeRegimen(InitYAMLObject): yaml_tag = '!ProbeRegimen' def __init__(self, args, max_epochs, params_path, reporting_root, max_gradient_steps=(- 1), eval_dev_every=(- 1)): self.args = args self.max_epochs = max_epochs self.reporting_root = reporting_root self.params_name = ...
def initialize_scores(model, init_type): print(f'Initialization relevance score with {init_type} initialization') for m in model.modules(): if hasattr(m, 'popup_scores'): if (init_type == 'kaiming_uniform'): nn.init.kaiming_uniform_(m.popup_scores) elif (init_type...
def get_affine_transform_for_beta_dist(target_min, target_max): if isinstance(target_min, (np.ndarray, np.generic)): assert np.all((target_min <= target_max)) else: assert (target_min <= target_max) return AffineTransformEx(loc=torch.tensor(target_min), scale=torch.tensor((target_max - targe...
def print_eval(prepare_data_fun, out_label): model_file = os.path.join(snapshot_dir, 'best_model.pth') pkl_res_file = os.path.join(snapshot_dir, ('best_model_predict_%s.pkl' % out_label)) out_file = os.path.join(snapshot_dir, ('best_model_predict_%s.json' % out_label)) data_set_test = prepare_data_fun(*...
def fftscore_setup(): pyfftw.interfaces.cache.enable() pyfftw.interfaces.cache.set_keepalive_time(8.0)
def combine_vit(vit_result, sent_lst, out_path): print(len(vit_result), len(sent_lst)) seg_result = [] for (idx, (cont, it)) in enumerate(vit_result): entgt = sent_lst[it] seg_result.append(' '.join(visual_viterb(cont, entgt))) with open(out_path, 'w') as f: for elem in seg_resul...
def _in_projection(q: Tensor, k: Tensor, v: Tensor, w_q: Tensor, w_k: Tensor, w_v: Tensor, b_q: Optional[Tensor]=None, b_k: Optional[Tensor]=None, b_v: Optional[Tensor]=None) -> Tuple[(Tensor, Tensor, Tensor)]: (Eq, Ek, Ev) = (q.size((- 1)), k.size((- 1)), v.size((- 1))) assert (Eq == Ek == Ev), 'query, key, an...
def interleave_offsets(batch, nu): groups = ([(batch // (nu + 1))] * (nu + 1)) for x in range((batch - sum(groups))): groups[((- x) - 1)] += 1 offsets = [0] for g in groups: offsets.append((offsets[(- 1)] + g)) assert (offsets[(- 1)] == batch) return offsets
def delta_function(r0): r0 = np.atleast_1d(r0) def pdf(*args): values = np.zeros_like(args[0]) diff = sum([((r0[i] - args[i]) ** 2) for i in range(len(args))]) idx = np.unravel_index(np.argmin(diff), diff.shape) values[idx] = 1 return values return pdf
def _demucs(pretrained, url, **kwargs): model = Demucs(**kwargs) if pretrained: state_dict = torch.hub.load_state_dict_from_url(url, map_location='cpu') model.load_state_dict(state_dict) return model
def train(train_loader, model, criterion, optimizer, metric, epoch, args): batch_time = AverageMeter('Time', ':6.3f') data_time = AverageMeter('Data', ':6.3f') losses = AverageMeter('Loss', ':.4e') mIoU = AverageMeter('mIoU', ':6.2f') progress = ProgressMeter(len(train_loader), batch_time, data_time...
def parse_stories(filename, word2id=None): with open(filename, 'r') as f: lines = f.readlines() print('go through lines') (stories, story) = ([], []) for line in lines: line = line.strip() (nid, line) = line.split(' ', 1) nid = int(nid) if (nid == 1): ...
def local_train_net_fednova(nets, selected, global_model, args, net_dataidx_map, test_dl=None, device='cpu'): avg_acc = 0.0 a_list = [] d_list = [] n_list = [] global_model.to(device) for (net_id, net) in nets.items(): if (net_id not in selected): continue dataidxs = ...
class KNearestNeighborDensityEstimatorTest(unittest.TestCase): def setUp(self): self.knn = KNearestNeighborDensityEstimator() def test_should_the_density_estimator_compute_the_right_distances_case1(self): solution1 = Solution(2, 2) solution1.objectives = [1, 5] solution2 = Soluti...
def corrector_relcoronpath_set(tol): from phcpy.phcpy2c3 import py2c_set_value_of_continuation_parameter as set return set(25, tol)
class TrainSessionParameters(object): def getSessionName(sessionName): return (sessionName if (sessionName is not None) else 'trainSession') def errorRequireChannelsTraining(): print('ERROR: Parameter "channelsTraining" needed but not provided in config file. This parameter should provide paths ...
class GroupingOperation(Function): def forward(ctx, features, idx): (B, nfeatures, nsample) = idx.size() (_, C, N) = features.size() ctx.for_backwards = (idx, N) return _ext.group_points(features, idx) def backward(ctx, grad_out): (idx, N) = ctx.for_backwards grad...
def remove_empty_line(original: str) -> str: lines = original.splitlines() c_lines = [x for x in lines if (not (x.strip() == ''))] return '\n'.join(c_lines)
def compute_eta_for_day(day, sc_parquet, supersegments, edge_maxspeeds_kph, edge_free_flows_kph, debug): sc_df = pd.read_parquet(sc_parquet) print(f'Read {len(sc_df)} rows from {sc_parquet}') maxspeed_cnt = 0 edge_speeds = {} for (uv, maxspeed) in edge_maxspeeds_kph.items(): if (uv in edge_f...
def mlp_constructor(dims, actv='Sigmoid', lastactv=True): if (type(actv) is str): actv = getattr(nn, actv) if (len(dims) <= 1): return nn.Sequential() else: return nn.Sequential(*((sum([[nn.Linear(dims[i], dims[(i + 1)]), actv()] for i in range((len(dims) - 2))], []) + [nn.Linear(dim...
class DwarvishMithrilCoat(BaseSuit): def __init__(self): super().__init__('dwarvish mithril-coat', weight=150, armour_class=6, material=M.Mithril)
def get_cam_model(input_size: tuple=(224, 224, 3), num_classes: int=3, trainable_layers: int=1, dropout: float=0.5, log_softmax: bool=False, mc_dropout: bool=False, *args, **kwargs): act_fn = (tf.nn.softmax if (not log_softmax) else tf.nn.log_softmax) baseModel = VGG16(weights='imagenet', include_top=False, inp...
def crawl_and_copy(current_folder, out_folder, prefix='fabian_', suffix='ummary.json'): s = subdirs(current_folder, join=False) f = subfiles(current_folder, join=False) f = [i for i in f if i.endswith(suffix)] if (current_folder.find('fold0') != (- 1)): for fl in f: shutil.copy(os.pa...
def qualification_loss(x_minus, x_plus, y_minus, y_plus, a, b, c, confidence=(- 0.1)): loss1 = ts.sigmoid_upper(torch.tanh(x_minus), b, ((a * x_minus) + c), y_minus, (y_plus * 0)) valid = (loss1 <= 0) loss1 = torch.clamp(loss1, min=confidence) loss2 = ts.sigmoid_upper(torch.tanh(x_plus), b, ((a * x_plus...
def replace_layer(state_dict, keyword1, keyword2): keys = [key for key in state_dict.keys()] for key in keys: if (keyword1 in key): new_key = key.replace(keyword1, keyword2) state_dict[new_key] = state_dict.pop(key) return state_dict
def tag_reference_line(line, kbs, record_titles_count): working_line1 = wash_line(line) working_line1 = tag_pos_volume(working_line1) working_line1 = wash_line(working_line1) working_line1 = tag_quoted_text(working_line1) working_line1 = tag_isbn(working_line1) working_line1 = tag_arxiv(working_...
def create_ucf101_files_for_frames(folder_files: str, frames_folder: str): if (not _HAS_PD): raise ImportError('pandas is required to use this function.') classes = {} def get_video_class_index(video: str): video = Path(video) if (video.parent.name not in classes): classe...
class Dataset(): def __init__(self, raw_data: Dict): self.raw_data = raw_data self.metadata: EasyDict = EasyDict(raw_data['metadata']) self.data: List[Dict] = raw_data['data'] def dataset_key(self): return self.metadata['dataset_key'] def __len__(self): return len(sel...
(version='2.0') def _prepare_inputs(pt_model, input_names, example_inputs): if (isinstance(example_inputs, dict) or isinstance(example_inputs, UserDict)): input_names = (input_names or list(example_inputs.keys())) if isinstance(example_inputs, UserDict): example_inputs = dict(example_inp...
class DeepAttentionWrapper(nn.Module): def __init__(self, x1_dim, x2_dim, x3_dims, att_cnt, prefix='deep_att', opt=None, dropout=None): super(DeepAttentionWrapper, self).__init__() self.opt = ({} if (opt is None) else opt) self.prefix = prefix self.x1_dim = x1_dim self.x2_dim...
def stable_softmax(t, dim=(- 1)): t = (t - t.amax(dim=dim, keepdim=True)) return t.softmax(dim=dim)
class PolicyOutput(QtWidgets.QWidget): def __init__(self, main_window, policy): super().__init__() self.main_window = main_window self.policy = policy self.action = None self.q_value_map = None self.q_value_map_image = QtWidgets.QLabel() self.setWindowTitle('P...
class Preset(IntEnum): Custom = 0 Default = 1 Hand = 2 HighAccuracy = 3 HighDensity = 4 MediumDensity = 5
def create_encoder(Module): class Encoder(Module): def __init__(self, *args, local_idx=None, multi_idx=None, conv_idx=None, fc_idx=None, **kwargs): super().__init__(*args, **kwargs) if (local_idx is None): raise ValueError('`local_idx` must be set') conv_i...
def _cfg(url='', **kwargs): return {'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.875, 'interpolation': 'bilinear', 'mean': IMAGENET_INCEPTION_MEAN, 'std': IMAGENET_INCEPTION_STD, 'first_conv': 'stem.conv', 'classifier': 'head.fc', **kwargs}
class ImageDataset(): def __init__(self, image_path, resize=None): self.image_path = image_path self.name = image_path.split('/')[(- 1)] with open(image_path, 'rb') as f: img = Image.open(f) img = img.convert('RGB') if (resize is not None): transfo...
class BlenderbotSmallPreTrainedModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def register_all_pascal_voc(root='datasets'): SPLITS = [('voc_2007_trainval', 'VOC2007', 'trainval'), ('voc_2007_train', 'VOC2007', 'train'), ('voc_2007_val', 'VOC2007', 'val'), ('voc_2007_test', 'VOC2007', 'test'), ('voc_2012_trainval', 'VOC2012', 'trainval'), ('voc_2012_train', 'VOC2012', 'train'), ('voc_2012_val...
def create_reconstruction_model(energy_mdl): x_in = Input(batch_shape=energy_mdl.input_shape) x = GaussianNoise(stddev=0.5)(x_in) energy = energy_mdl(x) rec = Lambda((lambda args: (args[1] - K.gradients(args[0], args[1]))), output_shape=energy_mdl.input_shape[1:])([energy, x]) return Model(x_in, rec...
def generate_paper_results(configurations, mode='experiment', save_dir=None, determinize=False): results_list = [] data_dict = {} for (mangle_method, article_section_set, current_config) in configurations: if (current_config.article_sections not in data_dict): data_dict[current_config.ar...
def bilinear_form_Potts_C(X1, X2, couplings): B = X1.shape[0] N1 = couplings.shape[0] N2 = couplings.shape[1] out = np.zeros(B, dtype=curr_float) out_buffer = np.zeros([B, N1], dtype=curr_float) for b in prange(B): for n1 in prange(N1): for n2 in range(N2): ou...
def train_model(model, dataset, evaluator, early_stop, logger, config): logger.info('train start ... !') early_stop.initialize() (test_score, train_time) = model.train_model(dataset, evaluator, early_stop, logger, config) return (test_score, train_time)
def parse_multisite(line: str) -> Multisite: line = drop_comment(line) if (not line): return None words = line.split() source_site = int(words[0]) dx = [int(x) for x in words[1::2]] dy = [int(x) for x in words[2::2]] return Multisite(source_site, dx, dy)
def build_matcap_nodes(node_tree: bpy.types.NodeTree, image_path: str) -> None: tex_coord_node = node_tree.nodes.new(type='ShaderNodeTexCoord') vector_transform_node = node_tree.nodes.new(type='ShaderNodeVectorTransform') mapping_node = node_tree.nodes.new(type='ShaderNodeMapping') texture_image_node = ...
class FusedMBConv(nn.Module): def __init__(self, cnf: FusedMBConvConfig, stochastic_depth_prob: float, norm_layer: Callable[(..., nn.Module)]) -> None: super().__init__() if (not (1 <= cnf.stride <= 2)): raise ValueError('illegal stride value') self.use_res_connect = ((cnf.stride...
(before=[init], after=[post]) def con_train_wbglobal(): USR.set('dataset', 'data/wb_aligned/') USR.set('decoder', 'crf') USR.set('L', '8') USR.set('layers', '2') USR.set('min_epochs', '8') USR.set('weight_decay', '0.0') USR.set('posterior_reg', '1') command = ('%(S_python_itrptr)s %(S_py...
def get_detection_weight(n): a = ((n.sum() - n) / n) w = (a * ((1 + a) / a).log()) return w[None]
def lowercase_and_remove_accent(text): text = ' '.join(text) text = text.lower() text = unicodedata.normalize('NFD', text) output = [] for char in text: cat = unicodedata.category(char) if (cat == 'Mn'): continue output.append(char) return ''.join(output).lowe...
def dropout(x, keep_prob, is_train, noise_shape=None, seed=None, name=None): with tf.name_scope((name or 'dropout')): if (keep_prob < 1.0): d = tf.nn.dropout(x, keep_prob, noise_shape=noise_shape, seed=seed) out = tf.cond(is_train, (lambda : d), (lambda : x)) return out ...
class _FP16OptimizerMixin(object): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._multiply_factor = 1.0 def has_flat_params(self): return (torch.is_tensor(self.fp32_params) or (isinstance(self.fp32_params, dict) and all((torch.is_tensor(t) for t in self.fp32...
def extract_frames_method2(video_path): video_path = video_path.replace('\n', '') video_fname = Path(video_path).name x = str((VIDEOS_DIR / video_path)) vidcap = cv2.VideoCapture(x) frame = 0 success = True while success: curr_frame_str = str(frame).zfill(6) vidcap.set(cv2.CA...
class DummyDataset(data.Dataset): def __init__(self): self.tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) if (getattr(self.tokenizer, 'pad_token', None) is None): self.tokenizer.pad_token = self.tokenizer.eos_token self.max_prompt_length = 128 self.max_length = 256...
def get_model_parallel_world_size(): return torch.distributed.get_world_size(group=get_model_parallel_group())
class EfficientNet(nn.Module): def __init__(self, inverted_residual_setting: Sequence[Union[(MBConvConfig, FusedMBConvConfig)]], dropout: float, stochastic_depth_prob: float=0.2, num_classes: int=1000, norm_layer: Optional[Callable[(..., nn.Module)]]=None, last_channel: Optional[int]=None, **kwargs: Any) -> None: ...
class ResNet18_128(ResNetBase): BLOCK = BasicBlock PLANES = (128, 128, 256, 512) LAYERS = (2, 2, 2, 2)
class CaffeSoftmaxLayer(CaffeLayerGenerator): def __init__(self, name): super(CaffeSoftmaxLayer, self).__init__(name, 'Softmax') def write(self, f): f.write(self.get_template().format(''))
def configurable(init_func): assert (init_func.__name__ == '__init__'), ' should only be used for __init__!' if init_func.__module__.startswith('detectron2.'): assert ((init_func.__doc__ is not None) and ('experimental' in init_func.__doc__)), f'configurable {init_func} should be marked experimental' ...
def test_python_inherit_from_mi(): class PyMVF(m.MVF): g = 7 def get_g_g(self): return self.g o = PyMVF() assert (o.b == 1) assert (o.c == 2) assert (o.d0 == 3) assert (o.d1 == 4) assert (o.e == 5) assert (o.f == 6) assert (o.g == 7) assert (o.get_g_g(...
class SegnetEncoder(nn.Module): def __init__(self, in_channels=3, is_unpooling=True): super(SegnetEncoder, self).__init__() self.in_channels = in_channels self.is_unpooling = is_unpooling self.down1 = segnetDown2(self.in_channels, 64) self.down2 = segnetDown2(64, 128) ...
def test_env_render_result_is_immutable(): from six import string_types environs = [envs.make('Taxi-v2'), envs.make('FrozenLake-v0'), envs.make('Reverse-v0')] for env in environs: env.reset() output = env.render(mode='ansi') assert isinstance(output, string_types) env.close()
def allocate_buffers(engine): inputs = [] outputs = [] bindings = [] stream = cuda.Stream() for binding in engine: size = (trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_size) dtype = trt.nptype(engine.get_binding_dtype(binding)) host_mem = cuda.pagelocked_e...
def get_neighbor_index(i, j): neighbor_matrix_ids = [] if ((j % 2) == 0): neighbor_matrix_ids = [[(i - 1), j], [i, (j + 1)], [(i + 1), (j + 1)], [(i + 1), j], [(i + 1), (j - 1)], [i, (j - 1)]] elif ((j % 2) == 1): neighbor_matrix_ids = [[(i - 1), j], [(i - 1), (j + 1)], [i, (j + 1)], [(i + 1...
class Storage(abc.ABC): def capacity(self): return self._capacity def size(self): return self._size def starts(self): return self._starts def ends(self): return self._ends def lengths(self): return self._lengths def bytes(self): return get_bytes(se...
class ImagesViewer(object): def __init__(self, temp_dir=None): if (temp_dir is None): temp_dir = tempfile.gettempdir() self.temp_dir = tempfile.mkdtemp(dir=temp_dir) if os.path.exists(self.temp_dir): shutil.rmtree(self.temp_dir) os.mkdir(self.temp_dir) ...
class ParserManager(object): def __init__(self, grammar_dir): if DEBUG_PARSER: self.parser_file_manager = ParserFileManager(grammar_dir) self.cache_dir = self.parser_file_manager.cache_dir self.grammar_dir = self.parser_file_manager.grammar_dir self.save_threa...
def main(): (train_loader, test_loader, criterion, model, optimizer, scheduler, starting_epoch, logfilename, model_path, device, writer) = prologue(args) for epoch in range(starting_epoch, args.epochs): before = time.time() train_loss = train(train_loader, model, optimizer, epoch, args.noise_sd,...
class FactorizedConv2DTucker(Layer): def __init__(self, filters, kernel_size, input_components=None, output_components=None, strides=(1, 1), padding='valid', data_format=None, dilation_rate=(1, 1), activation=None, use_bias=True, pre_kernel_initializer='glorot_uniform', kernel_initializer='glorot_uniform', post_ker...
class ImageSurrogate(ImageImputer): def __init__(self, surrogate, width, height, superpixel_size): super().__init__(width, height, superpixel_size) self.surrogate = surrogate def train(self, train_data, val_data, batch_size, max_epochs, loss_fn, validation_samples=1, validation_batch_size=None, ...
def imagenet1k(args, distributed=False): train_dirs = args.train_dirs val_dirs = args.val_dirs batch_size = args.batch_size val_batch_size = args.val_batch_size num_workers = args.num_workers color_jitter = args.color_jitter normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0...
def pts_to_distogram(pts: torch.Tensor, min_bin: torch.types.Number=2.3125, max_bin: torch.types.Number=21.6875, no_bins: int=64) -> torch.Tensor: boundaries = torch.linspace(min_bin, max_bin, (no_bins - 1), device=pts.device) dists = torch.sqrt(torch.sum(((pts.unsqueeze((- 2)) - pts.unsqueeze((- 3))) ** 2), di...
class PositionwiseFeedForward(nn.Module): def __init__(self, d_model, d_ff, dropout=0.1): super(PositionwiseFeedForward, self).__init__() self.w_1 = nn.Linear(d_model, d_ff) self.w_2 = nn.Linear(d_ff, d_model) self.layer_norm = onmt.modules.LayerNorm(d_model) self.dropout_1 =...
class ResNet18(ClassificationBase): def get_params_and_calculation_from_channel_num(self, channel_num, num_classes, ori_size): def get_input_size(index): size = ori_size if (not isinstance(size, int)): size = size[0] if ((index >= 0) and (index <= 10)): ...
def test_initial_solutions_are_correct(archive_fixture): (archive, _) = archive_fixture initial_solutions = [[0, 1, 2, 3], [(- 1), (- 2), (- 3), (- 4)]] emitter = GaussianEmitter(archive, sigma=1.0, initial_solutions=initial_solutions) assert np.all((emitter.ask() == initial_solutions)) assert np.al...
(sigma=1000.0) class Boundary(sc.SampleDomain): def __init__(self): self.points = geo.sample_boundary(1) self.constraints = {'u': np.cosh(self.points['x'])} def sampling(self, *args, **kwargs): return (self.points, self.constraints)
def run(dataset_dir): if (not tf.gfile.Exists(dataset_dir)): tf.gfile.MakeDirs(dataset_dir) if _dataset_exists(dataset_dir): print('Dataset files already exist. Exiting without re-creating them.') return dataset_utils.download_and_uncompress_tarball(_DATA_URL, dataset_dir) (photo...
class PretrainedFSMTModel(): def __init__(self, *args, **kwargs): requires_pytorch(self) def from_pretrained(self, *args, **kwargs): requires_pytorch(self)
def test(cfg_file, ckpt: str, combiner_cfg: dict, batch_class: Batch=Batch, output_path: str=None, save_attention: bool=False, datasets: dict=None) -> None: cfg = load_config(cfg_file) model_dir = cfg['training']['model_dir'] check_combiner_cfg(combiner_cfg) cfg['combiner'] = combiner_cfg if (len(lo...
def _get_signature_keys(obj): parameters = inspect.signature(obj.__init__).parameters required_parameters = {k: v for (k, v) in parameters.items() if (v.default == inspect._empty)} optional_parameters = set({k for (k, v) in parameters.items() if (v.default != inspect._empty)}) expected_modules = (set(re...
class EvoNormSample2d(nn.Module): def __init__(self, num_features, apply_act=True, groups=8, eps=1e-05, drop_block=None): super(EvoNormSample2d, self).__init__() self.apply_act = apply_act self.groups = groups self.eps = eps param_shape = (1, num_features, 1, 1) self....
class TFArgument(Argument): _str_values = ['', '1', 'sum', 'same', 'valid', 'zeros'] _float_values = [0.0, 1.0, (- 1.0), 63.0, (- 63.0)] _tensor_arg_dtypes = [ArgType.TF_TENSOR, ArgType.KERAS_TENSOR, ArgType.TF_VARIABLE] _dtypes = [tf.bfloat16, tf.bool, tf.complex128, tf.complex64, tf.double, tf.float16...
def main(args): (args, dataset, flownmt) = setup(args) print(args) (val_iter, test_iter) = init_dataloader(args, dataset) result_path = args.result_path if (args.decode == 'argmax'): tau = args.tau n_tr = args.ntr outfile = 'argmax.t{:.1f}.ntr{}.dev.mt'.format(tau, n_tr) ...
_module() class SegmindLoggerHook(LoggerHook): def __init__(self, interval=10, ignore_last=True, reset_flag=False, by_epoch=True): super(SegmindLoggerHook, self).__init__(interval, ignore_last, reset_flag, by_epoch) self.import_segmind() def import_segmind(self): try: import ...
def get_path_bond_feature(bond): if (bond is None): return np.zeros(N_BOND_FEATS) else: bond_type = onek_unk_encoding(bond.GetBondType(), BOND_TYPES) conj = [int(bond.GetIsConjugated())] ring = [int(bond.IsInRing())] return np.array(((bond_type + conj) + ring))
def convert_all_pt_checkpoints_to_tf(args_model_type, tf_dump_path, model_shortcut_names_or_path=None, config_shortcut_names_or_path=None, compare_with_pt_model=False, use_cached_models=False, remove_cached_files=False, only_convert_finetuned_models=False): assert os.path.isdir(args.tf_dump_path), '--tf_dump_path s...
def extract_ext_funcs(finit): fdict = {} def _list(name, func): fdict[name] = func myf = convert_to_tvm_func(_list) ret = finit(myf.handle) _ = myf if (ret != 0): raise RuntimeError(('cannot initialize with %s' % finit)) return fdict
class PositionwiseFeedForward(nn.Module): def __init__(self, d_in, d_hid, dropout=0.1): super().__init__() self.w_1 = nn.Conv1d(d_in, d_hid, 1) self.w_2 = nn.Conv1d(d_hid, d_in, 1) self.layer_norm = nn.LayerNorm(d_in) self.dropout = nn.Dropout(dropout) def forward(self, x...
def check_goldstein_conditions(step_size, loss, grad_norm, loss_next, c, beta_b, beta_f, bound_step_size, eta_max): found = 0 if (loss_next <= (loss - ((step_size * c) * (grad_norm ** 2)))): found = 1 if (loss_next >= (loss - ((step_size * (1 - c)) * (grad_norm ** 2)))): if (found == 1): ...
def get_bn_params(**params): axis = (4 if (backend.image_data_format() == 'channels_last') else 1) default_bn_params = {'axis': axis, 'epsilon': 9.e-06} default_bn_params.update(params) return default_bn_params
class Dataloder(): def __init__(self, config): normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform_train = transforms.Compose([transforms.Resize(256), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ColorJitter(0.4, 0.4, ...
class TableTransformerForObjectDetection(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
def load_lvis_json(annotations_json_file: str, image_root: str, dataset_name: str): lvis_api = _load_lvis_annotations(PathManager.get_local_path(annotations_json_file)) _add_categories_metadata(dataset_name) img_ids = sorted(lvis_api.imgs.keys()) imgs = lvis_api.load_imgs(img_ids) logger = logging.g...
class CAD(AbstractCAD): def __init__(self, model, dataset, optimizer, hparams): super(CAD, self).__init__(model, dataset, optimizer, hparams, is_conditional=False)
def load_pretrained(model_args, training_args) -> Tuple[(nn.Module, PREPROCESSOR)]: type_ = model_args.type if (type_ == 'llava'): return load_pretrained_llava(model_args, training_args) else: assert False
class MCTCTConfig(PretrainedConfig): model_type = 'mctct' def __init__(self, vocab_size=8065, hidden_size=1536, num_hidden_layers=36, intermediate_size=6144, num_attention_heads=4, attention_head_dim=384, max_position_embeddings=920, layer_norm_eps=1e-05, layerdrop=0.3, hidden_act='relu', initializer_range=0.02...
_module() class TensorRTDetector(TextDetectorMixin, SingleStageTextDetector): def __init__(self, trt_file: str, cfg: Any, device_id: int, show_score: bool=False): if ('type' in cfg.model): cfg.model.pop('type') SingleStageTextDetector.__init__(self, **cfg.model) TextDetectorMixin...
class IntegerNode(ExprNode): def __init__(self, parse_info=None, raw_text=None, value=None): super().__init__(IRNodeType.Integer, parse_info=parse_info, raw_text=raw_text) self.value = value
class SupervisedCorrectionReader(Reader): def __init__(self, labels, test=False): super().__init__(labels, test) self.db = FEVERDocumentDatabase('resources/wikipedia/fever.db') self.using_gold = False self.using_pipeline = False def generate_instances(self, instance): if ...