Fix bugs in ViT
This commit is contained in:
		
							
								
								
									
										294
									
								
								exps/basic/xmain.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										294
									
								
								exps/basic/xmain.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,294 @@ | |||||||
|  | ##################################################### | ||||||
|  | # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2019.01 # | ||||||
|  | ##################################################### | ||||||
|  | import sys, time, torch, random, argparse | ||||||
|  | from PIL import ImageFile | ||||||
|  |  | ||||||
|  | ImageFile.LOAD_TRUNCATED_IMAGES = True | ||||||
|  | from copy import deepcopy | ||||||
|  | from pathlib import Path | ||||||
|  |  | ||||||
|  | from xautodl.datasets import get_datasets | ||||||
|  | from xautodl.config_utils import load_config, obtain_basic_args as obtain_args | ||||||
|  | from xautodl.procedures import ( | ||||||
|  |     prepare_seed, | ||||||
|  |     prepare_logger, | ||||||
|  |     save_checkpoint, | ||||||
|  |     copy_checkpoint, | ||||||
|  | ) | ||||||
|  | from xautodl.procedures import get_optim_scheduler, get_procedures | ||||||
|  | from xautodl.models import obtain_model | ||||||
|  | from xautodl.xmodels import obtain_model as obtain_xmodel | ||||||
|  | from xautodl.nas_infer_model import obtain_nas_infer_model | ||||||
|  | from xautodl.utils import get_model_infos | ||||||
|  | from xautodl.log_utils import AverageMeter, time_string, convert_secs2time | ||||||
|  |  | ||||||
|  |  | ||||||
|  | def main(args): | ||||||
|  |     assert torch.cuda.is_available(), "CUDA is not available." | ||||||
|  |     torch.backends.cudnn.enabled = True | ||||||
|  |     torch.backends.cudnn.benchmark = True | ||||||
|  |     # torch.backends.cudnn.deterministic = True | ||||||
|  |     # torch.set_num_threads(args.workers) | ||||||
|  |  | ||||||
|  |     prepare_seed(args.rand_seed) | ||||||
|  |     logger = prepare_logger(args) | ||||||
|  |  | ||||||
|  |     train_data, valid_data, xshape, class_num = get_datasets( | ||||||
|  |         args.dataset, args.data_path, args.cutout_length | ||||||
|  |     ) | ||||||
|  |     train_loader = torch.utils.data.DataLoader( | ||||||
|  |         train_data, | ||||||
|  |         batch_size=args.batch_size, | ||||||
|  |         shuffle=True, | ||||||
|  |         num_workers=args.workers, | ||||||
|  |         pin_memory=True, | ||||||
|  |     ) | ||||||
|  |     valid_loader = torch.utils.data.DataLoader( | ||||||
|  |         valid_data, | ||||||
|  |         batch_size=args.batch_size, | ||||||
|  |         shuffle=False, | ||||||
|  |         num_workers=args.workers, | ||||||
|  |         pin_memory=True, | ||||||
|  |     ) | ||||||
|  |     # get configures | ||||||
|  |     model_config = load_config(args.model_config, {"class_num": class_num}, logger) | ||||||
|  |     optim_config = load_config(args.optim_config, {"class_num": class_num}, logger) | ||||||
|  |  | ||||||
|  |     if args.model_source == "normal": | ||||||
|  |         base_model = obtain_model(model_config) | ||||||
|  |     elif args.model_source == "nas": | ||||||
|  |         base_model = obtain_nas_infer_model(model_config, args.extra_model_path) | ||||||
|  |     elif args.model_source == "autodl-searched": | ||||||
|  |         base_model = obtain_model(model_config, args.extra_model_path) | ||||||
|  |     elif args.model_source in ("x", "xmodel"): | ||||||
|  |         base_model = obtain_xmodel(model_config) | ||||||
|  |     else: | ||||||
|  |         raise ValueError("invalid model-source : {:}".format(args.model_source)) | ||||||
|  |     flop, param = get_model_infos(base_model, xshape) | ||||||
|  |     logger.log("model ====>>>>:\n{:}".format(base_model)) | ||||||
|  |     logger.log("model information : {:}".format(base_model.get_message())) | ||||||
|  |     logger.log("-" * 50) | ||||||
|  |     logger.log( | ||||||
|  |         "Params={:.2f} MB, FLOPs={:.2f} M ... = {:.2f} G".format( | ||||||
|  |             param, flop, flop / 1e3 | ||||||
|  |         ) | ||||||
|  |     ) | ||||||
|  |     logger.log("-" * 50) | ||||||
|  |     logger.log("train_data : {:}".format(train_data)) | ||||||
|  |     logger.log("valid_data : {:}".format(valid_data)) | ||||||
|  |     optimizer, scheduler, criterion = get_optim_scheduler( | ||||||
|  |         base_model.parameters(), optim_config | ||||||
|  |     ) | ||||||
|  |     logger.log("optimizer  : {:}".format(optimizer)) | ||||||
|  |     logger.log("scheduler  : {:}".format(scheduler)) | ||||||
|  |     logger.log("criterion  : {:}".format(criterion)) | ||||||
|  |  | ||||||
|  |     last_info, model_base_path, model_best_path = ( | ||||||
|  |         logger.path("info"), | ||||||
|  |         logger.path("model"), | ||||||
|  |         logger.path("best"), | ||||||
|  |     ) | ||||||
|  |     network, criterion = torch.nn.DataParallel(base_model).cuda(), criterion.cuda() | ||||||
|  |  | ||||||
|  |     if last_info.exists():  # automatically resume from previous checkpoint | ||||||
|  |         logger.log( | ||||||
|  |             "=> loading checkpoint of the last-info '{:}' start".format(last_info) | ||||||
|  |         ) | ||||||
|  |         last_infox = torch.load(last_info) | ||||||
|  |         start_epoch = last_infox["epoch"] + 1 | ||||||
|  |         last_checkpoint_path = last_infox["last_checkpoint"] | ||||||
|  |         if not last_checkpoint_path.exists(): | ||||||
|  |             logger.log( | ||||||
|  |                 "Does not find {:}, try another path".format(last_checkpoint_path) | ||||||
|  |             ) | ||||||
|  |             last_checkpoint_path = ( | ||||||
|  |                 last_info.parent | ||||||
|  |                 / last_checkpoint_path.parent.name | ||||||
|  |                 / last_checkpoint_path.name | ||||||
|  |             ) | ||||||
|  |         checkpoint = torch.load(last_checkpoint_path) | ||||||
|  |         base_model.load_state_dict(checkpoint["base-model"]) | ||||||
|  |         scheduler.load_state_dict(checkpoint["scheduler"]) | ||||||
|  |         optimizer.load_state_dict(checkpoint["optimizer"]) | ||||||
|  |         valid_accuracies = checkpoint["valid_accuracies"] | ||||||
|  |         max_bytes = checkpoint["max_bytes"] | ||||||
|  |         logger.log( | ||||||
|  |             "=> loading checkpoint of the last-info '{:}' start with {:}-th epoch.".format( | ||||||
|  |                 last_info, start_epoch | ||||||
|  |             ) | ||||||
|  |         ) | ||||||
|  |     elif args.resume is not None: | ||||||
|  |         assert Path(args.resume).exists(), "Can not find the resume file : {:}".format( | ||||||
|  |             args.resume | ||||||
|  |         ) | ||||||
|  |         checkpoint = torch.load(args.resume) | ||||||
|  |         start_epoch = checkpoint["epoch"] + 1 | ||||||
|  |         base_model.load_state_dict(checkpoint["base-model"]) | ||||||
|  |         scheduler.load_state_dict(checkpoint["scheduler"]) | ||||||
|  |         optimizer.load_state_dict(checkpoint["optimizer"]) | ||||||
|  |         valid_accuracies = checkpoint["valid_accuracies"] | ||||||
|  |         max_bytes = checkpoint["max_bytes"] | ||||||
|  |         logger.log( | ||||||
|  |             "=> loading checkpoint from '{:}' start with {:}-th epoch.".format( | ||||||
|  |                 args.resume, start_epoch | ||||||
|  |             ) | ||||||
|  |         ) | ||||||
|  |     elif args.init_model is not None: | ||||||
|  |         assert Path( | ||||||
|  |             args.init_model | ||||||
|  |         ).exists(), "Can not find the initialization file : {:}".format(args.init_model) | ||||||
|  |         checkpoint = torch.load(args.init_model) | ||||||
|  |         base_model.load_state_dict(checkpoint["base-model"]) | ||||||
|  |         start_epoch, valid_accuracies, max_bytes = 0, {"best": -1}, {} | ||||||
|  |         logger.log("=> initialize the model from {:}".format(args.init_model)) | ||||||
|  |     else: | ||||||
|  |         logger.log("=> do not find the last-info file : {:}".format(last_info)) | ||||||
|  |         start_epoch, valid_accuracies, max_bytes = 0, {"best": -1}, {} | ||||||
|  |  | ||||||
|  |     train_func, valid_func = get_procedures(args.procedure) | ||||||
|  |  | ||||||
|  |     total_epoch = optim_config.epochs + optim_config.warmup | ||||||
|  |     # Main Training and Evaluation Loop | ||||||
|  |     start_time = time.time() | ||||||
|  |     epoch_time = AverageMeter() | ||||||
|  |     for epoch in range(start_epoch, total_epoch): | ||||||
|  |         scheduler.update(epoch, 0.0) | ||||||
|  |         need_time = "Time Left: {:}".format( | ||||||
|  |             convert_secs2time(epoch_time.avg * (total_epoch - epoch), True) | ||||||
|  |         ) | ||||||
|  |         epoch_str = "epoch={:03d}/{:03d}".format(epoch, total_epoch) | ||||||
|  |         LRs = scheduler.get_lr() | ||||||
|  |         find_best = False | ||||||
|  |         # set-up drop-out ratio | ||||||
|  |         if hasattr(base_model, "update_drop_path"): | ||||||
|  |             base_model.update_drop_path( | ||||||
|  |                 model_config.drop_path_prob * epoch / total_epoch | ||||||
|  |             ) | ||||||
|  |         logger.log( | ||||||
|  |             "\n***{:s}*** start {:s} {:s}, LR=[{:.6f} ~ {:.6f}], scheduler={:}".format( | ||||||
|  |                 time_string(), epoch_str, need_time, min(LRs), max(LRs), scheduler | ||||||
|  |             ) | ||||||
|  |         ) | ||||||
|  |  | ||||||
|  |         # train for one epoch | ||||||
|  |         train_loss, train_acc1, train_acc5 = train_func( | ||||||
|  |             train_loader, | ||||||
|  |             network, | ||||||
|  |             criterion, | ||||||
|  |             scheduler, | ||||||
|  |             optimizer, | ||||||
|  |             optim_config, | ||||||
|  |             epoch_str, | ||||||
|  |             args.print_freq, | ||||||
|  |             logger, | ||||||
|  |         ) | ||||||
|  |         # log the results | ||||||
|  |         logger.log( | ||||||
|  |             "***{:s}*** TRAIN [{:}] loss = {:.6f}, accuracy-1 = {:.2f}, accuracy-5 = {:.2f}".format( | ||||||
|  |                 time_string(), epoch_str, train_loss, train_acc1, train_acc5 | ||||||
|  |             ) | ||||||
|  |         ) | ||||||
|  |  | ||||||
|  |         # evaluate the performance | ||||||
|  |         if (epoch % args.eval_frequency == 0) or (epoch + 1 == total_epoch): | ||||||
|  |             logger.log("-" * 150) | ||||||
|  |             valid_loss, valid_acc1, valid_acc5 = valid_func( | ||||||
|  |                 valid_loader, | ||||||
|  |                 network, | ||||||
|  |                 criterion, | ||||||
|  |                 optim_config, | ||||||
|  |                 epoch_str, | ||||||
|  |                 args.print_freq_eval, | ||||||
|  |                 logger, | ||||||
|  |             ) | ||||||
|  |             valid_accuracies[epoch] = valid_acc1 | ||||||
|  |             logger.log( | ||||||
|  |                 "***{:s}*** VALID [{:}] loss = {:.6f}, accuracy@1 = {:.2f}, accuracy@5 = {:.2f} | Best-Valid-Acc@1={:.2f}, Error@1={:.2f}".format( | ||||||
|  |                     time_string(), | ||||||
|  |                     epoch_str, | ||||||
|  |                     valid_loss, | ||||||
|  |                     valid_acc1, | ||||||
|  |                     valid_acc5, | ||||||
|  |                     valid_accuracies["best"], | ||||||
|  |                     100 - valid_accuracies["best"], | ||||||
|  |                 ) | ||||||
|  |             ) | ||||||
|  |             if valid_acc1 > valid_accuracies["best"]: | ||||||
|  |                 valid_accuracies["best"] = valid_acc1 | ||||||
|  |                 find_best = True | ||||||
|  |                 logger.log( | ||||||
|  |                     "Currently, the best validation accuracy found at {:03d}-epoch :: acc@1={:.2f}, acc@5={:.2f}, error@1={:.2f}, error@5={:.2f}, save into {:}.".format( | ||||||
|  |                         epoch, | ||||||
|  |                         valid_acc1, | ||||||
|  |                         valid_acc5, | ||||||
|  |                         100 - valid_acc1, | ||||||
|  |                         100 - valid_acc5, | ||||||
|  |                         model_best_path, | ||||||
|  |                     ) | ||||||
|  |                 ) | ||||||
|  |             num_bytes = ( | ||||||
|  |                 torch.cuda.max_memory_cached(next(network.parameters()).device) * 1.0 | ||||||
|  |             ) | ||||||
|  |             logger.log( | ||||||
|  |                 "[GPU-Memory-Usage on {:} is {:} bytes, {:.2f} KB, {:.2f} MB, {:.2f} GB.]".format( | ||||||
|  |                     next(network.parameters()).device, | ||||||
|  |                     int(num_bytes), | ||||||
|  |                     num_bytes / 1e3, | ||||||
|  |                     num_bytes / 1e6, | ||||||
|  |                     num_bytes / 1e9, | ||||||
|  |                 ) | ||||||
|  |             ) | ||||||
|  |             max_bytes[epoch] = num_bytes | ||||||
|  |         if epoch % 10 == 0: | ||||||
|  |             torch.cuda.empty_cache() | ||||||
|  |  | ||||||
|  |         # save checkpoint | ||||||
|  |         save_path = save_checkpoint( | ||||||
|  |             { | ||||||
|  |                 "epoch": epoch, | ||||||
|  |                 "args": deepcopy(args), | ||||||
|  |                 "max_bytes": deepcopy(max_bytes), | ||||||
|  |                 "FLOP": flop, | ||||||
|  |                 "PARAM": param, | ||||||
|  |                 "valid_accuracies": deepcopy(valid_accuracies), | ||||||
|  |                 "model-config": model_config._asdict(), | ||||||
|  |                 "optim-config": optim_config._asdict(), | ||||||
|  |                 "base-model": base_model.state_dict(), | ||||||
|  |                 "scheduler": scheduler.state_dict(), | ||||||
|  |                 "optimizer": optimizer.state_dict(), | ||||||
|  |             }, | ||||||
|  |             model_base_path, | ||||||
|  |             logger, | ||||||
|  |         ) | ||||||
|  |         if find_best: | ||||||
|  |             copy_checkpoint(model_base_path, model_best_path, logger) | ||||||
|  |         last_info = save_checkpoint( | ||||||
|  |             { | ||||||
|  |                 "epoch": epoch, | ||||||
|  |                 "args": deepcopy(args), | ||||||
|  |                 "last_checkpoint": save_path, | ||||||
|  |             }, | ||||||
|  |             logger.path("info"), | ||||||
|  |             logger, | ||||||
|  |         ) | ||||||
|  |  | ||||||
|  |         # measure elapsed time | ||||||
|  |         epoch_time.update(time.time() - start_time) | ||||||
|  |         start_time = time.time() | ||||||
|  |  | ||||||
|  |     logger.log("\n" + "-" * 200) | ||||||
|  |     logger.log( | ||||||
|  |         "Finish training/validation in {:} with Max-GPU-Memory of {:.2f} MB, and save final checkpoint into {:}".format( | ||||||
|  |             convert_secs2time(epoch_time.sum, True), | ||||||
|  |             max(v for k, v in max_bytes.items()) / 1e6, | ||||||
|  |             logger.path("info"), | ||||||
|  |         ) | ||||||
|  |     ) | ||||||
|  |     logger.log("-" * 200 + "\n") | ||||||
|  |     logger.close() | ||||||
|  |  | ||||||
|  |  | ||||||
|  | if __name__ == "__main__": | ||||||
|  |     args = obtain_args() | ||||||
|  |     main(args) | ||||||
							
								
								
									
										277
									
								
								notebooks/spaces/test-transformer-encoder.ipynb
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										277
									
								
								notebooks/spaces/test-transformer-encoder.ipynb
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,277 @@ | |||||||
|  | { | ||||||
|  |  "cells": [ | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": 1, | ||||||
|  |    "id": "3f754c96", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [], | ||||||
|  |    "source": [ | ||||||
|  |     "import torch\n", | ||||||
|  |     "from xautodl import spaces\n", | ||||||
|  |     "from xautodl.xlayers import super_core\n", | ||||||
|  |     "\n", | ||||||
|  |     "def _create_stel(input_dim, output_dim, order):\n", | ||||||
|  |     "    return super_core.SuperSequential(\n", | ||||||
|  |     "        super_core.SuperLinear(input_dim, output_dim),\n", | ||||||
|  |     "        super_core.SuperTransformerEncoderLayer(\n", | ||||||
|  |     "            output_dim,\n", | ||||||
|  |     "            num_heads=spaces.Categorical(2, 4, 6),\n", | ||||||
|  |     "            mlp_hidden_multiplier=spaces.Categorical(1, 2, 4),\n", | ||||||
|  |     "            order=order,\n", | ||||||
|  |     "        ),\n", | ||||||
|  |     "    )" | ||||||
|  |    ] | ||||||
|  |   }, | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": 2, | ||||||
|  |    "id": "81d42f4b", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [], | ||||||
|  |    "source": [ | ||||||
|  |     "batch, seq_dim, input_dim = 1, 4, 6\n", | ||||||
|  |     "order = super_core.LayerOrder.PreNorm" | ||||||
|  |    ] | ||||||
|  |   }, | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": 3, | ||||||
|  |    "id": "8056b37c", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [ | ||||||
|  |     { | ||||||
|  |      "name": "stdout", | ||||||
|  |      "output_type": "stream", | ||||||
|  |      "text": [ | ||||||
|  |       "SuperSequential(\n", | ||||||
|  |       "  (0): SuperSequential(\n", | ||||||
|  |       "    (0): SuperLinear(in_features=6, out_features=Categorical(candidates=[12, 24, 36], default_index=None), bias=True)\n", | ||||||
|  |       "    (1): SuperTransformerEncoderLayer(\n", | ||||||
|  |       "      (norm1): SuperLayerNorm1D(shape=Categorical(candidates=[12, 24, 36], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "      (mha): SuperSelfAttention(\n", | ||||||
|  |       "        input_dim=Categorical(candidates=[12, 24, 36], default_index=None), proj_dim=Categorical(candidates=[12, 24, 36], default_index=None), num_heads=Categorical(candidates=[2, 4, 6], default_index=None), mask=False, infinity=1000000000.0\n", | ||||||
|  |       "        (q_fc): SuperLinear(in_features=Categorical(candidates=[12, 24, 36], default_index=None), out_features=Categorical(candidates=[12, 24, 36], default_index=None), bias=False)\n", | ||||||
|  |       "        (k_fc): SuperLinear(in_features=Categorical(candidates=[12, 24, 36], default_index=None), out_features=Categorical(candidates=[12, 24, 36], default_index=None), bias=False)\n", | ||||||
|  |       "        (v_fc): SuperLinear(in_features=Categorical(candidates=[12, 24, 36], default_index=None), out_features=Categorical(candidates=[12, 24, 36], default_index=None), bias=False)\n", | ||||||
|  |       "        (attn_drop): SuperDrop(p=0.0, dims=[-1, -1, -1, -1], recover=True)\n", | ||||||
|  |       "      )\n", | ||||||
|  |       "      (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "      (norm2): SuperLayerNorm1D(shape=Categorical(candidates=[12, 24, 36], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "      (mlp): SuperMLPv2(\n", | ||||||
|  |       "        in_features=Categorical(candidates=[12, 24, 36], default_index=None), hidden_multiplier=Categorical(candidates=[1, 2, 4], default_index=None), out_features=Categorical(candidates=[12, 24, 36], default_index=None), drop=None, fc1 -> act -> drop -> fc2 -> drop,\n", | ||||||
|  |       "        (_params): ParameterDict(\n", | ||||||
|  |       "            (fc1_super_weight): Parameter containing: [torch.FloatTensor of size 144x36]\n", | ||||||
|  |       "            (fc1_super_bias): Parameter containing: [torch.FloatTensor of size 144]\n", | ||||||
|  |       "            (fc2_super_weight): Parameter containing: [torch.FloatTensor of size 36x144]\n", | ||||||
|  |       "            (fc2_super_bias): Parameter containing: [torch.FloatTensor of size 36]\n", | ||||||
|  |       "        )\n", | ||||||
|  |       "        (act): GELU()\n", | ||||||
|  |       "        (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "      )\n", | ||||||
|  |       "    )\n", | ||||||
|  |       "  )\n", | ||||||
|  |       "  (1): SuperSequential(\n", | ||||||
|  |       "    (0): SuperLinear(in_features=Categorical(candidates=[12, 24, 36], default_index=None), out_features=Categorical(candidates=[24, 36, 48], default_index=None), bias=True)\n", | ||||||
|  |       "    (1): SuperTransformerEncoderLayer(\n", | ||||||
|  |       "      (norm1): SuperLayerNorm1D(shape=Categorical(candidates=[24, 36, 48], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "      (mha): SuperSelfAttention(\n", | ||||||
|  |       "        input_dim=Categorical(candidates=[24, 36, 48], default_index=None), proj_dim=Categorical(candidates=[24, 36, 48], default_index=None), num_heads=Categorical(candidates=[2, 4, 6], default_index=None), mask=False, infinity=1000000000.0\n", | ||||||
|  |       "        (q_fc): SuperLinear(in_features=Categorical(candidates=[24, 36, 48], default_index=None), out_features=Categorical(candidates=[24, 36, 48], default_index=None), bias=False)\n", | ||||||
|  |       "        (k_fc): SuperLinear(in_features=Categorical(candidates=[24, 36, 48], default_index=None), out_features=Categorical(candidates=[24, 36, 48], default_index=None), bias=False)\n", | ||||||
|  |       "        (v_fc): SuperLinear(in_features=Categorical(candidates=[24, 36, 48], default_index=None), out_features=Categorical(candidates=[24, 36, 48], default_index=None), bias=False)\n", | ||||||
|  |       "        (attn_drop): SuperDrop(p=0.0, dims=[-1, -1, -1, -1], recover=True)\n", | ||||||
|  |       "      )\n", | ||||||
|  |       "      (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "      (norm2): SuperLayerNorm1D(shape=Categorical(candidates=[24, 36, 48], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "      (mlp): SuperMLPv2(\n", | ||||||
|  |       "        in_features=Categorical(candidates=[24, 36, 48], default_index=None), hidden_multiplier=Categorical(candidates=[1, 2, 4], default_index=None), out_features=Categorical(candidates=[24, 36, 48], default_index=None), drop=None, fc1 -> act -> drop -> fc2 -> drop,\n", | ||||||
|  |       "        (_params): ParameterDict(\n", | ||||||
|  |       "            (fc1_super_weight): Parameter containing: [torch.FloatTensor of size 192x48]\n", | ||||||
|  |       "            (fc1_super_bias): Parameter containing: [torch.FloatTensor of size 192]\n", | ||||||
|  |       "            (fc2_super_weight): Parameter containing: [torch.FloatTensor of size 48x192]\n", | ||||||
|  |       "            (fc2_super_bias): Parameter containing: [torch.FloatTensor of size 48]\n", | ||||||
|  |       "        )\n", | ||||||
|  |       "        (act): GELU()\n", | ||||||
|  |       "        (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "      )\n", | ||||||
|  |       "    )\n", | ||||||
|  |       "  )\n", | ||||||
|  |       "  (2): SuperSequential(\n", | ||||||
|  |       "    (0): SuperLinear(in_features=Categorical(candidates=[24, 36, 48], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=True)\n", | ||||||
|  |       "    (1): SuperTransformerEncoderLayer(\n", | ||||||
|  |       "      (norm1): SuperLayerNorm1D(shape=Categorical(candidates=[36, 72, 100], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "      (mha): SuperSelfAttention(\n", | ||||||
|  |       "        input_dim=Categorical(candidates=[36, 72, 100], default_index=None), proj_dim=Categorical(candidates=[36, 72, 100], default_index=None), num_heads=Categorical(candidates=[2, 4, 6], default_index=None), mask=False, infinity=1000000000.0\n", | ||||||
|  |       "        (q_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "        (k_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "        (v_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "        (attn_drop): SuperDrop(p=0.0, dims=[-1, -1, -1, -1], recover=True)\n", | ||||||
|  |       "      )\n", | ||||||
|  |       "      (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "      (norm2): SuperLayerNorm1D(shape=Categorical(candidates=[36, 72, 100], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "      (mlp): SuperMLPv2(\n", | ||||||
|  |       "        in_features=Categorical(candidates=[36, 72, 100], default_index=None), hidden_multiplier=Categorical(candidates=[1, 2, 4], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), drop=None, fc1 -> act -> drop -> fc2 -> drop,\n", | ||||||
|  |       "        (_params): ParameterDict(\n", | ||||||
|  |       "            (fc1_super_weight): Parameter containing: [torch.FloatTensor of size 400x100]\n", | ||||||
|  |       "            (fc1_super_bias): Parameter containing: [torch.FloatTensor of size 400]\n", | ||||||
|  |       "            (fc2_super_weight): Parameter containing: [torch.FloatTensor of size 100x400]\n", | ||||||
|  |       "            (fc2_super_bias): Parameter containing: [torch.FloatTensor of size 100]\n", | ||||||
|  |       "        )\n", | ||||||
|  |       "        (act): GELU()\n", | ||||||
|  |       "        (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "      )\n", | ||||||
|  |       "    )\n", | ||||||
|  |       "  )\n", | ||||||
|  |       ")\n" | ||||||
|  |      ] | ||||||
|  |     } | ||||||
|  |    ], | ||||||
|  |    "source": [ | ||||||
|  |     "out1_dim = spaces.Categorical(12, 24, 36)\n", | ||||||
|  |     "out2_dim = spaces.Categorical(24, 36, 48)\n", | ||||||
|  |     "out3_dim = spaces.Categorical(36, 72, 100)\n", | ||||||
|  |     "layer1 = _create_stel(input_dim, out1_dim, order)\n", | ||||||
|  |     "layer2 = _create_stel(out1_dim, out2_dim, order)\n", | ||||||
|  |     "layer3 = _create_stel(out2_dim, out3_dim, order)\n", | ||||||
|  |     "model = super_core.SuperSequential(layer1, layer2, layer3)\n", | ||||||
|  |     "print(model)" | ||||||
|  |    ] | ||||||
|  |   }, | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": null, | ||||||
|  |    "id": "4fd53a7c", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [ | ||||||
|  |     { | ||||||
|  |      "name": "stdout", | ||||||
|  |      "output_type": "stream", | ||||||
|  |      "text": [ | ||||||
|  |       "> \u001b[0;32m/Users/xuanyidong/anaconda3/lib/python3.8/site-packages/xautodl-0.9.9-py3.8.egg/xautodl/xlayers/super_transformer.py\u001b[0m(116)\u001b[0;36mforward_raw\u001b[0;34m()\u001b[0m\n", | ||||||
|  |       "\u001b[0;32m    114 \u001b[0;31m              \u001b[0;32mimport\u001b[0m \u001b[0mpdb\u001b[0m\u001b[0;34m;\u001b[0m \u001b[0mpdb\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset_trace\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", | ||||||
|  |       "\u001b[0m\u001b[0;32m    115 \u001b[0;31m            \u001b[0;31m# feed-forward layer -- MLP\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", | ||||||
|  |       "\u001b[0m\u001b[0;32m--> 116 \u001b[0;31m            \u001b[0my\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mnorm2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", | ||||||
|  |       "\u001b[0m\u001b[0;32m    117 \u001b[0;31m            \u001b[0mouts\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmlp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", | ||||||
|  |       "\u001b[0m\u001b[0;32m    118 \u001b[0;31m        \u001b[0;32melif\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_order\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mLayerOrder\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mPostNorm\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", | ||||||
|  |       "\u001b[0m\n", | ||||||
|  |       "ipdb> print(self)\n", | ||||||
|  |       "SuperTransformerEncoderLayer(\n", | ||||||
|  |       "  (norm1): SuperLayerNorm1D(shape=Categorical(candidates=[36, 72, 100], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "  (mha): SuperSelfAttention(\n", | ||||||
|  |       "    input_dim=Categorical(candidates=[36, 72, 100], default_index=None), proj_dim=Categorical(candidates=[36, 72, 100], default_index=None), num_heads=Categorical(candidates=[2, 4, 6], default_index=None), mask=False, infinity=1000000000.0\n", | ||||||
|  |       "    (q_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "    (k_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "    (v_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "    (attn_drop): SuperDrop(p=0.0, dims=[-1, -1, -1, -1], recover=True)\n", | ||||||
|  |       "  )\n", | ||||||
|  |       "  (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "  (norm2): SuperLayerNorm1D(shape=Categorical(candidates=[36, 72, 100], default_index=None), eps=1e-06, elementwise_affine=True)\n", | ||||||
|  |       "  (mlp): SuperMLPv2(\n", | ||||||
|  |       "    in_features=Categorical(candidates=[36, 72, 100], default_index=None), hidden_multiplier=Categorical(candidates=[1, 2, 4], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), drop=None, fc1 -> act -> drop -> fc2 -> drop,\n", | ||||||
|  |       "    (_params): ParameterDict(\n", | ||||||
|  |       "        (fc1_super_weight): Parameter containing: [torch.FloatTensor of size 400x100]\n", | ||||||
|  |       "        (fc1_super_bias): Parameter containing: [torch.FloatTensor of size 400]\n", | ||||||
|  |       "        (fc2_super_weight): Parameter containing: [torch.FloatTensor of size 100x400]\n", | ||||||
|  |       "        (fc2_super_bias): Parameter containing: [torch.FloatTensor of size 100]\n", | ||||||
|  |       "    )\n", | ||||||
|  |       "    (act): GELU()\n", | ||||||
|  |       "    (drop): Dropout(p=0.0, inplace=False)\n", | ||||||
|  |       "  )\n", | ||||||
|  |       ")\n", | ||||||
|  |       "ipdb> print(inputs.shape)\n", | ||||||
|  |       "torch.Size([1, 4, 100])\n", | ||||||
|  |       "ipdb> print(x.shape)\n", | ||||||
|  |       "torch.Size([1, 4, 96])\n", | ||||||
|  |       "ipdb> print(self.mha)\n", | ||||||
|  |       "SuperSelfAttention(\n", | ||||||
|  |       "  input_dim=Categorical(candidates=[36, 72, 100], default_index=None), proj_dim=Categorical(candidates=[36, 72, 100], default_index=None), num_heads=Categorical(candidates=[2, 4, 6], default_index=None), mask=False, infinity=1000000000.0\n", | ||||||
|  |       "  (q_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "  (k_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "  (v_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "  (attn_drop): SuperDrop(p=0.0, dims=[-1, -1, -1, -1], recover=True)\n", | ||||||
|  |       ")\n", | ||||||
|  |       "ipdb> print(self.mha.candidate)\n", | ||||||
|  |       "*** AttributeError: 'SuperSelfAttention' object has no attribute 'candidate'\n", | ||||||
|  |       "ipdb> print(self.mha.abstract_candidate)\n", | ||||||
|  |       "*** AttributeError: 'SuperSelfAttention' object has no attribute 'abstract_candidate'\n", | ||||||
|  |       "ipdb> print(self.mha._abstract_child)\n", | ||||||
|  |       "None\n", | ||||||
|  |       "ipdb> print(self.abstract_child)\n", | ||||||
|  |       "None\n", | ||||||
|  |       "ipdb> print(self.abstract_child.abstract_child)\n", | ||||||
|  |       "*** AttributeError: 'NoneType' object has no attribute 'abstract_child'\n", | ||||||
|  |       "ipdb> print(self.mha)\n", | ||||||
|  |       "SuperSelfAttention(\n", | ||||||
|  |       "  input_dim=Categorical(candidates=[36, 72, 100], default_index=None), proj_dim=Categorical(candidates=[36, 72, 100], default_index=None), num_heads=Categorical(candidates=[2, 4, 6], default_index=None), mask=False, infinity=1000000000.0\n", | ||||||
|  |       "  (q_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "  (k_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "  (v_fc): SuperLinear(in_features=Categorical(candidates=[36, 72, 100], default_index=None), out_features=Categorical(candidates=[36, 72, 100], default_index=None), bias=False)\n", | ||||||
|  |       "  (attn_drop): SuperDrop(p=0.0, dims=[-1, -1, -1, -1], recover=True)\n", | ||||||
|  |       ")\n" | ||||||
|  |      ] | ||||||
|  |     } | ||||||
|  |    ], | ||||||
|  |    "source": [ | ||||||
|  |     "inputs = torch.rand(batch, seq_dim, input_dim)\n", | ||||||
|  |     "outputs = model(inputs)" | ||||||
|  |    ] | ||||||
|  |   }, | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": null, | ||||||
|  |    "id": "05332b98", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [], | ||||||
|  |    "source": [ | ||||||
|  |     "abstract_space = model.abstract_search_space\n", | ||||||
|  |     "abstract_space.clean_last()\n", | ||||||
|  |     "abstract_child = abstract_space.random(reuse_last=True)\n", | ||||||
|  |     "# print(\"The abstract child program is:\\n{:}\".format(abstract_child))\n", | ||||||
|  |     "model.enable_candidate()\n", | ||||||
|  |     "model.set_super_run_type(super_core.SuperRunMode.Candidate)\n", | ||||||
|  |     "model.apply_candidate(abstract_child)\n", | ||||||
|  |     "outputs = model(inputs)" | ||||||
|  |    ] | ||||||
|  |   }, | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": null, | ||||||
|  |    "id": "3289f938", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [], | ||||||
|  |    "source": [ | ||||||
|  |     "print(outputs.shape)" | ||||||
|  |    ] | ||||||
|  |   }, | ||||||
|  |   { | ||||||
|  |    "cell_type": "code", | ||||||
|  |    "execution_count": null, | ||||||
|  |    "id": "36951cdf", | ||||||
|  |    "metadata": {}, | ||||||
|  |    "outputs": [], | ||||||
|  |    "source": [] | ||||||
|  |   } | ||||||
|  |  ], | ||||||
|  |  "metadata": { | ||||||
|  |   "kernelspec": { | ||||||
|  |    "display_name": "Python 3", | ||||||
|  |    "language": "python", | ||||||
|  |    "name": "python3" | ||||||
|  |   }, | ||||||
|  |   "language_info": { | ||||||
|  |    "codemirror_mode": { | ||||||
|  |     "name": "ipython", | ||||||
|  |     "version": 3 | ||||||
|  |    }, | ||||||
|  |    "file_extension": ".py", | ||||||
|  |    "mimetype": "text/x-python", | ||||||
|  |    "name": "python", | ||||||
|  |    "nbconvert_exporter": "python", | ||||||
|  |    "pygments_lexer": "ipython3", | ||||||
|  |    "version": "3.8.8" | ||||||
|  |   } | ||||||
|  |  }, | ||||||
|  |  "nbformat": 4, | ||||||
|  |  "nbformat_minor": 5 | ||||||
|  | } | ||||||
| @@ -38,12 +38,15 @@ class SuperSelfAttention(SuperModule): | |||||||
|         self._use_mask = use_mask |         self._use_mask = use_mask | ||||||
|         self._infinity = 1e9 |         self._infinity = 1e9 | ||||||
|  |  | ||||||
|         mul_head_dim = (input_dim // num_heads) * num_heads |         mul_head_dim = ( | ||||||
|         self.q_fc = SuperLinear(input_dim, mul_head_dim, bias=qkv_bias) |             spaces.get_max(input_dim) // spaces.get_min(num_heads) | ||||||
|         self.k_fc = SuperLinear(input_dim, mul_head_dim, bias=qkv_bias) |         ) * spaces.get_min(num_heads) | ||||||
|         self.v_fc = SuperLinear(input_dim, mul_head_dim, bias=qkv_bias) |         assert mul_head_dim == spaces.get_max(input_dim) | ||||||
|  |         self.q_fc = SuperLinear(input_dim, input_dim, bias=qkv_bias) | ||||||
|  |         self.k_fc = SuperLinear(input_dim, input_dim, bias=qkv_bias) | ||||||
|  |         self.v_fc = SuperLinear(input_dim, input_dim, bias=qkv_bias) | ||||||
|  |  | ||||||
|         self.attn_drop = SuperDrop(attn_drop, [-1, -1, -1, -1], recover=True) |         self.attn_drop = SuperDrop(attn_drop or 0.0, [-1, -1, -1, -1], recover=True) | ||||||
|         if proj_dim is None: |         if proj_dim is None: | ||||||
|             self.proj = SuperLinear(input_dim, proj_dim) |             self.proj = SuperLinear(input_dim, proj_dim) | ||||||
|             self.proj_drop = SuperDropout(proj_drop or 0.0) |             self.proj_drop = SuperDropout(proj_drop or 0.0) | ||||||
| @@ -127,7 +130,18 @@ class SuperSelfAttention(SuperModule): | |||||||
|         attn_v1 = attn_v1.softmax(dim=-1)  # B * #head * N * N |         attn_v1 = attn_v1.softmax(dim=-1)  # B * #head * N * N | ||||||
|         attn_v1 = self.attn_drop(attn_v1) |         attn_v1 = self.attn_drop(attn_v1) | ||||||
|         feats_v1 = (attn_v1 @ v_v1).permute(0, 2, 1, 3).reshape(B, N, -1) |         feats_v1 = (attn_v1 @ v_v1).permute(0, 2, 1, 3).reshape(B, N, -1) | ||||||
|         return feats_v1 |         if C == head_dim * num_head: | ||||||
|  |             feats = feats_v1 | ||||||
|  |         else:  # The channels can not be divided by num_head, the remainder forms an additional head | ||||||
|  |             q_v2 = q[:, :, num_head * head_dim :] | ||||||
|  |             k_v2 = k[:, :, num_head * head_dim :] | ||||||
|  |             v_v2 = v[:, :, num_head * head_dim :] | ||||||
|  |             attn_v2 = (q_v2 @ k_v2.transpose(-2, -1)) * math.sqrt(q_v2.shape[-1]) | ||||||
|  |             attn_v2 = attn_v2.softmax(dim=-1) | ||||||
|  |             attn_v2 = self.attn_drop(attn_v2) | ||||||
|  |             feats_v2 = attn_v2 @ v_v2 | ||||||
|  |             feats = torch.cat([feats_v1, feats_v2], dim=-1) | ||||||
|  |         return feats | ||||||
|  |  | ||||||
|     def forward_candidate(self, input: torch.Tensor) -> torch.Tensor: |     def forward_candidate(self, input: torch.Tensor) -> torch.Tensor: | ||||||
|         # check the num_heads: |         # check the num_heads: | ||||||
|   | |||||||
| @@ -5,3 +5,6 @@ | |||||||
| ##################################################### | ##################################################### | ||||||
|  |  | ||||||
| from .transformers import get_transformer | from .transformers import get_transformer | ||||||
|  |  | ||||||
|  | def obtain_model(config): | ||||||
|  |   raise NotImplementedError | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user