code
stringlengths
17
6.64M
def special_traverse_model(module: nn.Module, depth: int, prefix: Optional[str]=None, basic_blocks: Tuple[Type[nn.Module]]=(), special_blocks: Tuple[Type[nn.Module]]=(), next_special_bb_id=None, full: bool=False, mark=False) -> Iterator[Tuple[(nn.Module, str, nn.Module, Optional[bool], Optional[int])]]: '\n it...
def traverse_params_buffs(module: nn.Module, prefix: Optional[str]=None) -> Iterator[Tuple[(torch.tensor, str)]]: "\n iterate over model's buffers and parameters yielding obj,obj_scope\n\n Parameters:\n -----------\n model:\n the model to iterate over\n " if (prefix is None): pre...
def layerDict(model: nn.Module, depth=1000, basic_blocks=()) -> Dict[(str, nn.Module)]: return {s: l for (l, s, _) in traverse_model(model, depth, basic_blocks=basic_blocks)}
def tensorDict(model: nn.Module) -> OrderedDict[(str, Tensor)]: return collections.OrderedDict(((s, t) for (t, s) in traverse_params_buffs(model)))
def nested_map(func, ts, full=False): if isinstance(ts, torch.Size): return func(ts) elif isinstance(ts, (list, tuple, set)): return type(ts)((nested_map(func, t, full=full) for t in ts)) elif isinstance(ts, dict): return {k: nested_map(func, v, full=full) for (k, v) in ts.items()}...
def flatten(ts): if isinstance(ts, torch.Size): (yield ts) elif isinstance(ts, (list, tuple, set)): (yield from chain(*[flatten(t) for t in ts])) elif isinstance(ts, dict): (yield from chain(*[flatten(t) for (k, t) in sorted(ts.items(), key=(lambda t: t[0]))])) else: (y...
def unflatten(xs, structure): return _unflatten(xs, structure)[0]
def _unflatten(xs, structure): if isinstance(structure, torch.Size): return (xs[0], 1) if (not isinstance(structure, (list, tuple, set, dict))): return (xs[0], 1) if isinstance(structure, (list, tuple, set)): offset = 0 elements = [] for s in structure: ...
def detach_tensors(ts): def detach_if_tensor(t): if isinstance(t, Tensor): return t.detach().requires_grad_(t.requires_grad) return t return nested_map(detach_if_tensor, ts)
def move_tensors(ts, device): def move(t): if isinstance(t, (nn.Module, Tensor)): return t.to(device) return t return nested_map(move, ts)
def set_grad_mode(ts, require_grad): def grad_mode(t): if isinstance(t, Tensor): return t.detach().requires_grad_((isinstance(t, nn.Parameter) or (require_grad and t.is_floating_point()))) return t return nested_map(grad_mode, ts)
def get_tensor_dtypes(ts): def get_dtype(t): if isinstance(t, Tensor): return t.dtype return type(t) return nested_map(get_dtype, ts)
def get_tensor_shapes(ts): def get_shape(t): if isinstance(t, Tensor): return (t.shape if t.shape else torch.Size([1])) elif isinstance(t, torch.Size): return torch.Size([len(t)]) return None return nested_map(get_shape, ts)
def get_device(ts) -> torch.device: for t in flatten(ts): if isinstance(t, Tensor): return t.device return torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
@contextmanager def force_out_of_place(func): prev_state = None modified = False if (hasattr(func, 'inplace') and isinstance(func.inplace, bool)): prev_state = func.inplace modified = True setattr(func, 'inplace', False) (yield) if modified: setattr(func, 'inplace',...
def get_call_site(*ignored_files) -> Optional[str]: ignored_files = ((__file__,) + ignored_files) curdir = os.path.dirname(os.path.realpath(__file__)) for f in inspect.stack(): frameinfo = inspect.getframeinfo(f[0]) file_name = frameinfo.filename if ((file_name not in ignored_files...
def convert_none_checks(input_file: str, output_file: str): 'utility to convert None checks which are unsupported by the traced to\n a convention we support\n\n we match patters like:\n if identifier is None => if is_None(identified)\n if identified is not None => if is_not_None(identifie...
class Parser(argparse.ArgumentParser, ABC): 'ArgumentParser for partitioning tasks,\n excluding tasks specific args (i.e model and data)\n ' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) model_args = self.add_argument_group('model_args') self._add_mo...
def download_and_extract(task, data_dir): print(('Downloading and extracting %s...' % task)) data_file = ('%s.zip' % task) urllib.request.urlretrieve(TASK2PATH[task], data_file) with zipfile.ZipFile(data_file) as zip_ref: zip_ref.extractall(data_dir) os.remove(data_file) print('\tCompl...
def format_mrpc(data_dir, path_to_data): print('Processing MRPC...') mrpc_dir = os.path.join(data_dir, 'MRPC') if (not os.path.isdir(mrpc_dir)): os.mkdir(mrpc_dir) if path_to_data: mrpc_train_file = os.path.join(path_to_data, 'msr_paraphrase_train.txt') mrpc_test_file = os.path...
def download_diagnostic(data_dir): print('Downloading and extracting diagnostic...') if (not os.path.isdir(os.path.join(data_dir, 'diagnostic'))): os.mkdir(os.path.join(data_dir, 'diagnostic')) data_file = os.path.join(data_dir, 'diagnostic', 'diagnostic.tsv') urllib.request.urlretrieve(TASK2P...
def get_tasks(task_names): task_names = task_names.split(',') if ('all' in task_names): tasks = TASKS else: tasks = [] for task_name in task_names: assert (task_name in TASKS), ('Task %s not found!' % task_name) tasks.append(task_name) return tasks
def main(arguments): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', help='directory to save data to', type=str, default='glue_data') parser.add_argument('--tasks', help='tasks to download data for as a comma separated string', type=str, default='all') parser.add_argument('--path_...
def download_file(url, DATA_DIR=''): local_filename = url.split('/')[(- 1)] local_filename = os.path.join(DATA_DIR, local_filename) if os.path.exists(local_filename): print(f'-I- file {local_filename} already exists, skipping download.') return local_filename with requests.get(url, str...
def download_wiki2(DATA_DIR=''): URL = 'https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip' path_to_zip_file = download_file(URL) print(f'-I- Donwloaded wikitext2 to {path_to_zip_file}. Extracting...') with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref: zip_ref.ex...
def download_wiki103(DATA_DIR=''): URL = 'https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-103-raw-v1.zip' path_to_zip_file = download_file(URL) print(f'-I- Donwloaded wikitext103 to {path_to_zip_file}. Extracting...') with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref: zip_...
def get_df(L_to_minmax, L_to_num_stages, L_to_best_objective): def list_keys(x): return list(x.keys()) assert (list_keys(L_to_num_stages) == list_keys(L_to_best_objective) == list_keys(L_to_minmax)) records = [dict(L=L, stages=stages, objective=objective) for (L, stages, objective) in zip(L_to_nu...
def plot_L_to_objective(df): sns.barplot(x='L', y='objective', data=df)
def t5_3b(): L_to_minmax = {8: 6636137.099132873, 16: 5638619.469868817, 24: 4589449.469869904, 32: 4287169.033868238, 40: 4103992.787624088, 48: 4155925.9036572957, 56: 4201891.442869065, 64: 4098424.4248143705} L_to_num_stages = {8: 8, 16: 15, 24: 23, 32: 31, 40: 35, 48: 45, 56: 46, 64: 61} L_to_best_ob...
def t5_base(): L_to_minmax = {8: 1134675.3105777686, 16: 849120.8780806304, 24: 941463.7233041492, 32: 804757.1768176018, 40: 805675.4889778851, 48: 774942.1858372729, 56: 789406.8785677295, 64: 766349.086868281} L_to_num_stages = {8: 8, 16: 15, 24: 23, 32: 27, 40: 33, 48: 45, 56: 48, 64: 60} L_to_best_ob...
def parse_cli() -> Tuple[(Namespace, Dict, PartitioningTask)]: task_parser = argparse.ArgumentParser(description='partitioning task parser', add_help=False) task_parser.add_argument('partitioning_task', help='partitioning task to perform') (task, rest) = task_parser.parse_known_args() (parser_cls, par...
def main(cmd_args: Namespace, model_args: Dict, partitioner: PartitioningTask, override_dict: Optional[Dict]=None): for (i, v) in override_dict.items(): if (i in model_args): raise ValueError(f'''override dict should not modify model creation arguments got {i} the intended use is for modifying...
def choose_blocks(model, args, blocks_arg_name='basic_blocks') -> Tuple[torch.nn.Module]: blocks = dict() for m in model.modules(): m_superclasses = {c.__name__: c for c in type(m).mro()} blocks.update(m_superclasses) blocks: Dict[(str, torch.nn.Module)] if (getattr(args, blocks_arg_na...
def record_cmdline(output_file): 'Add cmdline to generated python output file.' cmdline = ' '.join(map(shlex.quote, sys.argv[1:])) python_output_file = (output_file + '.py') cmdline = ((((('"""' + 'AutoGenerated with:\n') + 'python -m autopipe.partition ') + cmdline) + '\n') + '"""') if (sys.platf...
def record_transformer_cfg(python_output_file, args, model_type, explicitly_set_dict=dict(), do_resize_token_embedding=False): t = Template("\n\ndef ${function_name}():\n return dict(model_type='${model_type}',\n model_name_or_path='${model_name_or_path}',\n do_lower_case=${do_low...
def bruteforce_main(main, main_kwargs=None, override_dicts=None, NUM_RUNS=2, TMP='/tmp/partitioning_outputs/', remove_tmp=False): if (main_kwargs is None): main_kwargs = dict() results = {} best = None if (override_dicts is None): override_dicts = [] if (not override_dicts): ...
def register_task(task_name, parser_cls: Type[Parser], partitioner_cls: Type[PartitioningTask]): if (not isinstance(task_name, str)): raise ValueError(f'task name must be a string got {task_name} of type {type(task_name).__name__}') elif (task_name in REGISTRY): raise ValueError(f'task {task_n...
def get_parser_and_partitioner(task_name) -> Tuple[(Type[Parser], Type[PartitioningTask])]: if (task_name in REGISTRY): return REGISTRY[task_name] else: raise ValueError(f'unknown task {task_name} available tasks {list(REGISTRY.keys())}')
def import_tasks_from_dir(tasks_dir=os.path.dirname(__file__)): ' Automatically import any Python files in the tasks directory\n in order to automatically register all available tasks\n Args:\n tasks_dir: task dir to import from\n ' for file in os.listdir(tasks_dir): path = os.path...
def load_and_cache_examples(args, tokenizer): input_dir = (args.data_dir if args.data_dir else '.') cached_features_file = os.path.join(input_dir, 'cached_{}_{}_{}'.format('train', list(filter(None, args.model_name_or_path.split('/'))).pop(), str(args.max_seq_length))) if (os.path.exists(cached_features_f...
class ParsePartitioningOptsSquad(Parser): def _add_model_args(self, group): group.add_argument('--model_name_or_path', default=None, type=str, required=True, help='Path to pre-trained model or shortcut name in huggingface/models') group.add_argument('--precompute_attention_mask', action='store_tr...
class BertPartitioner(PartitioningTask): def __init__(self, args) -> None: super().__init__(args) self.tokenizer = BertTokenizer.from_pretrained(args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=(args.cache_dir if args.cache_dir else None)) @property def batch_dim(self...
def get_inputs_squad(args, tokenizer, analysis=False): batch_size = (args.analysis_batch_size if analysis else args.partitioning_batch_size) train_dataset = load_and_cache_examples(args, tokenizer) train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader(train_dataset, sampler=train_...
class CEPParser(Parser): def _add_model_args(self, group): group.add_argument('--N', type=int, default=361) group.add_argument('--C', type=int, default=10000) def _add_data_args(self, group): group.add_argument('--K', type=int, default=18) group.add_argument('--samples_num', ...
class CEPPartitioningTask(PartitioningTask): def __init__(self, args) -> None: super().__init__(args) @property def batch_dim(self) -> int: return 0 def register_functions(self): pass def get_model(self, args) -> torch.nn.Module: return Net(n=args.N, c=args.C) ...
class DumT5Partitioner(T5Partitioner): def get_model(self, args) -> torch.nn.Module: explicitly_set_dict = {'return_dict': False, 'use_cache': False, 'output_attentions': False, 'output_hidden_states': False, 'output_only': True, 'precomputed_masks': args.precompute_masks} config_class = T5Config...
class FunctionalModel(torch.nn.Module): def __init__(self): super(FunctionalModel, self).__init__() self.w1 = torch.nn.Parameter(torch.randn(_MODEL_DIM, _MODEL_DIM)) self.w2 = torch.nn.Parameter(torch.randn(_MODEL_DIM, _MODEL_DIM)) self.w3 = torch.nn.Parameter(torch.randn(_MODEL_D...
class DumTFunctionalModelPartitioner(T5Partitioner): def get_model(self, args) -> torch.nn.Module: return FunctionalModel() def get_input(self, args, analysis=False): if analysis: return torch.randn(args.analysis_batch_size, _MODEL_DIM) return torch.randn(args.partitionin...
def make_just_x(ds): d = defaultdict(list) for feature in ds: for (key, val) in vars(feature).items(): if (key == 'label'): continue if (val is None): continue d[key].append(val) print(d.keys()) return TensorDataset(*[torch.te...
def get_dataset(args, tokenizer, cache_name='glue_ds.pt'): cache_name += args.model_name_or_path if (os.path.exists(cache_name) and (not args.overwrite_cache)): print(f'-I- loading dataset from cahce {cache_name}...') flag = False try: ds = torch.load(cache_name) ...
def get_sample(args, tokenizer, analysis=False): train_dataset = get_dataset(args, tokenizer) train_sampler = RandomSampler(train_dataset) train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=(args.analysis_batch_size if analysis else args.partitioning_batch_size)) batch = ne...
class ParsePartitioningOptsGlue(Parser): def _add_model_args(self, group): group.add_argument('--task_name', type=str, default='mnli', help='Glue task') group.add_argument('--model_type', default=None, type=str, required=True, help=('Model type selected in the list: ' + ', '.join(MODEL_TYPES))) ...
class GluePartitioner(PartitioningTask): def __init__(self, args) -> None: super().__init__(args) self.tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=(args.cache_dir if args.cache_dir else None)) @property def batch_dim(self...
class TextDataset(Dataset): def __init__(self, tokenizer, args, file_path='train', block_size=512): assert os.path.isfile(file_path), file_path (directory, filename) = os.path.split(file_path) cached_features_file = os.path.join(directory, ((((args.model_name_or_path + '_cached_lm_') + st...
def load_and_cache_examples(args, tokenizer): return TextDataset(tokenizer, args, file_path=args.train_data_file, block_size=args.block_size)
class ParsePartitioningOptsLM(Parser): def _add_model_args(self, group): group.add_argument('--model_name_or_path', default='gpt2', type=str, help='The model checkpoint for weights initialization.') group.add_argument('--lmhead', default=False, action='store_true', help='Partition a model with LM...
class GPT2Partitioner(PartitioningTask): def __init__(self, args) -> None: super().__init__(args) self.tokenizer = GPT2Tokenizer.from_pretrained(args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=(args.cache_dir if args.cache_dir else None)) if (args.block_size <= 0): ...
class MegatronParser(Parser): def __init__(self) -> None: if (not has_fairseq): raise ImportError('\n\nPlease install fairseq_for_pipeline:') super().__init__() def _auto_file_name(self, args) -> str: bw_str = str(args.bw).replace('.', '_') model_str = str(args.ar...
class MegatronPartitioner(PartitioningTask): def __init__(self, args): super().__init__(args) if (not has_fairseq): raise ImportError('\n\nPlease install fairseq_for_pipeline:') distributed_utils.infer_init_method(args, force_distributed=True) args.device_id = 0 ...
class PartitioningTask(ABC): def __init__(self, args) -> None: pass @property @abstractmethod def batch_dim(self) -> int: pass @abstractmethod def get_model(self, args) -> torch.nn.Module: pass @abstractmethod def get_input(self, args, analysis=False): ...
class GetConfigFrom(Enum): HardCoded = auto() ParsedArgs = auto() Generated = auto()
def resize_token_embeddings(model, tokenizer): model_to_resize = (model.module if hasattr(model, 'module') else model) model_to_resize.resize_token_embeddings(len(tokenizer))
def pretrained_model_config_and_tokenizer(config_class, model_class, tokenizer_class, model_name_or_path: str, config_name: str='', tokenizer_name: str='', do_lower_case: bool=False, cache_dir: str='', stateless_tied=False, do_resize_token_embedding=True, explicitly_set_dict={}, **config_kw): config = config_clas...
def _register_model(dict_params, model_cls): global MODEL_CFG_TO_SAMPLE_MODEL global MODEL_CONFIGS MODEL_CONFIGS.update(dict_params) MODEL_CFG_TO_SAMPLE_MODEL.update({k: model_cls for k in dict_params.keys()})
class ParsePartitioningOptsVision(Parser): def _add_model_args(self, group): group.add_argument('--model', choices=MODEL_CONFIGS.keys(), default='wrn_16x4') def _add_data_args(self, group): group.add_argument('--crop', type=int, default=32, help='crop size to use. (e.g: 32 for cifar, 224 for...
class VisionPartioner(PartitioningTask): def get_model(self, args) -> torch.nn.Module: return MODEL_CFG_TO_SAMPLE_MODEL[args.model](**MODEL_CONFIGS[args.model]).train() @property def batch_dim(self) -> int: return 0 def get_input(self, args, analysis=False): if analysis: ...
def tmpt5_base_tied_lmheads_512_4_4p_bw12_squad1_mpipe(): return dict(model_type='new_t5_stateless', model_name_or_path='t5-base', do_lower_case=False, output_past=False, output_attentions=False, output_hidden_states=False, do_resize_token_embedding=True, explicitly_set_dict={'return_dict': False, 'use_cache': Fa...
class NewT5HFLoader(HFLoader): def __init__(self, hf_transformers_model_class=T5ForConditionalGeneration): super().__init__(hf_transformers_model_class=hf_transformers_model_class) def substitue_state_dict_keys_back_to_original(self, training_state_dict): d = dict() for (k, v) in tra...
class T5Stack(T5PreTrainedModel): def __init__(self, config, embed_tokens=None): super().__init__(config) self.embed_tokens = embed_tokens self.is_decoder = config.is_decoder self.precomputed_masks = config.precomputed_masks for i in range(config.num_layers): s...
@add_start_docstrings('The bare T5 Model transformer outputting raw hidden-stateswithout any specific head on top.', T5_START_DOCSTRING) class T5Model(T5PreTrainedModel): def __init__(self, config): super().__init__(config) self.shared = nn.Embedding(config.vocab_size, config.d_model) enc...
@add_start_docstrings('T5 Model with a `language modeling` head on top. ', T5_START_DOCSTRING) class T5ForConditionalGeneration(T5PreTrainedModel): def __init__(self, config): super().__init__(config) self.model_dim = config.d_model self.shared = nn.Embedding(config.vocab_size, config.d_m...
def copy_attrs(me, other, attr_names: List[str]): for name in attr_names: setattr(me, name, getattr(other, name))
class StatelessEmbedding(nn.Module): __constants__ = ['num_embeddings', 'embedding_dim', 'padding_idx', 'max_norm', 'norm_type', 'scale_grad_by_freq', 'sparse'] def __init__(self, other: nn.Embedding): super().__init__() self.num_embeddings = other.num_embeddings self.embedding_dim = ...
class StatelessLinear(nn.Module): ' Stateless Linear layer with shared weight.\n bias is not shared\n ' __constants__ = ['bias', 'in_features', 'out_features'] def __init__(self, other: nn.Linear): super().__init__() self.in_features = other.in_features self.out_features...
class StatelessSequential(nn.Sequential): 'Sequential model where first and last layers are tied.\n NOTE: it can be generalized to a model where more layers are tied\n ' def __init__(self, *args): if ((len(args) == 1) and isinstance(args[0], OrderedDict)): raise NotImplementedEr...
class CompositionStatelessSequential(nn.Module): def __init__(self, *args): super().__init__() stateless_seq = StatelessSequential(*args) self.tied_w = nn.Parameter(stateless_seq.pop_weight()) self.stateless_seq = stateless_seq def forward(self, *args, **kw): return s...
class PreTrainedModel(TransformersPretrainedModel): KEY_TRANSLATION = None @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): "Instantiate a pretrained pytorch model from a pre-trained model configuration.\n\n The model is set in evaluation mode by...
class Dataset(torch.utils.data.Dataset): def __init__(self, n, k, max_samples_num, just=None): self.just = just self.samples_num = int(max_samples_num) self.n = n self.node_list = list(range(n)) self.k = k self.edge_dict = {} (A, B) = np.tril_indices(n, k=(...
class Net(nn.Module): def __init__(self, n, c, n_split=4): super(Net, self).__init__() dim_1 = (2 + (((3 * n) * (n - 1)) // 4)) if ((dim_1 % n_split) != 0): warnings.warn('changed dim_1') dim_1 -= (dim_1 % n_split) self.input_layer = SplitLinear(nn.Linear((...
class NetWithoutSplit(nn.Module): def __init__(self, n, c): super(NetWithoutSplit, self).__init__() self.input_layer = nn.Linear(((n * (n - 1)) // 2), (((3 * n) * (n - 1)) // 4)) self.bn1 = nn.BatchNorm1d((((3 * n) * (n - 1)) // 4)) self.h1_layer = nn.Linear((((3 * n) * (n - 1)) /...
class Dummy(nn.Module): def __init__(self): super(Dummy, self).__init__() self.l0 = nn.Linear(100, 100) self.l1 = nn.Linear(100, 100) self.l2 = nn.Linear(100, 100) self.l3 = nn.Linear(100, 100) def forward(self, x): output2 = self.l0(x) t0 = self.l1(x)...
class Stage0(nn.Module): def __init__(self, layers, tensors): super(Stage0, self).__init__() assert ('Dummy/Linear[l0]' in layers) self.l = layers['Dummy/Linear[l0]'] assert isinstance(self.l, nn.Linear) def forward(self, x): return (self.l(x),)
class Stage1(nn.Module): def __init__(self, layers, tensors): super(Stage1, self).__init__() assert ('Dummy/Linear[l1]' in layers) self.l = layers['Dummy/Linear[l1]'] assert isinstance(self.l, nn.Linear) def forward(self, x): return (self.l(x),)
class Stage2(nn.Module): def __init__(self, layers, tensors): super(Stage2, self).__init__() assert ('Dummy/Linear[l2]' in layers) self.l = layers['Dummy/Linear[l2]'] assert isinstance(self.l, nn.Linear) def forward(self, x): return (self.l(x),)
class Stage3(nn.Module): def __init__(self, layers, tensors): super(Stage3, self).__init__() assert ('Dummy/Linear[l3]' in layers) self.l = layers['Dummy/Linear[l3]'] assert isinstance(self.l, nn.Linear) def forward(self, x): x = self.l(x) return (x, (x + 1))
class SplitLinear(nn.Module): ' Split Linear layer.\n by the dimension of out_features\n (For each split, the output will be smaller. Requires stack at the end)\n ' __constants__ = ['in_features', 'out_features'] def __init__(self, other: nn.Linear, n_split: int): super().__init_...
class SplitLinearIn(nn.Module): ' Split Linear layer.\n by the dimension of in_features\n (For each split, the input will be smaller.\n Requires sum and adding bias at the end)\n ' __constants__ = ['in_features', 'out_features'] def __init__(self, other: nn.Linear, n_split: int): ...
class NoReduceSplitLinear(SplitLinear): def __init__(self, *args, **kw): super().__init__(*args, **kw) def forward(self, input): return [F.linear(input, w, b) for (w, b) in zip(self.weights, self.biases)]
class NoReduceSplitLinearIn(SplitLinearIn): def __init__(self, *args, **kw): super().__init__(*args, **kw) def forward(self, split_input): return [F.linear(i, w) for (w, i) in zip(self.weights, split_input)]
class AlexNet(nn.Module): def __init__(self, num_classes=1000): super(AlexNet, self).__init__() self.features = nn.Sequential(nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(...
def alexnet(pretrained=False, **kwargs): 'AlexNet model architecture from the\n `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = AlexNet(**kwargs) if pretrained: model.load_s...
class _DenseLayer(nn.Sequential): def __init__(self, num_input_features, growth_rate, bn_size, drop_rate): super(_DenseLayer, self).__init__() (self.add_module('norm1', nn.BatchNorm2d(num_input_features)),) (self.add_module('relu1', nn.ReLU(inplace=True)),) (self.add_module('conv1...
class _DenseBlock(nn.Sequential): def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate): super(_DenseBlock, self).__init__() for i in range(num_layers): layer = _DenseLayer((num_input_features + (i * growth_rate)), growth_rate, bn_size, drop_rate) ...
class _Transition(nn.Sequential): def __init__(self, num_input_features, num_output_features): super(_Transition, self).__init__() self.add_module('norm', nn.BatchNorm2d(num_input_features)) self.add_module('relu', nn.ReLU(inplace=True)) self.add_module('conv', nn.Conv2d(num_input...
class DenseNet(nn.Module): 'Densenet-BC model class, based on\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n growth_rate (int) - how many filters to add each layer (`k` in paper)\n block_config (list of 4 ints) - how many layers in each pooli...
def densenet121(pretrained=False, **kwargs): 'Densenet-121 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = DenseNet(num_init_features=64, growth_rate=32...
def densenet169(pretrained=False, **kwargs): 'Densenet-169 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = DenseNet(num_init_features=64, growth_rate=32...
def densenet201(pretrained=False, **kwargs): 'Densenet-201 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = DenseNet(num_init_features=64, growth_rate=32...
def densenet161(pretrained=False, **kwargs): 'Densenet-161 model from\n `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`_\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n ' model = DenseNet(num_init_features=96, growth_rate=48...
class Inception(nn.Module): def __init__(self, in_planes, kernel_1_x, kernel_3_in, kernel_3_x, kernel_5_in, kernel_5_x, pool_planes): super(Inception, self).__init__() self.b1 = nn.Sequential(nn.Conv2d(in_planes, kernel_1_x, kernel_size=1), nn.BatchNorm2d(kernel_1_x), nn.ReLU(True)) self....