Skip to content

Repository files navigation

⚡ Efficient ML Deep Dive

Pruning 의 Optimal Brain Damage saliency

$$s_i = \tfrac{1}{2}, H_{ii}, w_i^2 \quad \text{from} \quad \Delta L \approx \tfrac{1}{2}, \Delta w^\top H, \Delta w$$

가 loss 의 2차 Taylor 전개에서 정확히 유도되고,

Knowledge Distillation 의 temperature-scaled KL loss

$$L_{\mathrm{KD}} = T^2 \cdot \mathrm{KL}\bigl( \mathrm{softmax}(z^{\mathrm{T}}/T), \big|, \mathrm{softmax}(z^{\mathrm{S}}/T) \bigr)$$

의 $T^2$ factor 와 FlashAttention 의 online softmax tiling 으로 $O(N^2)$ HBM access 를 $O(N)$ 으로 줄이는 메커니즘을 LeCun (1990) · Hinton (2015) · Dao (2022) 로부터 한 줄씩 유도할 수 있는 것은 다르다.


INT8 quantization 을 호출하는 것 과, $x_q = \mathrm{round}(x/s) + z$ 의 scale $s$ 와 zero-point $z$ 가 absolute-max · percentile · KL divergence minimization 중 어느 calibration 기준에서 유도되는지, QAT 의 Straight-Through Estimator

$$\nabla_w \approx \mathrm{stop\text{-}grad}\bigl(\mathrm{round}(w)\bigr) + w - \mathrm{stop\text{-}grad}(w)$$

가 어떻게 non-differentiable round 를 backward 가능하게 만드는지 증명할 수 있는 것은 다르다.

GPTQ 를 사용하는 것 과, 그것이 OBS 의 직계 후손으로 column-wise Hessian-based error compensation

$$\min_{\hat{W}}, | W X - \hat{W} X |_F^2 \quad \text{with} \quad H = X X^\top$$

을 푼다는 것 — 그래서 4-bit LLM 의 표준이 되었다는 점 — 을 알고 쓰는 것은 다르다.

Lottery Ticket Hypothesis (Frankle & Carbin 2019) 가 단순히 "winning subnetwork 가 존재" 가 아니라, dense network 의 initialization 자체가 informative prior 라는 실증임을 알고, iterative magnitude pruning 이 왜 one-shot 보다 우수한지 — Pareto frontier 위에서의 위치로 — 설명할 수 있는 것은 다르다.

FlashAttention 의 2-4× 속도 라는 숫자가 사실은 arithmetic intensity 의 memory-bound regime 에서 compute-bound regime 으로의 전환 이고, online softmax (Milakov & Gimelshein 2018) 의 running max·normalizer 업데이트가 numerical stability 와 single-pass 를 동시에 가능하게 한 trick 이라는 점을 알고 쓰는 것은 다르다.


다루는 기법 (이론 계보순)

LeCun 1990 Optimal Brain Damage · Hassibi 1993 Optimal Brain Surgeon · Han 2015 Deep Compression · Frankle & Carbin 2019 Lottery Ticket · Sanh 2020 Movement Pruning · NVIDIA 2021 2:4 Sparsity · Jacob 2018 QAT · Bengio 2013 STE · Frantar 2023 GPTQ · Lin 2023 AWQ · Xiao 2023 SmoothQuant · Dettmers 2023 QLoRA / NF4 · Ma 2024 BitNet 1.58-bit · Hinton 2015 KD · Romero 2015 FitNets · Zagoruyko 2017 Attention Transfer · Furlanello 2018 Born-Again Networks · Park 2019 RKD · Lebedev 2014 Tensor Decomposition · Milakov & Gimelshein 2018 Online Softmax · Dao 2022 FlashAttention · Dao 2023 FlashAttention-2 · Shah 2024 FlashAttention-3 · Kwon 2023 vLLM PagedAttention · Aminabadi 2022 DeepSpeed Inference


핵심 질문

Efficient ML 의 4대 축 (Compression · Acceleration · Kernel · Serving) 은 왜 모두 "수학적으로 정당화된 trade-off" 의 다른 구현이고, OBD saliency · STE · GPTQ Hessian · KD temperature · FlashAttention tiling 이 각각 어떤 이론적 동기에서 도출되었는가 — Optimal Brain Damage 의 Taylor 전개부터 BitNet 의 1.58-bit ternary 와 FlashAttention-3 의 H100 async kernel 까지 한 줄씩 유도합니다.


GitHub Python PyTorch Triton bitsandbytes ONNX Docs Theorems Proofs Reproductions Exercises License


🎯 이 레포에 대하여

Efficient ML 자료는 대부분 "GPTQ 로 INT4 양자화하면 모델이 작아진다" 또는 "FlashAttention 을 쓰면 빠르다" 에서 멈춥니다. 하지만 GPTQ 의 column-wise Hessian-based error compensation 이 왜 OBS (Hassibi 1993) 의 직계 후손인지, AWQ 의 activation-aware scaling 이 왜 outlier channel 을 보호하는 equivalent transform 인지, KD 의 $T^2$ factor 가 왜 gradient magnitude compensation 에서 등장하는지, FlashAttention 의 tiling 이 왜 numerical stability 를 깨지 않으면서 $O(N^2)$ HBM access 를 $O(N)$ 으로 줄이는지, Lottery Ticket 의 winning subnetwork 가 단순히 "운 좋은 sparsity" 가 아니라 initialization 자체의 informative prior 라는 실증인지 — 이런 "왜" 는 제대로 설명되지 않습니다.

