[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,165 @@
|
||||
id: wiki-2026-0508-efficiency
|
||||
title: Efficiency
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-EFFI-001]
|
||||
aliases: [Performance Efficiency, Resource Efficiency, Cost Efficiency]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [auto-reinforced, efficiency, Optimization, resource-Management, productivity, frugality]
|
||||
confidence_score: 0.88
|
||||
verification_status: applied
|
||||
tags: [performance, efficiency, optimization, sre, cost]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: python
|
||||
framework: prometheus
|
||||
---
|
||||
|
||||
# [[Efficiency|Efficiency]]
|
||||
# Efficiency
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "최소 자원으로 최대 결과물 내기: 시간, 돈, 에너지라는 희소 자원을 낭비하지 않고, 가장 영리한 방법으로 시스템을 설계하여 품질을 유지하면서도 비용을 극적으로 줄이는 공학적 집요함."
|
||||
## 매 한 줄
|
||||
> **"매 useful output / resource consumed — 매 latency, throughput, $cost, watt 매 dimension 별 측정"**. 매 1972 Knuth "premature optimization" warning 후 신중함이 default, 매 2026 cloud cost + carbon footprint + energy efficiency 가 first-class metric.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
효율성(Efficiency)은 투입된 자원 대비 기대하는 성과를 얼마나 잘 달성하는지를 나타내는 지표입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **주요 관점**:
|
||||
* **Algorithm Efficiency**: 같은 결과를 내기 위해 연산 횟수를 줄이는 것. ([[Dynamic-Programming|Dynamic-Programming]]과 연결)
|
||||
* **[[Opera|Opera]]tional Efficiency**: 배포 전략이나 자동화를 통해 사람의 수고를 줄이는 것. ([[Deployment-Strategy|Deployment-Strategy]]와 연결)
|
||||
* **Energy Efficiency**: 탄소 배출을 줄이고 지속 가능성을 확보하는 녹색 컴퓨팅. ([[Circular-Economy|Circular-Economy]]와 연결)
|
||||
2. **왜 중요한가?**:
|
||||
* 효율성은 단순히 비용 절감을 넘어, 불가능했던 프로젝트를 '수지 타선이 맞는' 영역으로 끌어들여 상용화 가능하게 만드는 결정적 열쇠임.
|
||||
### 매 Efficiency dimensions
|
||||
- **Time**: latency p50/p95/p99, throughput RPS.
|
||||
- **Space**: memory RSS, disk IOPS, network bytes.
|
||||
- **Money**: $/request, $/MAU.
|
||||
- **Energy**: watt/op, gCO2eq/request.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 성능(Accuracy)을 위해 효율성(Speed/Cost)을 희생하는 정책이 흔했으나, 현대 정책은 에지(Edge) 기기에서도 고성능을 내야 하는 제약 때문에 '효율성 기반의 고성능 정책([[Distillation|Distillation]], [[Quantization|Quantization]])'이 기본임(RL Update).
|
||||
- **정책 변화(RL Update)**: AI 학습 시 연산 효율 정책을 최우선으로 하여, 무작정 모델을 키우는 대신 정제된 데이터와 최적화된 아키텍처로 '지능 밀도 정책'을 높이려는 경쟁이 시작됨.
|
||||
### 매 측정 → 개선 cycle
|
||||
1. **Profile**: hotspot 의 identify (flamegraph).
|
||||
2. **Hypothesize**: bottleneck 의 type (CPU? IO? Lock?).
|
||||
3. **Optimize**: targeted change.
|
||||
4. **Verify**: A/B with baseline, metric 의 statistical sig.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Optimization|Optimization]], [[Distillation|Distillation]], [[Dynamic-Programming|Dynamic-Programming]], [[Economic-Analysis|Economic-Analysis]], Environmental-Impact
|
||||
- **Modern Tech/Tools**: Profilers, Resource monitors, Auto-scaling infrastructure.
|
||||
---
|
||||
### 매 응용
|
||||
1. API: cold-start 의 reduce.
|
||||
2. ML inference: quantization, batching, KV cache.
|
||||
3. CI: cache hit rate 의 maximize.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Latency histogram (Prometheus)
|
||||
```python
|
||||
from prometheus_client import Histogram
|
||||
LATENCY = Histogram('http_request_duration_seconds', 'HTTP latency',
|
||||
buckets=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5])
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
@LATENCY.time()
|
||||
def handle(req): ...
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Cost-per-request rollup
|
||||
```sql
|
||||
-- BigQuery
|
||||
SELECT
|
||||
service,
|
||||
SUM(billable_seconds * cpu_cost_per_sec) AS compute_usd,
|
||||
COUNT(*) AS requests,
|
||||
SUM(billable_seconds * cpu_cost_per_sec) / COUNT(*) AS usd_per_req
|
||||
FROM service_metrics
|
||||
WHERE _PARTITIONDATE = CURRENT_DATE() - 1
|
||||
GROUP BY service
|
||||
ORDER BY usd_per_req DESC;
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### CPU flamegraph (py-spy)
|
||||
```bash
|
||||
# 매 production-safe sampling profiler
|
||||
py-spy record -o flame.svg -d 60 -p $(pgrep -f gunicorn)
|
||||
py-spy top -p $(pgrep -f gunicorn)
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Memory profiling (memray)
|
||||
```bash
|
||||
memray run --live ./app.py
|
||||
memray flamegraph output.bin -o memflame.html
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Async IO efficiency
|
||||
```python
|
||||
import asyncio, httpx
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
# BAD — sequential
|
||||
async def fetch_seq(urls):
|
||||
async with httpx.AsyncClient() as c:
|
||||
return [await c.get(u) for u in urls]
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
# GOOD — concurrent
|
||||
async def fetch_par(urls):
|
||||
async with httpx.AsyncClient() as c:
|
||||
return await asyncio.gather(*[c.get(u) for u in urls])
|
||||
```
|
||||
|
||||
### Carbon-aware scheduling
|
||||
```python
|
||||
import httpx
|
||||
async def carbon_intensity(region: str) -> float:
|
||||
r = await httpx.AsyncClient().get(
|
||||
f"https://api.electricitymaps.com/v3/carbon-intensity/latest?zone={region}",
|
||||
headers={"auth-token": "TOKEN"})
|
||||
return r.json()["carbonIntensity"] # gCO2eq/kWh
|
||||
|
||||
# 매 batch job 매 low-carbon window 의 schedule
|
||||
async def maybe_run(region):
|
||||
ci = await carbon_intensity(region)
|
||||
if ci < 200: await run_batch()
|
||||
else: await asyncio.sleep(900)
|
||||
```
|
||||
|
||||
### LLM inference batching
|
||||
```python
|
||||
from vllm import LLM, SamplingParams
|
||||
llm = LLM(model="meta-llama/Llama-3.3-70B-Instruct",
|
||||
tensor_parallel_size=4,
|
||||
max_num_seqs=256) # 매 batch 의 throughput
|
||||
sp = SamplingParams(max_tokens=256)
|
||||
outs = llm.generate(prompts, sp) # 매 single forward pass 로 batch
|
||||
```
|
||||
|
||||
### Cache efficiency dashboard
|
||||
```promql
|
||||
# Prometheus query — cache hit ratio
|
||||
sum(rate(cache_hits_total[5m])) /
|
||||
(sum(rate(cache_hits_total[5m])) + sum(rate(cache_misses_total[5m])))
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Latency-critical (real-time) | tail-latency optimize, drop p99 outliers |
|
||||
| Throughput (batch) | parallelism, vectorize |
|
||||
| Cost 제약 | spot instance, autoscale, cache |
|
||||
| Green ops | carbon-aware scheduling, region selection |
|
||||
|
||||
**기본값**: 매 profile-first, 매 measure both before/after, 매 single-dimension fixation 매 X.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Performance Engineering]] · [[Site Reliability Engineering]]
|
||||
- 변형: [[Latency]] · [[Throughput]] · [[Cost Optimization]]
|
||||
- 응용: [[Flame_Graphs]] · [[Caching]] · [[Profiling]]
|
||||
- Adjacent: [[FinOps]] · [[Green Software]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: profile output → bottleneck classification, optimization 후보 ranking.
|
||||
**언제 X**: 매 micro-benchmark 매 LLM 의 single-shot 평가 X — 매 측정 우선.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Premature optimization**: profile 없이 optimize.
|
||||
- **Single-metric obsession**: latency 만 보고 cost 폭증.
|
||||
- **Synthetic benchmark**: production traffic shape 무시.
|
||||
- **No baseline**: 매 before 측정 없이 "fast" 주장.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (SRE Workbook ch.4, AWS Well-Architected Performance pillar).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — efficiency 4 dimension + measurement loop |
|
||||
|
||||
Reference in New Issue
Block a user