[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,91 +1,186 @@
|
||||
---
|
||||
id: wiki-2026-0508-just-in-time-jit
|
||||
title: Just In Time (JIT)
|
||||
title: Just-In-Time (JIT)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-JITT-001]
|
||||
aliases: [JIT Compilation, Dynamic Compilation, Tracing JIT]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [auto-reinforced, jit, just-in-time, compiler, Optimization, performance, logistics]
|
||||
verification_status: applied
|
||||
tags: [compiler, optimization, runtime, performance, llvm]
|
||||
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: jax
|
||||
---
|
||||
|
||||
# [[Just-In-Time (JIT)|Just-In-Time (JIT)]]
|
||||
# Just-In-Time (JIT)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "필요할 때 바로: 미리 정해진 계획에 따라 몽땅 해놓는 게 아니라, 실제 상황이 닥쳤을 때(런타임 혹은 주문 발생 시) 그 즉시 최적의 조치를 취함으로써 자원의 낭비를 줄이고 반응 속도를 극대화하는 민첩한 최적화."
|
||||
## 매 한 줄
|
||||
> **"매 compile 매 first call, 매 reuse 매 hot path"**. JIT compilation 매 source / bytecode / IR 의 native code 의 runtime translation — 매 profile-guided 의 hot region 의 optimize. 2026 ML 시대 매 JAX `jit`, PyTorch 2.x `torch.compile`, Mojo, JuliaLang 매 mainstream.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
JIT(Just-In-Time)는 컴퓨팅과 물류 분야에서 공통적으로 쓰이는 '적시 처리' 철학입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **분야별 사례**:
|
||||
* **Computing (JIT Compiler)**: 프로그램 전체를 미리 기계어로 바꾸지 않고, 실행되는 순간(Just-in-time) 필요한 부분만 컴파일하여 성능 최적화 (Java, Python 가속기 등). ([[Efficiency|Efficiency]]와 연결)
|
||||
* **Logistics (Toyota 생산 방식)**: 재고를 쌓지 않고 주문이 들어온 만큼만 부품을 조달하여 생산 (Lean과 유사).
|
||||
2. **왜 중요한가?**:
|
||||
* 정적인 미리 준비(Ahead-of-Time)보다 동적인 실제 상황 데이터를 반영할 수 있어 효율성과 유연성이 압도적으로 높음. (Optimization의 정수)
|
||||
### 매 JIT 의 mechanics
|
||||
- **Trace**: 매 input shape / dtype 의 capture 매 computational graph.
|
||||
- **Specialize**: 매 fixed shapes 의 specialized kernel 의 generate.
|
||||
- **Cache**: 매 (function, signature) → compiled artifact.
|
||||
- **Recompile**: 매 shape change → cache miss → recompile (avoid in hot loop).
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 JIT가 실행 시점에 부하를 준다는 정책적 우려가 있었으나, 현대 정책은 런타임 프로파일링 정책을 통해 '가장 자주 쓰이는 코드 정책'만 집중 가속하여 전체 성능을 사전 컴파일보다 높게 만드는 단계에 도달함(RL Update).
|
||||
- **정책 변화(RL Update)**: AI 추론 정책에서도 모든 모델 파라미터를 메모리에 올리기보다, 입력값에 따라 필요한 계층만 로드하거나 활성화하는 '동적 추론(JIT Inference) 정책'이 기기 내(On-device) AI의 핵심 기술로 부상함.
|
||||
### 매 vs AOT
|
||||
- **AOT (ahead-of-time)**: rustc, gcc — startup 빠름, 매 dynamic dispatch 부족.
|
||||
- **JIT**: 매 runtime info 의 use → better inlining, 매 startup 의 cost.
|
||||
- **Hybrid**: PyPy, V8, .NET — interpret first, JIT after N invocations.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Efficiency|Efficiency]], [[Optimization|Optimization]], [[Hardware|Hardware]], [[Distributed-Systems|Distributed-Systems]], Moore's Law
|
||||
- **Modern Tech/Tools**: JVM HotSpot, [[V8 Engine|V8 Engine]] ([[JavaScript|JavaScript]]), PyTorch JIT, JAX, Lean manufacturing.
|
||||
---
|
||||
### 매 ML JIT 의 specifics
|
||||
- **Static shape**: JAX `jit` 매 traced shape 의 specialize — dynamic shape 매 retrace.
|
||||
- **XLA / Triton backend**: 매 fused kernels — memory bandwidth dominant.
|
||||
- **Compilation cache**: persistent disk cache 매 cold-start 의 mitigate.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. ML training loop (JAX, torch.compile).
|
||||
2. Numerical Python (Numba `@njit`).
|
||||
3. JavaScript engines (V8, JSC).
|
||||
4. Database query plans (Snowflake, DuckDB).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Pattern 1: JAX jit (2026 standard)
|
||||
```python
|
||||
import jax
|
||||
import jax.numpy as jnp
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
@jax.jit
|
||||
def attention(q, k, v):
|
||||
scores = jnp.einsum("bhqd,bhkd->bhqk", q, k) / jnp.sqrt(q.shape[-1])
|
||||
weights = jax.nn.softmax(scores, axis=-1)
|
||||
return jnp.einsum("bhqk,bhkd->bhqd", weights, v)
|
||||
|
||||
- **정보 상태:** 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
|
||||
# First call: trace + compile (slow)
|
||||
# Subsequent: cached (fast)
|
||||
out = attention(q, k, v)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Pattern 2: torch.compile (PyTorch 2.x)
|
||||
```python
|
||||
import torch
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
model = MyTransformer().cuda()
|
||||
compiled = torch.compile(model, mode="reduce-overhead", fullgraph=True)
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
for batch in dataloader:
|
||||
out = compiled(batch) # 매 first batch 매 slow, subsequent 매 fast
|
||||
out.backward()
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Pattern 3: Static argnums (avoid retrace)
|
||||
```python
|
||||
from functools import partial
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
@partial(jax.jit, static_argnums=(1,))
|
||||
def topk(logits, k):
|
||||
return jax.lax.top_k(logits, k)
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
# 매 k=10 매 specialized — 매 k=20 매 separate compilation
|
||||
topk(logits, 10)
|
||||
topk(logits, 20) # new compile
|
||||
```
|
||||
|
||||
### Pattern 4: Numba JIT (Python → LLVM)
|
||||
```python
|
||||
from numba import njit
|
||||
import numpy as np
|
||||
|
||||
@njit(cache=True, fastmath=True)
|
||||
def mandelbrot(c, max_iter=100):
|
||||
z = 0.0 + 0.0j
|
||||
for i in range(max_iter):
|
||||
z = z * z + c
|
||||
if z.real * z.real + z.imag * z.imag > 4.0:
|
||||
return i
|
||||
return max_iter
|
||||
```
|
||||
|
||||
### Pattern 5: AOT cache 의 prewarm
|
||||
```python
|
||||
import os
|
||||
os.environ["JAX_COMPILATION_CACHE_DIR"] = "/var/cache/jax"
|
||||
|
||||
import jax
|
||||
jax.config.update("jax_persistent_cache_min_entry_size_bytes", 0)
|
||||
jax.config.update("jax_persistent_cache_min_compile_time_secs", 1.0)
|
||||
|
||||
# 매 first deployment 매 prewarm script 의 run — 매 next pods cold-start fast.
|
||||
```
|
||||
|
||||
### Pattern 6: Recompilation detection
|
||||
```python
|
||||
import jax
|
||||
from collections import Counter
|
||||
|
||||
class CompileCounter:
|
||||
def __init__(self):
|
||||
self.count = Counter()
|
||||
|
||||
def trace(self, fn_name: str, sig: tuple):
|
||||
self.count[(fn_name, sig)] += 1
|
||||
if self.count[(fn_name, sig)] > 3:
|
||||
print(f"매 thrash: {fn_name} recompiled {self.count[(fn_name, sig)]} times")
|
||||
|
||||
# Usage: hook into jax.config or torch dynamo logger
|
||||
```
|
||||
|
||||
### Pattern 7: Mojo JIT (2026)
|
||||
```mojo
|
||||
fn matmul[M: Int, N: Int, K: Int](a: Tensor, b: Tensor) -> Tensor:
|
||||
# 매 compile-time specialization 매 shapes — 매 SIMD auto-vectorize.
|
||||
var c = Tensor[DType.float32](M, N)
|
||||
for i in range(M):
|
||||
for j in range(N):
|
||||
var s: Float32 = 0
|
||||
for k in range(K):
|
||||
s += a[i, k] * b[k, j]
|
||||
c[i, j] = s
|
||||
return c
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Numerical Python tight loop | Numba `@njit`. |
|
||||
| ML training | JAX `jit` 또는 `torch.compile`. |
|
||||
| Variable shapes | Avoid JIT 또는 `dynamic=True`. |
|
||||
| One-shot script | 매 JIT overhead 매 not worth. |
|
||||
| Long-running server | JIT + persistent cache. |
|
||||
|
||||
**기본값**: ML 매 `torch.compile(mode="reduce-overhead")` 또는 `jax.jit`. Tight numerical loop 매 Numba.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Compilation]] · [[Performance-Optimization]]
|
||||
- 변형: [[Tracing-JIT]] · [[Method-JIT]] · [[AOT-Compilation]]
|
||||
- 응용: [[JAX]] · [[torch.compile]] · [[Numba]] · [[V8-Engine]]
|
||||
- Adjacent: [[XLA]] · [[Triton]] · [[LLVM]] · [[Profile-Guided-Optimization]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: ML training/serving where compile cost amortizes (>100 calls), tight numerical loops, long-running services.
|
||||
**언제 X**: One-shot scripts, code with constantly-changing shapes, debugging (use eager mode).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **JIT in hot Python loop with varying shapes**: 매 retrace 매 every call — slower than eager.
|
||||
- **No persistent cache**: 매 cold start 매 30s+ compile every deploy.
|
||||
- **JIT debugging**: 매 stacktrace 매 useless — eager 의 disable JIT first.
|
||||
- **Premature JIT**: profile first — 매 80% code 매 not bottleneck.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: JAX docs (2026), PyTorch 2.x docs, "Engineering a Compiler" (Cooper & Torczon), V8 design docs.
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with JAX/torch.compile/Numba/Mojo 2026 patterns |
|
||||
|
||||
Reference in New Issue
Block a user