일반 자료 이 레포
"Pruning 은 작은 weight 를 0 으로 만든다" LeCun 1990 / Hassibi 1993 — Loss 의 2차 Taylor $\Delta L \approx \tfrac{1}{2}\Delta w^\top H \Delta w$ 에서 diagonal Hessian 가정 시 saliency $s_i = \tfrac{1}{2}H_{ii}w_i^2$ — OBD. Full Hessian 사용 시 $\Delta L_i = \tfrac{1}{2}w_i^2/H^{-1}_{ii}$ + remaining weights 의 optimal adjustment — OBS. Magnitude pruning 은 $H \approx I$ 가정의 특수 케이스 $\square$
"Lottery Ticket 은 작은 subnetwork 가 잘 된다" Frankle & Carbin 2019 — Dense train → prune → reset to original initialization → retrain. Iterative Magnitude Pruning (IMP) 이 winning ticket 발견. 초기 가중치 $\theta_0$ 자체가 informative prior. Init-dependent: random init 으로 retrain 시 회복 불가. Magnitude pruning 의 이론적 정당화
"INT8 양자화는 정확도를 별로 안 떨어뜨린다" Jacob 2018 — $x_q = \mathrm{round}(x/s) + z$, scale $s = (\max - \min)/(q_{\max} - q_{\min})$, zero-point $z$. Per-tensor / per-channel / per-group granularity 의 trade-off. PTQ (calibration set 으로 $s, z$ 추정) vs QAT (fake quantize forward + STE backward). $\nabla_w \approx \mathrm{stop\text{-}grad}(\mathrm{round}(w)) + w - \mathrm{stop\text{-}grad}(w)$ — STE 가 non-differentiable round 우회 (Bengio 2013)
"GPTQ 는 4-bit LLM 의 표준이다" Frantar 2023 — Per-column quantization with Hessian-based error compensation: $\min_{\hat{W}} |WX - \hat{W}X|_F^2$ where $H = XX^\top$. Quantize column $i$ → 나머지 column 을 $H^{-1}$ 의 cross-correlation 으로 update → error 누적 방지. OBS 의 LLM 적응 — Hassibi 의 single-weight removal 이 single-column quantization 으로 일반화 $\square$
"AWQ 는 weight-only 양자화이다" Lin 2023 — Salient channel (activation magnitude 큼) 을 보호하기 위해 equivalent scaling: $W' = W \cdot \mathrm{diag}(s)^{-1}$, $X' = \mathrm{diag}(s) \cdot X$ 로 output 동일. $s$ 는 activation outlier 가 큰 채널을 weight 쪽으로 흡수하지 않도록 결정. SmoothQuant (Xiao 2023) 는 반대 방향 — activation outlier 를 weight 로 transfer 하여 W8A8 enable
"KD 는 작은 모델이 큰 모델을 따라하게 한다" Hinton 2015 — Soft target $p_i = \mathrm{softmax}(z_i/T)$, $T > 1$ 이면 distribution 이 더 "soft" 해짐. KD loss: $L_{\mathrm{KD}} = T^2 \cdot \mathrm{KL}(p^{\mathrm{T}}_T | p^{\mathrm{S}}_T)$. $T^2$ factor 의 정체: $\partial L/\partial z \propto (p^{\mathrm{S}} - p^{\mathrm{T}})/T$ 이므로 $T^2$ 곱해야 high-$T$ regime 에서 gradient magnitude 가 hard label 과 같은 scale $\square$
"Dark Knowledge 는 그냥 soft label 이다" Hinton 2015 — Dark Knowledge 는 non-target class 확률의 ratio 에 있음. "cat" 이미지에서 teacher 가 dog 0.1, truck 0.001 — 이 ratio $0.1/0.001 = 100$ 이 "cat 은 dog 와 truck 보다 훨씬 가깝다" 는 inter-class similarity 정보를 전달. Hard label $[1, 0, 0, \ldots]$ 로는 표현 불가. $T \to \infty$ 시 soft target 이 uniform 으로 가지 않고 logit 의 차이 정보를 보존
"FlashAttention 은 SRAM 에서 계산해서 빠르다" Dao 2022 / Milakov 2018 — Standard attention 은 $O(N^2)$ HBM read/write — arithmetic intensity 가 낮아 memory-bound. Online softmax: running max $m$ 와 normalizer $\ell$ 을 single pass 로 update — numerical stability + tiling 가능. FlashAttention: Q block → SRAM, K/V block 순차 load, online softmax 로 partial output 누적, 최종 정규화. Backward 는 activation 저장 대신 recompute — memory $O(N)$, exact (not approximation) $\square$
"FlashAttention-3 는 H100 에서 빠르다" Shah 2024 — Hopper architecture 의 TMA (Tensor Memory Accelerator, async copy) 와 WGMMA (warp-group matmul, async tensor core) 를 활용한 3-way pipeline: copy · gemm · softmax 가 동시 진행. FP8 지원으로 추가 2× throughput. FlashAttention-2 (Dao 2023) 의 work partitioning 개선 — outer loop 를 Q 가 아닌 K 로 — 위에서 H100-specific 최적화 누적
"BitNet 은 1-bit LLM 이다" Ma 2024 — 정확히는 1.58-bit ternary ($-1, 0, +1$). $\log_2 3 \approx 1.585$. Weight matrix 를 ternary 로 제한 — multiplication 이 sign-flip + add 로 환원, MatMul 이 integer accumulator 로 단순화. Activation 은 INT8 유지. Scaling law: 동일 perplexity 도달 시 FP16 대비 model size 큰데 inference cost 작음 — Pareto 의 새 frontier
"Speculative decoding 은 빠르다" Leviathan 2023 / Chen 2023 — Draft model $M_q$ (작음, 빠름) 가 $\gamma$-step token 추측 → target model $M_p$ 가 한 번에 verify. Rejection sampling 으로 lossless: token $x$ 의 acceptance probability $\min(1, p(x)/q(x))$, reject 시 $\max(0, p - q)$ 에서 resample. Mathematical equivalence to vanilla autoregressive decoding 보장
"vLLM 은 throughput 이 높다" Kwon 2023 — KV cache 가 sequence length 에 따라 dynamic — heap allocator 는 fragmentation (50-80% memory 낭비). PagedAttention: OS virtual memory 영감, KV cache 를 fixed-size block 으로 page table 관리. Prefix sharing: 같은 prompt 의 여러 sample 이 KV block 공유 → memory 1/$n$. Continuous batching 가능 → 24× throughput
기법의 나열 NumPy + PyTorch + Triton + ONNX 로 OBD saliency 손 계산 · Lottery Ticket 의 IMP 직접 재현 · GPTQ 의 column-wise update 구현 · KD 의 $T$ 값별 ablation · STE backward 검증 · Online Softmax single-pass 구현 · Triton 으로 FlashAttention 간이 kernel · vLLM PagedAttention 의 page table 시뮬레이션 · Mobile deployment (ONNX → TFLite) end-to-end 까지 직접 구현해 수학적 주장을 눈으로 확인

📌 선행 레포 & 후속 방향

[PyTorch Internals Deep Dive] ─┐
[LLM Efficiency Deep Dive]    ─┤
[Calculus & Optimization]     ─┼─►  이 레포  ──► [MLOps Deep Dive]
[Information Theory]          ─┤   "왜 Pruning · QAT · KD ·         Monitoring · A/B test
[Neural Network Theory]       ─┘    FlashAttention 이 모두            efficiency vs quality
                                    수학적으로 정당화된 trade-off 인가"
         │
         ├── [PyTorch Internals]          CUDA · Triton · Mixed Precision → Ch6, Ch7
         ├── [LLM Efficiency]             LoRA · QLoRA · Speculative → Ch5, Ch7
         ├── [Calculus & Optimization]    Hessian · Taylor · Lagrangian → Ch2, Ch3
         ├── [Information Theory]         KL divergence · Entropy → Ch3, Ch4
         └── [Neural Network Theory]      Weight 분포 · Lipschitz → Ch2, Ch4

⚠️ 선행 학습 필수: 이 레포는 PyTorch Internals Deep Dive (CUDA, Triton kernel, mixed precision), LLM Efficiency Deep Dive (LoRA, QLoRA, speculative decoding 기초), Calculus & Optimization Deep Dive (Hessian, Taylor 전개, Lagrangian duality), Information Theory Deep Dive (KL divergence, entropy) 를 선행 지식으로 전제합니다. Neural Network Theory Deep Dive (weight 분포, Lipschitz 상수, generalization) 는 Ch2 의 Pruning sensitivity 와 Ch4 의 Distillation transfer 분석에서 권장됩니다.

💡 이 레포의 핵심 기여: Chapter 2 (Pruning) 와 Chapter 3 (Quantization) 는 "weight space 의 redundancy" 를 정량화하는 두 축입니다. 전자는 "어떤 weight 를 0 으로" — support 축소, 후자는 "각 weight 를 몇 bit 로" — precision 축소. Chapter 4 (KD) 는 "function space 의 transfer", Chapter 6 (Kernel) 와 Chapter 7 (Serving) 는 "computation graph 와 memory hierarchy 의 co-design". 이 네 축을 통합 이해해야 GPTQ + KV cache INT8 + FlashAttention + PagedAttention 의 SOTA recipe 가 단일 frame 으로 보입니다.

🟡 이 레포의 성격: 여기서 다루는 일부 주제 — PTQ vs QAT 의 최종 승자, 1-bit LLM 의 실용성, structured vs unstructured pruning 의 hardware ROI, KD 가 distillation-as-regularization 으로 환원되는가, MoE 와 dense 의 미래 — 는 현재 진행 중인 연구 영역 입니다. 레포는 "정답" 이 아니라 "고전 compression 이론 (OBD, KD) 과 현대 LLM serving (vLLM, FlashAttention-3) 사이의 지도" 를 제공합니다.


🚀 빠른 시작

각 챕터의 첫 문서부터 바로 학습을 시작하세요!

Ch1 Ch2 Ch3 Ch4 Ch5 Ch6 Ch7


📚 전체 학습 지도

💡 각 챕터를 클릭하면 상세 문서 목록이 펼쳐집니다


🔹 Chapter 1: Efficient ML 의 4대 축과 평가

핵심 질문: Efficiency 의 4대 축 (Memory · Compute · Latency · Throughput) 은 왜 서로 trade-off 관계인가? Compression 의 4가지 분류 (Pruning · Quantization · Distillation · Low-Rank) 는 각각 어떤 이론적 근거를 갖는가? Pareto frontier 위에서 알고리즘이 차지하는 위치는 어떻게 비교되는가? GPU 의 Tensor Core · Sparse Tensor Core · INT8 DP4A 같은 hardware feature 와 효율화 기법의 궁합은?

