본문 바로가기

Capstone

Model Quantization and Hardware Acceleration for VisionTransformers: A Comprehensive Survey 논문 리뷰

https://arxiv.org/pdf/2405.00314

 

 

Abstract

Vision Transformers (ViTs)는 최근 CNNs의 대안으로 주목받고 있지만

모델 크기와 높은 계산이나 메모리 요구사항으로 인해 자원 제약이 있는 디바이스에서의 deployment가 어려운 상황

-> 이를 해결하기 위해 ViTs의 알고리즘과 하드웨어를 공동 설계해 성능 최적화하려는 필요성 제기됨

 

Model Quantization

고정밀 숫자(high-precision number)를 저정밀 숫자(low-precision number)로 변환해 계산 요구 사항과 메모리 줄임

> 양자화된 알고리즘에 최적화된 하드웨어 개발해 효율성 증대시킬 수 있음

 

본 논문은 ViTs의 quantization와 Hardware Acceleration에 대한 Comprehensive Survey

ViTs의 독특한 아키텍처 특성과 실행 성능 먼저 살펴본 후 Model Quantization 기본 원리와 최신 quantization 기법들을 비교 분석함

 


 

Introduction

ViT는 이미지 데이터 처리 위해 self attention 메커니즘 사용해 이미지 내 요소들 간 복잡한 관계 분석함

이 방식은 이미지를 한 번에 전체적으로 이해할 수 있게 해줌

 

ViT는 이미지 처리에서 뛰어난 성능 보이지만 그 크기와 계산량이 커서 자원 제약이 있는 장치에서 실행하는 데 어려움 있음

특히 autonomous driving이나 virtual reality 같은 실시간 응용 프로그램에서 적합한 성능 내기 어려움

 

이 문제 해결하려면 model compression 기술 필요함

pruning, quantization, knowledge distillation, low-rank factorization 같은 기법들이 ViT와 결합돼 모델 크기와 계산량 줄여줄 수 있음

 

ViT 모델을 효율적으로 실행하기 위해 알고리즘과 하드웨어를 함께 설계하는 게 중요함

Hardware Acceleration 설계해 ViT의 특성 활용하면 더 나은 성능 낼 수 있음

 

 


 

 

Overview of Vision Transformer Architecture

 

ViT 아키텍처는 주로 self-attention 메커니즘 활용해 입력 이미지에서 중요한 정보 학습하는 방식으로 구성됨

ViT는 입력 이미지를 여러 패치로 나누고, 각 패치에 대한 정보를 벡터로 임베딩한 후 이를 Transformer 모델에 입력함

이 과정에서 이미지 내 패치 간 관계 잘 학습해 이미지 특징 추출함

 

 

Self-Attention Mechanism (SAM)

ViT의 핵심 기능은 self-attention 통해 패치 간 관계 학습하는 것임

QQ, KK, VV: 각각 query, key, value matrix

이 과정 통해 각 패치의 관계 학습하고 중요한 정보 추출함

 

 

Multi-Head Attention (MHA)

ViT는 여러 개의 head 사용해 각기 다른 시각으로 패치 간 관계 학습함

각 head는 독립적으로 self-attention 수행하고, 이를 결합해 더 풍부한 정보 생성함

각 head는 별도로 계산된 후 최종 출력 도출하기 위해 결합됨

 

각 head 계산:

 

 

-> 각 head의 변환 행렬

 

 

Feed-Forward Network (FFN)

ViT는 각 attention 블록의 출력을 더 깊이 처리하기 위해 Feed-Forward Network(FFN) 사용

FFN은 two dense layers으로 구성되어 있으며 GELU 활성화 함수 사용함

이를 통해 Non-linear 추가해 더 복잡한 관계 학습할 수 있게 함

W_1, W_2: 선형 변환 행렬

b_1, b_2: 편향 값

 

 

ViT는 self-attention 통해 이미지 내 각 패치 간 관계 학습하고,

Multi-Head Attention 통해 다양한 관점에서 관계 분석함

FFN은 이 과정을 더 깊게 만들어 모델이 더 복잡한 특징 학습할 수 있도록 도움

 

 

 


 

 

Variant ViTs

ViTs는 이미지 처리 작업에서 subsequent Transformer 기반 모델들의 기초가 됨

다양한 크기와 복잡성 가진 이미지 처리하는 데 강력함

 

ViT의 장점을 바탕으로 DeiT 도입됨

-> 원래 아키텍처 유지하면서 데이터 효율성 높이기 위해 설계됨

 

Transformers 위한 새로운 teacher-student strategy 도입하고 distillation tokens 사용해 작은 데이터셋에서도 성능 손실 없이 효과적으로 학습할 수 있음을 보여줌

 

Swin-Transformer는 ViT의 중요한 발전 이뤘으며 hierarchical structure와 shifted windows 통합해 local features 캡처 능력 향상시키면서 global context 유지함

 

 


 

 

Roofline Model Analysis

 

Arithmetic intensity, calculated as the ratio of FLOPs to bytes accessed (FLOPs / B)

 

 

 

GPU doubles its speed from 330 TOP/s in FP16 to 660 TOP/s in INT8

 

The roofline model incorporates this by raising the performance ceiling when quantization is used, indicating better performance for compute-bound layers

 

 

 

224 크기 입력 이미지에 대해 ViT-base 각 연산에 대한 FLOPs, MOPs, Arithmetic intensity 분석

 

'FC1’과 ‘FC2’ 레이어는 높은 Arithmetic intensity 보여 컴퓨팅 자원을 효율적으로 활용함

반면 ‘qk matmul’과 ‘sv matmul’ 같은 연산은 작은 행렬 차원으로 query, key, value activation 나누기 때문에 낮은 Arithmetic intensity 보임

