diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ee5ab4f --- /dev/null +++ b/.gitignore @@ -0,0 +1,111 @@ +.DS_Store +fx_explore/ +# *test* +*.t7 +*.pth +# only keep the setup.py under root folder +./*.py +!./setup.py + +.idea/ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/: diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..aed71ce --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright 2021 Rex Geng + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a752ea4 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +This repository is written to simplify the common neural network pipeline + +In this repo, you will find: 1) code for training and evaluation of neural networks +; 2) code for layerwise analysis of computational complexity \ No newline at end of file diff --git a/nnutils/__init__.py b/nnutils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nnutils/cnn_complexity_analyzer/__init__.py b/nnutils/cnn_complexity_analyzer/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nnutils/cnn_complexity_analyzer/profile.py b/nnutils/cnn_complexity_analyzer/profile.py new file mode 100644 index 0000000..c6898e5 --- /dev/null +++ b/nnutils/cnn_complexity_analyzer/profile.py @@ -0,0 +1,218 @@ +from distutils.version import LooseVersion + +from torch import nn + +from .utils import NNComputeModuleProfile, ProfilerResult, is_compute_layer +from .vision_hooks import * + +logger = logging.getLogger(__name__) + + +def prRed(skk): print("\033[91m{}\033[00m".format(skk)) + + +def prGreen(skk): print("\033[92m{}\033[00m".format(skk)) + + +def prYellow(skk): print("\033[93m{}\033[00m".format(skk)) + + +if LooseVersion(torch.__version__) < LooseVersion("1.0.0"): + logger.warning( + "You are using an old version PyTorch {version}, which THOP is not going to support in the future.".format( + version=torch.__version__)) + +default_dtype = torch.float64 + +register_hooks = { + nn.ZeroPad2d: zero_ops, # padding does not involve any multiplication. + + nn.Conv1d: count_convNd, + nn.Conv2d: count_convNd, + nn.Conv3d: count_convNd, + # Conv2dSamePadding: count_convNd, + nn.ConvTranspose1d: count_convNd, + nn.ConvTranspose2d: count_convNd, + nn.ConvTranspose3d: count_convNd, + + nn.BatchNorm1d: count_bn, + nn.BatchNorm2d: count_bn, + nn.BatchNorm3d: count_bn, + + nn.ReLU: zero_ops, + nn.ReLU6: zero_ops, + nn.LeakyReLU: count_relu, + + nn.MaxPool1d: zero_ops, + nn.MaxPool2d: zero_ops, + nn.MaxPool3d: zero_ops, + nn.AdaptiveMaxPool1d: zero_ops, + nn.AdaptiveMaxPool2d: zero_ops, + nn.AdaptiveMaxPool3d: zero_ops, + + nn.AvgPool1d: count_avgpool, + nn.AvgPool2d: count_avgpool, + nn.AvgPool3d: count_avgpool, + nn.AdaptiveAvgPool1d: count_adap_avgpool, + nn.AdaptiveAvgPool2d: count_adap_avgpool, + nn.AdaptiveAvgPool3d: count_adap_avgpool, + + nn.Linear: count_linear, + nn.Dropout: zero_ops, + + nn.Upsample: count_upsample, + nn.UpsamplingBilinear2d: count_upsample, + nn.UpsamplingNearest2d: count_upsample, + +} + +if LooseVersion(torch.__version__) >= LooseVersion("1.1.0"): + register_hooks.update({ + nn.SyncBatchNorm: count_bn + }) + + +def profile(model: nn.Module, inputs, custom_ops=None, verbose=True): + handler_collection = {} + types_collection = set() + if custom_ops is None: + custom_ops = {} + + def add_hooks(m: nn.Module): + m.register_buffer('total_ops', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('total_params', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('num_act', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('num_dp', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('data_reuse', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('weight_reuse', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('dim_dp', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('input_dim', torch.zeros(1, dtype=torch.float64)) + m.register_buffer('output_dim', torch.zeros(1, dtype=torch.float64)) + + m_type = type(m) + + fn = None + if m_type in custom_ops: # if defined both op maps, use custom_ops to overwrite. + fn = custom_ops[m_type] + if m_type not in types_collection and verbose: + print("[INFO] Customize rule %s() %s." % (fn.__qualname__, m_type)) + elif m_type in register_hooks: + fn = register_hooks[m_type] + if m_type not in types_collection and verbose: + print("[INFO] Register %s() for %s." % (fn.__qualname__, m_type)) + else: + if m_type not in types_collection and verbose: + prRed("[WARN] Cannot find rule for %s. Treat it as zero Macs and zero Params." % m_type) + + if fn is not None: + handler_collection[m] = ( + m.register_forward_hook(fn), + m.register_forward_hook(count_parameters), + ) + types_collection.add(m_type) + + prev_training_status = model.training + + model.eval() + model.apply(add_hooks) + + with torch.no_grad(): + model(**inputs) + + per_compute_layer_complexity = [] + + def dfs_count(module: nn.Module, prefix="\t") -> (int, int): + total_ops, total_params = 0, 0 + total_num_act, total_num_dp = 0, 0 + for m in module.children(): + # if not hasattr(m, "total_ops") and not hasattr(m, "total_params"): # and len(list(m.children())) > 0: + # m_ops, m_params = dfs_count(m, prefix=prefix + "\t") + # else: + # m_ops, m_params = m.total_ops, m.total_params + if m in handler_collection and not isinstance(m, (nn.Sequential, nn.ModuleList)): + m_ops, m_params, m_num_act, m_num_dp, m_weight_reuse, m_input_reuse, m_dim_dp \ + = m.total_ops.item(), m.total_params.item(), m.num_act.item(), m.num_dp.item(), \ + m.weight_reuse.item(), m.input_reuse.item(), m.dim_dp.item() + else: + m_ops, m_params, m_num_act, m_num_dp = dfs_count(m, prefix=prefix + "\t") + m_weight_reuse = 0 + m_input_reuse = 0 + m_dim_dp = 0 + total_ops += m_ops + total_params += m_params + total_num_act += m_num_act + total_num_dp += m_num_dp + module_name = m._get_name() + # print(prefix, module_name, '(ops:', m_ops, 'params:', m_params, 'act:', m_num_act, 'dp:', m_num_dp,')') + + if is_compute_layer(m): + per_compute_layer_complexity.append([ + module_name, + m_ops, + m_params, + m_num_act, + m_num_dp, + m_dim_dp, + NNComputeModuleProfile(m, m.input_dim, m.output_dim) + ]) + + return total_ops, total_params, total_num_act, total_num_dp + + total_ops, total_params, total_num_act, total_num_dp = dfs_count(model) + + # reset model to original status + model.train(prev_training_status) + for m, (op_handler, params_handler) in handler_collection.items(): + op_handler.remove() + params_handler.remove() + m._buffers.pop("total_ops") + m._buffers.pop('total_params') + m._buffers.pop('num_act') + m._buffers.pop('num_dp') + m._buffers.pop('data_reuse') + m._buffers.pop('weight_reuse') + m._buffers.pop('dim_dp') + m._buffers.pop('input_dim') + m._buffers.pop('output_dim') + + return total_ops, total_params, total_num_act, total_num_dp, per_compute_layer_complexity + + +class Profiler: + def __init__(self, model, inputs): + self.model = model + self.inputs = inputs + + def profile(self): + macs, params, num_act, num_dp, per_compute_layer_complexity = profile(self.model, inputs=self.inputs) + return ProfilerResult(macs, params, num_act, num_dp, per_compute_layer_complexity) + + +def profile_compute_layers(model, inputs, custom_ops=None, verbose=False): + profiling_results = profile(model, inputs, custom_ops=custom_ops, verbose=verbose) + total_params = profiling_results[1] + + input_details = [p[-1] for p in profiling_results[-1]] + + ret = {} + count = 0 + + num_ones = 0 + num_ele = 0 + for idx, (n, m) in enumerate(model.named_modules()): + if idx == 0: + continue + + if not is_compute_layer(m): + continue + + setattr(input_details[count], 'param_proportion', input_details[count].num_param / total_params) + ret[n + '.weight'] = input_details[count] + + num_ones += input_details[count].mask.sum() + num_ele += input_details[count].mask.numel() + + count += 1 + + model_sparsity = 1 - 1.0 * num_ones.item() / num_ele + return ret, model_sparsity \ No newline at end of file diff --git a/nnutils/cnn_complexity_analyzer/utils.py b/nnutils/cnn_complexity_analyzer/utils.py new file mode 100644 index 0000000..6cf5d8e --- /dev/null +++ b/nnutils/cnn_complexity_analyzer/utils.py @@ -0,0 +1,57 @@ +from collections import Iterable + +import torch +from torch import nn + + +def is_compute_layer(m): + return isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear) + + +def clever_format(nums, format="%.2f"): + if not isinstance(nums, Iterable): + nums = [nums] + clever_nums = [] + + for num in nums: + if num > 1e12: + clever_nums.append(format % (num / 1e12) + "T") + elif num > 1e9: + clever_nums.append(format % (num / 1e9) + "G") + elif num > 1e6: + clever_nums.append(format % (num / 1e6) + "M") + elif num > 1e3: + clever_nums.append(format % (num / 1e3) + "K") + else: + clever_nums.append(format % num + "B") + + clever_nums = clever_nums[0] if len(clever_nums) == 1 else (*clever_nums,) + + return clever_nums + + +class NNComputeModuleProfile: + def __init__(self, module, input_dim, output_dim): + self.weight = module.weight.data + self.num_param = module.weight.data.numel() + + self.input_dim = input_dim + self.output_dim = output_dim + self.mask = torch.IntTensor((self.weight != 0).int()) + self.is_conv = self.weight.dim() == 4 + self.numzeros = (self.mask == 0).sum().item() + + def save(self, path): + profile = self.__dict__ + torch.save(profile, path) + + +class ProfilerResult: + def __init__(self, macs=0, num_params=0, num_act=0, num_dp=0, per_compute_layer_complexity=()): + # per_compute_layer complexity data format: + # module name, num_op, num_params + self.macs = macs + self.num_params = num_params + self.num_act = num_act + self.num_dp = num_dp + self.per_compute_layer_complexity = per_compute_layer_complexity diff --git a/nnutils/cnn_complexity_analyzer/vision_hooks.py b/nnutils/cnn_complexity_analyzer/vision_hooks.py new file mode 100644 index 0000000..e1b9507 --- /dev/null +++ b/nnutils/cnn_complexity_analyzer/vision_hooks.py @@ -0,0 +1,198 @@ +import logging + +import torch +from torch.nn.modules.conv import _ConvNd + +logger = logging.getLogger(__name__) +multiply_adds = 1 + + +def count_parameters(m, x, y): + total_params = 0 + for p in m.parameters(): + total_params += torch.DoubleTensor([p.numel()]) + m.total_params[0] = total_params + + +def zero_ops(m, x, y): + m.total_ops += torch.DoubleTensor([int(0)]) + m.num_act = torch.DoubleTensor([int(0)]) + m.num_dp = torch.DoubleTensor([int(0)]) + + m.input_reuse = torch.DoubleTensor([0]) + m.weight_reuse = torch.DoubleTensor([0]) + m.dim_dp = torch.DoubleTensor([0]) + # m.input_dim = torch.tensor(x.shape) + # m.output_dim = torch.tensor(y.shape) + + +def count_convNd(m: _ConvNd, x: (torch.Tensor,), y: torch.Tensor): + x = x[0] + + kernel_ops = torch.zeros(m.weight.size()[2:]).numel() # Kw x Kh + + bias_ops = 1 if m.bias is not None else 0 + + # N x Cout x H x W x (Cin x Kw x Kh + bias) + total_ops = y.nelement() * (m.in_channels // m.groups * kernel_ops) + # print(y.size()) + # print(y.nelement()) + + m.total_ops = torch.DoubleTensor([int(total_ops)]) + + num_act = x.nelement() + num_dp = y.nelement() + m.num_act = torch.DoubleTensor([num_act]) + m.num_dp = torch.DoubleTensor([num_dp]) + m.dim_dp = torch.DoubleTensor([m.in_channels // m.groups * kernel_ops]) + + m.input_reuse = torch.DoubleTensor([x.size()[2::].numel()]) + m.weight_reuse = torch.DoubleTensor([kernel_ops * y.size()[-3]]) + + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) + + +def count_bn(m, x, y): + x = x[0] + + nelements = x.numel() + if not m.training: + # subtract, divide, gamma, beta + total_ops = 2 * nelements + + m.total_ops += torch.DoubleTensor([int(0)]) + m.num_act = torch.DoubleTensor([int(0)]) + m.num_dp = torch.DoubleTensor([int(0)]) + + m.input_reuse = torch.DoubleTensor([0]) + m.weight_reuse = torch.DoubleTensor([0]) + m.dim_dp = torch.DoubleTensor([0]) + + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) + + +def count_relu(m, x, y): + x = x[0] + + nelements = x.numel() + + m.total_ops += torch.DoubleTensor([int(nelements)]) + m.num_act = torch.DoubleTensor([int(0)]) + m.num_dp = torch.DoubleTensor([int(0)]) + m.input_reuse = torch.DoubleTensor([0]) + m.weight_reuse = torch.DoubleTensor([0]) + m.dim_dp = torch.DoubleTensor([0]) + + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) + + +def count_softmax(m, x, y): + x = x[0] + + batch_size, nfeatures = x.size() + + total_exp = nfeatures + total_add = nfeatures - 1 + total_div = nfeatures + total_ops = batch_size * (total_exp + total_add + total_div) + + m.total_ops += torch.DoubleTensor([int(total_ops)]) + m.num_act = torch.DoubleTensor([int(0)]) + m.num_dp = torch.DoubleTensor([int(0)]) + m.input_reuse = torch.DoubleTensor([0]) + m.weight_reuse = torch.DoubleTensor([0]) + m.dim_dp = torch.DoubleTensor([0]) + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) + + +def count_avgpool(m, x, y): + # total_add = torch.prod(torch.Tensor([m.kernel_size])) + # total_div = 1 + # kernel_ops = total_add + total_div + kernel_ops = 1 + num_elements = y.numel() + total_ops = kernel_ops * num_elements + + m.total_ops += torch.DoubleTensor([int(0)]) + m.num_act = torch.DoubleTensor([int(0)]) + m.num_dp = torch.DoubleTensor([int(0)]) + m.input_reuse = torch.DoubleTensor([0]) + m.weight_reuse = torch.DoubleTensor([0]) + m.dim_dp = torch.DoubleTensor([0]) + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) + + +def count_adap_avgpool(m, x, y): + kernel = torch.DoubleTensor([*(x[0].shape[2:])]) // torch.DoubleTensor([*(y.shape[2:])]) + total_add = torch.prod(kernel) + total_div = 1 + kernel_ops = total_add + total_div + num_elements = y.numel() + total_ops = kernel_ops * num_elements + + m.total_ops += torch.DoubleTensor([int(0)]) + m.num_act = torch.DoubleTensor([int(0)]) + m.num_dp = torch.DoubleTensor([int(0)]) + m.input_reuse = torch.DoubleTensor([0]) + m.weight_reuse = torch.DoubleTensor([0]) + m.dim_dp = torch.DoubleTensor([0]) + + +# TODO: verify the accuracy +def count_upsample(m, x, y): + if m.mode not in ("nearest", "linear", "bilinear", "bicubic",): # "trilinear" + logger.warning("mode %s is not implemented yet, take it a zero op" % m.mode) + return zero_ops(m, x, y) + + if m.mode == "nearest": + return zero_ops(m, x, y) + + x = x[0] + if m.mode == "linear": + total_ops = y.nelement() * 5 # 2 muls + 3 add + elif m.mode == "bilinear": + # https://en.wikipedia.org/wiki/Bilinear_interpolation + total_ops = y.nelement() * 11 # 6 muls + 5 adds + elif m.mode == "bicubic": + # https://en.wikipedia.org/wiki/Bicubic_interpolation + # Product matrix [4x4] x [4x4] x [4x4] + ops_solve_A = 224 # 128 muls + 96 adds + ops_solve_p = 35 # 16 muls + 12 adds + 4 muls + 3 adds + total_ops = y.nelement() * (ops_solve_A + ops_solve_p) + elif m.mode == "trilinear": + # https://en.wikipedia.org/wiki/Trilinear_interpolation + # can viewed as 2 bilinear + 1 linear + total_ops = y.nelement() * (13 * 2 + 5) + + m.total_ops += torch.DoubleTensor([int(total_ops)]) + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) + + +# nn.Linear +def count_linear(m, x, y): + x = x[0] + # per output element + total_mul = m.in_features + # total_add = m.in_features - 1 + # total_add += 1 if m.bias is not None else 0 + num_elements = y.numel() + total_ops = total_mul * num_elements + + m.total_ops += torch.DoubleTensor([int(total_ops)]) + num_act = x.nelement() + num_dp = y.nelement() + m.num_act = torch.DoubleTensor([num_act]) + m.num_dp = torch.DoubleTensor([num_dp]) + + m.input_reuse = torch.DoubleTensor([num_elements]) + m.weight_reuse = torch.DoubleTensor([0]) + + m.dim_dp = torch.DoubleTensor([total_mul]) + m.input_dim = torch.tensor(x.shape) + m.output_dim = torch.tensor(y.shape) diff --git a/nnutils/training_pipeline/__init__.py b/nnutils/training_pipeline/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/nnutils/training_pipeline/accuracy_evaluator.py b/nnutils/training_pipeline/accuracy_evaluator.py new file mode 100644 index 0000000..f5cde73 --- /dev/null +++ b/nnutils/training_pipeline/accuracy_evaluator.py @@ -0,0 +1,48 @@ +import torch + +from .utils import AverageMeter + + +def accuracy(output, target, topk=(1,)): + """Computes the accuracy over the k top predictions for the specified values of k""" + with torch.no_grad(): + if type(output) is tuple: + _, _, output = output + maxk = max(topk) + batch_size = target.size(0) + + _, pred = output.topk(maxk, 1, True, True) + pred = pred.t() + correct = pred.eq(target.view(1, -1).expand_as(pred)) + + res = [] + for k in topk: + correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) + res.append(correct_k.mul_(1.0 / batch_size)) + return res, pred[0, :] + + +def eval(model, device, data_loader, criterion, print_acc=True): + model.eval() + top1 = AverageMeter('Acc@1', ':6.2f') + losses = AverageMeter('Loss', ':.4e') + + with torch.no_grad(): + for idx, data in enumerate(data_loader): + x, y = data + x = x.to(device) + y = y.to(device) + n_data = y.size(0) + + output = model(x) + loss = criterion(output, y) + accs, predictions = accuracy(output, y, topk=(1,)) + acc = accs[0] + + top1.update(acc.item(), n_data) + losses.update(loss.item(), n_data) + + if print_acc: + print(' * Acc@1 {top1.avg:.3f}'.format(top1=top1)) + + return top1.avg, losses.avg diff --git a/nnutils/training_pipeline/trainers/__init__.py b/nnutils/training_pipeline/trainers/__init__.py new file mode 100644 index 0000000..42ebdbc --- /dev/null +++ b/nnutils/training_pipeline/trainers/__init__.py @@ -0,0 +1,7 @@ +from .finetuner import FineTuner +from .vanilla_trainer import VanillaTrainer + +TRAINERS = { + 'finetuner': FineTuner, + 'vanilla': VanillaTrainer +} diff --git a/nnutils/training_pipeline/trainers/base_trainer.py b/nnutils/training_pipeline/trainers/base_trainer.py new file mode 100644 index 0000000..f0d7346 --- /dev/null +++ b/nnutils/training_pipeline/trainers/base_trainer.py @@ -0,0 +1,88 @@ +import time + +from .utils import SuppressPrints +from .. import accuracy_evaluator +from ..utils import AverageMeter, ProgressMeter, EPOCH_FMT_STR + + +class BaseTrainer: + def __init__(self, optimizer=None, criterion=None, device=None, lr_scheduler=None, num_epoch=-1, log_update_freq=1): + self.optimizer = optimizer + self.criterion = criterion + self.device = device + self.lr_scheduler = lr_scheduler + self.log_update_freq = log_update_freq + + self.batch_time = AverageMeter('Time', ':6.3f') + self.data_time = AverageMeter('Data Loading', ':6.3f') + self.data_copy_time = AverageMeter('Data to GPU', ':6.3f') + self.losses = AverageMeter('Loss', ':.4e') + self.top1 = AverageMeter('Acc@1', ':6.2f') + self.num_epoch = num_epoch + + def train(self, model, train_loader, test_loader, mask=None, verbose=True): + with SuppressPrints(not verbose): + progress = ProgressMeter( + len(train_loader), + [self.batch_time, self.data_time, self.data_copy_time, self.losses, self.top1], + prefix=EPOCH_FMT_STR.format(0) + ) + + for epoch in range(self.num_epoch): + cur_lr = self.optimizer.param_groups[0]['lr'] + print('Epoch: {}/{} - LR: {}'.format(epoch, self.num_epoch, cur_lr)) + + train_time_start = time.time() + + train_accuracy, train_loss = self.train_single_epoch(epoch, model, progress, train_loader, mask) + + train_time_before_valid = time.time() + + print( + "trainers one epoch(s) befor valid: " + "{:.2f}".format(train_time_before_valid - train_time_start)) + + benchmarking_acc, benchmarking_loss = accuracy_evaluator.eval(model, self.device, test_loader, + self.criterion) + print('Average train loss: {}, Average train top1 acc: {}'.format(train_loss, train_accuracy)) + print( + 'Average benchmarking loss: {}, Average benchmarking top1 acc: {}'.format( + benchmarking_loss, benchmarking_acc + ) + ) + train_time_end = time.time() + print("trainers one epoch(s): " + "{:.2f}".format(train_time_end - train_time_start)) + + # self.lr_scheduler.step() + return model + + def train_single_epoch(self, epoch, model, progress, train_loader, mask=None): + progress.prefix = EPOCH_FMT_STR.format(epoch) + self.batch_time.reset() + self.data_time.reset() + self.data_copy_time.reset() + self.losses.reset() + self.top1.reset() + model.train() + end = time.time() + for i, data in enumerate(train_loader): + self.data_time.update(time.time() - end) + x, y = data + x = x.to(self.device) + y = y.to(self.device) + self.data_copy_time.update(time.time() - end) + n_data = y.size(0) + + acc, loss = self.single_epoch_compute(model, x, y, mask) + + self.losses.update(loss.item(), n_data) + self.top1.update(acc.item(), n_data) + self.batch_time.update(time.time() - end) + end = time.time() + + if i % self.log_update_freq == 0: + progress.print2(i) + train_accuracy, train_loss = self.top1.avg, self.losses.avg + return train_accuracy, train_loss + + def single_epoch_compute(self, *args, **kwargs): + return NotImplementedError diff --git a/nnutils/training_pipeline/trainers/finetuner.py b/nnutils/training_pipeline/trainers/finetuner.py new file mode 100644 index 0000000..f7a328c --- /dev/null +++ b/nnutils/training_pipeline/trainers/finetuner.py @@ -0,0 +1,17 @@ +from .base_trainer import BaseTrainer +from .. import accuracy_evaluator + + +class FineTuner(BaseTrainer): + def __init__(self, *args, **kwargs): + super(FineTuner, self).__init__(*args, **kwargs) + + def single_epoch_compute(self, model, x, y, mask): + self.optimizer.zero_grad() + output = model(x) + loss = self.criterion(output, y) + accs, _ = accuracy_evaluator.accuracy(output, y, topk=(1,)) + acc = accs[0] + loss.backward() + self.optimizer.prune_step(mask) + return acc, loss diff --git a/nnutils/training_pipeline/trainers/utils.py b/nnutils/training_pipeline/trainers/utils.py new file mode 100644 index 0000000..bf5d06b --- /dev/null +++ b/nnutils/training_pipeline/trainers/utils.py @@ -0,0 +1,17 @@ +import os +import sys + + +class SuppressPrints: + def __init__(self, suppress=True): + self.suppress = suppress + + def __enter__(self): + if self.suppress: + self._original_stdout = sys.stdout + sys.stdout = open(os.devnull, 'w') + + def __exit__(self, exc_type, exc_val, exc_tb): + if self.suppress: + sys.stdout.close() + sys.stdout = self._original_stdout diff --git a/nnutils/training_pipeline/trainers/vanilla_trainer.py b/nnutils/training_pipeline/trainers/vanilla_trainer.py new file mode 100644 index 0000000..25cd68f --- /dev/null +++ b/nnutils/training_pipeline/trainers/vanilla_trainer.py @@ -0,0 +1,17 @@ +from .base_trainer import BaseTrainer +from .. import accuracy_evaluator + + +class VanillaTrainer(BaseTrainer): + def __init__(self, *args, **kwargs): + super(VanillaTrainer, self).__init__(*args, **kwargs) + + def single_epoch_compute(self, model, x, y, mask): + self.optimizer.zero_grad() + output = model(x) + loss = self.criterion(output, y) + accs, _ = accuracy_evaluator.accuracy(output, y, topk=(1,)) + acc = accs[0] + loss.backward() + self.optimizer.step() + return acc, loss diff --git a/nnutils/training_pipeline/utils.py b/nnutils/training_pipeline/utils.py new file mode 100644 index 0000000..4056881 --- /dev/null +++ b/nnutils/training_pipeline/utils.py @@ -0,0 +1,53 @@ +from torch import nn + +EPOCH_FMT_STR = "Epoch: [{}]" + + +def is_compute_layer(layer: nn.Module): + return isinstance(layer, nn.Conv2d) or isinstance(layer, nn.Linear) + + +class AverageMeter: + """Computes and stores the average and current value""" + + def __init__(self, name, fmt=':f'): + self.name = name + self.fmt = fmt + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + def __str__(self): + fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})' + return fmtstr.format(**self.__dict__) + + +class ProgressMeter: + def __init__(self, num_batches, meters, prefix=""): + self.batch_fmtstr = ProgressMeter._get_batch_fmtstr(num_batches) + self.meters = meters + self.prefix = prefix + + def print2(self, batch): + entries = [self.prefix + self.batch_fmtstr.format(batch)] + entries += [str(meter) for meter in self.meters] + print('\t'.join(entries)) + + @classmethod + def _get_batch_fmtstr(cls, num_batches): + num_digits = len(str(num_batches // 1)) + fmt = '{:' + str(num_digits) + 'd}' + return '[' + fmt + '/' + fmt.format(num_batches) + ']' diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..224a779 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description-file = README.md \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..8e4c199 --- /dev/null +++ b/setup.py @@ -0,0 +1,27 @@ +from distutils.core import setup + +setup( + name='nnutils', # How you named your package folder (MyLib) + packages=['nnutils'], # Chose the same as "name" + version='0.1', # Start with a small number and increase it with every change you make + license='MIT', # Chose a license from here: https://help.github.com/articles/licensing-a-repository + description='Common utility functions for training and evaluating neural networks as well as analyzing computational complexity', + # Give a short description about your library + author='Rex Geng', # Type in your name + author_email='hgeng4@illinois.edu', # Type in your E-Mail + url='https://github.com/rexxy-sasori/cnn_complexity_analyzer', + # Provide either the link to your github or to your website + download_url='https://github.com/rexxy-sasori/cnn_complexity_analyzer/archive/refs/tags/v0.1.tar.gz', # I explain this later on + keywords=['Complexity', 'Profiler', 'CNN'], # Keywords that define your package best + install_requires=[ # I get to this in a second + 'torch>=1.8.1', + ], + classifiers=[ + 'Development Status :: 3 - Alpha', + # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package + 'Intended Audience :: Developers', # Define that your audience are developers + 'Topic :: Software Development :: Build Tools', + 'License :: OSI Approved :: MIT License', # Again, pick a license + 'Programming Language :: Python :: 3.7', + ], +) \ No newline at end of file