PyTorch 量化

2020-09-15 11:12 更新

原文:PyTorch 量化

量化導論

量化是指用于執(zhí)行計算并以低于浮點精度的位寬存儲張量的技術。 量化模型對張量使用整數而不是浮點值執(zhí)行部分或全部運算。 這允許更緊湊的模型表示,并在許多硬件平臺上使用高性能矢量化操作。 與典型的 FP32 型號相比,PyTorch 支持 INT8 量化,從而可將模型大小減少 4 倍,并將內存帶寬要求減少 4 倍。 與 FP32 計算相比,對 INT8 計算的硬件支持通???2 到 4 倍。 量化主要是一種加速推理的技術,并且量化算子僅支持前向傳遞。

PyTorch 支持多種方法來量化深度學習模型。 在大多數情況下,該模型在 FP32 中訓練,然后將模型轉換為 INT8。 此外,PyTorch 還支持量化意識訓練,該訓練使用偽量化模塊對前向和后向傳遞中的量化誤差進行建模。 注意,整個計算是在浮點數中進行的。 在量化意識訓練結束時,PyTorch 提供轉換功能,將訓練后的模型轉換為較低的精度。

在較低級別,PyTorch 提供了一種表示量化張量并對其執(zhí)行操作的方法。 它們可用于直接構建以較低的精度執(zhí)行全部或部分計算的模型。 提供了更高級別的 API,這些 API 合并了將 FP32 模型轉換為較低精度并降低精度損失的典型工作流程。

如今,PyTorch 支持以下后端以有效地運行量化運算符:

  • 具有 AVX2 支持或更高版本的 x86 CPU(在沒有 AVX2 的情況下,某些操作的執(zhí)行效率較低)
  • ARM CPU(通常在移動/嵌入式設備中找到)

相應的實現是根據 PyTorch 構建模式自動選擇的。

注意

PyTorch 1.3 尚未在 CUDA 上提供量化的操作員實施-這是未來工作的方向。 將模型移至 CPU,以測試量化功能。

量化感知訓練(通過 FakeQuantize)支持 CPU 和 CUDA。

Note

