code
stringlengths
101
5.91M
class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride): super().__init__() if (not (1 <= stride <= 3)): raise ValueError('illegal stride value') self.stride = stride branch_features = (oup // 2) assert ((self.stride != 1) or (inp == (branch_featur...
def make_hot(): aa_dict = {} for (i, aa) in enumerate(amino_acids): aa_one_hot = ([0] * num_aa) aa_one_hot[i] = 1 aa_dict[aa] = aa_one_hot return aa_dict
class Fp16OptimizerHook(OptimizerHook): def __init__(self, grad_clip=None, coalesce=True, bucket_size_mb=(- 1), loss_scale=512.0, distributed=True): self.grad_clip = grad_clip self.coalesce = coalesce self.bucket_size_mb = bucket_size_mb self.loss_scale = loss_scale self.dist...
class NN_MBE(): def __init__(self, tfm_=None): self.nn_mbe = dict() if (tfm_ != None): for order in tfm_: print(tfm_[order]) self.nn_mbe[order] = TFMolManage(tfm_[order], None, False) return def NN_Energy(self, mol): mol.Generate_All_MB...
def train_single_epoch(epoch, model, train_loader, optimizer, eval_loader, plotfilename=None): model.train() (errs, losses) = ([], []) x = torch.unsqueeze(x, dim=1) optimizer.zero_grad() (x, y, clas) = (x.to(device), y.to(device), clas.to(device))
class hico(): def __init__(self, annotation_file): self.annotations = json.load(open(annotation_file, 'r')) self.train_annotations = json.load(open(annotation_file.replace('test_hico.json', 'trainval_hico.json'), 'r')) self.overlap_iou = 0.5 self.verb_name_dict = [] self.verb...
class CUDACallback(Callback): def on_train_epoch_start(self, trainer, pl_module): torch.cuda.reset_peak_memory_stats(trainer.root_gpu) torch.cuda.synchronize(trainer.root_gpu) self.start_time = time.time() def on_train_epoch_end(self, trainer, pl_module, outputs): torch.cuda.sync...
def get_real_dataloaders(dataset, data_dir, batch_size, num_workers, metadata, distributed=True): (transform_train, transform_val) = get_transforms(TRANFORMS_MAPPING[dataset], metadata.image_size) (train_set, val_set, train_sampler, val_sampler) = get_dataset(dataset, data_dir, transform_train, transform_val, d...
def batch_counter_hook(module, input, output): input = input[0] batch_size = input.shape[0] module.__batch_counter__ += batch_size
class OrRule(MappingRule): def __init__(self, *rules): self.rules = rules def matches(self, key): return any((r.matches(key) for r in self.rules)) def apply(self, key, value): items = [(key, value)] for r in self.rules: items = [r.apply(k, v) for (k, v) in items] ...
def reshape_patch(img_tensor, patch_size): assert (5 == img_tensor.ndim) batch_size = np.shape(img_tensor)[0] seq_length = np.shape(img_tensor)[1] img_height = np.shape(img_tensor)[2] img_width = np.shape(img_tensor)[3] num_channels = np.shape(img_tensor)[4] a = np.reshape(img_tensor, [batch...
class VAE_ID(nn.Module): def __init__(self, in_channels, latent_dim, hidden_dim=512, hidden_nums=5, **kwargs) -> None: super(VAE_ID, self).__init__() self.epoch = 0 self.step = 0 self.latent_dim = latent_dim self.in_channels_ori = in_channels modules = [] for ...
.skipif((not hasattr(m, 'has_string_view')), reason='no <string_view>') def test_string_view(capture): assert (m.string_view_chars('Hi') == [72, 105]) assert (m.string_view_chars('Hi ') == [72, 105, 32, 240, 159, 142, 130]) assert (m.string_view16_chars('Hi ') == [72, 105, 32, 55356, 57218]) assert (m.s...
def get_diml_indoor_loader(data_dir_root, batch_size=1, **kwargs): dataset = DIML_Indoor(data_dir_root) return DataLoader(dataset, batch_size, **kwargs)
def bottomPvis(): bPbu.switch() if (bPbu.status() == 'Bhide'): bottomP.off() elif (bPbu.status() == 'Bshow'): bottomP.on()
def test_interpsnapshotKeplerPotential_logR_eval(): s = pynbody.new(star=1) s['mass'] = 1.0 s['eps'] = 0.0 sp = potential.InterpSnapshotRZPotential(s, rgrid=(numpy.log(0.01), numpy.log(20.0), 251), logR=True, zgrid=(0.0, 0.2, 201), interpPot=True, zsym=True) kp = potential.KeplerPotential(amp=1.0) ...
class Pool5FnVGG(nn.Module): def __init__(self, opt): super(Pool5FnVGG, self).__init__() self.cfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'] self.x_conv_layers = self.make_conv_layers() self._initialize_weights() def make_conv_layer...
class MInstrDataset(QuestionTemplateMixin, Dataset): _repr_indent = 4 def __init__(self, filename, image_folder=None, filename_positive=None, filename_negative=None, image_folder_positive=None, image_folder_negative=None, label=None, label_negative=None, seed=None, **kwargs): super().__init__(**kwargs) ...
def get_args(): parser = argparse.ArgumentParser() parser.add_argument('config', type=str) (args, others) = parser.parse_known_args() config = OmegaConf.load(args.config) includes = config.get('includes', []) if (not isinstance(includes, collections.abc.Sequence)): raise AttributeError('...
_registry(operator_type='FusedBatchNormV3') class FusedBatchNormV3(Operator): def __init__(self): super().__init__() def set_attr(self, framework, node): if (framework == 'tensorflow'): self._attr['epsilon'] = node.attr['epsilon'].f self._attr['exponential_avg_factor'] = ...
class XLMRobertaModel(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
_model_architecture('transformer_lm', 'transformer_lm_gpt3_xl') def transformer_lm_gpt3_xl(args): args.decoder_layers = getattr(args, 'decoder_layers', 24) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 2048) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 32) base_g...
def IPOT_torch_uniform(C, n, m, beta=0.5): sigma = (torch.ones(int(m), 1).cuda() / m) T = torch.ones(n, m).cuda() A = torch.exp(((- C) / beta)) for t in range(50): Q = (A * T) for k in range(1): delta = (1 / (n * torch.mm(Q, sigma))) a = torch.mm(torch.transpose(Q...
class ImageCenterCrop(ImagePreprocessing): def __init__(self, crop_width, crop_height, is_clip=True, bigdl_type='float'): super(ImageCenterCrop, self).__init__(bigdl_type, crop_width, crop_height, is_clip)
class PytorchConverter(base_converter.ConverterInterface): activation_type = {'ReLU': ActivationType.RELU, 'ReLU6': ActivationType.RELUX} pooling_type_mode = {NodeKind.AvgPool2D: PoolingType.AVG, NodeKind.AdaptiveAvgPool2D: PoolingType.AVG, NodeKind.MaxPool2D: PoolingType.MAX} eltwise_type = {NodeKind.Add: ...
def stitch_boxes_into_lines(boxes, max_x_dist=10, min_y_overlap_ratio=0.8): if (len(boxes) <= 1): return boxes merged_boxes = [] x_sorted_boxes = sorted(boxes, key=(lambda x: np.min(x['box'][::2]))) skip_idxs = set() i = 0 for i in range(len(x_sorted_boxes)): if (i in skip_idxs):...
class HierarchicalSoftmax(Layer): def __init__(self, output_dim, init='glorot_uniform', **kwargs): self.init = initializations.get(init) self.output_dim = output_dim def hshape(n): from math import sqrt, ceil l1 = ceil(sqrt(n)) l2 = ceil((n / l1)) ...
def graph_hyperparamdist_file(filename, ymin=0, ymax=500, hpname='', gname=''): parsed = [[], [], []] with open(filename, 'r') as hp_dist: r = 0 for line_raw in hp_dist: line = line_raw.rstrip().split(',') parsed[r] = np.array(line[1:]).astype(float) r += 1 ...
def setup_camera(camera_parameters, camera_scale): bpy.data.objects['Camera'].location = (0, 0, 0) bpy.data.objects['Camera'].rotation_euler = (0, pi, pi) width = (camera_scale * camera_parameters['width']) height = (camera_scale * camera_parameters['height']) f = ((camera_scale * (camera_parameters...
class CoNLL03Reader(object): def __init__(self, file_path, word_alphabet, char_alphabet, pos_alphabet, chunk_alphabet, ner_alphabet): self.__source_file = open(file_path, 'r') self.__word_alphabet = word_alphabet self.__char_alphabet = char_alphabet self.__pos_alphabet = pos_alphabet...
class UBase(Gate): def __init__(self, theta, phi, lam): super().__init__('U', 1, [theta, phi, lam]) def inverse(self): return UBase((- self.params[0]), (- self.params[2]), (- self.params[1])) def to_matrix(self): (theta, phi, lam) = self.params return numpy.array([[numpy.cos(...
def is_valid_action(state: State, action: chex.Array) -> chex.Array: return (state.board[tuple(action)] == UNEXPLORED_ID)
def custom_scorer(net, ds, y=None): output = net.predict_proba(ds) if (output.shape[1] > 1): probas = torch.softmax(torch.Tensor(output), dim=1) preds = probas.argmax(dim=1) else: probas = torch.sigmoid(torch.Tensor(output)) preds = torch.round(probas) score = accuracy_sc...
class DepthwiseConv1d(nn.Module): def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int=1, padding: int=0, bias: bool=False) -> None: super(DepthwiseConv1d, self).__init__() assert ((out_channels % in_channels) == 0), 'out_channels should be constant multiple of in_ch...
class VGG(nn.Module): def __init__(self, features): super(VGG, self).__init__() self.features = features self.classifier = nn.Sequential(LIFSpike(), tdLayer(nn.Linear(512, 512)), LIFSpike(), tdLayer(nn.Linear(512, 512)), LIFSpike(), tdLayer(nn.Linear(512, 10)), LIFSpike()) (self.step...
def polar_position(r, theta, start_point): x = (r * math.cos(theta)) y = (r * math.sin(theta)) return (np.array([x, y]) + start_point)
def sizeof_fmt(size, suffix='B'): for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if (abs(size) < 1024.0): return f'{size:3.1f} {unit}{suffix}' size /= 1024.0 return f'{size:3.1f} Y{suffix}'
class VAE(nn.Module): def __init__(self, x_shape, prior=args.prior): super().__init__() self.x_shape = x_shape self.z_dim = args.z_dim self.z_shape = get_shape(self.z_dim) self.p_z = globals()[prior](self.z_shape) self.q_z = q_z(self.z_shape, self.x_shape) sel...
_registry(pattern_type='QuantizeFusion') class QuantizeFusion(Pattern): def __call__(self, model): def search_quant_fusion(node): if (node.input_tensors[0].source_op == []): return (None, False) pre_node = model.get_node_by_name(node.input_tensors[0].source_op[0]) ...
class FactorGNNSBMs(nn.Module): def __init__(self, g, num_layers, in_dim, num_hidden, num_latent, feat_drop, residual, n_cls=2): super(FactorGNNSBMs, self).__init__() self.g = g self.layers = nn.ModuleList() self.BNs = nn.ModuleList() self.feat_drop = feat_drop self.a...
class CPUinfo(): def __init__(self): self.cores = 0 self.sockets = 0 self.cpuinfo = [] if (platform.system() == 'Windows'): raise RuntimeError('Windows platform is not supported!!!') elif (platform.system() == 'Linux'): args = ['lscpu'] lsc...
def partition_data(datadir, partition, n_nets, alpha, logger): logger.info('partition data') (X_train, y_train, X_test, y_test) = load_cifar10_data(datadir) n_train = X_train.shape[0] if (partition == 'homo'): total_num = n_train idxs = np.random.permutation(total_num) batch_idxs...
def reduce_loss(loss, reduction): reduction_enum = F._Reduction.get_enum(reduction) if (reduction_enum == 0): return loss elif (reduction_enum == 1): return loss.mean() elif (reduction_enum == 2): return loss.sum()
def process_triples(mtriples): nodes = [] for m in mtriples: ms = m.firstChild.nodeValue ms = ms.strip().split(' | ') n1 = ms[0] n2 = ms[2] nodes1 = get_nodes(n1) nodes2 = get_nodes(n2) edge = get_relation(ms[1]) edge_split = camel_case_split(edge)...
class Pandaset(BaseDataset): def __init__(self, dataset_path, name='Pandaset', cache_dir='./logs/cache', use_cache=False, ignored_label_inds=[], test_result_folder='./logs/test_log', test_split=['115', '116', '117', '119', '120', '124', '139', '149', '158'], training_split=['001', '002', '003', '005', '011', '013',...
class ProjectWidget(): def __init__(self, viz): self.viz = viz self.search_dirs = [] self.project_path = '' self.browse_cache = dict() self.browse_refocus = False self.P = None self.slide_paths = [] self.model_paths = [] self.slide_idx = 0 ...
def test_simple_creation() -> None: tensor = tf.constant(np.random.rand(3, 2, 3)) box_tensor = TFSigmoidBoxTensor(tensor) assert (tensor.numpy() == box_tensor.data.numpy()).all() assert isinstance(box_tensor, TFBoxTensor) tensor = tf.constant(np.random.rand(2, 10)) box_tensor = TFSigmoidBoxTenso...
def read_results(filename, data_type: str, is_gt=False, is_ignore=False): if (data_type in ('mot', 'lab')): read_fun = read_mot_results else: raise ValueError('Unknown data type: {}'.format(data_type)) return read_fun(filename, is_gt, is_ignore)
def interpolation_str2int(interpolation): if isinstance(interpolation, (list, tuple)): return [interpolation_str2int(i) for i in interpolation] if (interpolation == 'cubic'): return cv2.INTER_CUBIC elif (interpolation == 'linear'): return cv2.INTER_LINEAR elif (interpolation == '...
class TFCTRLModelTester(object): def __init__(self, parent): self.parent = parent self.batch_size = 13 self.seq_length = 7 self.is_training = True self.use_token_type_ids = True self.use_input_mask = True self.use_labels = True self.use_mc_token_ids = ...
class cassieRLEnvStepInPlace(cassieRLEnvDelay): def __init__(self): self.sim = CassieSim() self.vis = CassieVis() self.observation_space = np.zeros(80) self.action_space = np.zeros(10) with open('step_in_place_trajectory', 'rb') as fp: self.trajectory = pickle.loa...
.parametrize('with_attention', [True, False]) .parametrize('quantization_setup', [{'numeric2': [0.0, 50.0, 100.0]}, None]) def test_chunk_tab_preprocessor_with_params(with_attention, quantization_setup): df = pd.read_csv(os.path.join(data_folder, fname)) tab_processor = TabPreprocessor(cat_embed_cols=cat_cols, ...
_grad() def validation_one_epoch(data_loader, model, device): criterion = torch.nn.CrossEntropyLoss() metric_logger = utils.MetricLogger(delimiter=' ') header = 'Val:' model.eval() for batch in metric_logger.log_every(data_loader, 10, header): images = batch[0] target = batch[1] ...
class Renderer(object): def ax_zoomable(ax): return bool((ax and ax.get_navigate())) def ax_has_xgrid(ax): return bool((ax and ax.xaxis._gridOnMajor and ax.yaxis.get_gridlines())) def ax_has_ygrid(ax): return bool((ax and ax.yaxis._gridOnMajor and ax.yaxis.get_gridlines())) def c...
def postprocess_results(dataset: TextToSpeechDataset, sample, hypos, resample_fn, dump_target): def to_np(x): return (None if (x is None) else x.detach().cpu().numpy()) sample_ids = [dataset.ids[i] for i in sample['id'].tolist()] texts = (sample['src_texts'] if ('src_texts' in sample) else ([''] * l...
class AstronomicalObject(): def __init__(self, **kwargs): self.dec = kwargs.get('dec') if (self.dec is None): raise AstronomicalObjectError("Error constructing AstronomicalObject. Missing variable 'dec'") self.los_id = kwargs.get('los_id') if (self.los_id is None): ...
def encode_image(model, processor, image_url: str, device='cpu'): import requests from io import BytesIO import torch from PIL import Image response = requests.get(image_url) image = Image.open(BytesIO(response.content)) with torch.no_grad(): photo_preprocessed = processor(text=None,...
def camel_case_split(identifier): matches = re.finditer('.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)', identifier) d = [m.group(0) for m in matches] new_d = [] for token in d: token = token.replace('(', '') token_split = token.split('_') for t in token_split: ...
def drop_blocks(drop_block_rate=0.0): return [None, None, (DropBlock2d(drop_block_rate, 5, 0.25) if drop_block_rate else None), (DropBlock2d(drop_block_rate, 3, 1.0) if drop_block_rate else None)]
class Av2DataModule(LightningDataModule): def __init__(self, data_root: str, data_folder: str, train_batch_size: int=32, val_batch_size: int=32, test_batch_size: int=32, shuffle: bool=True, num_workers: int=8, pin_memory: bool=True, test: bool=False): super(Av2DataModule, self).__init__() self.data_...
def check_Xs(Xs, multiview=False, enforce_views=None, copy=False, return_dimensions=False): if (not isinstance(Xs, list)): if (not isinstance(Xs, np.ndarray)): msg = f'If not list, input must be of type np.ndarray, not {type(Xs)}' raise ValueError(msg) if (Xs.n...
class SudokuStateManager(StateManagerBase): def __init__(self) -> None: super().__init__() self.sudoku_matrix_history = [] def update_state(self, solution) -> bool: solution_key = json.dumps(solution.tolist()) for state in self.sudoku_matrix_history: state_key = json....
def load_json_config(path): with open(path) as data_file: config = json.load(data_file) config = config_init(config) return config
def main(): device = 'cuda:3' torch.random.manual_seed(42) model = NoiseNet(is_train=True).to(device) model.apply(functools.partial(weights_init_kaiming, scale=0.001)) data_set = GenImageDataset('data_new/train/clean', phase='train', crop_size=128) train_loader = torch.utils.data.DataLoader(data...
def create_tfkeras_pruning_callback(*args, **kwargs): from bigdl.nano.deps.automl.hpo_api import create_optuna_tfkeras_pruning_callback return create_optuna_tfkeras_pruning_callback(*args, **kwargs)
def dlib_and_3DDFA(dlib_landmark_model='shape_predictor_68_face_landmarks.dat', checkpoint_fp='phase1_wpdc_vdc.pth.tar', arch='mobilenet_1'): face_regressor = dlib.shape_predictor(dlib_landmark_model) face_detector = dlib.get_frontal_face_detector() checkpoint = torch.load(checkpoint_fp, map_location=(lambd...
class YolosOnnxConfig(OnnxConfig): torch_onnx_minimum_version = version.parse('1.11') def inputs(self) -> Mapping[(str, Mapping[(int, str)])]: return OrderedDict([('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'})]) def atol_for_validation(self) -> float: return 0.000...
class TestFrozenPbModel(unittest.TestCase): def setUp(self) -> None: super().setUp() get_model_type_patcher = patch('neural_insights.components.model.model_type_getter.nc_get_model_type') self.addCleanup(get_model_type_patcher.stop) get_model_type_mock = get_model_type_patcher.start(...
class EvalHook(Hook): def __init__(self, dataloader, interval=1, by_epoch=False, **eval_kwargs): if (not isinstance(dataloader, DataLoader)): raise TypeError(f'dataloader must be a pytorch DataLoader, but got {type(dataloader)}') self.dataloader = dataloader self.interval = inter...
class TensorBoardOutput(LogOutput): def __init__(self, log_dir, x_axis=None, additional_x_axes=None, flush_secs=120, histogram_samples=1000.0): if (x_axis is None): assert (not additional_x_axes), 'You have to specify an x_axis if you want additional axes.' additional_x_axes = (additiona...
_model def tf_efficientnetv2_b0(pretrained=False, **kwargs): kwargs['bn_eps'] = BN_EPS_TF_DEFAULT kwargs['pad_type'] = 'same' model = _gen_efficientnetv2_base('tf_efficientnetv2_b0', pretrained=pretrained, **kwargs) return model
class ActNormScale(nn.Module): def __init__(self, num_channels): super().__init__() self.register_parameter('log_scale', torch.nn.Parameter(torch.zeros([1, num_channels, 1, 1]))) self.initialized = False def scale(self): return torch.exp(self.log_scale) def forward(self, x): ...
class TokenAttention(nn.Module): def __init__(self, encoding_size, query_dims=0, condition_attention=False, tokenwise_attention=False): super(TokenAttention, self).__init__() self.condition_attention = condition_attention if condition_attention: self.attn_MLP_hidden_dims = 32 ...
def score_classifications(instances: List[dict], annotations: List[Annotation], docs: Dict[(str, List[str])], aopc_thresholds: List[float]) -> Dict[(str, float)]: def compute_kl(cls_scores_, faith_scores_): keys = list(cls_scores_.keys()) cls_scores_ = [cls_scores_[k] for k in keys] faith_sc...
def get_vgg(blocks, bias=True, use_bn=False, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs): if (blocks == 11): layers = [1, 1, 2, 2, 2] elif (blocks == 13): layers = [2, 2, 2, 2, 2] elif (blocks == 16): layers = [2, 2, 3, 3, 3] elif (blo...
def parse_args(): parser = argparse.ArgumentParser(description='Train a segmentor') parser.add_argument('config', help='train config file path') parser.add_argument('--work-dir', help='the dir to save logs and models') parser.add_argument('--load-from', help='the checkpoint file to load weights from') ...
def register_criterion(name): def register(criterion): CRITERIA[name] = criterion return criterion return register
def add_token(tokenizer, object, current_token, word_vector, glove): tokenizer['vocab2token'][object] = current_token tokenizer['token2vocab'][current_token] = object current_token += 1 if (object == '"walk"'): object = 'walk' try: word_vector.append(glove[object.lower()]) except...
class DentexChallenge(): def __init__(self, categories, prediction_file, gt_file, output_file='/output/metrics.json'): self.categories = categories self.prediction_file = prediction_file self.gt_file = gt_file self.output_file = output_file self._case_results = {} sel...
class BlenderbotSmallForConditionalGeneration(metaclass=DummyObject): _backends = ['torch'] def __init__(self, *args, **kwargs): requires_backends(self, ['torch'])
class AbstractMazeWalk(physics.AbstractForce, metaclass=abc.ABCMeta): def __init__(self, speed, maze_layer='walls'): self._speed = speed self._maze_layer = maze_layer def reset(self, state): self._maze = maze_lib.Maze.from_state(state, maze_layer=self._maze_layer) def step(self, *spr...
def main(): np.random.seed(SEED) run_kfold(data_fn=FLAGS.data_fn, method=FLAGS.method, prop_missing=FLAGS.prop_missing, max_num_feature=FLAGS.max_num_feature, feature_selection=FLAGS.feature_selection, which_half=FLAGS.which_half, data_dir=FLAGS.data_dir, cache_dir=FLAGS.cache_dir, out_dir=FLAGS.out_dir)
_on_pypy def test_to_python(): mat = m.Matrix(5, 5) assert (memoryview(mat).shape == (5, 5)) assert (mat[(2, 3)] == 0) mat[(2, 3)] = 4 assert (mat[(2, 3)] == 4) mat2 = np.array(mat, copy=False) assert (mat2.shape == (5, 5)) assert (abs(mat2).sum() == 4) assert (mat2[(2, 3)] == 4) ...
def verify_metadata(metadata, has_bounding_box): index_has_bounding_box = all([(MetadataKW.BOUNDING_BOX in metadata[MetadataKW.INPUT_METADATA][i]) for i in range(len(metadata[MetadataKW.INPUT_METADATA]))]) for gt_metadata in metadata[MetadataKW.GT_METADATA]: if (gt_metadata is not None): ind...
class PopularNegativeSampler(AbstractNegativeSampler): def code(cls): return 'popular' def generate_negative_samples(self): popular_items = self.items_by_popularity() negative_samples = {} print('Sampling negative items') for user in trange(self.user_count): s...
class Solver(): def __init__(self, model, modelDir, loadWeights, optimizer, criterions, iouThreshold): self.model = model self.optimizer = optimizer self.device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu')) self.modelDir = modelDir if loadWeights: ...
class MoleculeModel(nn.Module): def __init__(self, args: TrainArgs, featurizer: bool=False): super(MoleculeModel, self).__init__() self.args = args self.classification = (args.dataset_type == 'classification') self.multiclass = (args.dataset_type == 'multiclass') self.featuri...
_optimizer('adadelta') class Adadelta(FairseqOptimizer): def __init__(self, args, params): super().__init__(args) self._optimizer = torch.optim.Adadelta(params, **self.optimizer_config) def add_args(parser): parser.add_argument('--adadelta-rho', type=float, default=0.9, metavar='RHO', he...
def require_torch_or_tf(test_case): return unittest.skipUnless((is_torch_available() or is_tf_available()), 'test requires PyTorch or TensorFlow')(test_case)
def paser_cfgs(cfgs): ops_name = [] layer_output_infos_ids = [] op_infos_from_cfgs = {} input_tensor_ids_op_name = {} output_tensor_ids_op_name = {} for module_key in cfgs.keys(): for state in cfgs[module_key]: if (state == 'layer_output_infos'): for (index, o...
class ByoModelCfg(): blocks: Tuple[(Union[(ByoBlockCfg, Tuple[(ByoBlockCfg, ...)])], ...)] downsample: str = 'conv1x1' stem_type: str = '3x3' stem_pool: Optional[str] = 'maxpool' stem_chs: int = 32 width_factor: float = 1.0 num_features: int = 0 zero_init_last: bool = True fixed_inpu...
_config def il_blind(): cfg = {} cfg['learner'] = {'model_kwargs': {'base_kwargs': {'perception_unit_kwargs': {'extra_kwargs': {'main_perception_network': 'TaskonomyFeaturesOnlyNet', 'sidetune_kwargs': {'base_class': None, 'base_weights_path': None, 'base_kwargs': {}, 'side_class': None, 'side_weights_path': No...
class TextDocumentItem(TypedDict): uri: DocumentUri languageId: string version: integer text: string
def output_combined_files(path, dataset_name, output_files_dict, category_names, write): categorized_train_val_test_filenames = {category_name: [[], [], []] for category_name in category_names} for (dir_name, category_dict) in output_files_dict.items(): for (category_name, paths) in category_dict.items(...
def _check_and_coerce_cfg_value_type(replacement, original, key, full_key): original_type = type(original) replacement_type = type(replacement) if (replacement_type == original_type): return replacement def conditional_cast(from_type, to_type): if ((replacement_type == from_type) and (or...
_materialize('core') class CastF32(Cast): out_dtypes = [(DType.float32,)] def __init__(self): super().__init__(DType.float32)
def create_lmsm_solver(outfname, net_name, max_iter=10000, lr=0.1, weight_decay=0.0005, snapshot_dir='snapshots', solver_mode='GPU'): txt = open('model/cifar_solver.prototxt', 'r').read() txt = txt.replace('_NET_NAME_', net_name) txt = txt.replace('_MAX_ITER_', str(max_iter)) txt = txt.replace('_LR_', s...
class WeightedTreeLSTMLayer(object): def __init__(self, model, dim, W, Wf, Uf, dropout, dropout_mask_x, dropout_mask_h, path_dropout, device, init_to_zero=False): self.model = model self.device = device self.dim = dim self.W = dynet.parameter(W) self.Wf = dynet.parameter(Wf) ...
_model def dla46_c(pretrained=None, num_classes=1000, in_chans=3, **kwargs): default_cfg = default_cfgs['dla46_c'] model = DLA(levels=[1, 1, 1, 2, 2, 1], channels=[16, 32, 64, 64, 128, 256], block=DlaBottleneck, num_classes=num_classes, in_chans=in_chans, **kwargs) model.default_cfg = default_cfg if pre...
class HardtanhActivationMixin(): def init_activation(self, upperbound=1.0, eps=1e-08, **kwargs): self._activation_func = nn.Hardtanh(0, upperbound) self.upperbound = torch.tensor(upperbound) self.eps = eps self.activation_func = (lambda x: (self._activation_func(x) + eps)) se...