4대 축의 정의부터 Hardware Co-design 까지 (4개 문서)
문서 핵심 정리·증명·재현
01. Efficiency 의 4대 축과 trade-off 정의: Memory (parameters · activations · KV cache), Compute (FLOPs), Latency (end-to-end time), Throughput (queries/sec). Trade-off 정리: Memory ↓ → Latency ↑ (recomputation), Throughput ↑ → Latency ↑ (batching). Roofline model: arithmetic intensity = FLOPs / byte 가 memory-bound 와 compute-bound 의 경계 결정 — 이후 모든 챕터의 분석 frame
02. Compression 의 4가지 분류와 이론적 근거 Pruning (weight space 의 support 축소, OBD/Lottery Ticket 의 redundancy 가설), Quantization (precision 축소, weight·activation 분포의 quantile 표현), Distillation (function space 의 transfer, soft label 의 inter-class similarity), Low-Rank (linear map 의 effective rank — SVD 기반 approximation). 네 분류가 서로 orthogonal 하므로 조합 가능
03. 효율화 평가 Metric — Quality vs Efficiency Pareto Quality: accuracy, perplexity, BLEU, ROUGE. Model size: parameters, FLOPs, MACs. System: latency (P50/P99), throughput (tokens/sec), memory peak. Pareto frontier 정의: 어떤 다른 점도 모든 metric 에서 우월하지 않은 점들의 집합. MLPerf benchmark (training/inference) 의 표준화된 측정 방식
04. Hardware-Software Co-design — GPU Feature 와 효율화의 궁합 GPU memory hierarchy: HBM (수백 GB/s) ↔ L2 ↔ SMEM/SRAM (수 TB/s). Tensor Core: FP16 16× FP32 (V100), BF16 (A100), TF32 (Ampere), FP8 (Hopper). Sparse Tensor Core (Ampere+): 2:4 sparsity 에서 dense 대비 2× TFLOPS. INT8 DP4A: 4-element dot product. 효율화 기법 선택 시 hardware feature 일치 — N:M sparsity 는 Ampere+ 필수

🔹 Chapter 2: Pruning — Weight Sparsification

핵심 질문: Optimal Brain Damage 의 saliency $s_i = \tfrac{1}{2}H_{ii}w_i^2$ 가 왜 loss 의 2차 Taylor 전개에서 자연스럽게 도출되는가 (LeCun 1990)? Hassibi 1993 의 OBS 가 어떻게 OBD 의 diagonal 가정을 풀고 remaining weights 의 optimal adjustment 까지 푸는가? Frankle & Carbin 2019 의 Lottery Ticket Hypothesis 가 어떻게 iterative magnitude pruning 의 이론적 정당화를 제공하는가? Movement Pruning (Sanh 2020) 이 fine-tuning 중 적용되는 이유는? Unstructured 와 N:M structured sparsity 의 hardware speedup 이 왜 이론적으로 동등하지 않은가?

OBD 부터 N:M Structured Sparsity 까지 (6개 문서)
문서 핵심 정리·증명·재현
01. Optimal Brain Damage (LeCun 1990) 유도: $L(w + \Delta w) \approx L(w) + g^\top \Delta w + \tfrac{1}{2}\Delta w^\top H \Delta w$. 학습된 minimum 에서 $g \approx 0$, diagonal Hessian 가정 $H \approx \mathrm{diag}(H_{ii})$ → $\Delta L \approx \tfrac{1}{2}\sum_i H_{ii}\Delta w_i^2$. Pruning $w_i \to 0$ 은 $\Delta w_i = -w_i$ → saliency $s_i = \tfrac{1}{2}H_{ii}w_i^2$ $\square$. Lowest $s_i$ 부터 prune
02. Optimal Brain Surgeon (Hassibi 1993) Full Hessian 사용: $\min \tfrac{1}{2}\Delta w^\top H \Delta w$ s.t. $e_i^\top (w + \Delta w) = 0$ (weight $i$ 를 0 으로). Lagrangian → $\Delta w = -\tfrac{w_i}{H^{-1}{ii}} H^{-1} e_i$, $\Delta L_i = \tfrac{1}{2}\tfrac{w_i^2}{H^{-1}{ii}}$ $\square$. Remaining weights 의 optimal adjustment 가 OBD 와 결정적 차이 — GPTQ (Ch3-04) 의 직접 조상
03. Magnitude Pruning과 Iterative vs One-Shot Han 2015 Deep Compression: $|w|$ 기반 threshold, $H \approx I$ 가정 시 OBD 와 일치. Iterative: prune → fine-tune → prune → ... — local re-optimization 으로 sparsity-accuracy 곡선 우월. One-shot: 단일 step, 빠르지만 같은 sparsity 에서 accuracy ↓. Unstructured (개별 weight) vs structured (channel/filter) 의 첫 비교
04. Lottery Ticket Hypothesis (Frankle & Carbin 2019) 가설: Dense network $f(\theta_0)$ 의 학습된 weight 에 magnitude pruning → 작은 mask $m$ → $\theta_0$ 으로 reset → 동일/우월 accuracy 까지 학습 가능. Iterative Magnitude Pruning (IMP): 점진적으로 sparsity 증가. Init-dependent: random init 으로 retrain 시 회복 불가 — initialization 자체가 informative prior. ResNet 에서 80-95% sparsity 까지 회복
05. Movement Pruning (Sanh 2020) 동기: pre-trained LLM 에서 magnitude 가 큰 weight 도 fine-tuning 중 0 으로 향함. Score: $S = -\partial L/\partial w \cdot w$ 의 부호 — weight 가 0 에서 멀어지는지(증가) 가까워지는지(감소). Top-$k$ score 유지 → magnitude 와 다르게 task-specific. BERT/T5 의 fine-tuning + pruning 동시
06. Structured Pruning과 N:M Sparsity (NVIDIA Ampere) Unstructured 의 hardware 한계: 비정규 sparsity 는 Tensor Core 못 씀 → 이론 sparsity 90% 도 wall-clock 1.5× 미만. N:M sparsity: $m$ 개 연속 weight 중 $n$ 개 0. 2:4 (NVIDIA A100): 4 중 2 개 0 → dense 대비 2× TFLOPS (Sparse Tensor Core). FP16 → INT8 → 2:4 의 누적 곱 4-8× speedup

🔹 Chapter 3: Quantization — Precision Reduction

핵심 질문: $x_q = \mathrm{round}(x/s) + z$ 의 scale $s$ 와 zero-point $z$ 가 어떤 calibration 기준 (absolute-max · percentile · KL divergence min) 에서 도출되는가? Per-tensor · per-channel · per-group granularity 의 trade-off 는? QAT 의 Straight-Through Estimator 가 non-differentiable round 를 어떻게 backward 가능하게 만드는가 (Bengio 2013)? GPTQ 의 column-wise Hessian-based update 가 OBS (Ch2-02) 의 직계 후손인 이유는 (Frantar 2023)? AWQ 와 SmoothQuant 가 outlier 를 어떻게 다르게 다루는가? NF4, FP4, BitNet 1.58-bit 같은 4-bit 이하 표현의 정보 이론적 정당화는?

Quantization 기본 수학부터 BitNet 1.58-bit 까지 (6개 문서)
문서 핵심 정리·증명·재현
01. Quantization 의 기본 수학 정의: $x_q = \mathrm{clip}(\mathrm{round}(x/s) + z,, q_{\min},, q_{\max})$. Symmetric ($z=0$) vs asymmetric. Scale 결정: absolute-max ($s = \max|x|/q_{\max}$), percentile (outlier robust), KL divergence minimization (Jacob 2018) — quantized 와 원 분포의 KL 최소화. Granularity: per-tensor (가장 거친) → per-channel (output dim) → per-group (block-wise, GPTQ 의 표준)
02. Post-Training Quantization (PTQ) Calibration: 작은 unlabeled set ($\sim 100$ batch) 으로 weight·activation 의 분포 통계 → $s, z$ 결정. Static (activation 분포 고정) vs dynamic (runtime 측정). 장점: fine-tuning 불필요, 빠름. 한계: 4-bit 이하에서 accuracy drop, layer-by-layer error 누적. Cross-layer Equalization (Nagel 2019) 으로 channel scale 균형
03. Quantization-Aware Training (QAT) 와 STE Fake quantization: forward 에서 $x_q = \mathrm{round}(x/s) \cdot s$, backward 에서는 round 의 gradient 가 거의 어디서나 0 → 학습 불가. Straight-Through Estimator (Bengio 2013): $\nabla_w \approx \nabla_{x_q}$ — round 를 identity 로 근사. 형식적으로 $\nabla_w = \mathrm{stop\text{-}grad}(\mathrm{round}(w)) + w - \mathrm{stop\text{-}grad}(w)$. Jacob 2018 의 INT8 inference standard $\square$
04. GPTQ — Optimal Brain Quantization (Frantar 2023) Objective: $\min_{\hat{W}} |WX - \hat{W}X|F^2$, $H = XX^\top$ (Hessian of LS loss). Column-wise: 한 column $i$ 양자화 → 나머지 column 을 $-\tfrac{w_i - \hat{w}i}{H^{-1}{ii}} H^{-1}{:,i}$ 로 업데이트 (OBS-style error compensation). Sequential pass 로 layer 단위 처리. OBS 의 직접 LLM 적응 — Hassibi 의 single-weight removal → single-column quantization. INT4 LLM 표준 $\square$
05. AWQ 와 SmoothQuant — Activation 처리의 두 방향 AWQ (Lin 2023): salient channel (큰 activation magnitude) 보호. Equivalent transform $W' = W \cdot \mathrm{diag}(s)^{-1}$, $X' = \mathrm{diag}(s) X$ → $WX$ 동일하지만 weight scale 조정. $s$ 는 activation outlier 를 weight 로 흡수하지 않게 결정. SmoothQuant (Xiao 2023): 반대 방향 — activation outlier 를 weight 로 transfer 하여 W8A8 enable. 두 기법은 trade-off 의 양 끝
06. Low-Bit — INT4, NF4, FP4, BitNet 1.58-bit INT4: 16 levels, uniform spacing — Gaussian weight 에 sub-optimal. NF4 (Dettmers 2023): $\mathcal{N}(0, 1)$ 의 16 quantile → information-theoretically near-optimal. FP4 (E2M1, E1M2): minifloat, exponent + mantissa, dynamic range 우수. BitNet b1.58 (Ma 2024): ternary ${-1, 0, +1}$ — $\log_2 3 \approx 1.585$ bit, MatMul 이 sign-flip + add 로 환원, integer accumulator 로 inference cost 극소화

