Edge AI & Cloud/On-Device AI & Edge Hardware

Transformer On-Device LLM 메모리 계산법: Parameter 수 및 KV Cache VRAM Estimation

임베디드 친구 2026. 7. 25. 15:09
반응형

Transformer 모델의 On-Device LLM 이식성 및 DRAM/VRAM 메모리 제약 배경

엣지 디바이스 및 안드로이드 시스템 환경에서 대규모 언어 모델(LLM)을 구동하려면 하드웨어 리소스 제약을 정밀하게 계산해야 합니다. NPU, GPU, AP CPU 공유 메모리 구조를 사용하는 임베디드 디바이스에서는 VRAM 및 DRAM 대역폭 한계로 인해 Out of Memory (OOM) 에러 및 Thermal Throttling 현상이 빈번하게 발생합니다. 본 글에서는 Transformer 모델 매개변수(Parameters), 정밀도 데이터 타입(FP16, INT8, INT4), 문맥 길이(Context Length)에 따른 KV 캐시(Key-Value Cache)의 메모리 점유량을 수학적으로 계산하고 엣지 하드웨어 이식 가능성을 판별하는 기준을 제공합니다.

Transformer On-Device LLM 메모리 요구량 핵심 요약 (Quick VRAM Estimation Summary)

  • Model Weight Memory Formula:
    • Model Size (Bytes) = Parameters * Bytes per Parameter.
    • (FP16 = 2 Bytes, INT8 = 1 Byte, INT4 = 0.5 Bytes).
  • KV Cache Memory Formula:
    • KV Cache Size (Bytes) = 2 * Layers * Attention Heads * Head Dimension * Sequence Length * Batch Size * Bytes per Precision.
  • System Overhead Margin:
    • Ensure an additional 20% VRAM headroom for Activation Memory, OS allocations, and Framebuffer execution.

Transformer LLM VRAM 계산 공식 및 KV Cache 상세 분석

1. 파라미터 수 및 데이터 타입별 가중치(Weight) 메모리 점유량 계산

Transformer 모델의 기본 가중치 메모리는 모델의 총 파라미터 수와 비트 정밀도(Precision)에 결정됩니다.

$$\text{Weight VRAM} = P \times B$$

  • $P$: Total Number of Model Parameters
  • $B$: Precision Bytes (FP32 = 4, FP16/BF16 = 2, INT8 = 1, INT4 = 0.5)
Model Parameter Size Precision Type Bytes per Parameter Pure Weight VRAM Usage Recommended System Memory
7B Parameters FP16 2 Bytes ~14.0 GB 18 GB+
7B Parameters INT8 1 Byte ~7.0 GB 10 GB+
7B Parameters INT4 (GGUF/AWQ) 0.5 Bytes ~3.5 GB 6 GB+
13B Parameters FP16 2 Bytes ~26.0 GB 32 GB+
13B Parameters INT4 (GGUF/AWQ) 0.5 Bytes ~6.5 GB 10 GB+

2. KV 캐시(Key-Value Cache) 메모리 메커니즘 및 확장 계산식

Transformer Decoder 인퍼런스 과정에서는 이전 토큰들의 Key, Value 벡터를 재계산하지 않고 메모리에 유지합니다. Sequence Length가 증가함에 따라 KV Cache 메모리는 선형적으로 증가합니다.

$$\text{KV Cache VRAM (Bytes)} = 2 \times L \times H \times D \times S \times B \times N$$

  • $L$: Number of Layers (num_hidden_layers)
  • $H$: Number of Key-Value Attention Heads (num_key_value_heads)
  • $D$: Head Dimension Size (hidden_size / num_attention_heads)
  • $S$: Sequence Length (Tokens)
  • $B$: Precision Bytes (FP16 = 2, INT8 = 1)
  • $N$: Batch Size

Llama-3-8B 모델 기준 KV Cache 메모리 계산 예시 (FP16 기준)

  • Layers ($L$) = 32
  • KV Heads ($H$) = 8 (Grouped-Query Attention 적용)
  • Head Dimension ($D$) = 128
  • Precision ($B$) = 2 Bytes (FP16)
  • Batch Size ($N$) = 1
# Python script for precision KV Cache VRAM calculation
def calculate_kv_cache_vram(layers: int, kv_heads: int, head_dim: int, seq_len: int, bytes_per_elem: int = 2) -> float:
    # 2 represents Key and Value tensors
    total_bytes = 2 * layers * kv_heads * head_dim * seq_len * bytes_per_elem
    gigabytes = total_bytes / (1024 ** 3)
    return gigabytes

# Llama-3-8B FP16 at 8192 context length
llama3_8b_kv_vram = calculate_kv_cache_vram(layers=32, kv_heads=8, head_dim=128, seq_len=8192, bytes_per_elem=2)
print(f"KV Cache VRAM Required: {llama3_8b_kv_vram:.3f} GB")
# Output: KV Cache VRAM Required: 1.000 GB

On-Device LLM 최적화를 위한 시스템 엔지니어링 팁

  1. Grouped-Query Attention (GQA) 모델 활용
    • Multi-Head Attention (MHA) 대신 GQA 구조를 갖춘 모델(예: Llama-3)을 채택하세요. KV Head 수가 대폭 줄어들어 KV Cache 메모리 점유량이 최대 8배 감소합니다.
  2. FlashAttention 및 PagedAttention적용
    • 메모리 파편화를 방지하기 위해 가상 메모리 페이징 기법 기반의 PagedAttention 백엔드를 통합하세요.
  3. Android sysfs 및 Perfetto를 통한 실시간 메모리 추적
    • 임베디드 Linux/Android 환경에서 Shell 명령어를 이용하여 텐서 할당 시 peak memory를 추적하세요.
# Monitor system available memory and swap usage in real time
adb shell cat /proc/meminfo | grep -E "MemTotal|MemFree|MemAvailable|Cached"

# Monitor GPU memory allocation via debugfs for Qualcomm Snapdragon Adreno GPU
adb shell cat /sys/kernel/debug/kgsl/proc/<PID>/mem

온디바이스 LLM 배포 시 흔히 하는 실수 및 예외 상황

  1. Activation Memory 및 Temporary Tensor Buffer 계산 누락
    • 문제: Model Weight와 KV Cache만 계산하여 VRAM을 할당할 경우, Inference 실행 도중 std::bad_alloc 또는 OOM Kille에 의해 프로세스가 강제 종료됩니다.
    • 해결책: 전체 VRAM 계산 시 최소 15% ~ 20%의 여유 메모리(Margin)를 오버헤드로 추가 설정하세요.
  2. Context Length 확장 시 KV Cache 급증으로 인한 Crash
    • 문제: max_position_embeddings를 32k 이상으로 구성할 경우 Sequence Length 가 늘어남에 따라 KV Cache 메모리가 가중치 크기를 초과할 수 있습니다.
    • 해결책: KV Cache Quantization (INT8/INT4 KV Cache)을 적용하여 KV 벡터의 메모리 소요량을 줄이세요.

결론

Transformer 기반 LLM을 온디바이스 하드웨어에 이식하기 위해서는 Model Weight VRAM, KV Cache VRAM, Activation Overhead의 정확한 합산이 필수적입니다. FP16 모델을 INT4 Quantization으로 전환하고 GQA 모델 구조와 KV Cache Quantization 기법을 병행하여 엣지 디바이스의 제한된 VRAM 내에서 안정적인 인퍼런스 파이프라인을 구축하세요.

반응형