softmax 연산은 상당한 메모리 엑세스 요구하지만 FLOPs는 적어 추론 시 오버헤드 될 수 있음

 

RTX 4090 같은 고급 GPU에서 Arithmetic intensity 200 이하인 연산은 메모리 제한에 의해 성능 제한됨

-> faster memory access 최적화에 집중해야 함

8bit 이하 형식으로 데이터 표현하는 quantization 적용하면 메모리 용량 줄이고 데이터 전송 가속화해 모델 인퍼런스 향상시킬 수 있음

 

 

 

The computational demands, in terms of FLOPs and MOPs, increase more than proportionally with the size of the image

-> super-linear growth 원인은 sequence length l에 대한 activation multiplication의 이차 복잡성(quadratic complexity)에 있음

예를 들어 feature dimension d와 number of head h에서 ‘qk matmul’의 dimension은 l × d/h × l로 변함

ViT-large 모델은 더 큰 feature dimension d로 인해 Arithmetic intensity 증가함 (ViT-large는 1024, ViT-small은 384)

 

이미지 크기 커질수록 이 모델은 FP16 같은 표준 정밀도 형식(standard precision formats) 사용할 때 계산이 제한되는 경향 있음 RTX4090에서의 roofline model을 보면 Fig.3에서 모델 성능이 파란 선과 일치하여 계산이 제한되는(compute-bound) 상태임

이런 상황에서 INT8 precision 채택하는 게 중요한 최적화 방법(crucial optimization)이 됨

이는 계산 병목 완화(mitigates computational bottlenecks)하고 quantized computing의 효율성과 처리량 극대화해 성능 크게 향상시킴

 

 


 

 

Fundamental of quantization

Linear Quantization

Linear Quantization는 weight나 activation 값을 continuous range에서 이산적인 레벨로 선형 매핑

이 과정은 involves three key steps: scaling, rounding(반올림), and zero point adjustment

 

Linear Quantization function 정의

r: 입력 실수값

q: 출력 양자화된 정수(output quantized integers)

S: 실수형 scaling factor

Z: 정수형 zero point

 

This mapping is linear, meaning that the quantization levels are evenly spaced (고른 간격 두고 분포)

균등 간격(uniform spacing)은 계산 단순화하며 균등 산술 연산 선호하는 하드웨어에서 효율적임

quantized integers는 다시 부동소수점 표현(floating-point representations)으로 변환될 수 있음

 

이 과정을 dequantization라고 함

이때 얻어진 실수값은 rounding에 의해 발생하는 근사화로 인해 원래 실수값 r과 일치하지 않음

 

 

Symmetric and Asymmetric Quantization

 

Scaling factor S and zero point Z are two significant hyper parameters

-> 입력 실수 값을 여러 구간으로 나누는 역할 함

 

[rmin, rmax]와 [qmin, qmax]는 각각 실수와 정수 값의 clipping range(자르기 범위) 나타냄

Calibration은 clipping range를 식별하는 과정임

 

Scaling factor S가 rmin과 rmax에서 직접 유도되면 asymmetric quantization(비대칭 양자화)로 불림

이때 정의된 clipping range는 zero point를 중심으로 대칭 이루지 않음

asymmetric quantization범위가 대칭적이지 않거나 왜곡된 경우(not symmetric or skewed)에 더 적합함

 

반면 symmetric quantization(대칭 양자화)는 분자를 최대 실수 절댓값 rmax - rmin = 2max(|rmax|, |rmin|)으로 변경함

 

clipping range가 symmetric이면 zero point Z는 0이 됨

q = round(r/S)로 단순화될 수 있음

-> 구현을 단순화하고 더 효율적인 인퍼런스 가능하게 함

 

qmin과 qmax에 대해서는 “full range”나 “restricted range” 사용할 수 있음

 

full range 모드에서는 S = 2max(|r|)/2^n-1이며 n은 quantization bit width 나타냄

INT8은 full range  [-128, 127] 가짐

 

restricted range 모드에서는 S = max(|r|)/2^n-1이고 INT8은 범위 [-127, 127] 가짐

However, directly using the min/max values to determine the clipping range may be sensitive to outliers, resulting low resolution of quantization

이 문제를 해결하기 위해 Percentile(백분위수)나 KL divergence(KL 발산) 전략 사용

 

 

Static and Dynamic Quantization

Dynamic Quantization와 Static Quantization는 weight의 clipping range 결정하는 방식에 따라 다름

 

Dynamic Quantization는 실행 중에 각 활성화 맵에 대해 동적으로 범위 결정함

이 방법은 minimum, maximum, percentile 등의 입력 메트릭을 실시간 계산해야 함 -> computational costs 크게 증가할 수 있음

그러나 각 입력에 대해 signal range를 정확히 결정하기 때문에 더 높은 precision(정밀도) 달성하는 경향이 있음

 

반면, Static Quantization는 실행 전에 range를 미리 계산하고 결정함

이 방법은 computational costs 증가시키지 않지만 accuracy 떨어질 수 있음

range 미리 계산하는 방법은 Calibration 입력 세트를 처리해 average range of activations를 결정하는 것임

평균 제곱 오차(MSE)나 엔트로피는 range 선택 위한 지표로 자주 사용됨

또한 clipping range는 훈련 과정에서 학습되어 결정될 수도 있음

 

 

Quantization Granularity

The determination of the clipping range can be categorized into layerwise, channelwise, and groupwise quantization, based on the level of granularity employed(사용된 세분화 수준에 따라!)

 

level of granularity 높아질수록 computational overhead 증가함

Layerwise quantization는 레이어 내 모든 파라미터의 statistics 고려해 clipping range 결정하고 모든 weight에 동일한 범위 적용함 -> 간단하지만 accuracy 손실될 수 있음