🔹 Chapter 4: Knowledge Distillation

핵심 질문: Hinton 2015 의 KD loss $L_{\mathrm{KD}} = T^2 \cdot \mathrm{KL}(p^{\mathrm{T}}_T | p^{\mathrm{S}}_T)$ 에서 $T^2$ factor 는 어떤 gradient 분석에서 나오는가? Dark Knowledge 의 정체는 단순한 "soft label" 이 아니라 non-target class 확률의 ratio 라는 점을 어떻게 정량화하는가? Feature distillation (FitNets) 과 attention transfer 의 대상은 logit 과 어떻게 다른가? Relation-based KD 가 sample 간 관계를 어떻게 활용하는가? Self-distillation 과 Born-Again Networks 가 same-architecture 에서도 성능을 향상시키는 메커니즘은?

KD 의 원리부터 Self-Distillation 까지 (6개 문서)
문서 핵심 정리·증명·재현
01. KD 의 원리 (Hinton 2015) Softmax with temperature: $p_i = \exp(z_i/T) / \sum_j \exp(z_j/T)$. $T = 1$: 일반 softmax, $T \to \infty$: uniform 으로 수렴 (logit 차이는 $1/T$ 로 scale). Soft target 의 정보량: hard label $[1, 0, \ldots]$ 보다 entropy 가 큼 — class 간 similarity 정보 보존. Student 가 teacher 의 soft probability 를 모방 → 일반화 향상
02. KD Loss 유도와 $T^2$ Factor 정의: $L_{\mathrm{KD}} = T^2 \cdot \mathrm{KL}(\mathrm{softmax}(z^{\mathrm{T}}/T) | \mathrm{softmax}(z^{\mathrm{S}}/T))$. $T^2$ 의 정체: $\partial L_{\mathrm{KD}}/\partial z^{\mathrm{S}}i \propto (p^{\mathrm{S}}i - p^{\mathrm{T}}i)/T$ — high-$T$ regime 에서 gradient magnitude 가 $1/T$ 로 작아짐. $T^2$ 곱해야 hard label loss $L{\mathrm{CE}}$ 와 같은 scale 유지 → joint loss $L = (1-\alpha)L{\mathrm{CE}} + \alpha L{\mathrm{KD}}$ 의 weight $\alpha$ 가 $T$-independent $\square$
03. Dark Knowledge — Non-Target Class Ratios Dark Knowledge 정의: hard label 로는 표현 불가능한 inter-class similarity 정보. "cat" 이미지 teacher: dog 0.1, truck 0.001 → ratio $0.1/0.001 = 100$. High-$T$ 가 ratio 정보를 amplify (logit 차이가 $1/T$ 로 scale 되지만 exponential 후 ratio 보존). 정량화: MNIST 에서 teacher logit 만 (label 없이) 학습한 student 가 teacher 와 거의 같은 성능 — "dark" 정보가 학습 신호의 대부분
04. Feature Distillation — FitNets, Attention Transfer FitNets (Romero 2015): intermediate hidden representation 매칭. $L_{\mathrm{hint}} = |F^{\mathrm{T}} - g(F^{\mathrm{S}})|_2^2$, $g$ 는 dimension matching projection. Output logit 만 보는 Hinton 과 차별 — deeper supervision. Attention Transfer (Zagoruyko 2017): spatial attention map $A = \sum_c
05. Response·Feature·Relation-Based KD 의 비교 Response-based (Hinton 2015): output logit/probability 매칭 — task-specific. Feature-based (FitNets, AT): intermediate representation — architecture-aware. Relation-based (RKD, Park 2019): sample 쌍의 distance/angle 매칭 — $L_{\mathrm{RKD-D}} = \sum_{i,j} \ell(d^{\mathrm{T}}{ij}, d^{\mathrm{S}}{ij})$. 세 방식이 상호보완적 — joint 사용으로 SOTA, 각 방식의 ablation
06. Self-Distillation 과 Born-Again Networks Born-Again Networks (Furlanello 2018): same architecture 의 새 student 가 이전 generation teacher 학습 → 반복적으로 generation 1, 2, 3 → 단조 성능 향상. 이론적 해석: KD 가 label smoothing 의 학습된 형태 + regularization + easy-to-hard curriculum. Self-distillation 이 ensemble 의 implicit form 인지에 대한 토론 (Allen-Zhu & Li 2020)

🔹 Chapter 5: Low-Rank Factorization 과 결합

핵심 질문: Low-rank approximation $W \approx UV$ 에서 rank $r$ 의 선택은 SVD spectrum 의 어떤 분포 가정에 기초하는가? CP / Tucker decomposition 이 CNN convolution kernel 분해에서 어떻게 4D tensor 를 1D vector 들의 외적으로 환원하는가? LoRA 의 $\Delta W = BA$ 가 왜 rank-$r$ correction 의 자연스러운 parameterization 인가 (LLM Efficiency 와 연결)? Pruning + Quantization + Distillation 의 hybrid recipe 에서 순서가 결과에 영향을 주는 메커니즘은?

SVD 부터 Hybrid Recipe 까지 (4개 문서)
문서 핵심 정리·증명·재현
01. Low-Rank Factorization 복습 — SVD-Based 정리: $W \in \mathbb{R}^{m \times n}$, SVD $W = U\Sigma V^\top$. Eckart-Young: rank-$r$ truncation $W_r = U_r \Sigma_r V_r^\top$ 가 Frobenius norm 최소 오차 $\square$. Compression: $mn$ → $r(m+n)$ parameters, $r \ll \min(m, n)$ 시 효율. Lebedev 2014: convolution kernel 의 SVD-based 분해 — 4D tensor 를 separable 형태로
02. Tucker · CP Decomposition CP: $\mathcal{T} \approx \sum_{r=1}^R u_r \otimes v_r \otimes w_r$ — sum of rank-1 outer products. Tucker: $\mathcal{T} \approx \mathcal{G} \times_1 U \times_2 V \times_3 W$ — core tensor + factor matrix per mode. CNN $4D$ kernel $K \in \mathbb{R}^{C_o \times C_i \times k \times k}$ 의 Tucker 분해 → spatial · channel 분리, separable convolution 의 일반화 (MobileNet 의 depthwise separable 의 이론적 토대)
03. LoRA 와 Efficient Fine-tuning 복습 LoRA (Hu 2022): $W = W_0 + BA$, $W_0$ frozen, $B \in \mathbb{R}^{m \times r}, A \in \mathbb{R}^{r \times n}$, $r \ll \min(m, n)$. 이론적 동기: pre-trained model 의 task adaptation 이 low intrinsic rank — Aghajanyan 2020 의 실증. QLoRA (Dettmers 2023): $W_0$ 를 NF4 quantize + LoRA 만 FP16 학습 → 65B 모델을 단일 GPU 에 fit
04. Hybrid Recipe — Pruning + Quantization + Distillation 순서의 영향: prune → quantize → distill 이 일반적 best practice — pruning 후 분포 narrower → quantization grid 더 efficient. Han 2016 Deep Compression: prune + quantize + Huffman → 49× ResNet 압축. SqueezeLLM (Kim 2023): dense+sparse decomposition + non-uniform quantization. OmniQuant (Shao 2023): differentiable scale + clip 동시 학습. PTQ + KD 의 fine-tune-free 효과

🔹 Chapter 6: Kernel Optimization