在準備量化模型時,有必要確保 qconfig 和用于量化計算的引擎與將在其上執(zhí)行模型的后端匹配。 量化目前支持兩個后端:fbgemm(用于 x86, https://github.com/pytorch/FBGEMM)和 qnnpack(用于 ARM QNNPACK 庫 https://github.com)。 com / pytorch / QNNPACK)。 例如,如果您對量化要在 ARM 上運行的模型感興趣,建議通過調用以下命令設置 qconfig:

qconfig = torch.quantization.get_default_qconfig('qnnpack')

用于后期訓練量化和

qconfig = torch.quantization.get_default_qat_qconfig('qnnpack')

用于量化意識訓練。

另外,torch.backends.quantized.engine 參數應設置為與后端匹配。 為了使用 qnnpack 進行推理,將后端設置為 qnnpack,如下所示

torch.backends.quantized.engine = 'qnnpack'

量化張量

PyTorch 支持每個張量和每個通道非對稱線性量化。 每個張量意味著張量內的所有值都以相同的方式縮放。 每通道意味著對于每個尺寸(通常是張量的通道尺寸),張量中的值都按比例縮放并偏移一個不同的值(實際上,比例和偏移成為矢量)。 這樣可以在將張量轉換為量化值時減少誤差。

通過使用以下命令轉換浮點張量來執(zhí)行映射

_images/math-quantizer-equation.png

注意,我們確保在量化后浮點中的零表示沒有錯誤,從而確保諸如填充之類的操作不會引起額外的量化誤差。

為了在 PyTorch 中進行量化,我們需要能夠在 Tensor 中表示量化數據。 量化張量允許存儲量化數據(表示為 int8 / uint8 / int32)以及諸如 scale 和 zero_point 之類的量化參數。 量化張量除了允許以量化格式序列化數據外,還允許許多有用的操作使量化算術變得容易。

經營范圍

量化張量支持常規(guī)全精度張量的有限數據處理方法子集。 (請參閱下面的列表)

對于 PyTorch 中包含的 NN 運算符,我們將支持范圍限制為:

  1. 8 位權重(data_type = qint8)

    1. 8 位激活(data_type = quint8)

請注意,運算符實現目前僅支持轉換線性運算符的權重的每個通道量化。 此外,將輸入數據的最小值和最大值線性映射到量化數據類型的最小值和最大值,以使零表示時沒有量化誤差。

可以通過定制運算符機制實現其他數據類型和量化方案。

在與torchtorch.nn中的全浮點版本相同的 API 下,可以使用許多量化張量操作。 torch.nn.quantized中提供了執(zhí)行重新量化的 NN 模塊的量化版本。 這些操作在操作簽名中顯式采用輸出量化參數(scale 和 zero_point)。

另外,我們還支持與影響量化的常見融合模式相對應的融合版本:torch.nn.intrinsic.quantized。

對于量化意識訓練,我們在 torch.nn.qat 和 torch.nn.intrinsic.qat 支持支持量化意識訓練的模塊

當前的量化操作列表足以覆蓋典型的 CNN 和 RNN 模型:

量化torch.Tensor操作

可從torch命名空間獲得的操作或作為 Tensor 上用于量化張量的方法的操作:

  • quantize_per_tensor() -將浮點張量轉換為具有每個張量標度和零點的量化張量

  • quantize_per_channel() -使用每通道標度和零點將浮點張量轉換為量化張量

  • 基于視圖的操作,例如 view() , as_strided() , expand() , flatten() , select() ,python 風格的索引等-與常規(guī)張量一樣工作(如果不是按通道量化)

  • Comparators
    
    
    
    

  • ne() -不相等
  • eq() -相等
  • ge() -大于或等于
  • le() -小于或等于
  • gt() -更大
  • lt() -少

  • copy_() -將 src 復制到原位

  • clone() -返回傳入張量的深層副本

  • dequantize() -將量化張量轉換為浮點張量

  • equal() -比較兩個張量,如果量化參數和所有整數元素相同,則返回 true

  • int_repr() -打印量化張量的基礎整數表示

  • max() -返回張量的最大值(僅減小)

  • mean() -均值功能。 支持的變體:縮小,變暗,變暗

  • min() -返回張量的最小值(僅減?。?/li>

  • q_scale() -返回每個張量量化張量的小數位數

  • q_zero_point() -返回每個張量量化零點的 zero_point

  • q_per_channel_scales() -返回每通道量化張量的小數位數

  • q_per_channel_zero_points() -返回每通道量化張量的零點

  • q_per_channel_axis() -返回每通道量化張量的通道軸

  • resize_() -就地調整大小

  • sort() -對張量進行排序

  • topk() -返回張量的 k 個最大值

torch.nn.functional

支持基本激活。

  • relu() -整流線性單位(副本)
  • relu_() -整流線性單位(就位)
  • max_pool2d() -最大池
  • adaptive_avg_pool2d() -自適應平均池
  • avg_pool2d() -平均池
  • interpolate() -插值
  • upsample() -上采樣
  • upsample_bilinear() -雙線性上采樣
  • upsample_nearest() -最近的升采樣

torch.nn.intrinsic

提供融合模塊以用于 CNN 中的常見模式。 將多個運算(例如卷積和 relu)組合在一起可以實現更好的量化精度

  • torch.nn.intrinsic — float versions of the modules, can be swapped with quantized version 1 to 1
    
    
    
    

  • ConvBn2d -Conv2d + BatchNorm
  • ConvBnReLU2d -Conv2d + BatchNorm + ReLU
  • ConvReLU2d — Conv2d + ReLU
  • ConvReLU3d — Conv3d + ReLU
  • LinearReLU -線性+ ReLU

  • torch.nn.intrinsic.qat — versions of layers for quantization-aware training
    
    
    
    

  • ConvBn2d -Conv2d + BatchNorm
  • ConvBnReLU2d -Conv2d + BatchNorm + ReLU
  • ConvReLU2d — Conv2d + ReLU
  • LinearReLU -線性+ ReLU

  • torch.nn.intrinsic.quantized — quantized version of fused layers for inference (no BatchNorm variants as it's usually folded into convolution for inference)
    
    
    
    

  • LinearReLU -線性+ ReLU
  • ConvReLU2d — 2D 卷積+ ReLU
  • ConvReLU3d — 3D 卷積+ ReLU

torch.nn.qat

量化意識訓練的層次

  • Linear -線性(完全連接)層
  • Conv2d — 2D 卷積

torch.quantization

  • Functions for quantization
    
    
    
    

  • add_observer_() -為葉子模塊添加觀察者(如果提供了量化配置)
  • add_quant_dequant() -使用 QuantWrapper 包裝葉子子模塊
  • convert() -將具有觀察者的 float 模塊轉換為其量化的對應物。 必須具有量化配置
  • get_observer_dict() -遍歷模塊子級并將所有觀察者收集到dict
  • prepare() -準備模型的副本以進行量化
  • prepare_qat() -準備用于量化意識訓練的模型副本
  • propagate_qconfig_() -通過模塊層次結構傳播量化配置,并將其分配給每個葉模塊
  • quantize() -將 float 模塊轉換為量化版本
  • quantize_dynamic() -將 float 模塊轉換為動態(tài)量化版本
  • quantize_qat() -將浮點模塊轉換為用于量化意識訓練的量化版本
  • swap_module() -交換模塊及其量化的對應對象(如果量化并且具有觀察者)

  • default_eval_fn() - torch.quantization.quantize() 使用的默認評估功能

  • fuse_modules()

  • FakeQuantize -用于在訓練時模擬量化/去量化的模塊

  • Default Observers. The rest of observers are available from torch.quantization.observer
    
    
    
    

  • default_observer-與MinMaxObserver.with_args(reduce_range=True)相同
  • default_weight_observer-與MinMaxObserver.with_args(dtype=torch.qint8, qscheme=torch.per_tensor_symmetric)相同
  • Observer —觀察者的抽象基類

  • Quantization configurations
    
    
    
    

  • QConfig -量化配置類
  • default_qconfig —與QConfig(activation=default_observer, weight=default_weight_observer)相同(請參閱QConfig
  • default_qat_qconfig —與QConfig(activation=default_fake_quant, weight=default_weight_fake_quant)相同(請參閱QConfig
  • default_dynamic_qconfig —與QConfigDynamic(weight=default_weight_observer)相同(請參閱QConfigDynamic
  • float16_dynamic_qconfig —與QConfigDynamic(weight=NoopObserver.with_args(dtype=torch.float16))相同(請參閱QConfigDynamic

  • Stubs
    
    
    
    

  • DeQuantStub -浮點型模型中用于 dequantize()操作的占位符模塊
  • QuantStub -用于浮點值模型中的 quantize()操作的占位符模塊
  • QuantWrapper -包裝要量化的模塊。 插入 QuantStubDeQuantStub

觀察者,用于計算量化參數

  • MinMaxObserver -從觀察到的張量輸入的運行最小值和最大值(每個張量變量)得出量化參數

  • MovingAverageMinMaxObserver -從觀測到的張量輸入的最大值和最小值的運行平均值(每個張量變量)得出量化參數

  • PerChannelMinMaxObserver -從觀測到的張量輸入的運行最小值和最大值得出量化參數(每個通道變量)

  • MovingAveragePerChannelMinMaxObserver -從觀測到的張量輸入的最小值和最大值的運行平均值(每個通道變量)得出量化參數

  • HistogramObserver -通過創(chuàng)建運行最小值和最大值的直方圖來得出量化參數。

  • Observers that do not compute the quantization parameters:
    
    
    
    

  • RecordingObserver -記錄所有傳入的張量。 僅用于調試。
  • NoopObserver -直通觀察器。 用于沒有量化參數(即量化為float16)的情況

torch.nn.quantized

標準 NN 層的量化版本。

  • Quantize -量化層,用于自動替換 QuantStub
  • DeQuantize -脫層層,用于替換 DeQuantStub
  • FloatFunctional —包裝器類,使無狀態(tài)的浮點操作成為有狀態(tài)的,以便可以用量化版本替換它們
  • QFunctional -包裝類,用于無狀態(tài)操作(例如`torch.add)的量化版本
  • Conv2d — 2D 卷積
  • Conv3d — 3D 卷積
  • Linear -線性(完全連接)層
  • MaxPool2d -2D 最大合并
  • ReLU -整流線性單元
  • ReLU6 -校正后的線性單位,其量化表示為 6

torch.nn.quantized.dynamic

動態(tài)量化模型中使用的圖層(即僅根據權重進行量化)

  • Linear -線性(完全連接)層
  • LSTM —長期內存 RNN 模塊

torch.nn.quantized.functional

量化 NN 層的功能版本(其中許多接受顯式的量化輸出參數)

  • adaptive_avg_pool2d() —二維自適應平均池
  • avg_pool2d() -2D 平均池
  • conv2d() — 2D 卷積
  • conv3d() — 3D 卷積
  • interpolate() -下/上采樣器
  • linear() -線性(完全連接)運算
  • max_pool2d() -2D 最大合并
  • relu() -整流線性單元
  • upsample() -上采樣器。 將不推薦使用 interpolate()
  • upsample_bilinear() -雙鏡頭上采樣器。 將不推薦使用 interpolate()
  • upsample_nearest() -最近的鄰居上采樣器。 將不推薦使用 interpolate()

量化 dtype 和量化方案

  • torch.qscheme — Type to describe the quantization scheme of a tensor. Supported types:
    
    
    
    

  • torch.per_tensor_affine-每個張量,不對稱
  • torch.per_channel_affine-每個通道,不對稱
  • torch.per_tensor_symmetric-每個張量,對稱
  • torch.per_channel_symmetric-每個張量,對稱

  • torch.dtype — Type to describe the data. Supported types:
    
    
    
    

  • torch.quint8-8 位無符號整數
  • torch.qint8 — 8 位有符號整數
  • torch.qint32 — 32 位有符號整數

量化工作流程

PyTorch 提供了三種量化模型的方法。

  1. 訓練后動態(tài)量化:這是最簡單的量化形式,其中權重被提前量化,而激活在推理過程中被動態(tài)量化。 這用于以下情況:模型執(zhí)行時間主要由從內存中加載權重而不是計算矩陣乘法來決定。 對于小批量的 LSTM 和 Transformer 類型的模型,這是正確的。 只需調用一次 torch.quantization.quantize_dynamic() ,即可將動態(tài)量化應用于整個模型。 請參閱量化教程

  1. 訓練后靜態(tài)量化:這是最常用的量化形式,其中權重是提前量化的,并且基于觀察校準過程中模型的行為來預先計算激活張量的比例因子和偏差。 訓練后量化通常是在內存帶寬和計算節(jié)省都很重要的情況下進行的,而 CNN 是典型的用例。 進行訓練后量化的一般過程是:

  1. 準備模型: 通過添加 QuantStub 和 DeQuantStub 模塊,指定在何處明確量化激活和量化數量。 b。 確保不重復使用模塊。 C。 將所有需要重新量化的操作轉換為模塊
  2. 將諸如 conv + relu 或 conv + batchnorm + relu 之類的保險絲操作融合在一起,以提高模型的準確性和性能。
  3. 指定'97 量化方法的配置,例如選擇對稱或非對稱量化以及 MinMax 或 L2Norm 校準技術。
  4. 使用 torch.quantization.prepare() 插入將在校準期間觀察激活張量的模塊
  5. 通過對校準數據集進行推斷來校準模型
  6. 最后,使用 torch.quantization.convert()方法轉換模型本身。 這可以做幾件事:它量化權重,計算并存儲要在每個激活張量中使用的比例和偏差值,并替換關鍵運算符的量化實現。

請參閱量化教程

  1. 量化意識訓練:在極少數情況下,訓練后量化不能提供足夠的準確性,可以使用 torch.quantization.FakeQuantize 通過模擬量化來進行訓練。 計算將在 FP32 中進行,但將值取整并四舍五入以模擬 INT8 量化的效果。 步驟的順序非常相似。

  1. 步驟(1)和(2)相同。
  2. 指定偽量化方法'97 的配置,例如選擇對稱或非對稱量化以及 MinMax 或移動平均或 L2Norm 校準技術。
  3. 使用 torch.quantization.prepare_qat() 插入將在訓練過程中模擬量化的模塊。
  4. 訓練或微調模型。
  5. 與步驟(6)相同,用于訓練后量化

See the quantization tutorials

雖然提供了根據觀察到的張量數據選擇比例因子和偏差的觀察者的默認實現,但開發(fā)人員可以提供自己的量化功能。 量化可以選擇性地應用于模型的不同部分,也可以針對模型的不同部分進行不同的配置。

我們還為 conv2d(), conv3d()linear()的每個通道量化提供支持

量化工作流程通過在模型的模塊層次結構中添加(例如,將觀察者添加為.observer子模塊)或替換(例如,將nn.Conv2d轉換為nn.quantized.Conv2d)來工作。 這意味著該模型在整個過程中都將保留基于常規(guī)nn.Module的實例,因此可以與其他 PyTorch API 一起使用。

量化的模型準備

當前有必要在量化之前對模型定義進行一些修改。 這是因為當前量化在逐個模塊的基礎上進行。 具體來說,對于所有量化技術,用戶需要:

  1. 將需要輸出重新量化(因此具有其他參數)的所有操作從功能轉換為模塊形式。
  2. 通過在子模塊上分配`.qconfig屬性或通過指定qconfig_dict,指定需要量化模型的哪些部分

對于量化激活的靜態(tài)量化技術,用戶還需要執(zhí)行以下操作:

  1. 指定對激活進行量化和反量化的位置。 這是使用 QuantStubDeQuantStub 模塊完成的。
  2. 使用 torch.nn.quantized.FloatFunctional 將需要特殊處理以將量化量化的張量操作包裝到模塊中。 例如addcat之類的操作,需要特殊處理才能確定輸出量化參數。
  3. 保險絲模塊:將操作/模塊組合為一個模塊,以獲得更高的精度和性能。 這是通過 torch.quantization.fuse_modules() API 完成的,該 API 接收要融合的模塊列表。 我們目前支持以下融合:[Conv,Relu],[Conv,BatchNorm],[Conv,BatchNorm,Relu],[Linear,Relu]

torch量化

該模塊實現您直接調用的功能,以將模型從 FP32 轉換為量化形式。 例如, prepare() 用于后期訓練量化,以為校準步驟準備模型,而 convert() 實際上將權重轉換為 int8,并用其量化的對等物替換運算 。 還有其他幫助程序功能,例如對模型的輸入進行量化以及執(zhí)行 conv + relu 等關鍵融合。

頂級量化 API

torch.quantization.quantize(model, run_fn, run_args, mapping=None, inplace=False)?

將浮點模型轉換為量化模型。

首先,它將準備進行校準或訓練的模型,然后調用 <cite>run_fn</cite> ,它將運行校準步驟或訓練步驟,之后我們將調用 <cite>convert</cite> ,它將模型轉換為 量化模型。

參數

  • 模型 –輸入模型
  • run_fn –用于評估準備好的模型的函數,可以是僅運行準備好的模型或訓練循環(huán)的函數
  • run_args – <cite>run_fn</cite> 的位置參數
  • 就地 –就地進行模型轉換,原始模塊已變異
  • 映射 –原始模塊類型與量化對應項之間的對應關系

退貨

量化模型。

torch.quantization.quantize_dynamic(model, qconfig_spec=None, dtype=torch.qint8, mapping=None, inplace=False)?

將浮動模型轉換為動態(tài)(即僅權重)量化模型。

用僅動態(tài)權重的量化版本替換指定的模塊,然后輸出量化的模型。

對于最簡單的用法,請?zhí)峁?<cite>dtype</cite> 參數,該參數可以是 float16 或 qint8。 默認情況下,僅對權重較大的圖層(即線性和 RNN 變體)執(zhí)行僅權重量化。

通過 <cite>qconfig</cite> 和<cite>映射</cite>的細粒度控制是可能的,它們的作用類似于 <cite>Quantize()</cite>。 如果提供了 <cite>qconfig</cite> ,則將忽略 <cite>dtype</cite> 參數。

Parameters

  • 模塊 –輸入模型

  • qconfig_spec

要么:

  • 從子模塊的名稱或類型映射到量化配置的字典,qconfig 適用于給定模塊的所有子模塊,除非為子模塊指定了 qconfig(當子模塊已經具有 qconfig 屬性時)。 字典中的條目必須是 QConfigDynamic 實例。
  • 一組類型和/或子模塊名稱,用于對其進行動態(tài)量化,在這種情況下, <cite>dtype</cite> 自變量用于指定位寬

  • inplace – carry out model transformations in-place, the original module is mutated

  • 映射 –將子模塊的類型映射到需要替換子模塊的對應動態(tài)量化版本的類型

torch.quantization.quantize_qat(model, run_fn, run_args, inplace=False)?

進行量化意識訓練并輸出量化模型

Parameters

  • model – input model
  • run_fn –用于評估準備好的模型的函數,可以是僅運行準備好的模型或訓練循環(huán)的函數
  • run_args – positional arguments for <cite>run_fn</cite>

Returns

Quantized model.

torch.quantization.prepare(model, qconfig_dict=None, inplace=False)?

為量化校準或量化意識訓練準備模型的副本。

量化配置可以作為 <cite>qconfig_dict</cite> 傳遞,也可以搶先分配給 <cite>.qconfig</cite> 屬性中的各個子模塊。

該模型將附加觀察者或偽造的 quant 模塊,并傳播 qconfig。

Parameters

  • 模型-要就地修改的輸入模型
  • qconfig_dict –從子模塊的名稱或類型映射到量化配置的字典,除非指定了子模塊的 qconfig,否則 qconfig 適用于給定模塊的所有子模塊(當子模塊已經具有 qconfig 屬性時)
  • inplace – carry out model transformations in-place, the original module is mutated

torch.quantization.prepare_qat(model, mapping=None, inplace=False)?

為量化校準或量化意識訓練準備模型的副本,并將其轉換為量化版本。

量化配置可以作為 <cite>qconfig_dict</cite> 傳遞,也可以搶先分配給 <cite>.qconfig</cite> 屬性中的各個子模塊。

Parameters

  • model – input model to be modified in-place
  • 映射 –將浮點模塊映射到要替換的量化模塊的字典。
  • 就地 –就地進行模型轉換,原始模塊已變異

torch.quantization.convert(module, mapping=None, inplace=False)?

將帶有觀察者的 float 模塊(我們可以在其中獲得量化參數)轉換為量化模塊。

Parameters

  • 模塊 –帶有觀察者的校準模塊
  • 映射 –從浮點模塊類型映射到量化模塊類型的字典,可以重寫以允許交換用戶定義的模塊
  • inplace – carry out model transformations in-place, the original module is mutated

class torch.quantization.QConfig?

描述如何通過分別提供激活和權重的設置(觀察者類)來量化網絡的一部分或一部分。

請注意,QConfig 需要包含觀察者(如 MinMaxObserver)或一個可調用的可調用對象,該可調用對象在調用時返回實例,而不是具體的觀察者實例本身。 量化準備功能將為每個層多次實例化觀察者。

觀察者類通常具有合理的默認參數,但是可以使用 <cite>with_args</cite> 方法(行為類似于 functools.partial)來覆蓋它們:

my_qconfig = QConfig(激活= MinMaxObserver.with_args(dtype = torch.qint8),權重= default_observer.with_args(dtype = torch.qint8))

class torch.quantization.QConfigDynamic?

描述如何通過提供權重設置(觀察者類別)動態(tài)量化網絡的一部分或一部分。

就像 QConfig,但用于動態(tài)量化。

請注意,QConfigDynamic 需要包含觀察者(如 MinMaxObserver)或一個可調用的可調用對象,該調用可在調用時返回實例,而不是具體的觀察者實例本身。 量化功能將為每個層多次實例化觀察者。

Observer classes have usually reasonable default arguments, but they can be overwritten with <cite>with_args</cite> method (that behaves like functools.partial):

my_qconfig = QConfigDynamic(權重= default_observer.with_args(dtype = torch.qint8))

準備量化模型

torch.quantization.fuse_modules(model, modules_to_fuse, inplace=False, fuser_func=<function fuse_known_modules>)?

將模塊列表融合到一個模塊中

僅融合以下模塊序列:

  • 轉換,bn
  • 轉換,bn,relu
  • 轉換,relu
  • 線性,相對

所有其他序列保持不變。 對于這些序列,將列表中的第一項替換為融合模塊,并將其余模塊替換為 identity。

Parameters

  • 模型 –包含要融合的模塊的模型
  • modules_to_fuse –要融合的模塊名稱列表的列表。 如果只有一個要融合的模塊列表,則也可以是字符串列表。
  • 就位 –布爾值指定是否在模型上發(fā)生融合,默認情況下會返回新模型
  • fuser_func –接收模塊列表并輸出相同長度的融合模塊列表的功能。 例如,fuser_func([convModule,BNModule])返回列表[ConvBNModule,nn.Identity()]默認為 torch.quantization.fuse_known_modules

Returns

融合模塊的模型。 如果 inplace = True,則創(chuàng)建一個新副本。

例子:

>>> m = myModel()
>>> # m is a module containing  the sub-modules below
>>> modules_to_fuse = [ ['conv1', 'bn1', 'relu1'], ['submodule.conv', 'submodule.relu']]
>>> fused_m = torch.quantization.fuse_modules(m, modules_to_fuse)
>>> output = fused_m(input)


>>> m = myModel()
>>> # Alternately provide a single list of modules to fuse
>>> modules_to_fuse = ['conv1', 'bn1', 'relu1']
>>> fused_m = torch.quantization.fuse_modules(m, modules_to_fuse)
>>> output = fused_m(input)

class torch.quantization.QuantStub(qconfig=None)?

量化存根模塊,在校準之前,與觀察者相同,將被交換為 <cite>nnq。在<cite>中將</cite>轉換為</cite>。

Parameters

qconfig -張量的量化配置,如果未提供 qconfig,我們將從父模塊獲取 qconfig

class torch.quantization.DeQuantStub?

消除存根模塊,在校準之前,它與標識相同,將交換為 <cite>nnq.DeQuantize <cite>中的</cite>轉換為</cite>。

class torch.quantization.QuantWrapper(module)?

包裝器類,用于包裝輸入模塊,添加 QuantStub 和 DeQuantStub 并將對模塊的調用與對 Quant 和 Dequant 模塊的調用包圍。

<cite>量化</cite>實用程序功能使用此函數添加量化和反量化模塊,然后<cite>轉換</cite>函數 <cite>QuantStub</cite> 只是觀察者,它觀察輸入張量,之后 <cite>轉換為</cite>, <cite>QuantStub</cite> 將交換為 <cite>nnq.Quantize</cite> 進行實際量化。 對于<cite>類似地,DeQuantStub</cite> 也是如此。

torch.quantization.add_quant_dequant(module)?

如果葉子模塊具有有效的 qconfig,則將其包裝在 QuantWrapper 中。請注意,此函數將就地修改模塊的子模塊,并且它可以返回一個新的模塊,該模塊也將輸入模塊包裝起來。

Parameters

  • 模塊 –具有所有葉子模塊的 qconfig 屬性的輸入模塊
  • 我們要量化(等于)–

Returns

使用基于 qconfig 的 <cite>QuantWrapper</cite> 中包裝有子模塊的就地修改模塊,或包裝輸入模塊的新 <cite>QuantWrapper</cite> 模塊,后一種情況僅在輸入模塊是葉模塊且 我們要量化它。

實用功能

torch.quantization.add_observer_(module)?

為模塊的葉子添加觀察者。

此函數將觀察者模塊插入具有有效 qconfig 屬性的所有葉子模塊。

Parameters

模塊 –具有要配置的所有葉子模塊的 qconfig 屬性的輸入模塊

Returns

無,通過添加觀察者模塊和 forward_hooks 來就地修改模塊

torch.quantization.swap_module(mod, mapping)?

如果模塊具有量化的對應項并且連接了<cite>觀察器</cite>,則交換該模塊。

Parameters

  • mod –輸入模塊
  • 映射 –從 nn 模塊映射到 nnq 模塊的字典

Returns

<cite>mod</cite> 的相應量化模塊

torch.quantization.propagate_qconfig_(module, qconfig_dict=None)?

通過模塊層次結構傳播 qconfig 并在每個葉子模塊上分配 <cite>qconfig</cite> 屬性

Parameters

  • 模塊 –輸入模塊
  • qconfig_dict –從子模塊的名稱或類型映射到量化配置的字典,除非指定了子模塊的 qconfig,否則 qconfig 適用于給定模塊的所有子模塊(當子模塊已經具有 qconfig 屬性時)

Returns

無,模塊已附加 qconfig 進行就地修改

torch.quantization.default_eval_fn(model, calib_data)?

默認評估函數采用 torch.utils.data.Dataset 或輸入張量列表,并在數據集上運行模型

觀察者

class torch.quantization.MinMaxObserver(dtype=torch.quint8, qscheme=torch.per_tensor_affine, reduce_range=False)?

觀察器模塊,用于基于運行的最小值和最大值來計算量化參數。

該觀察者使用張量最小/最大統(tǒng)計量來計算量化參數。 該模塊記錄輸入張量的運行最小值和最大值,并使用此統(tǒng)計信息計算量化參數。

Parameters

  • dtype –量化數據類型
  • qscheme –要使用的量化方案
  • reduce_range –將量化數據類型的范圍縮小 1 位

給定最小/最大值為imgimg,標度img和零點img計算為:

最小/最大運行時間img計算如下:

img

其中img是觀察到的張量。

然后,將比例img和零點img計算為:

img

其中imgimg是量化數據類型的最小值和最大值。

警告

僅適用于torch.per_tensor_symmetric量化方案

Warning

dtype只能使用torch.qint8torch.quint8。

Note

如果運行最小值等于運行最大值,則將 scale 和 zero_point 設置為 1.0 和 0。

class torch.quantization.MovingAverageMinMaxObserver(averaging_constant=0.01, dtype=torch.quint8, qscheme=torch.per_tensor_affine, reduce_range=False)?

觀察器模塊,用于根據最小值和最大值的移動平均值來計算量化參數。

該觀察者根據傳入張量的最小值和最大值的移動平均值來計算量化參數。 該模塊記錄輸入張量的平均最小值和最大值,并使用此統(tǒng)計信息計算量化參數。

Parameters

  • averaging_constant -最小/最大的平均常數。
  • dtype – Quantized data type
  • qscheme – Quantization scheme to be used
  • reduce_range – Reduces the range of the quantized data type by 1 bit

最小/最大移動平均值計算如下

img

其中img是運行平均最小值/最大值,img是傳入張量,imgaveraging_constant。

然后按MinMaxObserver中的比例和零點進行計算。

Note

僅適用于torch.per_tensor_affine量化模式。

Note

If the running minimum equals to the running maximum, the scale and zero_point are set to 1.0 and 0.

class torch.quantization.PerChannelMinMaxObserver(ch_axis=0, dtype=torch.quint8, qscheme=torch.per_channel_affine, reduce_range=False)?

觀察器模塊,用于基于每個通道的運行最小值和最大值來計算量化參數。

該觀察者使用張量最小/最大統(tǒng)計量來計算每個通道的量化參數。 該模塊記錄輸入張量的運行最小值和最大值,并使用此統(tǒng)計信息計算量化參數。

Parameters

  • ch_axis –通道軸
  • dtype – Quantized data type
  • qscheme – Quantization scheme to be used
  • reduce_range – Reduces the range of the quantized data type by 1 bit

量化參數的計算方法與MinMaxObserver中的計算方法相同,不同之處在于,每個通道都存儲運行的最小/最大值。 因此,每個通道也可以計算比例和零點。

Note

如果運行最小值等于運行最大值,則將 scales 和 zero_points 設置為 1.0 和 0。

class torch.quantization.MovingAveragePerChannelMinMaxObserver(averaging_constant=0.01, ch_axis=0, dtype=torch.quint8, qscheme=torch.per_channel_affine, reduce_range=False)?

Observer module for computing the quantization parameters based on the running per channel min and max values.

This observer uses the tensor min/max statistics to compute the per channel quantization parameters. The module records the running minimum and maximum of incoming tensors, and uses this statistic to compute the quantization parameters.

Parameters

  • averaging_constant – Averaging constant for min/max.
  • ch_axis – Channel axis
  • dtype – Quantized data type
  • qscheme – Quantization scheme to be used
  • reduce_range – Reduces the range of the quantized data type by 1 bit

量化參數的計算方法與MovingAverageMinMaxObserver中的計算方法相同,不同之處在于,每個通道都存儲運行的最小/最大值。 因此,每個通道也可以計算比例和零點。

Note

If the running minimum equals to the running maximum, the scales and zero_points are set to 1.0 and 0.

class torch.quantization.HistogramObserver(bins=2048, upsample_rate=128, dtype=torch.quint8, qscheme=torch.per_tensor_affine, reduce_range=False)?

該模塊記錄張量值以及最小/最大值的運行直方圖。 calculate_qparams將計算比例和 zero_point。

Parameters

  • bins –直方圖使用的 bin 數
  • upsample_rate –直方圖被上采樣的因子,用于對觀測值變化范圍內的直方圖進行插值
  • dtype – Quantized data type
  • qscheme – Quantization scheme to be used
  • reduce_range – Reduces the range of the quantized data type by 1 bit

標度和零點計算如下:

  1. Create the histogram of the incoming inputs.
    
    
    
    

直方圖是連續(xù)計算的,每個 bin 的范圍隨觀察到的每個新張量而變化。

  1. Search the distribution in the histogram for optimal min/max values.
    
    
    
    

搜索最小值/最大值可確保相對于浮點模型的量化誤差最小。

  1. Compute the scale and zero point the same way as in the
    
    
    
    

MinMaxObserver

class torch.quantization.FakeQuantize(observer=<class 'torch.quantization.observer.MovingAverageMinMaxObserver'>, quant_min=0, quant_max=255, **observer_kwargs)?

在訓練時間內模擬量化和反量化操作。 該模塊的輸出由下式給出

x_out =(鉗位(round(x / scale + zero_point),quant_min,quant_max)-zero_point)*比例

  • scale定義用于量化的比例因子。

  • zero_point指定浮點數 0 映射到的量化值

  • quant_min指定最小允許量化值。

  • quant_max指定最大允許量化值。

  • fake_quant_enable控制偽量化在張量上的應用,請注意統(tǒng)計信息仍然可以更新。

  • observer_enable控制張量的統(tǒng)計信息收集

  • dtype specifies the quantized dtype that is being emulated with fake-quantization,
    
    
    
    

允許的值為 torch.qint8 和 torch.quint8。 應該選擇 quant_min 和 quant_max 的值與 dtype 一致

Parameters

  • 觀察器(模塊)–用于觀察輸入張量的統(tǒng)計信息并計算刻度和零點的模塊。
  • quant_min (python:int )–最小允許量化值。
  • quant_max (python:int )–允許的最大量化值。
  • viewer_kwargs (可選)–觀察者模塊的參數

Variables

?FakeQuantize.observer (模塊)–用戶提供的模塊,用于收集輸入張量的統(tǒng)計信息,并提供一種計算標度和零點的方法。

class torch.quantization.NoopObserver(dtype=torch.float16)?

觀察者什么也不做,只是將其配置傳遞給量化模塊的.from_float()。

主要用于量化為 float16,不需要確定范圍。

Parameters

dtype – Quantized data type

調試工具

torch.quantization.get_observer_dict(mod, target_dict, prefix='')?

遍歷模塊并將所有觀察者保存到 dict 中。 這主要用于量化精度調試:param mod:我們要保存所有觀察者的頂層模塊:param prefix:當前模塊的前綴:param target_dict:用于保存所有觀察者的字典

class torch.quantization.RecordingObserver(**kwargs)?

該模塊主要用于調試,并在運行時記錄張量值。

Parameters

  • dtype – Quantized data type
  • qscheme – Quantization scheme to be used
  • reduce_range – Reduces the range of the quantized data type by 1 bit

torch

此模塊實現組合(融合)模塊 conv + relu,然后可以對其進行量化。

ConvBn2d

class torch.nn.intrinsic.ConvBn2d(conv, bn)?

這是一個順序容器,稱為 Conv 2d 和 Batch Norm 2d 模塊。 在量化過程中,它將被相應的融合模塊替換。

ConvBnReLU2d

class torch.nn.intrinsic.ConvBnReLU2d(conv, bn, relu)?

這是一個順序容器,稱為 Conv 2d,Batch Norm 2d 和 ReLU 模塊。 在量化過程中,它將被相應的融合模塊替換。

轉化率

class torch.nn.intrinsic.ConvReLU2d(conv, relu)?

這是一個順序容器,調用 Conv 2d 和 ReLU 模塊。 在量化過程中,它將被相應的融合模塊替換。

ConvReLU3d

class torch.nn.intrinsic.ConvReLU3d(conv, relu)?

這是一個順序容器,調用 Conv 3d 和 ReLU 模塊。 在量化過程中,它將被相應的融合模塊替換。

線性 ReLU

class torch.nn.intrinsic.LinearReLU(linear, relu)?

這是一個順序容器,調用 Linear 和 ReLU 模塊。 在量化過程中,它將被相應的融合模塊替換。

torch.nn.instrinsic.qat

該模塊實現了量化意識訓練所需的那些融合操作的版本。

ConvBn2d

class torch.nn.intrinsic.qat.ConvBn2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', eps=1e-05, momentum=0.1, freeze_bn=False, qconfig=None)?

ConvBn2d 模塊是由 Conv2d 和 BatchNorm2d 融合而成的模塊,附加了 FakeQuantize 模塊以用于輸出激活和權重,用于量化意識訓練。

我們結合了 torch.nn.Conv2dtorch.nn.BatchNorm2d 的接口。

實施細節(jié): https://arxiv.org/pdf/1806.08342.pdf 第 3.2.2 節(jié)

torch.nn.Conv2d 相似,其中 FakeQuantize 模塊已初始化為默認值。

Variables

  • ?ConvBn2d.freeze_bn
  • ?ConvBn2d.activation_post_process –用于輸出激活的偽量化模塊
  • ?ConvBn2d.weight_fake_quant –偽造的權重量化模塊

classmethod from_float(mod, qconfig=None)?

從 float 模塊或 qparams_dict 創(chuàng)建一個 qat 模塊

Args: <cite>mod</cite> 一個浮點模塊,由 torch.quantization 實用程序生成或直接從用戶獲取

ConvBnReLU2d

class torch.nn.intrinsic.qat.ConvBnReLU2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', eps=1e-05, momentum=0.1, freeze_bn=False, qconfig=None)?

ConvBnReLU2d 模塊是由 Conv2d,BatchNorm2d 和 ReLU 融合而成的模塊,附加了 FakeQuantize 模塊以用于輸出激活和權重,用于量化意識訓練。

我們組合了 torch.nn.Conv2dtorch.nn.BatchNorm2dtorch.nn.ReLU 的接口。

實施細節(jié): https://arxiv.org/pdf/1806.08342.pdf

與 <cite>torch.nn.Conv2d</cite> 相似,其中 FakeQuantize 模塊已初始化為默認值。

Variables

  • ?ConvBnReLU2d.observer –用于激活輸出的虛假量化模塊,稱為觀察員,與后期訓練流程保持一致
  • ?ConvBnReLU2d.weight_fake_quant –偽造的權重量化模塊

ConvReLU2d

class torch.nn.intrinsic.qat.ConvReLU2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', qconfig=None)?

ConvReLU2d 模塊是 Conv2d 和 ReLU 的融合模塊,附加了 FakeQuantize 模塊,用于輸出激活和權重,以進行量化感知訓練。

我們結合了 Conv2dBatchNorm2d 的接口。

Variables

  • ?ConvReLU2d.activation_post_process –用于輸出激活的偽量化模塊
  • ?ConvReLU2d.weight_fake_quant –偽造的權重量化模塊

LinearReLU

class torch.nn.intrinsic.qat.LinearReLU(in_features, out_features, bias=True, qconfig=None)?

由 Linear 和 ReLU 模塊融合而成的 LinearReLU 模塊,與 FakeQuantize 模塊相連,用于輸出激活和權重,用于量化意識訓練。

我們采用與 torch.nn.Linear 相同的接口。

與 <cite>torch.nn.intrinsic.LinearReLU</cite> 相似,其中 FakeQuantize 模塊已初始化為默認值。

Variables

  • ?LinearReLU.activation_post_process –用于輸出激活的偽量化模塊
  • ?LinearReLU.weight –偽造的權重量化模塊

Examples:

>>> m = nn.qat.LinearReLU(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30])

torch nn 本征量化

該模塊實現了諸如 conv + relu 之類的融合操作的量化實現。

ConvReLU2d

class torch.nn.intrinsic.quantized.ConvReLU2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')?

ConvReLU2d 模塊是 Conv2d 和 ReLU 的融合模塊

我們采用與 torch.nn.quantized.Conv2d 相同的接口。

Variables

as torch.nn.quantized.Conv2d (Same )–

ConvReLU3d

class torch.nn.intrinsic.quantized.ConvReLU3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')?

ConvReLU3d 模塊是 Conv3d 和 ReLU 的融合模塊

我們采用與 torch.nn.quantized.Conv3d 相同的接口。

屬性:與 torch.nn.quantized.Conv3d 相同

LinearReLU

class torch.nn.intrinsic.quantized.LinearReLU(in_features, out_features, bias=True)?

由 Linear 和 ReLU 模塊融合而成的 LinearReLU 模塊

我們采用與 torch.nn.quantized.Linear 相同的接口。

Variables

為 torch.nn.quantized.Linear (相同)–

Examples:

>>> m = nn.intrinsic.LinearReLU(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30])

torch

此模塊實現了關鍵 nn 模塊 Conv2d()Linear()的版本,這些版本在 FP32 中運行,但四舍五入以模擬 INT8 量化的效果。

轉換 2d

class torch.nn.qat.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', qconfig=None)?

隨附有 FakeQuantize 模塊的 Conv2d 模塊,用于輸出激活和權重,用于量化意識訓練。

我們采用與 <cite>torch.nn.Conv2d</cite> 相同的界面,請參閱 https://pytorch.org/docs/stable/nn.html?highlight=conv2d#torch.nn.Conv2d 獲取文檔。

Similar to <cite>torch.nn.Conv2d</cite>, with FakeQuantize modules initialized to default.

Variables

  • ?Conv2d.activation_post_process –用于輸出激活的偽量化模塊
  • ?Conv2d.weight_fake_quant –偽造的權重量化模塊

classmethod from_float(mod, qconfig=None)?

Create a qat module from a float module or qparams_dict

Args: <cite>mod</cite> a float module, either produced by torch.quantization utilities or directly from user

線性的

class torch.nn.qat.Linear(in_features, out_features, bias=True, qconfig=None)?

附帶有 FakeQuantize 模塊的線性模塊,用于輸出激活和權重,用于量化意識訓練。

我們采用與 <cite>torch.nn.Linear</cite> 相同的接口,請參閱 https://pytorch.org/docs/stable/nn.html#torch.nn.Linear 以獲取文檔。

類似于 <cite>torch.nn.Linear</cite> ,其中 FakeQuantize 模塊已初始化為默認值。

Variables

  • ?Linear.activation_post_process –用于輸出激活的偽量化模塊
  • ?Linear.weight –偽造的權重量化模塊

classmethod from_float(mod, qconfig=None)?

Create a qat module from a float module or qparams_dict

Args: <cite>mod</cite> a float module, either produced by torch.quantization utilities or directly from user

torch量化

此模塊實現 nn 層的量化版本,例如 Conv2dReLU

功能界面

功能界面(已量化)。

torch.nn.quantized.functional.relu(input, inplace=False) → Tensor?

按元素應用整流線性單位函數。 有關更多詳細信息,請參見 ReLU

Parameters

  • 輸入 –量化輸入
  • 就地 –就地執(zhí)行計算

torch.nn.quantized.functional.linear(input, weight, bias=None, scale=None, zero_point=None)?

對輸入的量化數據進行線性變換:img。 參見 Linear

Note

當前的實現在每個調用中都包含權重,這會降低性能。 如果要避免開銷,請使用 Linear 。

Parameters

  • 輸入 (tensor)–類型為 <cite>Torch.quint8</cite> 的量化輸入
  • 重量 (tensor)–類型 <cite>Torch.qint8</cite> 的量化重量
  • 偏差 (tensor)–類型為 <cite>Torch.float</cite> 的無或 fp32 偏差。
  • 標度()–輸出標度。 如果為無,則從輸入比例得出
  • zero_point (python:long )–輸出零點。 如果為 None,則從輸入 zero_point 派生

Shape:

  • 輸入:img其中 <cite>*</cite> 表示任意數量的附加尺寸
  • 重量:img
  • 偏差:img
  • 輸出:img

torch.nn.quantized.functional.conv2d(input, weight, bias, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', scale=1.0, zero_point=0, dtype=torch.quint8)?

在由多個輸入平面組成的量化 2D 輸入上應用 2D 卷積。

有關詳細信息和輸出形狀,請參見 Conv2d 。

Parameters

  • 輸入 –形狀為img的量化輸入張量
  • 權重 –形狀為img的量化濾波器
  • 偏置非量化的形狀為img的偏置張量。 張量類型必須為 <cite>torch.float</cite> 。
  • 步幅 –卷積內核的步幅。 可以是單個數字或元組<cite>(sH,sW)</cite>。 默認值:1
  • 填充 –輸入兩側的隱式填充。 可以是單個數字或元組<cite>(padH,padW)</cite>。 默認值:0
  • 膨脹 –內核元素之間的間距。 可以是單個數字或元組<cite>(dH,dW)</cite>。 默認值:1
  • –將輸入分成組,img應該可被組數整除。 默認值:1
  • padding_mode –要使用的填充模式。 目前僅對量化卷積支持“零”。 默認值:“零”
  • 標度 –輸出的量化標度。 默認值:1.0
  • zero_point -輸出的量化 zero_point。 默認值:0
  • dtype –要使用的量化數據類型。 默認值:torch.quint8

Examples:

>>> from torch.nn.quantized import functional as qF
>>> filters = torch.randn(8, 4, 3, 3, dtype=torch.float)
>>> inputs = torch.randn(1, 4, 5, 5, dtype=torch.float)
>>> bias = torch.randn(4, dtype=torch.float)
>>>
>>> scale, zero_point = 1.0, 0
>>> dtype = torch.quint8
>>>
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype)
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype)
>>> qF.conv2d(q_inputs, q_filters, bias, scale, zero_point, padding=1)

torch.nn.quantized.functional.conv3d(input, weight, bias, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', scale=1.0, zero_point=0, dtype=torch.quint8)?

在由多個輸入平面組成的量化 3D 輸入上應用 3D 卷積。

有關詳細信息和輸出形狀,請參見 Conv3d 。

Parameters

  • 輸入 –形狀為img的量化輸入張量
  • 權重 –形狀為img的量化濾波器
  • 偏置非量化的形狀為img的偏置張量。 張量類型必須為 <cite>torch.float</cite> 。
  • 步幅 –卷積內核的步幅。 可以是單個數字或元組<cite>(sD,sH,sW)</cite>。 默認值:1
  • 填充 –輸入兩側的隱式填充。 可以是單個數字或元組<cite>(padD,padH,padW)</cite>。 默認值:0
  • 膨脹 –內核元素之間的間距。 可以是單個數字或元組<cite>(dD,dH,dW)</cite>。 默認值:1
  • –將輸入分成組,img應該可被組數整除。 默認值:1
  • padding_mode –要使用的填充模式。 目前僅對量化卷積支持“零”。 默認值:“零”
  • scale – quantization scale for the output. Default: 1.0
  • zero_point – quantization zero_point for the output. Default: 0
  • dtype – quantization data type to use. Default: torch.quint8

Examples:

>>> from torch.nn.quantized import functional as qF
>>> filters = torch.randn(8, 4, 3, 3, 3, dtype=torch.float)
>>> inputs = torch.randn(1, 4, 5, 5, 5, dtype=torch.float)
>>> bias = torch.randn(4, dtype=torch.float)
>>>
>>> scale, zero_point = 1.0, 0
>>> dtype = torch.quint8
>>>
>>> q_filters = torch.quantize_per_tensor(filters, scale, zero_point, dtype)
>>> q_inputs = torch.quantize_per_tensor(inputs, scale, zero_point, dtype)
>>> qF.conv3d(q_inputs, q_filters, bias, scale, zero_point, padding=1)

torch.nn.quantized.functional.max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)?

在由幾個量化輸入平面組成的量化輸入信號上應用 2D max 合并。

Note

輸入量化參數傳播到輸出。

有關詳細信息,請參見MaxPool2d。

torch.nn.quantized.functional.adaptive_avg_pool2d(input, output_size)?

在由幾個量化輸入平面組成的量化輸入信號上應用 2D 自適應平均池。

Note

輸入量化參數傳播到輸出。

有關詳細信息和輸出形狀,請參見AdaptiveAvgPool2d。

Parameters

output_size –目標輸出大小(單整數或雙整數元組)

torch.nn.quantized.functional.avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None)?

以步長img步長在img區(qū)域中應用 2D 平均合并操作。 輸出要素的數量等于輸入平面的數量。

Note

輸入量化參數傳播到輸出。

有關詳細信息和輸出形狀,請參見AvgPool2d。

Parameters

  • 輸入 –量化輸入張量img
  • kernel_size –池區(qū)域的大小。 可以是單個數字或元組<cite>(kH,kW)</cite>
  • 跨度 –合并操作的跨度。 可以是單個數字或元組<cite>(sH,sW)</cite>。 默認值:kernel_size
  • 填充 –輸入兩側的隱式零填充。 可以是單個數字或元組<cite>(padH,padW)</cite>。 默認值:0
  • ceil_mode –為 True 時,將在公式中使用 <cite>ceil</cite> 而不是 <cite>floor</cite> 計算輸出形狀。 默認值:False
  • count_include_pad –為 True 時,將在平均計算中包括零填充。 默認值:True
  • divisor_override –如果指定,它將用作除數,否則將使用池化區(qū)域的大小。 默認值:無

torch.nn.quantized.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', align_corners=None)?

向下/向上采樣輸入給定size或給定scale_factor的輸入

有關實現的詳細信息,請參見 torch.nn.functional.interpolate()

輸入尺寸以以下形式解釋:<cite>微型批處理 x 通道 x [可選深度] x [可選高度] x 寬度</cite>。

Note

The input quantization parameters propagate to the output.

Note

量化輸入僅支持 2D 輸入

Note

量化輸入僅支持以下模式:

  • <cite>雙線性</cite>
  • <cite>最近的</cite>

Parameters

  • 輸入 (tensor)–輸入張量
  • 大小 (python:int 元組 [ python:int ]或 元組 [ python:int python:int ]或 元組 [ python:int , python:int , python:int ] )–輸出空間大小。
  • scale_factor (python:float 元組 [ python:float ] )–空間大小的乘數。 如果是元組,則必須匹配輸入大小。
  • 模式 (str )–用于上采樣的算法:'nearest' | 'bilinear'
  • align_corners (布爾 , 可選)–在幾何上,我們將輸入和輸出的像素視為正方形而不是點。 如果設置為True,則輸入和輸出張量將按其角點像素的中心對齊,并保留角點像素處的值。 如果設置為False,則輸入和輸出張量按其角點像素的角點對齊,并且插值對邊界值使用邊緣值填充,從而使此操作獨立于輸入 scale_factor保持相同時的尺寸。 僅當mode'bilinear'時才有效。 默認值:False

torch.nn.quantized.functional.upsample(input, size=None, scale_factor=None, mode='nearest', align_corners=None)?

將輸入上采樣到給定的size或給定的scale_factor

Warning

不推薦使用此功能,而推薦使用 torch.nn.quantized.functional.interpolate() 。 與nn.quantized.functional.interpolate(...)等效。

See torch.nn.functional.interpolate() for implementation details.

The input dimensions are interpreted in the form: <cite>mini-batch x channels x [optional depth] x [optional height] x width</cite>.

Note

The input quantization parameters propagate to the output.

Note

Only 2D input is supported for quantized inputs

Note

Only the following modes are supported for the quantized inputs:

  • <cite>bilinear</cite>
  • <cite>nearest</cite>

Parameters

  • 輸入 (tensor)–量化輸入張量
  • size (python:int or Tuple[python:int__] or Tuple[python:int__, python:int__] or Tuple[python:int__, python:int__, python:int__]) – output spatial size.
  • scale_factor (python:float 元組 [ python:float ] )–空間大小的乘數。 必須是整數。
  • 模式(字符串)–用于上采樣的算法:'nearest' | 'bilinear'
  • align_corners (bool__, optional) – Geometrically, we consider the pixels of the input and output as squares rather than points. If set to True, the input and output tensors are aligned by the center points of their corner pixels, preserving the values at the corner pixels. If set to False, the input and output tensors are aligned by the corner points of their corner pixels, and the interpolation uses edge value padding for out-of-boundary values, making this operation independent of input size when scale_factor is kept the same. This only has an effect when mode is 'bilinear'. Default: False

Warning

使用align_corners = True時,線性插值模式(<cite>雙線性</cite>)不會按比例對齊輸出像素和輸入像素,因此輸出值可能取決于輸入大小。 這是這些模式(0.3.1 版之前)的默認行為。 從那時起,默認行為是align_corners = False。 有關如何影響輸出的具體示例,請參見 Upsample 。

torch.nn.quantized.functional.upsample_bilinear(input, size=None, scale_factor=None)?

使用雙線性上采樣對輸入進行上采樣。

Warning

不推薦使用此功能,而推薦使用 torch.nn.quantized.functional.interpolate() 。 與nn.quantized.functional.interpolate(..., mode='bilinear', align_corners=True)等效。

Note

The input quantization parameters propagate to the output.

Note

僅支持 2D 輸入

Parameters

  • 輸入 (tensor)–量化輸入
  • 大小 (python:int 元組 [ python:int , python:int ] )–輸出空間大小。
  • scale_factor (python:int 元組 [ python:int , python:int ] )–空間大小的乘數

torch.nn.quantized.functional.upsample_nearest(input, size=None, scale_factor=None)?

使用最近鄰的像素值對輸入進行上采樣。

Warning

不推薦使用此功能,而推薦使用 torch.nn.quantized.functional.interpolate() 。 與nn.quantized.functional.interpolate(..., mode='nearest')等效。

Note

The input quantization parameters propagate to the output.

Note

Only 2D inputs are supported

Parameters

  • input (Tensor) – quantized input
  • 大小 (python:int 元組 [ python:int python:int ]或 元組 [ python:int , python:int python:int ] )–輸出空間大小。
  • scale_factor (python:int )–空間大小的乘數。 必須是整數。

ReLU

class torch.nn.quantized.ReLU(inplace=False)?

按元素應用量化整流線性單位函數:

img,其中img是零點。

有關 ReLU 的更多文檔,請參見 https://pytorch.org/docs/stable/nn.html#torch.nn.ReLU

Parameters

就地 –(當前不支持)可以選擇就地進行操作。

Shape:

  • 輸入:img其中 <cite>*</cite> 表示任意數量的附加尺寸
  • 輸出:img,形狀與輸入相同

Examples:

>>> m = nn.quantized.ReLU()
>>> input = torch.randn(2)
>>> input = torch.quantize_per_tensor(input, 1.0, 0, dtype=torch.qint32)
>>> output = m(input)

ReLU6

class torch.nn.quantized.ReLU6(inplace=False)?

應用逐元素函數:

img,其中img是 zero_point,img是數字 6 的量化表示。

Parameters

就地 –可以選擇就地進行操作。 默認值:False

Shape:

  • Input: img where <cite>*</cite> means, any number of additional dimensions
  • Output: img, same shape as the input

_images/ReLU6.png

Examples:

>>> m = nn.quantized.ReLU6()
>>> input = torch.randn(2)
>>> input = torch.quantize_per_tensor(input, 1.0, 0, dtype=torch.qint32)
>>> output = m(input)

Conv2d

class torch.nn.quantized.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')?

在由多個量化輸入平面組成的量化輸入信號上應用 2D 卷積。

有關輸入參數,參數和實現的詳細信息,請參見 Conv2d 。

Note

padding_mode參數僅支持<cite>零</cite>。

Note

輸入數據類型僅支持 <cite>torch.quint8</cite> 。

Variables```


- **?Conv2d.weight** (*tensor*)–從可學習的權重參數得出的壓縮張量。
- **?Conv2d.scale** (*tensor*)–輸出比例的標量
- **?Conv2d.zero_point** (*tensor*)–輸出零點的標量


有關其他屬性,請參見 `Conv2d` 。


Examples:

&& # With square kernels and equal stride
&& m = nn.quantized.Conv2d(16, 33, 3, stride=2)
&& # non-square kernels and unequal stride and with padding
&& m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
&& # non-square kernels and unequal stride and with padding and dilation
&& m = nn.quantized.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
&& input = torch.randn(20, 16, 50, 100)
&& # quantize input to qint8
&& q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.qint32)
&& output = m(input)
```

classmethod from_float(mod)?

從 float 模塊或 qparams_dict 創(chuàng)建量化模塊。

Parameters

mod (模塊)–浮點模塊,由 Torch.quantization 實用程序生產或由用戶提供

轉換 3d

class torch.nn.quantized.Conv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')?

在由幾個量化輸入平面組成的量化輸入信號上應用 3D 卷積。

有關輸入參數,參數和實現的詳細信息,請參見 Conv3d 。

Note

Only <cite>zeros</cite> is supported for the padding_mode argument.

Note

Only <cite>torch.quint8</cite> is supported for the input data type.

Variables

  • ?Conv3d.weight (tensor)–從可學習的重量參數得出的壓縮張量。
  • ?Conv3d.scale (tensor)–輸出比例的標量
  • ?Conv3d.zero_point (tensor)–輸出零點的標量

有關其他屬性,請參見 Conv3d

Examples:

>>> # With square kernels and equal stride
>>> m = nn.quantized.Conv3d(16, 33, 3, stride=2)
>>> # non-square kernels and unequal stride and with padding
>>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2))
>>> # non-square kernels and unequal stride and with padding and dilation
>>> m = nn.quantized.Conv3d(16, 33, (3, 5, 5), stride=(1, 2, 2), padding=(1, 2, 2), dilation=(1, 2, 2))
>>> input = torch.randn(20, 16, 56, 56, 56)
>>> # quantize input to qint8
>>> q_input = torch.quantize_per_tensor(input, scale=1.0, zero_point=0, dtype=torch.qint32)
>>> output = m(input)

classmethod from_float(mod)?

Creates a quantized module from a float module or qparams_dict.

Parameters

mod (Module) – a float module, either produced by torch.quantization utilities or provided by the user

浮動功能

class torch.nn.quantized.FloatFunctional?

浮點運算符的狀態(tài)收集器類。

在某些操作中,可以使用此類的實例代替torch.前綴。 請參閱下面的示例用法。

Note

此類不提供forward掛鉤。 相反,您必須使用基礎功能之一(例如add)。

Examples:

>>> f_add = FloatFunctional()
>>> a = torch.tensor(3.0)
>>> b = torch.tensor(4.0)
>>> f_add.add(a, b)  # Equivalent to ``torch.add(3, 4)

Valid operation names:

  • add_relu
  • add_scalar
  • mul_scalar

Q 功能

class torch.nn.quantized.QFunctional?

量化運算符的包裝器類。

可以使用此類的實例代替torch.ops.quantized前綴。 請參閱下面的示例用法。

Note

This class does not provide a forward hook. Instead, you must use one of the underlying functions (e.g. add).

Examples:

>>> q_add = QFunctional('add')
>>> a = torch.quantize_per_tensor(torch.tensor(3.0), 1.0, 0, torch.qint32)
>>> b = torch.quantize_per_tensor(torch.tensor(4.0), 1.0, 0, torch.qint32)
>>> q_add.add(a, b)  # Equivalent to ``torch.ops.quantized.add(3, 4)

Valid operation names:

  • add
  • cat
  • mul
  • add_relu
  • add_scalar
  • mul_scalar

量化

class torch.nn.quantized.Quantize(scale, zero_point, dtype)?

量化傳入張量

Parameters

  • 標度 –輸出量化張量的標度
  • zero_point –輸出量化張量的 zero_point
  • dtype –輸出量化張量的數據類型

Variables

zero_point,dtype (scale )–

Examples::

>>> t = torch.tensor([[1., -1.], [1., -1.]])
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
>>> qm = Quantize(scale, zero_point, dtype)
>>> qt = qm(t)
>>> print(qt)
tensor([[ 1., -1.],
        [ 1., -1.]], size=(2, 2), dtype=torch.qint8, scale=1.0, zero_point=2)

解量化

class torch.nn.quantized.DeQuantize?

使進入的張量均衡化

Examples::

>>> input = torch.tensor([[1., -1.], [1., -1.]])
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
>>> qm = Quantize(scale, zero_point, dtype)
>>> quantized_input = qm(input)
>>> dqm = DeQuantize()
>>> dequantized = dqm(quantized_input)
>>> print(dequantized)
tensor([[ 1., -1.],
        [ 1., -1.]], dtype=torch.float32)

Linear

class torch.nn.quantized.Linear(in_features, out_features, bias_=True)?

具有量化張量作為輸入和輸出的量化線性模塊。 我們采用與 <cite>torch.nn.Linear</cite> 相同的接口,請參閱 https://pytorch.org/docs/stable/nn.html#torch.nn.Linear 以獲取文檔。

Linear 類似,屬性將在模塊創(chuàng)建時隨機初始化,稍后將被覆蓋

Variables

  • ?線性權重 (tensor)–形狀為img的模塊的不可學習的量化權重。
  • ?線性偏差 (tensor)–形狀為img的模塊的不可學習的偏差。 如果biasTrue,則值將初始化為零。
  • ?線性比例 – <cite>比例</cite>輸出量化張量的參數,類型:double
  • ?Linear.zero_point – <cite>zero_point</cite> 輸出量化張量的參數,類型:long

Examples:

>>> m = nn.quantized.Linear(20, 30)
>>> input = torch.randn(128, 20)
>>> input = torch.quantize_per_tensor(input, 1.0, 0, torch.quint8)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30])

classmethod from_float(mod)?

從 float 模塊或 qparams_dict 創(chuàng)建量化模塊

Parameters

mod (Module) – a float module, either produced by torch.quantization utilities or provided by the user

torch量化的動態(tài)

Linear

class torch.nn.quantized.dynamic.Linear(in_features, out_features, bias_=True)?

具有量化張量作為輸入和輸出的動態(tài)量化線性模塊。 我們采用與 <cite>torch.nn.Linear</cite> 相同的接口,請參閱 https://pytorch.org/docs/stable/nn.html#torch.nn.Linear 以獲取文檔。

torch.nn.Linear 類似,屬性將在模塊創(chuàng)建時隨機初始化,稍后將被覆蓋

Variables

  • ?線性權重 (tensor)–形狀為img的模塊的不可學習的量化權重。
  • ~Linear.bias (Tensor) – the non-learnable bias of the module of shape img. If bias is True, the values are initialized to zero.

Examples:

>>> m = nn.quantized.dynamic.Linear(20, 30)
>>> input = torch.randn(128, 20)
>>> output = m(input)
>>> print(output.size())
torch.Size([128, 30])

classmethod from_float(mod)?

從 float 模塊或 qparams_dict 創(chuàng)建動態(tài)量化模塊

Parameters

mod (Module) – a float module, either produced by torch.quantization utilities or provided by the user

LSTM

class torch.nn.quantized.dynamic.LSTM(*args, **kwargs)?
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號