예를 들어 범위가 제한된 weight matrix은 더 넓은 범위를 가진 other weight matrices로 인해 quantization resolution가 감소할 수 있음

 

Channelwise quantization is a common choice

동일 레이어 내 서로 다른 채널은 각 채널에 별도의 scaling factors 사용함으로써 더 적합한 resolution 가질 수 있음 -> often leads to improved accuracy 

 

Groupwise quantization에서는 groups of parameters in weights or activations 기준으로 clipping range 결정함

-> layerwise와 channelwise quantization에 비해 더 세분화된 방법일 수 있음

이 방법은 레이어 내에서 weights나 activations가 크게 달라질 수 있어 유용하지만 상당한 overhead 추가될 수 있음

 

 

Post-Training Quantization (PTQ)

훈련이나 세부 조정 없이 pre-trained 모델의 weight와 activation에 양자화 연산 적용하는 기법

PTQ는 pre-trained model과 calibration data 사용해 clipping range 및 scaling factors와 같은 하이퍼파라미터 조정하고 결정함

Calibration 후 PTQ는 quantization 연산 수행해 quantized model 생성함

PTQ는 적은 양의 데이터만 필요하므로 상대적으로 낮은 overhead 가짐

그러나 low-precision quantization에서는 accuracy 떨어질 수 있음

 

 

Quantization Aware Training (QAT)

훈련 중에 quantization 통합하는 과정

backward pass에서 기울기 누적(gradient accumulation)이 부동소수점(floating point) 계산 사용해 실행되며 고정밀 가중치(high precision weights)는 재학습 동안 유지됨

이 weights는 forward pass 동안 정수로 양자화됨

데이터를 사용해 모델 재학습하거나 fine tuning한 후 quantized model 얻을 수 있음

QAT는 PTQ로 인한 정확도 저하를 복구할 수 있지만, 전체 훈련 데이터에 접근해야 하며 time-consuming(시간 많이 소요됨) especially for extremely low bits like binary quantization

 

 

Data-Free Quantization (DFQ) / ZeroShot Quantization (ZSQ)

actual data 사용하지 않고 quantization 수행하는 방법

real-world datasets에 대한 전통적인 요구 사항을 우회해 original training data와 유사한 fake data 생성함

이렇게 합성된 데이터는 PTQ 동안 모델을 보정(calibrate)하는 데 사용되며 QAT 내 fine tuning에도 사용됨

DFQ의 주요 장점은 데이터량, 개인정보 보호 및 보안 문제를 해결할 수 있다는 점임(data volume, privacy, and security)

 

 


 

 

Model quantization for vits

 

A. Activation Quantization Optimization

Fig.5a에서 보여주듯이 softmax 함수 이후의 activation distribution is highly unbalanced

값의 대부분은 0에 집중되어 있고 minority(highlighted in darker hue)은 1에 가까움

-> single scaling factor를 사용할 때 quantization precision이 균일하지 않게 만드는 문제 초래함

이는 하나의 이상치(solitary outlier)가 across the entire tensor에서 균일한 quantization precision를 불균형하게 영향을 미치기 때문

 

Fig.5b 히스토그램은 GELU activation 이후에도 similar imbalance 나타내며,

대부분의 값이 0 주위에 집중되어 있음(clustered around zero)

분포의 비대칭성(특히 음수 값의 제한된 범위)(asymmetry of the distribution)은 하드웨어에서 대칭 양자화(symmetric quantization)에 적합하지 않음을 보여줌

 

LayerNorm 레이어 출력에 대해 layer-wise quantization(layer별 양자화) 적용하면 성능 저하 발생하는데,

이는 Fig.5c에 나타난 채널 간 변동성(variability) 통해 확인됨

이 변동성은 채널 간 균일한 양자화 효율성(uniform quantization efficacy) 유지하는 데 어려움 초래함

 

 

1) Post-Softmax Activation

 

Fig.6에서 보여주듯 PTQ4ViT는 Post-Softmax activations에서 twin uniform quantization 개념 도입함

Softmax 이후 activation values을 two distinct quantization ranges인 R1, R2로 나누며 각 범위는 고유한 스케일링 팩터 ∆R1과 ∆R2에 의해 조정됨

-> dual-range strategy더 작은 값/ 더 큰 값을 효과적으로 구분할 수 있도록 해 더 세밀한 양자화 과정(more nuanced quantization process) 가능하게 함

FQ-ViTlog2 quantization 채택해 Post-Softmax activation (attention maps)에서 자주 발생하는 작은 값에 더 많은 bins 할당

-> 4-bit uniform quantization와 대비되며 4-bit uniform quantization는 이러한 값에 대해 only one bin만 할당함

 

APQ-ViT는 이전 방법들의 한계 해결함

이전 방법들은 주로 mutual information에 집중했으나 Softmax 함수의 Matthew 효과 간과했음

-> 이 효과 유지 위해 asymmetric linear quantization 구현함

Softmax 출력의 최대값에 비례하는 quantization step size 사용해 Softmax 범위 내 distribution of quantization error를 더 uniform하게 만드는 것 목표로 함

 

RepQ-ViT, RepQuant, LRP-QViT는 initially employs log√ 2 quantization

-> 지수 법칙 분포(power-law distributions) 가진 activations에서의 properties of attention scores에 더 적합함

이후 scales을 reparameterize해 2를 기반으로 바꾸고 bit-shifting operations을 수행할 수 있게 해 hardware-friendly 성능 제공함

 

TSPTQ-ViT비정규 분포 값(non-normally distributed values)에서 비트 희소성(bit sparsity) 활용해 post-softmax 값의 다른 영역에 다른 scaling factors 할당

 

I&S-ViT는 “Shift-Uniform-Log2 Quantizer” (SULQ) 도입해 log2 변환 이전에 shift bias 추가함