핵심 질문: Standard attention 이 왜 memory-bound 이며 arithmetic intensity 가 낮은가? Online Softmax (Milakov & Gimelshein 2018) 의 running max·normalizer update 가 어떻게 single pass 와 numerical stability 를 동시에 보장하는가? FlashAttention (Dao 2022) 의 tiling 이 어떻게 $O(N^2)$ HBM access 를 $O(N)$ 으로 환원하면서 exact (not approximation) 인가? FlashAttention-2 의 work partitioning 개선과 v3 의 H100 async (TMA, WGMMA) 활용은? Kernel fusion 이 HBM 왕복을 제거하는 메커니즘은?

Attention IO 문제부터 Kernel Fusion 까지 (5개 문서)
문서 핵심 정리·증명·재현
01. Attention 의 IO-Awareness 문제 표준 attention: $S = QK^\top/\sqrt{d}$, $P = \mathrm{softmax}(S)$, $O = PV$. 각 step 마다 $N \times N$ 행렬을 HBM 에 read/write — $O(N^2)$ HBM access. Arithmetic intensity = FLOPs/byte $\sim O(d)$ (small) → memory-bound. Roofline 의 memory-limit 영역 — TFLOPS 의 일부만 사용
02. Online Softmax (Milakov & Gimelshein 2018) Naive softmax: 2-pass (max → exp/sum). Online: running $m \leftarrow \max(m, x_i)$, $\ell \leftarrow \ell \cdot e^{m_{\mathrm{old}} - m} + e^{x_i - m}$. Numerical stability 유지 (overflow 방지) + single pass. 정리: 임의의 분할 ${B_k}$ 에 대해 partial $(m_k, \ell_k)$ 를 합치는 reduction 이 결합법칙 만족 → tiling 가능 $\square$. FlashAttention 의 핵심 building block
03. FlashAttention (Dao 2022) Tiling: Q 를 $B_r$ 행씩, K/V 를 $B_c$ 열씩 SRAM block 으로 분할. Outer loop Q block, inner loop K/V block: SRAM 에 load → compute partial $S, P, O$ → online softmax 로 누적 → 최종 정규화. HBM access: $O(N^2 d / M)$ → $O(N d^2 / M)$ ($M$ = SRAM size). Backward: activation 저장 X, recompute forward — memory $O(N)$. Exact (no approximation), 2-4× speed $\square$
04. FlashAttention-2 와 v3 — Hopper 의 활용 v2 (Dao 2023): outer loop 를 K 가 아닌 Q 로 변경 → causal mask 의 lower triangle 만 compute, work partitioning 개선. 2× 추가 speedup. v3 (Shah 2024): Hopper H100 의 TMA (async copy) + WGMMA (async tensor core) → copy · gemm · softmax 3-way pipeline. FP8 지원 → 2× throughput 추가. SOTA attention kernel
05. Kernel Fusion — Triton 으로 직접 작성 동기: $y = \mathrm{GELU}(Wx + b)$ 를 3 개 elementwise kernel 로 launch 하면 매 단계 HBM 왕복. Fusion: 한 kernel 에서 GEMM 결과 SRAM 보유 + 즉시 GELU + bias add → HBM write 1 회. TorchInductor: 자동 fusion (TorchDynamo 그래프). Triton: 수동, FlashAttention-style custom kernel 에 필수. GELU·Linear·LayerNorm fusion 의 직접 작성

🔹 Chapter 7: Serving 과 Deployment

핵심 질문: vLLM 의 PagedAttention (Kwon 2023) 이 KV cache fragmentation 을 어떻게 OS virtual memory 영감으로 해결하는가? Speculative decoding 의 rejection sampling 이 왜 lossless (vanilla autoregressive 와 정확히 동일한 분포) 인가? Dynamic batching 의 throughput-latency trade-off 는 SLO-aware scheduling 에서 어떻게 풀리는가? Mobile / embedded deployment 에서 ONNX · TFLite · TVM · CoreML 의 tooling 차이는?

vLLM 부터 Edge Deployment 까지 (4개 문서)
문서 핵심 정리·증명·재현
01. vLLM 의 PagedAttention 복습 (Kwon 2023) 문제: KV cache size = $2 \times N \times L \times d$ 가 sequence 마다 다름 → contiguous allocation 시 internal fragmentation (over-reserved) + external fragmentation (gap). 60-80% memory 낭비. PagedAttention: KV cache 를 fixed-size block (page) 단위로 관리, page table 로 logical → physical mapping. Prefix sharing: 같은 prompt 의 여러 sample 이 KV block 공유 → memory 1/$n$. Continuous batching 가능 → 24× throughput $\square$
02. Speculative Decoding 의 수학 복습 Setup: draft $M_q$ (작음, 빠름) 가 $\gamma$-step 추측 $x_1, \ldots, x_\gamma$, target $M_p$ 가 한 번에 verify ($\gamma+1$ logit 동시 계산). Rejection sampling: token $x$ 의 acceptance probability $\min(1, p(x | \mathrm{ctx})/q(x | \mathrm{ctx}))$. Reject 시 $\max(0, p - q)$ 에서 resample. 정리: 결과 분포 = vanilla $p$ 와 정확히 동일 (lossless) $\square$. Speedup: 1 + acceptance rate $\times \gamma$
03. Dynamic Batching 과 SLO Optimization Trade-off: 큰 batch → high throughput, large queue delay → P99 latency ↑. Continuous batching (Orca, vLLM): 매 step 마다 finished sequence drop, new request 추가 — static batch 의 padding 낭비 제거. SLO-aware scheduling: deadline 가까운 request 우선, multi-tenant priority. Latency-throughput Pareto 위에서 시스템 운영점 결정
04. Edge Deployment — Mobile / Embedded Tooling: ONNX (interchange) → ONNX Runtime / TensorRT (server) / TFLite / CoreML / TVM (edge). Compression recipe for mobile: ① distill large → small (Ch4), ② prune 50%+ (Ch2), ③ INT8 PTQ (Ch3), ④ ONNX export → target compile. Whisper on iPhone: 1.5GB → 200MB, real-time on A14. TVM: AutoSchedule + LLVM backend 로 ARM CPU/GPU/NPU custom kernel — heterogeneous edge

🆕 2026-04 최신 업데이트: Ch2-01 의 OBD 유도에 Taylor 전개의 minimum 가정과 diagonal Hessian 의 정당화를 step-by-step 으로 분리, Ch3-04 의 GPTQ 증명을 OBS (Ch2-02) 에서 column-wise 일반화로 보강, Ch4-02 의 $T^2$ factor 유도에 gradient magnitude 분석 추가, Ch6-02 의 Online Softmax tiling 의 결합법칙 증명을 명시적으로 분리, Ch6-03 의 FlashAttention HBM access 계산을 SRAM size $M$ 에 대한 정량적 형태로 재정리했습니다. 11-섹션 문서 골격이 전체 35개 문서에서 일관됩니다.

🏆 핵심 정리 인덱스

이 레포에서 완전한 증명 또는 원 논문 실험 재현 을 제공하는 대표 결과 모음입니다. 각 챕터 문서에서 $\square$ 로 종결되는 엄밀한 증명 또는 results/ 하의 학습 곡선·plot 을 확인할 수 있습니다.

정리·결과 서술 출처 문서
Roofline & Arithmetic Intensity Memory-bound vs compute-bound 경계의 정량적 정의 Ch1-01
OBD Saliency $s_i = \tfrac{1}{2}H_{ii}w_i^2$ — Taylor 2차 + diagonal Hessian Ch2-01
OBS Optimal Adjustment $\Delta L_i = \tfrac{1}{2}w_i^2/H^{-1}_{ii}$ + remaining weights 의 closed-form update Ch2-02
Lottery Ticket Hypothesis Init-dependent winning subnetwork 의 IMP 발견 가능성 Ch2-04
N:M Sparsity Hardware Speedup 2:4 sparsity 가 dense 대비 정확히 2× TFLOPS (Sparse Tensor Core) Ch2-06
STE Identity for Round $\nabla_w \approx \mathrm{stop\text{-}grad}(\mathrm{round}(w)) + w - \mathrm{stop\text{-}grad}(w)$ Ch3-03
GPTQ as OBS Generalization Column-wise Hessian-based update 가 OBS 의 직계 일반화임을 증명 Ch3-04
AWQ Equivalent Transform $W' = W \mathrm{diag}(s)^{-1}$, $X' = \mathrm{diag}(s) X$ 가 output 보존 Ch3-05
NF4 Quantile Optimality Gaussian 가정 하 NF4 가 information-theoretic near-optimal Ch3-06
KD $T^2$ Factor High-$T$ regime 에서 gradient magnitude compensation Ch4-02
Dark Knowledge Ratio Information Non-target class 확률 ratio 가 inter-class similarity 인코딩 Ch4-03
Eckart-Young Theorem Rank-$r$ SVD truncation 의 Frobenius-optimality Ch5-01
LoRA Intrinsic Rank Pre-trained adaptation 의 low intrinsic rank 가설 Ch5-03
Online Softmax Reduction Associativity Partial $(m, \ell)$ 의 결합법칙 → tiling 가능 Ch6-02
FlashAttention HBM Access $O(N^2 d/M)$ HBM 으로 $N \times N$ matrix materialize 회피 Ch6-03
PagedAttention Fragmentation Bound Page-based KV cache 가 internal+external fragmentation 동시 해결 Ch7-01
Speculative Decoding Lossless Rejection sampling 의 결과 분포 = vanilla $p$ 와 정확히 동일 Ch7-02

