[간단리뷰 2주차] Model Quantization Papers

선정논문

  • Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference, 2017
  • Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation, 2020

Integer Quantization for Deep Learning Inference: Principles and Empirical Evaluation

Part 2.1 – Related Works

Part 2.2 – Known Facts / Miscellaneous

  • 처음/마지막 레이어는 Quantization하지 않음 (Quantization에 민감함)
  • Quantization에는 Uniform, Non-uniform Quantization이 있음
  • LSTM, RNN에서 적용했을 때 PTQ 방식이 더 성과가 있었음
  • MobileNetV2에서도 마찬가지로 PTQ 방식에서 성과가 있었음
  • KL-Divergence 문제를 해결하여 Quantization range를 결정하는 방식도 있음
  • So on… (논문 참조)

Part 3 – Fundementals

균일(Uniform) 양자화를 이용하여 Float-range의 값을 Integer-range의 값으로, 아래 총 두 단계에 걸쳐서 Mapping을 진행합니다.
1단계로 양자화를 할 실수(Float)의 범위(=Activation range)를 지정하고, 이외의 값은 Clamp(최대/최소값 고정)를 수행합니다.
2단계로 실수-정수 매핑을 수행합니다. 양자화를 수행할 때 가장 가까운 실수와 매핑합니다(Mapping real value to the cloest integer value).

  • Quantize: 실수→양자회된 정수 표현 (fp32→int8)
  • Dequantize: 양자화된 정수→실수 표현 (int8→fp32)
  • Range Mapping: f(x)=s*x+z 의 형태로 실수(x)를 정수 공간으로 매핑합니다. 이를 Affine Quantization 방식이라고 하며, z=0인 특수한 경우를 Scale Quantization 방식이라고 합니다.
(1)은 Scale factor “s”를, (2)는 Zero-point “z”를 의미한다.

z의 경우 영점(0)을 의미하는데, 어떤 정수 값이 실수 0에 매핑되는지를 결정합니다. 실수의 0에 해당하는 값을 보정하는 역할을 합니다.

(3)은 Quantization operation 상에서 실수를 정수로 Mapping하는 과정을, (4)는 전체 과정을 나타낸다.

전체 Quantization 과정은 (4)와 같습니다. round()는 실수를 가장 가까운 정수로 매핑합니다. 이렇게 양자화된 값을, 반대로 역양자화(Dequantize)하여 해당하는 실수값과의 차이를 계산할 수 있습니다.

(5)는 Dequantization 과정을 나타낸다.

Scale Quantization의 경우 “z”값 없이 scale만을 quantize합니다. 영점이 이동하지 않으므로 z를 구해주거나 더해주는 연산이 줄어들게 됩니다. 보통 Symmetric Quantization이라고도 하는데, 실수공간과 정수공간이 동일하게 0을 중심으로 하게 됩니다. 논문에서는 signed int8 type을 이용하여, Symmetric(대칭크기)을 위해 -128을 제외하고 -127~127까지를 사용합니다.

(6)에서는 (1)과 마찬가지로 Scale을 정의하며, (7)에서는 전체 Quantization Process를 나타낸다.

여기서 Dequantization에 사용되는 수식은 아래와 같습니다.

(8)은 Scale Quantization의 Dequantization을 의미한다.
  • Tensor Quantization Granularity: Tensor Quantization에서 parameter (s, z 또는 s)를 어떤 context까지 사용할 것인지를 의미합니다. 예로, Finest granularity는 Element-wise로 parameter를 가질 것이며, Intermediate granularity는 Tensor의 Dimension-wise로 parameter를 가질 것입니다 (같은 Dimension이라면 같은 Parameter를 가짐).
    → Granularity를 결정하는 Factor: Model Accuracy Impact Factor, Computational Cost
    …TBR
  • Computational Cost of Affine Quantization
Affine Quantization을 GEMM으로 확장하여 풀어쓴 식