-> comprehensive representation of the input domain’s full range and effectively aligns with the long-tail distribution characteristic of post-Softmax activations

 

 

2) Post-LayerNorm Activation

FQ-ViT는 Pre-LayerNorm quantization 위해 Power-of-Two Factor (PTF) 제안함

PTF의 core idea는 different quantization parameters 사용하는 대신 각 채널에 different factors 할당하는 것

-> input activation X quantizing하고 각 채널에 대해 layer-wise quantization parameters s와 zp 적용하며, PTF α 추가해 채널별로 다르게 설정함

여기서 s와 zp는 X의 최대값과 최소값 기준으로 계산되며 α_c는 각 channel c에 대해 quantization 를 최소화하도록 선택됨

 

RepQ-ViT는 Post-LayerNorm activations에 대해 Scale Reparam 방법 제안함

먼저 channel-wise quantization 적용해 채널 간의 큰 변동을 정확하게 capture함

그 후 중요한 재매개변수(reparameterization) 통해 channel-wise quantization scales과 zero points을 더 hardware-friendly layer-wise format으로 변환함

이 변환에 따라 LayerNorm의 affine factors와 following layer의 weights 수정됨

이를 확장해 RepQuant는 각 채널에 대해 상한선/ 하한선 설정하는 dual clipping strategy 채택해 quantization의 정확성 높이고 quantization space 내 bias 최소화함.

 

TSPTQ-ViT데이터에서 outlier channels 식별하고 다른 채널들의 scaling factors와 구별되는 unique scaling factor 할당하는 방법 제안

K-means algorithm 사용해 모든 채널에서 절대 최대값(absolute maximum values) 기준으로 outliers 탐지하고,

outliers 식별 후 Hessian-guided 스케일링 팩터를 선형적으로 나누어진 후보 집합에서 결정함

이 스케일링 팩터는 데이터 처리의 효율성을 위해 가중치의 scaling factors와 함께 공동 최적화됨

 

I&S-ViT는 "smooth optimization strategy" (SOS) 도입함

고변동성 활성화(highvariant activations) 처리 위한 세 가지 단계로 구성됨

  • 첫 번째 단계에서는 모델이 고정밀도 가중치(full-precision weights)와 LayerNorm 이후 quantized per-channel activations 사용해 세부 조정됨. 나머지 activations는 quantized on a per-layer basis로 처리됨
  • 두 번째 단계에서는 모델이 channel-wise quantization에서 layer-wise quantization로 전환되며, scale reparameterization technique 적용함
  • 마지막 단계에서는 weight quantization로 인한 성능 저하 복구 위해 weights와 activations가 모두 quantization된 상태로 additional finetuning 진행함

 

MPTQ-ViT는 Smoothquant 따르며, Post-LayerNorm value에 동일한 변환 적용하고 분포(distribution) 이동시키기 위해 bias 항 도입해 distribution가 0을 중심으로 더 symmetric 되도록 만듦

 

LRP-QViT는 clipped reparameterization(클리핑된 재매개변화) 제안함

each channel’s activations에서 outliers를 clipping해 변동성(variations) 완화함

이는 channel-wise quantization에서 얻은 scale과 zero-point parameters 조정 후,

clipping으로 인해 발생한 distribution 변화에 compensate하기 위해 LayerNorm의 affine factors와 subsequent layer의 weights 및 biases을 reparameterizing함

 

3) Post-GELU Activation

PTQ4ViT는 post-GELU activations에 대해 twin uniform quantization 적용함

post-Softmax scenarios에서 구현한 방식과 유사함

 

이 경우, quantization process은 activation values을 sign에 따라 구분함:

negative values는 range R1에 속하고 더 정교한 scaling factor(∆R1) 사용해 quantized되며, positive values은 range R2에 속하고 상대적으로 더 큰 scaling factor(∆R2) 사용해 quantized됨

 

Post-Softmax values에 대한 적용과 비교했을 때, TSPTQ-ViTsign bit의 존재에 맞게 조정된 유사한 two-region strategy를 통합함

 

traditional hand-crafted quantizers는 Post-GELU distributions를 정확하게 표현하는 데 어려움 겪지만,

MPTQ-ViT는 data-dependent approach 제안해 region-specific scaling factors를 자동으로 결정함

이를 통해 수동 캘리브레이션(manual calibration)의 필요성 없애고 adaptability 향상시킴

 

이 방법은 Post-GELU values을 negative values, small positive values, and large positive values로 나누어 각 영역에 specific SF 할당하고, bit shifts 조정을 통해 hardware-friendly alignment 보장함

 

 

Summary and Comparative analysis


Table II의 activation quantization optimization strategies을 살펴보면 모든 quantization technique은 softmax activation 이후 optimization 포함하고 있으며 이는 quantization processes에서 softmax의 중요한 역할과 sensitivity 강조함

 

GELU activation은 quantization에 큰 영향 미치지 않으며, GELU가 일정 수준의 robustness 가지고 있음을 시사함

모든 방법은 quantizing to 8-bit 했을 때 near-original accuracy 성능 달성함

이는 ViTs architectures 고유 특성에 맞춘 innovative designs 보여줌.

 

bit dept를 4-bi로 줄였을 때 I&S-ViT가 가장 우수한 성능 보였으며,

softmax output 이후 unbalanced distribution 처리하는 데 뛰어난 log2 quantizer 사용했기 때문으로 추정됨

-> limited dataset에서 가능한 fine-tuning process과 결합되어 효과적임을 입증함

 

strategic quantizer design과 targeted fine-tuning이 lower bit-widths에서도 substantial benefits 제공할 수 있음 나타냄

 

 

B. Calibration Optimization

PTQ는 QAT에 비해 GPU resources, time, and data requirements을 크게 절약할 수 있는 매력적인 대안으로 떠오름

PTQ의 핵심은 optimal quantization scale factor를 찾는 데 있으며 이는 full-precision model과 quantized model 간 불일치(discrepancy) 최소화하는 데 의존

이 과정은 quantization 후 모델 출력의 충실도(model’s output postquantization) 유지하는 데 중요한 역할 함

 

1). Pearson Correlation Coefficient and Ranking Loss

Liu et al.은 Pearson Correlation Coefficient 활용해 Transformer 모듈 내 original과 quantized outputs 간 일치 평가

quantization이 성능에 중요한 영향 미치는 order of attention scores 변경하는 문제 해결하기 위해 ranking loss 도입함

이 loss는 selfattention layer’s output hierarchy 유지하도록 특별히 설계돼 Transformer가 global feature의 relevance 구별할 수 있는 고유 능력 보존함

calibration process은 weights와 inputs의 quantization intervals을 fine-tuning하며, smaller calibration dataset 사용해 original과 quantized outputs 간의 similarity 향상시키는 데 중점 둠

 

 

2) Hessian Guided Metric

PTQ4ViT는 scaling factors 결정 위해 Hessian-guided metric의 효율성 강조함

다른 metrics들이 task-specific losses에 맞지 않는 경우와 달리 quantized vision transformers 성능을 크게 향상시킬 수 있음

quantization로 인한 교란(perturbations)은 Taylor series expansion를 통해 정량화할 수 있음

 

full Hessian matrix 계산하는 데 필요한 second-order gradient computations의 방대한 계산 피하기 위해 approximate optimization strategy 적용됨

 

APQ-ViT는 ultra low-bit scenarios에서 Hessian Guided Metric이 중요한 오류를 놓칠 수 있음을 알아냄

이를 해결하기 위해 quantization errors를 blockwise로 고려하는 방식으로 접근법 개선했으며,

이 방법은 errors across adjacent layers를 더 세밀하게 인식할 수 있게 함

모델의 최종 출력에 중요한 영향 미치는 오류를 우선 처리하기 위해 bottom-elimination mechanism(하단 제거 메커니즘) 도입해 entire error landscape 고려하는 대신 prioritize errors만 반영

 

 

3) Layer-by-layer Reconstruction Error

Evol-Q는 optimal quantization scales 결정 위해 contrastive loss mechanism 사용함

optimal quantization scales에서 영감 받아 각 레이어에 대해 best scales 찾기 위해 block-wise로 진화적 검색 전략 적용함

하나의 블록에 대해 검색 완료한 후 다음 블록으로 진행되어 체계적이고 목표 지향적인 scale optimization 보장함

 

simple layerwise squared loss 사용하는 COMQ는 coordinate descent optimization 이용하며, 각 레이어의 scaling factors와 bit-codes를 sequentially optimizing함

backpropagation 없이 반복되며, 주로 내적 연산(dot products)과 반올림(rounding)만 포함되며 hyperparameters 사용하지 않음

 

 

4) Quantization Error with Noisy Bias

quantization 접근 방식은 다르게 나타나며, EasyQuantcosine similarity 사용한 linear quantizer 제안함

 

PTQ4ViT는 Hessian metric 기반 non-linear quantizer 제시함

 

NoisyQuantquantization error 개선 위해 input activations에 Noisy Bias 추가하는 quantizer-agnostic method(독립적 방법) 도입

Noisy Bias N은 uniform distribution에서 N ∼ U (−n,n)로 추출되며, 경계(bounds)는 x ≤ n ≤ 2b−x로 결정됨

최적 n 찾기 위한 탐색은 quantization error function 사용되며, 수식 14, 15에서 정의된 calibration data의 subset 사용해 최적화됨

 

 

5) Data-Free Calibration

PSAQ-ViT는 ViT의 양자화를 위해 혁신적인 Data-Free Quantization approach 도입

calibration 과정에서 실제 이미지 사용할 필요 없이, ViT의 self-attention module 내 patch similarity의 고유한 다양성 활용

이 similarity의 차분 엔트로피(differential entropy)를 최적화 목표로 사용해 Gaussian noise의 최적화 유도함

실제 이미지의 distribution를 근사하려고 하며, Fig.8처럼 구현됨

 

 

PSAQ-ViT V2는 이를 향상시켜, full-precision(teacher) model 지도 하에 synthetic samples(합성 샘플) 생성하는 적응형 teacher-student paradigm 통합함

model discrepancies 최소화 위한 minmax game 통해 구현되며, 중요한 점은 auxiliary category guidance에 의존 않고 task와 modelindependen한 선험적 지식 사용함으로써 다양한 vision tasks와 models에의 적용 가능성 넓힌다는 점임

 

 

6) Floating Point Format

Lee et al.는 fixed-point and floating-point formats에 대한 오류 모델을 종합 분석해 calibration process에서 가장 적합한 수치 형식 식별 방법 제시함

 

floating-point quantization 분야를 더 깊이 다룬 LLM-FP4는 floating-point variables와 그 quantization 수식을 자세히 설명함

효율적인 quantization 결과 보장 위해 exponent bits와 scaling parameters 신중하게 선택하는 게 중요함을 강조

각 레이어에 대해 optimal format and clipping range 결정하는 search-based algorithm 도입해 floating-point quantization 관련 문제 해결함

 

LLM-FP4는 혁신적인 pre-shifted exponent bias method 제안함

Transformer 모델에서 자주 발생하는 high inter-channel variance 관리하는 데 효과적이며, activations quantization의 precision 향상시킴

 

 

Summary and Comparative Analysis

 

대부분 PTQ 방법들이 8-bit quantization에 최적화되어 있으며, 8 bits 미만으로 quantization할 경우 accuracy 손실될 수 있음을 나타냄