💡 챕터별 문서·정리/정의 수 (실측):

챕터 문서 수 정리·정의
Ch1 4대 축과 평가 4 28
Ch2 Pruning 6 48
Ch3 Quantization 6 52
Ch4 Knowledge Distillation 6 46
Ch5 Low-Rank · Hybrid 4 32
Ch6 Kernel Optimization 5 42
Ch7 Serving · Deployment 4 32
합계 35 280

추가로 130+ 엄밀한 $\square$ 증명 + 105 연습문제 (모두 해설 포함) + 130+ NumPy/PyTorch/Triton/ONNX 실험 코드 (### 실험 N 형식).

Ch1, Ch5, Ch7 은 4 문서 로 구성 — foundation 과 hybrid/serving 은 mature 주제만 다룸 (Chapters 2–4 의 6 문서, Ch6 의 5 문서와 의도적 차이).


💻 실험 환경

모든 챕터의 실험은 아래 환경에서 재현 가능합니다.

# requirements.txt
numpy==1.26.0
scipy==1.11.0
torch==2.1.0
triton==2.1.0                  # custom kernel (Ch6)
bitsandbytes==0.41.0           # NF4·INT8 (Ch3)
torch-pruning==1.3.0           # structured pruning (Ch2)
transformers==4.35.0           # teacher/student (Ch4)
accelerate==0.24.0
datasets==2.14.0
onnx==1.15.0                   # interchange (Ch7)
onnxruntime==1.16.0
onnxruntime-gpu==1.16.0
flash-attn==2.3.0              # FlashAttention-2 (Ch6)
vllm==0.2.0                    # PagedAttention (Ch7)
matplotlib==3.8.0
seaborn==0.13.0
tqdm==4.66.0
jupyter==1.0.0
# 선택 사항
tensorboard==2.15.0            # 실험 곡선
wandb==0.16.0                  # 실험 추적
auto-gptq==0.5.0               # GPTQ (Ch3)
autoawq==0.1.6                 # AWQ (Ch3)
einops==0.7.0                  # tensor 재구성
tvm==0.14.0                    # edge compile (Ch7)
# 환경 설치 (CUDA 12.1 기준)
pip install numpy==1.26.0 scipy==1.11.0 torch==2.1.0 triton==2.1.0 \
            bitsandbytes==0.41.0 torch-pruning==1.3.0 \
            transformers==4.35.0 accelerate==0.24.0 datasets==2.14.0 \
            onnx==1.15.0 onnxruntime-gpu==1.16.0 \
            flash-attn==2.3.0 vllm==0.2.0 \
            matplotlib==3.8.0 seaborn==0.13.0 tqdm==4.66.0 \
            jupyter==1.0.0 einops==0.7.0

# 실험 노트북 실행
jupyter notebook
# 대표 실험 ① — OBD saliency 와 Magnitude Pruning 비교 (Ch2-01, Ch2-03)
import torch
import torch.nn as nn
import torch.nn.functional as F

def obd_saliency(model, loader, criterion, n_samples=500):
    """diagonal Hessian 근사 (Fisher diagonal) 로 saliency 계산"""
    sal = {n: torch.zeros_like(p) for n, p in model.named_parameters() if p.requires_grad}
    for x, y in loader:
        model.zero_grad()
        loss = criterion(model(x), y)
        grads = torch.autograd.grad(loss, [p for _, p in model.named_parameters()])
        for (n, p), g in zip(model.named_parameters(), grads):
            sal[n] += g.pow(2)             # E[(∂L/∂w)²] ≈ H_diag
        if n_samples == 0: break
    return {n: 0.5 * s * p.detach().pow(2) for (n, p), s in zip(model.named_parameters(), sal.values())}

def magnitude_prune(model, sparsity=0.5):
    """가장 작은 |w| 부터 prune"""
    for name, p in model.named_parameters():
        if 'weight' in name and p.dim() >= 2:
            thr = torch.quantile(p.abs().flatten(), sparsity)
            mask = (p.abs() > thr).float()
            p.data *= mask
    return model

# 대표 실험 ② — N:M Structured Sparsity (Ch2-06)
def nm_sparsity(weight, n=2, m=4):
    """4 개 연속 weight 중 magnitude 큰 2 개만 보존 — A100 Sparse Tensor Core 호환"""
    shape = weight.shape
    w = weight.reshape(-1, m)
    _, idx = w.abs().topk(n, dim=1)
    mask = torch.zeros_like(w).scatter_(1, idx, 1)
    return (w * mask).reshape(shape)

# 대표 실험 ③ — QAT 의 Straight-Through Estimator (Ch3-03)
class FakeQuantize(torch.autograd.Function):
    """Forward: round, Backward: identity (STE, Bengio 2013)"""
    @staticmethod
    def forward(ctx, x, num_bits=8):
        q_min, q_max = -(2**(num_bits-1)), 2**(num_bits-1) - 1
        scale = x.abs().max().clamp_min(1e-8) / q_max
        return torch.clamp(torch.round(x / scale), q_min, q_max) * scale
    @staticmethod
    def backward(ctx, grad_output):
        return grad_output, None    # ∇w ≈ ∇x_q

class QuantizedLinear(nn.Module):
    def __init__(self, in_f, out_f, num_bits=8):
        super().__init__()
        self.weight = nn.Parameter(torch.randn(out_f, in_f) * 0.01)
        self.num_bits = num_bits
    def forward(self, x):
        return F.linear(x, FakeQuantize.apply(self.weight, self.num_bits))

# 대표 실험 ④ — Knowledge Distillation 과 T² factor (Ch4-02)
def kd_loss(student_logits, teacher_logits, T=4.0):
    """L_KD = T² · KL(softmax(z^T/T) || softmax(z^S/T))"""
    p_t = F.softmax(teacher_logits / T, dim=-1)
    log_p_s = F.log_softmax(student_logits / T, dim=-1)
    kl = (p_t * (p_t.clamp_min(1e-12).log() - log_p_s)).sum(-1)
    return (T ** 2) * kl.mean()      # T² 가 hard label loss 와 같은 scale 유지

def total_kd(s_logits, t_logits, labels, T=4.0, alpha=0.7):
    return (1 - alpha) * F.cross_entropy(s_logits, labels) + alpha * kd_loss(s_logits, t_logits, T)

# 대표 실험 ⑤ — Online Softmax (FlashAttention 핵심) (Ch6-02)
def online_softmax(x):
    """running max m, normalizer ℓ, single-pass numerically stable softmax"""
    m, l = -float('inf'), 0.0
    for xi in x.tolist():
        m_new = max(m, xi)
        l = l * float(torch.tensor(m - m_new).exp()) + float(torch.tensor(xi - m_new).exp())
        m = m_new
    return torch.tensor([float(torch.tensor(xi - m).exp()) / l for xi in x.tolist()])

x = torch.randn(64)
diff = (F.softmax(x, dim=0) - online_softmax(x)).abs().max()
print(f'Standard vs Online Softmax max diff: {diff:.2e}')   # ~1e-7

# 대표 실험 ⑥ — FlashAttention skeleton in Triton (Ch6-03)
import triton
import triton.language as tl

@triton.jit
def flash_attention_fwd(Q, K, V, O, sm_scale,
                        stride_qz, stride_qh, stride_qm, stride_qk,
                        Z, H, N, D,
                        BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr,
                        BLOCK_D: tl.constexpr):
    """
    Tiling 핵심:
      1. Q block (BLOCK_M × D) → SRAM
      2. K, V block (BLOCK_N × D) 순차 → SRAM
      3. S = Q K^T · sm_scale, online softmax 누적
      4. O = P V 누적
      5. 최종 정규화 후 O write
    전체 구현: Dao 2022 Figure 1 / FlashAttention repo 참조
    """
    pass

# 대표 실험 ⑦ — End-to-end compression pipeline (Ch5-04)
def compress_pipeline(model, val_loader, teacher=None):
    # Step 1: 50% magnitude pruning + iterative fine-tune
    model = magnitude_prune(model, sparsity=0.5)
    # Step 2: KD with teacher (Ch4)
    if teacher is not None:
        # ... KD training loop with total_kd loss ...
        pass
    # Step 3: INT8 QAT (Ch3) — replace nn.Linear with QuantizedLinear
    # Step 4: ONNX export → ONNX Runtime / TFLite / TVM (Ch7-04)
    # torch.onnx.export(model, dummy, "model.onnx", opset_version=17)
    return model

📖 각 문서 구성 방식

모든 문서는 다음 11-섹션 골격 으로 작성됩니다.

# 섹션 내용
1 🎯 핵심 질문 이 문서가 답하는 3~5개의 본질적 질문
2 🔍 왜 이 효율화 기법이 실전에 필수인가 해당 이론·기법이 ML 의 어떤 핵심 비효율을 푸는지
3 📐 수학적 선행 조건 PyTorch Internals · LLM Efficiency · Calc · Info 레포의 어떤 정리를 전제하는지
4 📖 직관적 이해 OBD · STE · KD temperature · FlashAttention tiling 의 기하·물리적 직관
5 ✏️ 엄밀한 정의 Saliency · Quantization grid · Soft target · Online softmax · Page table 등
6 🔬 정리와 증명 OBD saliency · GPTQ as OBS · KD $T^2$ factor · Online softmax associativity · Speculative lossless 등
7 💻 PyTorch / Triton / ONNX 구현 검증 4 가지 실험 (### 실험 1 ~ ### 실험 4) — toy MLP · ResNet · LLM · Triton kernel · ablation
8 🔗 실전 활용 언제 PTQ 언제 QAT · 언제 unstructured 언제 N:M · KD 의 task 별 recipe — 환경별 선택 가이드
9 ⚖️ 가정과 한계 Hessian diagonal 가정 · activation outlier · KD teacher quality · hardware 의존성 등
10 📌 핵심 정리 한 장으로 요약 ($\boxed{}$ 핵심 수식 + Pareto frontier 위치)
11 🤔 생각해볼 문제 (+ 해설) 기초 / 심화 / 논문 비평 의 3 문제, <details> 펼침 해설

📚 연습문제 총 105개 (35 문서 × 3 문제): 기초 / 심화 / 논문 비평 의 3-tier 구성, 모든 문제에 <details> 펼침 해설 포함. OBD saliency 손 유도부터 GPTQ 의 column-wise update 직접 구현, KD 의 $T^2$ factor gradient 증명, FlashAttention 의 HBM access 정량 계산, Speculative decoding 의 lossless 증명, BitNet 의 1.58-bit 정보량 분석까지 단계적으로 심화됩니다.

🧭 푸터 네비게이션: 각 문서 하단에 ◀ 이전 / 📚 README / 다음 ▶ 링크가 항상 제공됩니다. 챕터 경계에서도 다음 챕터 첫 문서로 자동 연결됩니다.

⏱️ 학습 시간 추정: 문서당 평균 약 500600줄 (정의·증명·코드·연습문제 포함) 기준 **약 60분1시간 30분**. 전체 35문서는 약 40~50시간 상당 (증명 재구성·Triton kernel 작성·LLM 양자화 재현 포함 시 70시간+).


🗺️ 추천 학습 경로

🟢 "GPTQ 와 FlashAttention 은 쓰지만 왜 작동하는지 이론적으로 이해하고 싶다" — 입문 투어 (1주, 약 13~15시간)
Day 1  Ch1-01  Efficiency 4대 축과 trade-off
       Ch1-02  Compression 4분류
Day 2  Ch2-01  Optimal Brain Damage
       Ch2-03  Magnitude Pruning · Iterative
Day 3  Ch3-01  Quantization 기본 수학
       Ch3-03  QAT 와 STE
Day 4  Ch3-04  GPTQ (OBS 의 LLM 적응)
       Ch3-06  NF4 · BitNet 1.58-bit
Day 5  Ch4-01  KD 의 원리
       Ch4-02  $T^2$ factor 유도
Day 6  Ch6-02  Online Softmax
       Ch6-03  FlashAttention
Day 7  Ch7-01  vLLM PagedAttention
       Ch7-02  Speculative Decoding
🟡 "Pruning + Quantization + KD 의 통합 이론을 정복한다" — 이론 집중 (2주, 약 26~30시간)
1주차 — Foundation · Pruning · Quantization
  Day 1    Ch1-01~04   4대 축 + Compression 분류 + Metric + Hardware
  Day 2    Ch2-01~02   OBD + OBS (Hessian-based 두 축)
  Day 3    Ch2-03~04   Magnitude + Lottery Ticket
  Day 4    Ch2-05~06   Movement + N:M Structured
  Day 5    Ch3-01~02   Quantization 기본 + PTQ
  Day 6    Ch3-03~04   QAT + STE + GPTQ
  Day 7    Ch3-05~06   AWQ/SmoothQuant + Low-bit

2주차 — Distillation · Hybrid · Kernel · Serving
  Day 1    Ch4-01~02   KD 원리 + $T^2$ factor
  Day 2    Ch4-03~04   Dark Knowledge + Feature Distillation
  Day 3    Ch4-05~06   Taxonomy + Self-Distillation
  Day 4    Ch5-01~02   SVD + Tucker/CP
  Day 5    Ch5-03~04   LoRA + Hybrid Recipe
  Day 6    Ch6-01~03   Attention IO + Online Softmax + FlashAttention
  Day 7    Ch6-04~05   FlashAttention v2/v3 + Kernel Fusion
🔴 "Efficient ML 의 수학을 완전 정복한다" — 전체 정복 (8주, 약 40~50시간 + 재현 실험 15~20시간)
1주차   Chapter 1 전체 — Foundation
         → Roofline model 손 계산 (특정 GPU 의 boundary)
         → 4 compression 의 orthogonality 증명
         → Pareto frontier 시각화 (MLPerf 데이터)

2주차   Chapter 2 전체 — Pruning
         → OBD Taylor 전개 손 유도 (diagonal H 가정 명시)
         → OBS 의 closed-form adjustment 직접 도출
         → Lottery Ticket 의 IMP 직접 재현 (ResNet-20 + CIFAR-10)
         → 2:4 N:M sparsity 의 cuSPARSELt 호환 검증

3주차   Chapter 3 전체 — Quantization
         → STE 의 미분 우회 직접 증명
         → GPTQ 의 column-wise update 를 OBS 에서 한 줄 한 줄 일반화
         → AWQ 의 equivalent transform 손 유도
         → NF4 의 Gaussian quantile near-optimality 정량화

4주차   Chapter 4 전체 — Knowledge Distillation
         → $T^2$ factor 의 gradient magnitude 분석
         → Dark Knowledge 의 ratio 정보량 정량 측정 (MNIST teacher logit)
         → FitNets / Attention Transfer 의 ablation
         → Born-Again Network 의 generation 별 성능

5주차   Chapter 5 전체 — Low-Rank · Hybrid
         → Eckart-Young 정리 손 증명
         → Tucker decomposition 으로 ResNet conv 분해
         → LoRA intrinsic rank 측정
         → Han 2016 Deep Compression 49× 직접 재현

6주차   Chapter 6 전체 — Kernel Optimization
         → Online Softmax 결합법칙 손 증명
         → FlashAttention HBM access 의 SRAM size 의존성 정량
         → Triton 으로 FlashAttention forward kernel 직접 작성
         → 측정: standard vs Flash, FP16 vs FP8 (H100)

7주차   Chapter 7 (1~2) — Serving 의 핵심
         → PagedAttention 의 page table 직접 구현 (single-machine 시뮬레이션)
         → Speculative decoding 의 rejection sampling lossless 증명 + 재현

8주차   Chapter 7 (3~4) + 종합 — Edge & Production
         → Continuous batching 의 latency-throughput Pareto 측정
         → Mobile end-to-end: distill → prune → INT8 → ONNX → TFLite
         → Whisper-mobile 재현 (1.5GB → 200MB, real-time on phone)
         → 종합 토론: "GPTQ + FlashAttention + PagedAttention 이 LLM serving 의 새 표준이 된 이유"

🔗 연관 레포지토리

레포 주요 내용 연관 챕터
pytorch-internals-deep-dive CUDA · Triton · Mixed Precision · autograd Ch6 전체 (kernel), Ch3-03 (QAT autograd)
llm-efficiency-deep-dive LoRA · QLoRA · MoE · Speculative 기초 Ch5-03 (LoRA), Ch7-02 (Speculative)
calculus-optimization-deep-dive Hessian · Taylor · Lagrangian · KKT Ch2 (OBD/OBS), Ch3-04 (GPTQ Hessian)
information-theory-deep-dive KL divergence · Entropy · Quantile Ch3 (calibration), Ch4 (KD KL loss)
neural-network-theory-deep-dive Weight 분포 · Lipschitz · Generalization Ch2 (pruning sensitivity), Ch4 (KD transfer)
advanced-rl-deep-dive TRPO · PPO · SAC · TD3 · RLHF · DPO RLHF inference 의 효율화에서 교차
mlops-deep-dive (다음) Monitoring · A/B test · Quality drift Ch7 이후 의 production 운영
transformer-deep-dive Attention · KV cache · Scaling Law Ch6 전체 (FlashAttention), Ch7-01 (PagedAttention)

💡 이 레포는 "Pruning · Quantization · KD · Kernel · Serving 이 모두 수학적으로 정당화된 trade-off 의 다른 구현이고, OBD saliency · STE · GPTQ Hessian · KD $T^2$ · FlashAttention tiling 이 왜 각각의 이론적 동기를 갖는가" 에 집중합니다. PyTorch Internals 에서 CUDA 와 Triton 을, LLM Efficiency 에서 LoRA 와 speculative 를, Calc & Optim 에서 Hessian 과 Taylor 를, Info 에서 KL 과 entropy 를 익힌 후 오면 Chapter 2 (OBD-OBS-GPTQ 일직선) 와 Chapter 6 (Online Softmax → FlashAttention → v3 H100) 의 증명이 훨씬 자연스럽습니다. MLOps Deep Dive 와 함께 보면 Ch7 의 PagedAttention · Continuous Batching · Edge deployment 가 production serving 의 표준이 된 맥락이 선명해집니다.


📖 Reference

🪓 Pruning

  • Optimal Brain Damage (LeCun, Denker, Solla, 1990) — OBD 효시
  • Second Order Derivatives for Network Pruning: Optimal Brain Surgeon (Hassibi & Stork, 1993) — OBS
  • Learning both Weights and Connections for Efficient Neural Networks (Han, Pool, Tran, Dally, 2015) — Magnitude Pruning
  • Deep Compression (Han, Mao, Dally, 2016) — Pruning + Quantization + Huffman
  • The Lottery Ticket Hypothesis: Finding Sparse, Trainable Neural Networks (Frankle & Carbin, 2019)
  • Linear Mode Connectivity and the Lottery Ticket Hypothesis (Frankle, Dziugaite, Roy, Carbin, 2020)
  • Movement Pruning: Adaptive Sparsity by Fine-Tuning (Sanh, Wolf, Rush, 2020)
  • Accelerating Sparse Deep Neural Networks (Mishra et al., NVIDIA, 2021) — 2:4 N:M Sparsity
  • A Survey on Deep Neural Network Pruning (Cheng et al., 2024)

🔢 Quantization

  • Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation (Bengio, Léonard, Courville, 2013) — STE
  • Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference (Jacob et al., 2018) — QAT
  • PACT: Parameterized Clipping Activation for Quantized Neural Networks (Choi et al., 2018)
  • Data-Free Quantization Through Weight Equalization and Bias Correction (Nagel et al., 2019)
  • GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers (Frantar, Ashkboos, Hoefler, Alistarh, 2023)
  • AWQ: Activation-Aware Weight Quantization for LLM Compression and Acceleration (Lin et al., 2023)
  • SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models (Xiao et al., 2023)
  • QLoRA: Efficient Finetuning of Quantized LLMs (Dettmers, Pagnoni, Holtzman, Zettlemoyer, 2023) — NF4
  • The Era of 1-bit LLMs: All Large Language Models are in 1.58 Bits (Ma et al., 2024) — BitNet b1.58
  • OmniQuant: Omnidirectionally Calibrated Quantization for Large Language Models (Shao et al., 2023)

🧪 Knowledge Distillation

  • Distilling the Knowledge in a Neural Network (Hinton, Vinyals, Dean, 2015) — KD 효시
  • FitNets: Hints for Thin Deep Nets (Romero et al., 2015)
  • Paying More Attention to Attention (Zagoruyko & Komodakis, 2017) — Attention Transfer
  • Born Again Neural Networks (Furlanello et al., 2018) — Self-Distillation
  • Relational Knowledge Distillation (Park, Kim, Lu, Cho, 2019) — RKD
  • Knowledge Distillation: A Survey (Gou et al., 2021)
  • Towards Understanding Ensemble, Knowledge Distillation and Self-Distillation in Deep Learning (Allen-Zhu & Li, 2020)
  • DistilBERT, a distilled version of BERT (Sanh, Debut, Chaumond, Wolf, 2019)
  • TinyBERT: Distilling BERT for Natural Language Understanding (Jiao et al., 2020)

🧮 Low-Rank · Hybrid Compression

  • Speeding-up Convolutional Neural Networks Using Fine-tuned CP-Decomposition (Lebedev et al., 2014)
  • Tensor Decompositions for Learning Latent Variable Models (Anandkumar et al., 2014)
  • LoRA: Low-Rank Adaptation of Large Language Models (Hu et al., 2022)
  • Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning (Aghajanyan, Zettlemoyer, Gupta, 2020)
  • SqueezeLLM: Dense-and-Sparse Quantization (Kim et al., 2023)
  • A Unified Framework of Soft Threshold Pruning (Liu et al., 2023)

⚙️ Kernel · System

  • Online Normalizer Calculation for Softmax (Milakov & Gimelshein, 2018) — Online Softmax
  • FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (Dao, Fu, Ermon, Rudra, Ré, 2022)
  • FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning (Dao, 2023)
  • FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-Precision (Shah et al., 2024)
  • Self-Attention Does Not Need O(n²) Memory (Rabe & Staats, 2021) — Memory-efficient attention
  • Triton: An Intermediate Language and Compiler for Tiled Neural Network Computations (Tillet, Kung, Cox, 2019)
  • TorchInductor / TorchDynamo (PyTorch 2.0 stack) — automatic kernel fusion

🚀 Serving · Inference

  • Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023) — vLLM
  • DeepSpeed-Inference: Enabling Efficient Inference of Transformer Models at Unprecedented Scale (Aminabadi et al., 2022)
  • Fast Inference from Transformers via Speculative Decoding (Leviathan, Kalman, Matias, 2023)
  • Accelerating Large Language Model Decoding with Speculative Sampling (Chen et al., 2023)
  • Orca: A Distributed Serving System for Transformer-Based Generative Models (Yu et al., 2022) — Continuous Batching
  • MEDUSA: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads (Cai et al., 2024)
  • Online Speculative Decoding (Liu et al., 2024)

📱 Edge · Compiler

  • TVM: An Automated End-to-End Optimizing Compiler for Deep Learning (Chen et al., 2018)
  • MLC-LLM: Universal LLM Deployment Engine with ML Compilation (MLC team, 2023)
  • TensorFlow Lite Micro (David et al., 2021)
  • MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications (Howard et al., 2017)

🛠️ Implementation · Libraries

  • bitsandbytes (Dettmers, 2022) — INT8 / NF4 quantization
  • AutoGPTQ — community GPTQ implementation
  • AutoAWQ — community AWQ implementation
  • vLLM (Kwon et al., 2023) — PagedAttention serving
  • TensorRT-LLM (NVIDIA, 2023)
  • HuggingFace Optimum — ONNX / TensorRT export 통합
  • Hugging Face Transformers (Wolf et al., 2020)

⭐️ 도움이 되셨다면 Star 를 눌러주세요!

Made with ❤️ by IQ AI Lab


"GPTQ 를 호출하는 것과 — LeCun 1990 의 OBD saliency 가 loss 의 2차 Taylor 에서 정확히 도출됨을 증명 · Hassibi 1993 의 OBS 가 어떻게 remaining weights 의 optimal adjustment 까지 푸는지 손 유도 · Frantar 2023 가 OBS 의 column-wise 일반화로 4-bit LLM 표준이 된 한 줄씩의 진화 추적 · Hinton 2015 의 $T^2$ factor 가 gradient magnitude compensation 에서 자연스럽게 도출됨을 미분 · Bengio 2013 의 STE 가 non-differentiable round 를 어떻게 우회하는지 분석 · Milakov 2018 의 Online Softmax 가 Dao 2022 의 FlashAttention tiling 으로 어떻게 일반화되는지 — 그리고 Kwon 2023 의 PagedAttention 이 OS virtual memory 영감으로 KV cache fragmentation 을 어떻게 해결하는지 — 이 모든 '왜' 를 직접 유도할 수 있는 것은 다르다"

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors