PyTorch 2.2 中文官方教程(十五)(1)https://developer.aliyun.com/article/1482579
第 2 部分。微调可量化模型
在这部分中,我们微调用于迁移学习的特征提取器,并对特征提取器进行量化。请注意,在第 1 部分和第 2 部分中,特征提取器都被量化。不同之处在于,在第 1 部分中,我们使用了一个预训练的量化模型。而在这部分中,我们在感兴趣的数据集上微调后创建了一个量化的特征提取器,因此这是一种在迁移学习中获得更好准确性并具有量化优势的方法。请注意,在我们的具体示例中,训练集非常小(120 张图像),因此整个模型微调的好处并不明显。然而,这里展示的过程将提高在具有更大数据集的迁移学习中的准确性。
预训练的特征提取器必须是可量化的。为确保它是可量化的,请执行以下步骤:
- 使用
torch.quantization.fuse_modules融合(Conv, BN, ReLU)、(Conv, BN)和(Conv, ReLU)。- 将特征提取器与自定义头连接。这需要对特征提取器的输出进行去量化。
- 在特征提取器的适当位置插入伪量化模块,以在训练过程中模拟量化。
对于第(1)步,我们使用torchvision/models/quantization中的模型,这些模型具有成员方法fuse_model。此函数将所有conv、bn和relu模块融合在一起。对于自定义模型,这将需要手动调用torch.quantization.fuse_modules API,并提供要手动融合的模块列表。
第(2)步由前一节中使用的create_combined_model函数执行。
第(3)步通过使用torch.quantization.prepare_qat来实现,该函数插入了伪量化模块。
作为第(4)步,您可以开始“微调”模型,然后将其转换为完全量化的版本(第 5 步)。
要将微调后的模型转换为量化模型,您可以调用torch.quantization.convert函数(在我们的情况下,只有特征提取器被量化)。
注意
由于随机初始化,您的结果可能与本教程中显示的结果不同。
# notice `quantize=False` model = models.resnet18(pretrained=True, progress=True, quantize=False) num_ftrs = model.fc.in_features # Step 1 model.train() model.fuse_model() # Step 2 model_ft = create_combined_model(model) model_ft[0].qconfig = torch.quantization.default_qat_qconfig # Use default QAT configuration # Step 3 model_ft = torch.quantization.prepare_qat(model_ft, inplace=True)
微调模型
在当前教程中,整个模型都被微调。一般来说,这会导致更高的准确性。然而,由于这里使用的训练集很小,我们最终会过拟合训练集。
步骤 4. 微调模型
for param in model_ft.parameters(): param.requires_grad = True model_ft.to(device) # We can fine-tune on GPU if available criterion = nn.CrossEntropyLoss() # Note that we are training everything, so the learning rate is lower # Notice the smaller learning rate optimizer_ft = optim.SGD(model_ft.parameters(), lr=1e-3, momentum=0.9, weight_decay=0.1) # Decay LR by a factor of 0.3 every several epochs exp_lr_scheduler = optim.lr_scheduler.StepLR(optimizer_ft, step_size=5, gamma=0.3) model_ft_tuned = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25, device=device)
步骤 5. 转换为量化模型
from torch.quantization import convert model_ft_tuned.cpu() model_quantized_and_trained = convert(model_ft_tuned, inplace=False)
让我们看看量化模型在几张图片上的表现
visualize_model(model_quantized_and_trained) plt.ioff() plt.tight_layout() plt.show()
(beta)在 PyTorch 中使用急切模式的静态量化
原文:
pytorch.org/tutorials/advanced/static_quantization_tutorial.html译者:飞龙
作者:Raghuraman Krishnamoorthi 编辑:Seth Weidman,Jerry Zhang
本教程展示了如何进行后训练静态量化,以及展示了两种更高级的技术 - 按通道量化和量化感知训练 - 以进一步提高模型的准确性。请注意,目前量化仅支持 CPU,因此在本教程中我们将不使用 GPU/CUDA。通过本教程,您将看到 PyTorch 中的量化如何导致模型尺寸显著减小,同时提高速度。此外,您将看到如何轻松应用一些高级量化技术,使您的量化模型比以往更少地准确性下降。警告:我们从其他 PyTorch 存储库中使用了大量样板代码,例如定义MobileNetV2模型架构,定义数据加载器等。当然我们鼓励您阅读它;但如果您想了解量化功能,请随时跳到“4. 后训练静态量化”部分。我们将从进行必要的导入开始:
import os import sys import time import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader import torchvision from torchvision import datasets import torchvision.transforms as transforms # Set up warnings import warnings warnings.filterwarnings( action='ignore', category=DeprecationWarning, module=r'.*' ) warnings.filterwarnings( action='default', module=r'torch.ao.quantization' ) # Specify random seed for repeatable results torch.manual_seed(191009)
1. 模型架构
我们首先定义 MobileNetV2 模型架构,进行了几个显著的修改以实现量化:
- 用
nn.quantized.FloatFunctional替换加法 - 在网络的开头和结尾插入
QuantStub和DeQuantStub。 - 用 ReLU 替换 ReLU6
注意:此代码取自这里。
from torch.ao.quantization import QuantStub, DeQuantStub def _make_divisible(v, divisor, min_value=None): """ This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return: """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v class ConvBNReLU(nn.Sequential): def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1): padding = (kernel_size - 1) // 2 super(ConvBNReLU, self).__init__( nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), nn.BatchNorm2d(out_planes, momentum=0.1), # Replace with ReLU nn.ReLU(inplace=False) ) class InvertedResidual(nn.Module): def __init__(self, inp, oup, stride, expand_ratio): super(InvertedResidual, self).__init__() self.stride = stride assert stride in [1, 2] hidden_dim = int(round(inp * expand_ratio)) self.use_res_connect = self.stride == 1 and inp == oup layers = [] if expand_ratio != 1: # pw layers.append(ConvBNReLU(inp, hidden_dim, kernel_size=1)) layers.extend([ # dw ConvBNReLU(hidden_dim, hidden_dim, stride=stride, groups=hidden_dim), # pw-linear nn.Conv2d(hidden_dim, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup, momentum=0.1), ]) self.conv = nn.Sequential(*layers) # Replace torch.add with floatfunctional self.skip_add = nn.quantized.FloatFunctional() def forward(self, x): if self.use_res_connect: return self.skip_add.add(x, self.conv(x)) else: return self.conv(x) class MobileNetV2(nn.Module): def __init__(self, num_classes=1000, width_mult=1.0, inverted_residual_setting=None, round_nearest=8): """ MobileNet V2 main class Args: num_classes (int): Number of classes width_mult (float): Width multiplier - adjusts number of channels in each layer by this amount inverted_residual_setting: Network structure round_nearest (int): Round the number of channels in each layer to be a multiple of this number Set to 1 to turn off rounding """ super(MobileNetV2, self).__init__() block = InvertedResidual input_channel = 32 last_channel = 1280 if inverted_residual_setting is None: inverted_residual_setting = [ # t, c, n, s [1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2], [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2], [6, 320, 1, 1], ] # only check the first element, assuming user knows t,c,n,s are required if len(inverted_residual_setting) == 0 or len(inverted_residual_setting[0]) != 4: raise ValueError("inverted_residual_setting should be non-empty " "or a 4-element list, got {}".format(inverted_residual_setting)) # building first layer input_channel = _make_divisible(input_channel * width_mult, round_nearest) self.last_channel = _make_divisible(last_channel * max(1.0, width_mult), round_nearest) features = [ConvBNReLU(3, input_channel, stride=2)] # building inverted residual blocks for t, c, n, s in inverted_residual_setting: output_channel = _make_divisible(c * width_mult, round_nearest) for i in range(n): stride = s if i == 0 else 1 features.append(block(input_channel, output_channel, stride, expand_ratio=t)) input_channel = output_channel # building last several layers features.append(ConvBNReLU(input_channel, self.last_channel, kernel_size=1)) # make it nn.Sequential self.features = nn.Sequential(*features) self.quant = QuantStub() self.dequant = DeQuantStub() # building classifier self.classifier = nn.Sequential( nn.Dropout(0.2), nn.Linear(self.last_channel, num_classes), ) # weight initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out') if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.BatchNorm2d): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.zeros_(m.bias) def forward(self, x): x = self.quant(x) x = self.features(x) x = x.mean([2, 3]) x = self.classifier(x) x = self.dequant(x) return x # Fuse Conv+BN and Conv+BN+Relu modules prior to quantization # This operation does not change the numerics def fuse_model(self, is_qat=False): fuse_modules = torch.ao.quantization.fuse_modules_qat if is_qat else torch.ao.quantization.fuse_modules for m in self.modules(): if type(m) == ConvBNReLU: fuse_modules(m, ['0', '1', '2'], inplace=True) if type(m) == InvertedResidual: for idx in range(len(m.conv)): if type(m.conv[idx]) == nn.Conv2d: fuse_modules(m.conv, [str(idx), str(idx + 1)], inplace=True)
2. 辅助函数
接下来,我们定义了几个辅助函数来帮助模型评估。这些大部分来自这里。
class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() 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__) def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): 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].reshape(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res def evaluate(model, criterion, data_loader, neval_batches): model.eval() top1 = AverageMeter('Acc@1', ':6.2f') top5 = AverageMeter('Acc@5', ':6.2f') cnt = 0 with torch.no_grad(): for image, target in data_loader: output = model(image) loss = criterion(output, target) cnt += 1 acc1, acc5 = accuracy(output, target, topk=(1, 5)) print('.', end = '') top1.update(acc1[0], image.size(0)) top5.update(acc5[0], image.size(0)) if cnt >= neval_batches: return top1, top5 return top1, top5 def load_model(model_file): model = MobileNetV2() state_dict = torch.load(model_file) model.load_state_dict(state_dict) model.to('cpu') return model def print_size_of_model(model): torch.save(model.state_dict(), "temp.p") print('Size (MB):', os.path.getsize("temp.p")/1e6) os.remove('temp.p')
3. 定义数据集和数据加载器
作为我们最后的主要设置步骤,我们为训练集和测试集定义数据加载器。
ImageNet 数据
要使用整个 ImageNet 数据集运行本教程中的代码,请首先按照ImageNet 数据中的说明下载 imagenet。将下载的文件解压缩到“data_path”文件夹中。
数据下载完成后,我们展示下面的函数定义数据加载器,我们将使用这些数据读取。这些函数大部分来自这里。
def prepare_data_loaders(data_path): normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) dataset = torchvision.datasets.ImageNet( data_path, split="train", transform=transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ])) dataset_test = torchvision.datasets.ImageNet( data_path, split="val", transform=transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ])) train_sampler = torch.utils.data.RandomSampler(dataset) test_sampler = torch.utils.data.SequentialSampler(dataset_test) data_loader = torch.utils.data.DataLoader( dataset, batch_size=train_batch_size, sampler=train_sampler) data_loader_test = torch.utils.data.DataLoader( dataset_test, batch_size=eval_batch_size, sampler=test_sampler) return data_loader, data_loader_test
接下来,我们将加载预训练的 MobileNetV2 模型。我们提供了下载模型的 URL here。
data_path = '~/.data/imagenet' saved_model_dir = 'data/' float_model_file = 'mobilenet_pretrained_float.pth' scripted_float_model_file = 'mobilenet_quantization_scripted.pth' scripted_quantized_model_file = 'mobilenet_quantization_scripted_quantized.pth' train_batch_size = 30 eval_batch_size = 50 data_loader, data_loader_test = prepare_data_loaders(data_path) criterion = nn.CrossEntropyLoss() float_model = load_model(saved_model_dir + float_model_file).to('cpu') # Next, we'll "fuse modules"; this can both make the model faster by saving on memory access # while also improving numerical accuracy. While this can be used with any model, this is # especially common with quantized models. print('\n Inverted Residual Block: Before fusion \n\n', float_model.features[1].conv) float_model.eval() # Fuses modules float_model.fuse_model() # Note fusion of Conv+BN+Relu and Conv+Relu print('\n Inverted Residual Block: After fusion\n\n',float_model.features[1].conv)
最后,为了获得“基线”准确性,让我们看看我们未量化模型与融合模块的准确性。
num_eval_batches = 1000 print("Size of baseline model") print_size_of_model(float_model) top1, top5 = evaluate(float_model, criterion, data_loader_test, neval_batches=num_eval_batches) print('Evaluation accuracy on %d images, %2.2f'%(num_eval_batches * eval_batch_size, top1.avg)) torch.jit.save(torch.jit.script(float_model), saved_model_dir + scripted_float_model_file)
在整个模型上,我们在包含 50,000 张图像的评估数据集上获得了 71.9%的准确率。
这将是我们用来比较的基线。接下来,让我们尝试不同的量化方法
4. 后训练静态量化
静态后训练量化不仅涉及将权重从浮点转换为整数,如动态量化那样,还包括首先通过网络传递数据批次并计算不同激活的结果分布的额外步骤(具体来说,这是通过在不同点插入观察器模块记录这些数据来完成的)。然后使用这些分布来确定如何在推断时量化不同的激活(一个简单的技术是将整个激活范围分成 256 个级别,但我们也支持更复杂的方法)。重要的是,这个额外的步骤允许我们在操作之间传递量化值,而不是在每个操作之间将这些值转换为浮点数 - 然后再转换为整数,从而实现显著的加速。
num_calibration_batches = 32 myModel = load_model(saved_model_dir + float_model_file).to('cpu') myModel.eval() # Fuse Conv, bn and relu myModel.fuse_model() # Specify quantization configuration # Start with simple min/max range estimation and per-tensor quantization of weights myModel.qconfig = torch.ao.quantization.default_qconfig print(myModel.qconfig) torch.ao.quantization.prepare(myModel, inplace=True) # Calibrate first print('Post Training Quantization Prepare: Inserting Observers') print('\n Inverted Residual Block:After observer insertion \n\n', myModel.features[1].conv) # Calibrate with the training set evaluate(myModel, criterion, data_loader, neval_batches=num_calibration_batches) print('Post Training Quantization: Calibration done') # Convert to quantized model torch.ao.quantization.convert(myModel, inplace=True) # You may see a user warning about needing to calibrate the model. This warning can be safely ignored. # This warning occurs because not all modules are run in each model runs, so some # modules may not be calibrated. print('Post Training Quantization: Convert done') print('\n Inverted Residual Block: After fusion and quantization, note fused modules: \n\n',myModel.features[1].conv) print("Size of model after quantization") print_size_of_model(myModel) top1, top5 = evaluate(myModel, criterion, data_loader_test, neval_batches=num_eval_batches) print('Evaluation accuracy on %d images, %2.2f'%(num_eval_batches * eval_batch_size, top1.avg))
对于这个量化模型,在评估数据集上看到准确率为 56.7%。这是因为我们使用简单的最小/最大观察器来确定量化参数。尽管如此,我们将模型的大小减小到了将近 3.6 MB,几乎减少了 4 倍。
此外,我们可以通过使用不同的量化配置显着提高准确性。我们使用为 x86 架构量化推荐的配置重复相同的练习。此配置执行以下操作:
- 按通道对权重进行量化
- 使用直方图观察器收集激活的直方图,然后以最佳方式选择量化参数。
per_channel_quantized_model = load_model(saved_model_dir + float_model_file) per_channel_quantized_model.eval() per_channel_quantized_model.fuse_model() # The old 'fbgemm' is still available but 'x86' is the recommended default. per_channel_quantized_model.qconfig = torch.ao.quantization.get_default_qconfig('x86') print(per_channel_quantized_model.qconfig) torch.ao.quantization.prepare(per_channel_quantized_model, inplace=True) evaluate(per_channel_quantized_model,criterion, data_loader, num_calibration_batches) torch.ao.quantization.convert(per_channel_quantized_model, inplace=True) top1, top5 = evaluate(per_channel_quantized_model, criterion, data_loader_test, neval_batches=num_eval_batches) print('Evaluation accuracy on %d images, %2.2f'%(num_eval_batches * eval_batch_size, top1.avg)) torch.jit.save(torch.jit.script(per_channel_quantized_model), saved_model_dir + scripted_quantized_model_file)
仅改变这种量化配置方法就使准确率提高到 67.3%以上!但是,这仍然比上面实现的 71.9%的基准差 4%。所以让我们尝试量化感知训练。
5. 量化感知训练
量化感知训练(QAT)通常是产生最高准确率的量化方法。使用 QAT 时,在训练的前向和后向传递中,所有权重和激活都被“伪量化”:即,浮点值被四舍五入以模拟 int8 值,但所有计算仍然使用浮点数。因此,在训练期间进行的所有权重调整都是在“意识到”模型最终将被量化的情况下进行的;因此,在量化之后,这种方法通常会产生比动态量化或静态后训练量化更高的准确率。
实际执行 QAT 的整体工作流程与以前非常相似:
- 我们可以使用与以前相同的模型:对于量化感知训练,不需要额外的准备工作。
- 我们需要使用一个
qconfig指定在权重和激活之后要插入什么样的伪量化,而不是指定观察器
我们首先定义一个训练函数:
def train_one_epoch(model, criterion, optimizer, data_loader, device, ntrain_batches): model.train() top1 = AverageMeter('Acc@1', ':6.2f') top5 = AverageMeter('Acc@5', ':6.2f') avgloss = AverageMeter('Loss', '1.5f') cnt = 0 for image, target in data_loader: start_time = time.time() print('.', end = '') cnt += 1 image, target = image.to(device), target.to(device) output = model(image) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() acc1, acc5 = accuracy(output, target, topk=(1, 5)) top1.update(acc1[0], image.size(0)) top5.update(acc5[0], image.size(0)) avgloss.update(loss, image.size(0)) if cnt >= ntrain_batches: print('Loss', avgloss.avg) print('Training: * Acc@1 {top1.avg:.3f} Acc@5 {top5.avg:.3f}' .format(top1=top1, top5=top5)) return print('Full imagenet train set: * Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f}' .format(top1=top1, top5=top5)) return
我们像以前一样融合模块
qat_model = load_model(saved_model_dir + float_model_file) qat_model.fuse_model(is_qat=True) optimizer = torch.optim.SGD(qat_model.parameters(), lr = 0.0001) # The old 'fbgemm' is still available but 'x86' is the recommended default. qat_model.qconfig = torch.ao.quantization.get_default_qat_qconfig('x86')
最后,prepare_qat执行“伪量化”,为量化感知训练准备模型
torch.ao.quantization.prepare_qat(qat_model, inplace=True) print('Inverted Residual Block: After preparation for QAT, note fake-quantization modules \n',qat_model.features[1].conv)
训练一个准确率高的量化模型需要准确地模拟推断时的数值。因此,对于量化感知训练,我们通过修改训练循环来进行:
- 在训练结束时切换批量归一化以使用运行时均值和方差,以更好地匹配推断数值。
- 我们还会冻结量化器参数(比例和零点)并微调权重。
num_train_batches = 20 # QAT takes time and one needs to train over a few epochs. # Train and check accuracy after each epoch for nepoch in range(8): train_one_epoch(qat_model, criterion, optimizer, data_loader, torch.device('cpu'), num_train_batches) if nepoch > 3: # Freeze quantizer parameters qat_model.apply(torch.ao.quantization.disable_observer) if nepoch > 2: # Freeze batch norm mean and variance estimates qat_model.apply(torch.nn.intrinsic.qat.freeze_bn_stats) # Check the accuracy after each epoch quantized_model = torch.ao.quantization.convert(qat_model.eval(), inplace=False) quantized_model.eval() top1, top5 = evaluate(quantized_model,criterion, data_loader_test, neval_batches=num_eval_batches) print('Epoch %d :Evaluation accuracy on %d images, %2.2f'%(nepoch, num_eval_batches * eval_batch_size, top1.avg))
量化感知训练在整个 imagenet 数据集上的准确率超过 71.5%,接近 71.9%的浮点准确率。
更多关于量化感知训练:
- QAT 是一种超集,包含了更多的调试后量化技术。例如,我们可以分析模型的准确性是否受到权重或激活量化的限制。
- 由于我们使用伪量化来模拟实际量化算术的数值,因此我们还可以模拟量化模型在浮点数上的准确性。
- 我们也可以轻松地模拟后训练量化。
从量化中加速
最后,让我们确认我们上面提到的一点:我们的量化模型是否确实执行推断更快?让我们测试一下:
def run_benchmark(model_file, img_loader): elapsed = 0 model = torch.jit.load(model_file) model.eval() num_batches = 5 # Run the scripted model on a few batches of images for i, (images, target) in enumerate(img_loader): if i < num_batches: start = time.time() output = model(images) end = time.time() elapsed = elapsed + (end-start) else: break num_images = images.size()[0] * num_batches print('Elapsed time: %3.0f ms' % (elapsed/num_images*1000)) return elapsed run_benchmark(saved_model_dir + scripted_float_model_file, data_loader_test) run_benchmark(saved_model_dir + scripted_quantized_model_file, data_loader_test)
在 MacBook Pro 上本地运行,常规模型的运行时间为 61 毫秒,量化模型仅为 20 毫秒,显示了与浮点模型相比,我们通常看到的 2-4 倍加速。
结论
在本教程中,我们展示了两种量化方法 - 后训练静态量化和量化感知训练 - 描述了它们在 PyTorch 中的使用方法。
感谢阅读!我们始终欢迎任何反馈意见,如果您有任何问题,请在这里创建一个问题。
PyTorch 2.2 中文官方教程(十五)(3)https://developer.aliyun.com/article/1482585