calibration 중 layer-by-layer reconstruction error 적용은 효과적인 것으로 나타났지만 적절한 quantization scaling factors 식별 위해 더 긴 calibration 시간이 필요함

 

LLM-FP4는 limited number of exponent and mantissa bits 상황에서 고무적인 결과 보였으며 이는 축소된 bit-widths에서 quantization 위한 floating-point formats 구현의 실용성 강조

existing and forthcoming hardware architectures에서 효율성 향상 가능성 시사함

 

 

C. Gradient-base Optimization For QAT

QAT는 model quantization에서 효과적 접근법으로 등장함

특히 PTQ의 제약 해결에 유용함

 

PTQ는 일반적으로 pre-trained full-precision models에서 quantized parameters 결정하는데, 종종 최적이 아닌 성능 보임

 

반면 QAT는 training cycle 내에서 quantization 통합해 훈련과정에서 quantization 이루어지므로 성능 저하되지 않도록 함

특히 4bits 이하 같은 초저비트 정밀도로 축소할 때 PTQ가 성능 손실을 겪는 반면 QAT는 효과적으로 이를 해결

QAT는 역전파 과정에 quantization 포함시킴으로써 quantization에 의한 performance degradation 줄임

 

QAT에도 도전 과제 존재함

미분 불가능한 quantization 함수에 대해 gradients 근사하는 어려움과 quantization oscillation(양자화 진동) 발생해 optimization process에 방해 될 수 있음

 

 

1) Differentiable Search for Group Assignment

Quantformerentropy information를 capacityaware metric으로 활용해 quantized and full-precision self-attention layers 간의 불일치 최소화함으로써 self-attention 순위 일관되게 유지함

computational costs 최소화하며 self-attention 순위 유지함

patch feature dimensions의 그룹화를 최적화하는 differentiable search mechanism(미분 가능한 검색 메커니즘) 도입해 동일 그룹 내 patch feature들이 공통의 quantization approach 사용하도록 보장함

변동성 큰 patch features들에서 발생하는 rounding and clipping inaccuracies 완화함

 

 

2) Distillation-assisted Training

Knowledge distillation (KD)

더 큰 "teacher" 모델에서 더 작은 "student" 모델로 지식 전달하는 방법론임

QAT에서 발생하는 정확도 손실 완화에 효과적임

 

Q-ViT양자화된 ViT 프레임워크에서 분류 출력 직접 감독하는 distillation token 도입

Quantized attention 모듈에서 발생하는 분포 변화 다루기 위해 Information Rectification Module (IRM) 도입하고,

후방 과정에서는 Distribution Guided Distillation (DGD) 전략 통해 양자화된 ViT와 전체 정밀도 모델 간 분포 차이 줄임

 

GPUSQ-ViT는 calibration losses for the hard label, soft logits and feature maps 사용하며,

Huang et al.은 multi-crop knowledge distillation strategy와 module-dependent quantization 기법 도입해 QAT 중의 변동성과 훈련 과정 안정화함

Oscillation-aware Bin Regularization 기법 제시해 훈련 중 발생할 수 있는 weight distribution 완화

 

 

3) Progressive Training

Quantizing real-valued pretrained models to extremely low-bit은 loss landscape이 복잡하고 non-convex이기 때문에 큰 도전 과제 제시함

 

TerViT8-bit model을 먼저 quantized and trained, 이를 ternary weight training으로 전환하는 혁신적인 접근법 도입함

 

Bit-shrinkingQuantization 중 발생하는 잡음과 밀접하게 관련된 'sharpness' term 제어하는 새로운 기법 제시함

loss landscape 부드럽게 해 모델 정확도 유지하는 데 중요함

bit-width을 점진적으로 줄이면서 sharpness의 증가를 규제함으로써 Quantization 과정에서 모델 정확도 보존함

  

4) Outlier-Aware Training

PackQViT는 Quantization 중 이상치에 대한 훈련 접근 방식 도입함

이전과는 달리 훈련의 각 반복에서 이상치의 채널 인덱스와 power-of-two 계수를 l2 최소화 사용해 검색

이후 이상치의 부정적 영향 완화하기 위해 양자화된 파라미터 업데이트함

 

5) Oscillation-free Training

QFQ는 QAT 중 발생하는 weight oscillation(가중치 진동)이 모델 성능에 미치는 부정적 영향 조사하며,

학습 가능한 스케일링 팩터가 이 문제를 악화시킨다고 강조함

 

문제 완화 위해 세 가지 기술 제안:

  • robust quantization 위한 Statistical Weight Quantization (StatsQ)
  • weight oscillation 안정화하는 Confidence-Guided Annealing (CGA)
  • ViT의 self-attention layer에서 얽힌 진동 해결하는 Query-Key Reparametrization (QKR)

 

 

Summary and Comparative Analysis

 

Table III 비교 결과는 PTQ와 QAT 간 성능 차이 명확히 보여줌

 

QAT은 PTQ보다 우수한 성과 보이며 4bit와 같은 초저비트로 양자화할 때도 accuracy 손실 없이 성능 유지

그러나 QAT는 더 많은 훈련 비용 수반

 

Distillation-aware training은 하드웨어에 더 높은 메모리 요구 사항 가지지만, 실험된 방법 중 가장 높은 성능 보임

4bit에서 accuracy 유지할 수 있는 능력은 이 bit-width에서 효율적 계산 수행할 수 있는 전용 hardware acceleratorsd에 대한 관심 불러일으킴

-> 결과 품질 유지하면서 computational resources 최적화하려는 trend 반영함

 

 

D. Binary Quantization

ViT에서 Binary quantization는 1bit parameters 사용해 모델 크기 극단적으로 줄이며 효율적 bit 연산 가능하게 함

-> computational demands 크게 줄이지만 parameter precision의 급감으로 인해 성능 저하하는 문제 겪음

     이 reduction hampers(정밀도 감소)는 모델이 복잡한 정보 처리하는 능력 저하시킴

  • BiViT: Softmax-aware Binarization을 제안하여 이진화 과정에서 발생하는 오류를 동적으로 조정함. 이를 통해 softmax attention values이 binarization 될 때 발생하는 오류 줄이고 attention mechanism 더 정확하게 표현할 수 있게 됨
  • Gradient Regularization Scheme (GRS): Xiao et al.는 weight oscillation(가중치 진동) 줄이기 위해 도입함. activation에서 information distortion 최소화 위해 Activation Shift Module (ASM)을 추가함.
  • BinaryViT: CNN의 key architectural features 도입해 pure ViTs architecture에서 합성곱 사용하지 않고도 성능 향상시킴.  cls-token pooling 대신 global average pooling 사용하고, multiple average pooling branches와 residual connections 이전의 affine transformations, pyramid structure 등 통합함. 이는 ViTs의 representational capability and computational efficiency 크게 향상시키는 것 목표로 함

 

Summary and Comparative Analysis


Binary Quantization methodologies의 부족함 드러남

이 도메인에서 본질적 도전 과제가 크다는 것 나타냄

 

표에 나타난 결과는 full-precision model에 비해 10% 이상의 accuracy deficit 강조함
-> binary quantization의 trade-off intrinsic 잘 보여줌:

     computational overhead와 storage의 감소는 model’s fidelity(모델의 충실도) 감소하는 것과 상쇄됨

 

그럼에도 current research trajectories are promising(연구 방향 유망!)

 

binary quantization와 auxiliary modules(보조 모듈) 결합하거나 new architectures 설계하는 통합 접근법들이 제시됨

이는 binary quantization의 efficiency과 model accuracy의 로버스틱함을 동시 확보할 수 있는 가능성 열어줌

이런 연구들은 binary quantization의 efficiency을 model accuracy 유지와 조화시키기 위한 방향으로 나아가고 있음

 

 


 

V. Hardware acceleration for quantized ViT

 

A. Accelerating Non-Linear Operations
quantization된 ViT에서 non-linear operations을 최적화하는 것은 여러 이유로 중요함

quantization의 핵심인 low bit computing units은 computational efficiency and memory footprint reduction 측면에서 상당한 이점 제공함

 

하지만 이런 units은 주로 linear operations에 최적화되어 있으며,

ViT architectures에 필수적인 GELU, LayerNorm, Softmax 같은 non-linear operations을 원래 지원 안함

-> 효율적 non-linear operations mechanisms 없으면 quantization의 장점 사라지고 processing speed and energy efficiency에 bottlenecks 발생할 수 있음

 

non-linear operations 위해 32-bit floating-point (FP32) arithmetic units에 의존하는 건 significant overheads 초래함

ViT에서 inference time의 많은 부분이 floating-point non-linear activations, normalizations, and the associated quantization and dequantization operations에 소비됨

-> throughput(처리량) 감소시키고 energy consumption 증가시켜 quantization 이점 저하시킴

 

optimizations의 주요 아이디어는 floating-point non-linear operations을 integer approximations으로 교체하고 불필요한 quantization 및 dequantization(복원 연산) 피해 이를 specialized hardware accelerators에서 더 빠르고 저렴하게 구현하는 것임

 

  • FQ-ViT: "Log-Int-Softmax" 도입해 softmax function의 integeronly variant(정수 전용 변형) 제공함. 이는 exponential component를 second-order polynomial(2차 다항식)으로 근사화하며, 효율적 계산 위해 Log2 quantization 함께 사용함. For LayerNorm, Powers-of-Two Scale factors 적용해 quantization된 activations 이동시키고, integer arithmetic 사용해 mean and variance 계산해 hardware compatibility 향상시킴
  • PackQViT: second-order polynomial approximation 피하고 softmax equation에서 natural constant e 대신 2 사용해 보다 직관적인 방법 사용함. 이는 retraining 후 accuracy loss 없이 효과적으로 작동함
  • I-ViT: "shiftmax" 사용해 softmax function의 exponential 부분을 2를 기준으로 변환함. 이는 bit-shifting 통한 operational efficiency 극대화하는 데 도움 됨. I-ViT는 LayerNorm에서 square root 계산할 때 ightweight integer-based iterative method 사용하며, 이는 Newton's Method에서 영감 받음. 이는 bit-shifting 활용해 더욱 개선됨. GELU approximation 위해 "ShiftGELU" 도입되었으며, 이는 sigmoidbased approximation 사용하고 exponentiation and division를 주로 bit-shifting으로 단순화함

 

  • EdgeKernel: softmax division operations에서 발생하는 precision challenges 해결 위해 ideal bit shift parameter M 선택하는 방법을 세밀히 분석함. 이는 precision 유지하면서도 중요한 bit truncations 피하는 데 필수적임. EdgeKernel은 LayerNorm inputs에 대해 asymmetric quantization 적용해 uint16 data type 사용하며, computational efficiency과 integrity of the data 유지의 균형 맞춤. 기존 연구가 여전히 highprecision multiplication and broad bit-width data storage (eg., INT32)에 의존하는 반면, EdgeKernel은 데이터 형식 간 변환 피함
  • SOLE: E2Softmax 도입해 8-bit quantized inputs을 fixed-point arithmetic 사용해 처리함. 이 방법은 지수 함수 후 log2 quantization 적용하고 approximate logarithmic division 사용해 traditional high-precision operations 피함. SOLE은 Power-of-Two Factor 사용해 Layer Normalization statistics의 dynamic compression 수행하고, 혁신적으로 two-stage LayerNorm Unit 설계함. 이는 pipelined computations and flexible batch processing에 유리하며, robust error tolerance과 reduced buffering and multiplication 특징으로 함

 

 

B. Hardware Accelerator For Quantized ViTs

quantized ViTs 위한 맞춤형 hardware accelerators 설계는 중요함

-> complex attention mechanisms and unusual memory access patterns 같은 unique computational demands을 generalpurpose hardware가 효율적으로 처리하지 못하기 때문임

 

이런 accelerators는 quantization의 challenges를 관리하면서 model performance 유지하고 precision 낮추는 데 최적화할 수 있으며, edge devices의 energy efficiency and low-latency requirements 충족하는 데 중요함

 

Custom hardware solutions은 various applications에서 ViT를 energy-efficient으로 배치할 수 있게 해주며, real-time processing 보장하고 edge computing environments의 resource constraints에 맞출 수 있음

  • VAQF: FPGA 구현 위한 ViT 모델 최적화 다룸. computation and storage needs 줄이기 위해 16-bit fixed-point representations 사용하는 것부터 시작하고, block RAM 사용과 data transfer latency 최소화하는 data packing techniques 구현하며, optimal tiling sizes 결정해 computation parallelism 극대화함. 이 accelerators는 quantized and unquantized computations 모두 처리할 수 있으며, unquantized layers에 대해 specific parameters 설정함. desired frame rate targets 달성하기 위해 parameters fine-tuned하고, compilation step에서 activations에 필요한 precision 결정함
  • Auto-ViT-Acc: design spaces 탐색하는 mechanism, FPGA resource utilization modeling module, ViT의 multi-head attention mechanism에 맞춤화된 FPGA compute engine을 특징으로 하는 종합 프레임워크 제시함. 이는 지정된 목표 FPS 달성하기 위해 quantization bit-widths and scheme mixing ratios의 최적 조합을 자율 결정할 수 있음. 이를 통해 quantization process과 FPGA accelerators design을 효율적으로 유도함
  • Huang et al.는 nonlinear operations 위한 integer-only quantization strategy 구현해 계산 단순화하고 edge devices와의 compatibility 향상시킴. 이 접근법의 핵심은 matrix multiplication tasks의 효율적 실행 위해 최적화된 versatile group vector systolic array임. 이 프레임워크는 data movement and storage을 효율적으로 촉진하는 데이터 패키징에 대한 unified strategy 사용하고, high throughput and low latency 유지하기 위해 dynamic on-/off-chip data storage management strategy 채택함
  • SOLE: efficient transformer inference 위해 custom hardware 설계하고, Softmax와 LayerNorm 연산 최적화함. Fig.11에 나타난 E2Softmax Unit은 large lookup tables and multiplications 피하고, exponent function outputs에 대해 log2 quantization 사용하며, 중간 결과를 4-bit representations으로 저장해 memory usage 줄임. 이는 online normalization and ping-pong buffers 통합해 throughput 극대화함. AILayerNorm Unit은 low-precision statistic calculation, dynamic compression, and Power-of-Two Factor quantization 사용하며, square functions and shift operations 위한 16-entry lookup table 사용하고 pingpong buffers 통해 smooth data flow 촉진함

 


 

VI. Conclusions and future directions

ViT의 quantization and hardware acceleration 조사해 challenge 다룸

ViT는 unique self-attention module의 특징이 있으며, optimal compression rates 달성하면서도 application accuracy 손상시키지 않도록 tailored quantization techniques이 필요함

efficient computation, higher bandwidth, a limited set of operations and opportunities for data reuse가 quantized ViTs에 대한 전문 specialized hardware accelerators의 개발 이끌어 왔음

이 서베이는 ViT quantization의 포괄적 로드맵 제공하며, 다양한 방법 간 상호 연결 explore하고 미래 연구 방향 제시함

Extremely Low-Bit: ViT를 ub-2-bit representations으로 quantization하는 문제는 model accuracy가 10% 이상 감소하는 문제강조함

ViT의 extremely low-bit quantization 적용에 있어 중요한 bottleneck 현상 드러냄

이런 성능 저하는 similar quantization constraints에서 CNN에서 보여지는 near-lossless performance와 대조됨

 

이 도메인에서 Continued innovation은 computational and memory footprints를 최소화하면서 효율적인 ViT 배치 위한 길을 열어줄 수 있음

 

 

Sub-8-bit Hardware: 현재의 hardware landscape은 주로 8-bit computations에 최적화되어 있음

그러나 PTQ에서 4-bit quantization algorithms 관련된 minimal accuracy loss은 sub-8-bit operations 위한 accelerators 개발하는 것의 feasibility and potential benefits 강조함

이런 low-bit accelerators 디자인하면 computational efficiency and throughput 크게 향상시킬 수 있고, energy consumption 줄이고 lower hardware costs 낮출 수 있음

 

Combination with Other Compression Methods: quantization를 여러 compression techniques(예: pruning)과 결합하는 건 아직 충분히 연구되지 않았지만 유망한 분야임

model compression에 대한 이 holistic approach(통합 접근법)는 model size and computational demands에서 상당한 감소 가져올 수 있음

 

Lower-level ViTs Quantization: object detection and image generation 같은 Quantizing ViTs for lower-level tasks는 distinct challenges 제시함

이 도메인은 quantization의 efficiency 최대한 활용하면서 ViT가 다양한 applications에서 효과적으로 작동하도록 하는 전문화된 전략 필요로 함 -> 추가 연구 필요함

 

Robustness and Generalization: quantized ViTs가 diverse tasks and datasets에서 robustness and generalization 능력 유지하는 게 중요함

향후 연구는 quantization가 model’s ability to generalize에 미치는 영향 조사하고, adverse effects 완화하는 기술 제안해 real-world applications에서 model’s utility 향상시키는 방법 모색해야 함

 

 

 

 


Tiny Star