[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,63 +2,160 @@
|
||||
id: wiki-2026-0508-mobile-ai-optimization
|
||||
title: Mobile AI Optimization
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [AI-MOB-OPT-001]
|
||||
aliases: [On-device AI, Mobile Inference, Edge ML, Mobile AI 최적화]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [ai, mobile-ai, Optimization, Quantization, on-device-ai, Edge-Computing]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [mobile, edge, inference, coreml, tflite, mlx, npu, quantization, distillation]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack: { language: swift-kotlin-python, framework: coreml-tflite-mlx }
|
||||
---
|
||||
|
||||
# Mobile AI Optimization (모바일 AI 최적화)
|
||||
# Mobile AI Optimization
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "거대 모델의 지능을 스마트폰이라는 좁은 틀에 맞춰 압축하되, 그 핵심적인 사고의 깊이는 잃지 마라" — 모바일 기기의 제한된 컴퓨팅 자원(CPU, GPU, NPU)과 배터리 환경에서 AI 모델이 지연 시간 없이 효율적으로 작동하도록 수행하는 모델 경량화 및 실행 최적화 기술.
|
||||
## 매 한 줄
|
||||
> **"매 와트, 매 메가바이트, 매 밀리초"**. Mobile AI 최적화는 모델 크기·메모리·전력·지연을 동시에 압축해 NPU/GPU/CPU 가 실시간으로 돌릴 수 있게 만드는 기술 묶음 — quantization, distillation, NPU compile, runtime cache 가 핵심 축.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Lightweight Inference and [[Hardware|Hardware]] Awareness" — 모델의 정확도 손실을 최소화하면서 파라미터 크기를 줄이고, 타겟 기기의 전용 가속기(NPU 등)를 최대로 활용하여 실시간성에 가까운 추론 속도를 확보하는 하드웨어 친화적 최적화 패턴.
|
||||
- **주요 최적화 기법:**
|
||||
- **Quantization (양자화):** 32비트 부동소수점을 8비트 정수 등으로 변환하여 용량과 연산 속도 개선.
|
||||
- **Pruning (가지치기):** 성능에 기여도가 낮은 가중치를 제거하여 모델 크기 축소.
|
||||
- **Knowledge [[Distillation|Distillation]] (지식 증류):** 큰 모델(Teacher)의 지식을 작은 모델(Student)로 전수.
|
||||
- **Hardware Acceleration:** CoreML, TensorFlow Lite, ONNX 등을 활용한 하드웨어 최적화 런타임 사용.
|
||||
- **의의:** 서버 연결 없이도 개인정보를 보호하며 오프라인에서 즉각 응답하는 '온디바이스 AI(On-device AI)' 시대를 여는 핵심 기술.
|
||||
## 매 핵심
|
||||
### 매 타겟 하드웨어
|
||||
- **Apple Neural Engine (ANE)**: A12+/M-series, INT8/FP16, CoreML 통한 접근.
|
||||
- **Apple Silicon GPU + MLX**: M1+ 통합 메모리, FP16/BF16 LLM 친화.
|
||||
- **Qualcomm Hexagon NPU (SNPE/QNN)**: Snapdragon 8 Gen3+, INT4/INT8 가속.
|
||||
- **Google Tensor TPU / NNAPI**: Pixel 시리즈, edge TPU.
|
||||
- **MediaTek APU**, **Samsung Exynos NPU** — 각자 SDK.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 모바일 AI는 단순히 '작은 모델'을 의미했으나, 이제는 기기 자체에서 소규모 학습이나 개인화가 가능한 지능형 엣지 노드로 역할이 고도화됨.
|
||||
- **정책 변화:** Antigravity 프로젝트는 모바일 인터페이스나 로컬 에이전트 브레인 구현 시, 4비트 양자화 기술을 적용하여 최소한의 메모리 점유로 최대의 추론 성능을 보장하는 것을 원칙으로 함.
|
||||
### 매 최적화 축
|
||||
1. **모델 압축**: pruning, quantization (FP16/INT8/INT4), low-rank factorization.
|
||||
2. **지식 증류 (distillation)**: 큰 teacher → 작은 student.
|
||||
3. **아키텍처 search**: MobileNet, EfficientNet, MobileViT, Phi-3-mini, Gemma-Nano.
|
||||
4. **컴파일러**: CoreML, TFLite, ONNX Runtime Mobile, ExecuTorch, MLX, MLC-LLM.
|
||||
5. **런타임**: graph fusion, weight sharing, KV cache, speculative decode (LLM).
|
||||
6. **System**: thermal throttle 회피, BG mode 제한, ANE/NPU off-load.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Inference-Optimization|Inference-Optimization]], [[Knowledge-Distillation|Knowledge-Distillation]], [[Hardware-Acceleration-for-AI|Hardware-Acceleration-for-AI]], [[Local-Brain-Management|Local-Brain-Management]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Mobile-AI-Optimization.md
|
||||
### 매 LLM-on-device 트렌드
|
||||
- 1B–7B 모델 + 4-bit quant → iPhone/Android 실행.
|
||||
- Apple Foundation Models (~3B), Gemini Nano, Phi-3-mini, Llama-3.2-1B/3B.
|
||||
- KV cache 가 메모리 dominant — paged / sliding window.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
### 1. PyTorch → CoreML
|
||||
```python
|
||||
import coremltools as ct, torch
|
||||
model.eval()
|
||||
example = torch.randn(1,3,224,224)
|
||||
ts = torch.jit.trace(model, example)
|
||||
mlmodel = ct.convert(
|
||||
ts, inputs=[ct.ImageType(shape=example.shape, scale=1/255.)],
|
||||
compute_units=ct.ComputeUnit.CPU_AND_NE,
|
||||
minimum_deployment_target=ct.target.iOS17
|
||||
)
|
||||
mlmodel = ct.models.neural_network.quantization_utils.quantize_weights(mlmodel, nbits=8)
|
||||
mlmodel.save("Model.mlpackage")
|
||||
```
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 2. TFLite INT8 PTQ
|
||||
```python
|
||||
import tensorflow as tf
|
||||
conv = tf.lite.TFLiteConverter.from_saved_model("model")
|
||||
conv.optimizations = [tf.lite.Optimize.DEFAULT]
|
||||
conv.representative_dataset = lambda: ([np.random.randn(1,224,224,3).astype(np.float32)] for _ in range(100))
|
||||
conv.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
|
||||
conv.inference_input_type = tf.int8
|
||||
conv.inference_output_type = tf.int8
|
||||
open("model_int8.tflite","wb").write(conv.convert())
|
||||
```
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 3. MLX LLM (Apple Silicon)
|
||||
```python
|
||||
from mlx_lm import load, generate
|
||||
model, tok = load("mlx-community/Llama-3.2-3B-Instruct-4bit")
|
||||
print(generate(model, tok, prompt="Hello", max_tokens=128))
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### 4. Knowledge distillation
|
||||
```python
|
||||
T = 4.0
|
||||
loss_kd = (T*T) * F.kl_div(F.log_softmax(s/T,-1), F.softmax(t/T,-1), reduction="batchmean")
|
||||
loss = 0.7*loss_kd + 0.3*F.cross_entropy(s, y)
|
||||
```
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### 5. Structured pruning
|
||||
```python
|
||||
import torch.nn.utils.prune as P
|
||||
P.ln_structured(layer, name="weight", amount=0.3, n=2, dim=0) # channel prune
|
||||
P.remove(layer, "weight")
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### 6. ONNX Runtime Mobile (Android)
|
||||
```kotlin
|
||||
val env = OrtEnvironment.getEnvironment()
|
||||
val opts = OrtSession.SessionOptions().apply { addNnapi() }
|
||||
val session = env.createSession(modelBytes, opts)
|
||||
val out = session.run(mapOf("input" to OnnxTensor.createTensor(env, input)))
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### 7. KV cache + sliding window for LLM
|
||||
```python
|
||||
# generate loop 에서 past_key_values 재사용 → O(N) → O(1)/token
|
||||
out = model(input_ids, past_key_values=past, use_cache=True)
|
||||
past = out.past_key_values
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### 8. Thermal-aware scheduling
|
||||
```swift
|
||||
let thermal = ProcessInfo.processInfo.thermalState
|
||||
let units: MLComputeUnits = (thermal == .nominal) ? .cpuAndNeuralEngine : .cpuOnly
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### 9. Asset slimming
|
||||
- weight 압축 (zstd) + on-launch decompress, mmap, partial load.
|
||||
- multi-target export (small/medium/large) + adaptive download.
|
||||
|
||||
### 10. Profiling
|
||||
```bash
|
||||
xcrun coremlcompiler --target iphoneos17.0 ...
|
||||
# Xcode Instruments → Core ML / Neural Engine / GPU / Energy
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 목표 | 우선 기법 |
|
||||
|---|---|
|
||||
| latency ↓ | NPU off-load + INT8 + graph fusion |
|
||||
| 모델 크기 ↓ | INT4 quant + pruning + distillation |
|
||||
| 전력 ↓ | NPU 전용 + 낮은 freq + thermal-aware |
|
||||
| 정확도 보존 | QAT > PTQ, distill |
|
||||
| 빠른 iteration | TFLite/CoreML PTQ → 바로 측정 |
|
||||
| LLM-on-device | 4-bit + KV cache + 작은 ctx |
|
||||
|
||||
**기본값**: PTQ INT8 + NPU 컴파일, accuracy drop > 1% 시 QAT, 6B+ LLM 은 4-bit + MLX/MLC.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Edge-AI]], [[Model-Compression]]
|
||||
- 변형: [[Quantization]], [[Knowledge-Distillation]], [[Pruning]], [[NAS]]
|
||||
- 응용: [[On-Device-LLM]], [[AR-Filter]], [[Camera-AI]], [[Voice-Assistant]]
|
||||
- Adjacent: [[CoreML]], [[TFLite]], [[MLX]], [[ExecuTorch]], [[MLC-LLM]], [[ONNX-Runtime]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: pipeline boilerplate, quant config 추천, 모델 크기 추정.
|
||||
**언제 X**: 실제 디바이스 latency/전력 측정 (실측 필수).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- INT8 PTQ 후 정확도만 보고 deploy — latency/메모리 측정 누락.
|
||||
- NPU 미지원 op 가 들어가 매 step CPU fallback — graph 가 분절되면 NPU 이득 사라짐.
|
||||
- LLM ctx 32k on-device — KV cache 가 RAM 폭주.
|
||||
- BG 에서 무거운 inference — OS 가 kill 하거나 thermal throttle.
|
||||
- 한 디바이스만 테스트 — Snapdragon/Tensor/Apple 다 다른 결과.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified. 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup |
|
||||
|
||||
Reference in New Issue
Block a user