Affine Quantization을 MatMul으로 개념을 확장하여 풀어서 쓰면 (11)과 같습니다. 이 때, MAdd 연산을 총 3개로 분할할 수 있습니다. (1)은 Int8(Activation Map)*Int8(Weight) 연산이며, (2)는 Zero-point multiplication 연산입니다. bias 역시 weight의 일부이므로 여기에 포함됩니다. (1)의 경우 필수적이며, (2)의 경우 각 term이 weight와 zero point로만 이루어져 있으므로 선계산(compute offline)하여 Inference time을 줄일 수 있습니다. 다만 마지막 (3) term의 경우 입력 Activation과 Zero point의 multiplication 연산이므로, Extra cost를 유발합니다.
→ Zero-point를 고려하기에는 Computational Cost가 높아져 버리는 효과를 발생함

따라서, 논문은 되도록이면 Scale quantization을 사용할 것을 권장합니다. 또한 논문의 실험에 따르면 모든 네트워크가 INT8 Quantization task에서는 Scale quantization만으로도 충분하다고 합니다.

  • Calibration: 입력값범위(alpha, beta)를 찾는 과정입니다. 이 값은 Activation map(입력 레이어)의 값들의 범위를 한정하는 역할을 합니다. 다만 Scale quantization에서는 이 범위가 Symmetric이므로, 값이 alpha=beta로 한정됩니다. 찾는 방식은 {Max, Entropy, Percentile}이 있습니다.
    (물론 Activation 값들을 나열할 때는 Absolute Value로 나열될 것입니다.)
    • Max: 보여진 값들 중 가장 큰 값
    • Entropy: Quantization을 진행할 때 표현되는 값들의 정보손실이 최소화되는 KL-Divergence를 수행하여, 해당 값을 취합니다. TensorRT에서는 이 방식이 기본적으로 사용된다고 합니다.
    • Percentile: n%의 값들을 취하고, 나머지 (100-n)%에 해당하는 값들은 Clip해버립니다.

Part 4 – Post Training Quantization

…TBR

  • Weight Quantizationn
  • Activation Quantization

Part 5 – Techniques to Recover Accuracy

…TBR

  • Partial Quantization
  • Quantization-Aware Training (QAT): …TBR
  • Learning Quantization Parameters

Part 6 – Recommended Workflow

TBR…

Part 7 – Conclusion

TBR…

[간단리뷰 1주차] MobileNetV2: Inverted Residuals and Linear Bottlenecks

  • 원문: https://arxiv.org/abs/1801.04381
  • 참고자료: 논문, 블로그
  • 대분야: Optimization
  • 소분야: Model Optimization, TBD …
  • 제안 기법
    • TBD
  • 키워드: TBD

MobileNet V1 돌아보기 (간단요약)

  • 문제제기: Robotics, Self-driving car, Augmented Reality 등 실시간 처리가 필요한 분야에서는 낮은 컴퓨팅 성능으로 정확한 결과를 요구함
  • 제안사항: 경량화 CNN과 speed-accuracy tradeoff를 조절하는 Hyperparameter 제안
    • Depthwise Separable-Convolution
    • width/resolution multiplier
  • 결과 1 – Depthwise Separable Convolution으로 Full-Convolution의 계산량을 약 85% 줄임
    (ImageNet 기준 Accuracy는 1.1%p 감소)
  • 결과 2 – 모델 구성에 따라 41~569 mAddsMillion Multiply-Adds (0.5~4.2 Million parameters)로 구성이 가능 → Flexible하게 모델 크기를 구성할 수 있도록 선택지를 제공 but 이에 따른 accuracy 차이가 존재
  • 결과 3 – MobileNet 구조를 사용한 Object Detector 모델에서 낮은 연산량 대비 준수한 성능을 보여주고 있음

MobileNet V2

  • 문제제기
    • SOTA 네트워크가 요구하는 컴퓨팅 성능이 높아 모바일, 임베디드에 적용이 불가능합니다.
    • ReLU Activation의 비선형성 효과로 인해, 정보(manifold)가 손실됩니다.
      → 채널 수가 충분히 많아야 정보를 보존할 수 있습니다.
  • 제안
    • Depthwise Separable Convolution (MobileNet V1)
  • Linear Bottlenecks
    • ReLU Activation은 채널 내의 정보를 불가피하게 손실됩니다.
    • 채널 내에서의 정보는 손실되지만, 여러 채널 사이에서 Input Manifold로부터 임베딩된 정보(Manifold of Interest)를 얻을 수 있다고 합니다.
  • Inverted Residual
    • Bottleneck 블록은 모든 입력이 Bottleneck-Expansion 뒤에 따라오는 형태의 Residual Block과 형태가 비슷합니다.
    • 기존에 제안된 Residual Block에 Linear Bottleneck 형태를 붙인 형태

[Tutorial] Building lastest raspberry pi kernel for 64-bit Ubuntu (20.10)

One of the great parts about running Ubuntu is that just about all the Ubuntu-isms you’ve learned for other platforms work here too. Start with these links:

https://wiki.ubuntu.com/Kernel/BuildYourOwnKernel
https://wiki.ubuntu.com/KernelTeam/ARMK … ossCompile
https://wiki.ubuntu.com/KernelTeam/Kern … k_failures
https://askubuntu.com/questions/500095/ … er-version
https://bugs.launchpad.net/ubuntu/+sour … ug/1701756

What follows isn’t very polished, since came out of my notebook verbatim. This is how I built the kernel.

First uncomment the relevant line int /etc/apt/sources.list:

deb-src http://ports.ubuntu.com/ubuntu-ports focal-updates main restricted

Update the package database:

apt update

Get the kernel source package, as root in some place where you want it. Alternatively replace $(uname -r) with the version you want. This is probably easiest to do on the target:

apt-get source linux-image-$(uname -r)

If this is on a target, copy it to a dev machine.

Over on the dev machine, hack up your kernel as you please. Then in debian.raspi/changelog, edit the first version number from something like this:

linux-raspi (5.4.0-1019.21) focal; urgency=medium

to something like this:

linux-raspi (5.4.0-1019.21+g34950~20200925) focal; urgency=medium

Note that CONFIG_LOCALVERSION will break the Ubuntu scripts, and EXTRAVERSION in the highest level makefile doesn’t do anything interesting.

Set some environment variables:

export $(dpkg-architecture -aarm64); export CROSS_COMPILE=aarch64-linux-gnu-

Now change into the root directory of the source tree and clean the build area:

fakeroot debian/rules clean

Kick off a menuconfig session with script:

fakeroot debian/rules editconfigs

menuconfig insists on running once each for 32 and 64 bit builds of kernel.

Now build the kernel and associated packages. We skip checks that are likely to break because of a changed list of modules:

fakeroot debian/rules binary skipmodule=true skipabi=true

This will result in the following .deb packages being created in the level ABOVE the kernel source tree:

linux-buildinfo-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
linux-headers-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
linux-image-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
linux-modules-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
linux-raspi-headers-5.4.0-1019_5.4.0-1019.21+g34950~20200925_arm64.deb

After copying to the target, each of the relevant packages may be installed there with dpkg:

dpkg -i linux-headers-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
dpkg -i linux-image-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
dpkg -i linux-modules-5.4.0-1019-raspi_5.4.0-1019.21+g34950~20200925_arm64.deb
dpkg -i linux-raspi-headers-5.4.0-1019_5.4.0-1019.21+g34950~20200925_arm64.deb

[베이스리뷰 2주차] 간단정리 – Pyramid Attention Network

  • 원문: https://arxiv.org/abs/1805.10180
  • 참고자료: 논문요약
  • 대분야: Image Segmentation
  • 소분야: Semantic Segmentation, Network Hierarchy
  • 키워드: PAN (Pyramid Attention Network), GAU (Global Attention Upsample)

문제점

FCN의 경우 작은 객체부분이 손상되어 있다.

[1] 공간해상도 손실 (Spatial resolution loss)

작은 객체 부분 Segmentation 정확도가 낮습니다. 다중 스케일 상에서 객체들의 카테고리를 결정하는데 문제가 있어 SPP나 ASPP를 사용하게 됩니다.

Part Ⅶ. Semantic Segmentation] 6. DeepLab [1] - 라온피플 머신러닝 아카데미 - : 네이버 블로그
그리드 모양의 Artifact

다만 이렇게 하면, 그리드 모양의 Artifact를 만들어 버린다는 단점이 있습니다. 논문에서는 이러한 단점을 보완하여 CNN의 출력으로부터 High-level feature의 Pixel-level attention을 추출하는 FPA(Feature Pyramid Attention)을 제안합니다.

[2] Segmentation Detail 손실 (Weak in restructuring original resolution binary prediction)

최상단의 그림에서 볼 수 있듯이, FCN의 경우 Segmetnation의 결과가 sharp하지 않습니다. 자전거의 핸들은 아예 없어져 있습니다. 이러한 문제는 U-Net 구조를 이용하거나 Kernel을 크게 접으면 어느정도 해결된다고 알려져 있습니다(논문 참조). 다만 연산량이 많아지는 문제가 있습니다. 이러한 문제를 논문에서는 GAU(Global Attention Upsample)모듈을 제안하고 이 모듈에서 global context를 추출하였습니다. 다른 방식들보다 연산량이 적다고 합니다. VOC2012 Cityscapes에서 SOTA를 달성했다고 합니다.

제안요소

Feature Pyramid Attention (FPA) Module

네트워크는 인코더-디코더 아키텍쳐로 구성되어 있습니다. Res-5까지 거쳐서 인코딩된 결과가 Feature Pyramid를 통과해 Attention을 받아(?), 원본 크기로 다시 커지게 됩니다. 파란색 선이 Downsampling, 빨간색 선이 Upsampling입니다.

  • 참고: Spatial Pyramid Pooling
  • 특징
    • Feature Pyramid Network와 비슷한 구성
    • 3개의 스케일을 이용하여 U-Shape structure 구성
    • Feature 자체가 작아서, 커널 크기를 크게 해도 (e.g. 7×7) 계산량이 매우 커지지는 않음

Global Attention Upsample (GAU) Module

Decoder단에서의 성능을 끌어올리기 위해 PSPNet이나 DeepLab에 사용된 Bilinear 방식과, DUC에서 사용된 One-step decoder module에서의 문제점을 지적하였습니다. GAU에서는 Decoder에서의 Upsampling 시, Low-level feature과 High-level feature를 동시에 볼 수 있는 방식을 고안하였습니다. (마찬가지로, 빨간색이 Upsampling입니다.)

성능

SE는 SENet Attention Module을, C333/C357은 각각 커널 사이즈 3-3-3과 3-5-7의 Feature Pyramid Attention Module의 사용을 나타냅니다. MAX와 AVE는 각각 Max Pooling, Average Pooling을 나타내며 GP는 Global Pooling Branch (FPA 상단)를 나타냅니다.

[베이스리뷰 2주차] 간단정리 – SPP (Spatial Pyramid Pooling)

  • SPP: Fast R-CNN에서 참고한 개념. SPPNet에서 제안
  • 요약: Conv Layer에서는 사실 Resolution이 문제되지 않으나, 마지막 FC Layer의 입력 Size는 고정입니다. 이로 인해 Input Image는 무조건 같은 크기로 Resizing해서 모델에 입력해야하는 제약 조건이 생겨나게 되었는데, SPP는 이를 같은 크기의 Feature로 조절해주는 Pooling을 제안합니다.

알고리즘

  1. Input Feature Map을, 미리 정해진 영역 (4×4, 2×2, 1×1 등)으로 분할합니다. 이 때, 분할한 각 영역을 Pyramid라고 합니다.
  2. 여기서는 Pyramid의 갯수가 3개입니다. 이 때 피라미드 내 한 칸(하나의 cell)을 bin이라고 합니다.
  3. 실제 Feature의 크기보다 bin이 더 큰 영역을 나타냅니다. Feature의 각 bin에 해당하는 부분에서 MaxPooling을 수행합니다.
  4. 결과 bin을 Flatten하여 이어붙입니다.
  5. 결과적으로 bin의 갯수는 동일하므로, FC-Layer의 입력은 항상 동일한 값이 됩니다!

[베이스리뷰 1주차] 간단정리 – CRF(Conditional Random Fields)

CRF란?

  • 영상보다는 자연어처리 분야에서 많이 사용되는 통계적 모델링 기법입니다.
  • 사진 하나의 행동을 분류할 때, 하나의 행동 Sequence만을 보고 판단하지 않고 사진을 찍은 순간의 이전/이후를 참조하여 지금 상태를 결정합니다.

[베이스리뷰 1주차] DeepLab V1 “Semantic Image Segmentation With Deep Convolutional Nets And Fully Connected CRFs”

  • 원문: https://arxiv.org/abs/1412.7062
  • 참고자료: 라온피플 블로그
  • 대분야: Image Segmentation
  • 소분야: Semantic Segmentation, Statistical Learning
  • 제안 기법
    • CRF(Conditional Random Field)를 Convolutional network에 적용하여 Segment boundary를 localize하는 기법 제안
    • 공간적 정보 손실을 최소화하기 위한 Atrous Convolution 기법 제안 → Dilated Convolution으로 이어짐
  • 키워드: Conditional Random Field, Atrous Convolution

Preliminary Knowledges

  • Conditional Random Field:

Problems & Proposal

  • Single downsampling – Maxpool 레이어와 Downsampling으로 인한 Signal resolution reduction 현상이 발생합니다.
    • Atrous Convolution을 제안하여 Signal reduction을 최소화합니다. → 추후 Dilated Convolution이라는 이름으로 다시 사용됩니다.
  • Spatial insensitivity (Spatial invariance)
    • 기존의 DCNN의 경우 공간적 정확도가 떨어지는 특성이 있습니다.
    • fully-connected Conditioal Random Field를 이용하여 model 결과의 Fine-detail을 살립니다. CRF의 경우 기존 Classifier의 class score와 Low-level pixel/edge information을 결합하는데 사용되었습니다.
    • 계층의존구조(Hierarchical dependency)를 모델링하는데 Fully Connected Pairwise CRF를 사용하였습니다. 이는 기존 Boose-based Pixel-level Classifier(Semantic Segmentation)에서 성능을 높이는데 사용되었습니다.

Hole Algorithm = Atrous Convolution

  • 논문에서는 Maxpool Layer 뒤에 따라오는 8-pixel Strided Convolution 을 사용하는 대신, Sparse하게 Convolution을 수행할 수 있도록 Convolution 시 중간에 Hole을 채워넣는 연산입니다.
Atrous Convolution | 출처

같은 Kernel size의 컨볼루션을 한 번만 수행하면, Stride의 수를 늘린것과 동일하게 Feature가 작아지는 효과가 있고 이와 동시에 Receptive Field의 크기가 확장되는 효과를 얻을 수 있습니다.

Atrous Convolution은 기존 Wavelet을 이용한 신호분석에 사용되던 방식이지만, 이를 영상과 같은 2차원 데이터에도 활용하여 연산량을 줄이는 효과를 얻을 수 있습니다.

Fully-Connected Conditional Random Field For Accurate Localization

CRF Iteration에 따른 Boundary localization | 출처

DeepLab V1에서는 Atrous convolution과 함께 CRF를 후처리 과정으로 사용해 예측 정확도를 높혔습니다. 기존 Short-Range CRF는 Segmentation noise를 없애는 용도로 사용되었는데, 전체 픽셀에 대한 Fully-Connected CRF을 수행할 경우 높은 정확도로 Segmentation이 가능한 것으로 알려져 Fully-Connected CRF를 수행하였습니다.

기존의 Short-range CRF의 경우 Local connection (Neighbor-) 정보만을 사용하게 되므로 오히려 Segmentation이 뭉뚱그려지고, Sharp한 boundary보다는 Noise에 강인한 결과를 얻을 수 있었습니다.

이를 Fully-Connected CRF (추후 DeepLab V3에서는 DenseCRF라고 불립니다)를 이용하여 Pixel-by-pixel로 Fully Connected Graph로 연결합니다. 물론 노드의 수가 상당히 많은 Markov Chain이므로 시간이 상당히 오래 걸리는 Task인데, DenseCRF 논문에서는 이를 Mean Field Approximation이라는 방법으로 해결하였습니다. 이 방식을 적용하여 Message passing을 이용한 iteration 방식을 이용하면, 효과적(효율적)으로 DenseCRF를 수행할 수 있게 됩니다.