[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,65 +2,166 @@
|
||||
id: wiki-2026-0508-precision-recursion
|
||||
title: Precision Recursion
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-PREC-001]
|
||||
aliases: [Mixed-Precision Recursive Refinement, Iterative Refinement]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced, precision-recursion, methodology, Feedback-Loops, Optimization, _systematic-thinking]
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [numerical-methods, mixed-precision, iterative-refinement, ML]
|
||||
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: python
|
||||
framework: pytorch-mlx-cuda
|
||||
---
|
||||
|
||||
# [[Precision-Recursion|Precision-Recursion]]
|
||||
# Precision Recursion
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "완벽을 향한 무한 루프: 한 번의 시도로 끝내는 것이 아니라, 결과물을 다시 자기 자신의 입력(Input)으로 넣어 매번 오차를 좁혀가며 정밀도를 극한으로 끌어올리는, 우리 시스템(P-Reinforce)의 핵심 정제 엔진."
|
||||
## 매 한 줄
|
||||
> **"매 lower precision 으로 fast 계산 → 매 higher precision 으로 residual 매 correct → 매 recurse"**. 매 numerical iterative refinement 의 modern variant — 매 H100/H200/MI300X 의 FP8/FP16 throughput 을 활용하면서 매 FP64-equivalent accuracy 를 달성. 매 Higham (1997) 의 classical refinement 매 GPU mixed-precision 시대에서 매 부활.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
정밀 재귀(Precision-Recursion)는 결과물을 반복적으로 재투입하여 품질을 점진적으로 강화하는 방법론입니다. (P-Reinforce 정책의 근간)
|
||||
## 매 핵심
|
||||
|
||||
1. **3대 작동 원칙**:
|
||||
* **Self-Referencing**: 결과가 다시 원재료가 됨 (Feedback Loop). (Feedback-Loops와 연결)
|
||||
* **Incremental [[Refinement|Refinement]]**: 한 번에 다 고치지 않고, 매 회차마다 가장 치명적인 오차 하나만 해결. ([[Incrementalism|Incrementalism]]와 연결)
|
||||
* **Boundary Checking**: 설정한 정밀도(Quality Threshold)에 도달할 때까지 반복 종료하지 않음.
|
||||
2. **왜 중요한가?**:
|
||||
* 단번에 완벽할 수 없는 복잡한 지식 구조를 구축할 때, 이 재귀적 엔진은 시간이 흐를수록 시스템을 '무결점' 상태로 수렴시키기 때문임. (Optimization의 정점)
|
||||
### 매 기본 mechanism
|
||||
```
|
||||
1. Solve A x_lo = b in low precision (FP16/FP8) — fast
|
||||
2. Compute residual r = b - A x_lo in high precision (FP32/FP64)
|
||||
3. Solve A d = r in low precision — fast
|
||||
4. x ← x_lo + d
|
||||
5. Repeat until ||r|| < tol
|
||||
```
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 무한 루프에 따른 '자원 낭비 정책'을 걱정했으나, 현대 정책은 AI 성능이 고도화됨에 따라 '자가 비판 및 수정을 3번 이상 반복하는 정책(Multi-step [[Reasoning|Reasoning]])'이 단발성 출력보다 압도적으로 우수한 품질 정책을 낸다는 것을 입증함(RL Update).
|
||||
- **정책 변화(RL Update)**: 본 지식 베이스 구축 정책에서도, 600개 파일을 한 번에 만드는 게 아니라 배치별로 주입하고 다시 검증하는 정밀 재귀 정책을 통해 대표님의 승인 품질 정책을 확보 중임.
|
||||
### 매 핵심 invariant
|
||||
- **Residual computation**: 매 high precision 필수 (X cancellation error).
|
||||
- **Solve**: 매 low precision OK (errors absorbed by refinement).
|
||||
- **Convergence**: 매 condition number κ(A) 적절시 매 quadratic.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Feedback-Loops|Feedback-Loops]], [[Incrementalism|Incrementalism]], [[Optimization|Optimization]], [[P-Reinforce|P-Reinforce]], [[Iterative-Development|Iterative-Development]]
|
||||
- **Internal [[Reference|Reference]]**: Antigravity's recursion policy, Self-Correction loops.
|
||||
---
|
||||
### 매 응용
|
||||
1. **Linear solve**: GMRES-IR (Carson & Higham 2018).
|
||||
2. **LLM inference**: FP8 forward + FP32 residual streams.
|
||||
3. **Optimization**: Adam in FP16 + FP32 master weights.
|
||||
4. **Eigensolve**: 매 inverse iteration 매 mixed precision.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Iterative refinement (linear solve)
|
||||
```python
|
||||
import numpy as np
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
def iterative_refinement(A, b, tol=1e-12, max_iter=10):
|
||||
"""매 mixed-precision linear solve."""
|
||||
A_lo = A.astype(np.float16)
|
||||
x = np.zeros_like(b)
|
||||
for k in range(max_iter):
|
||||
r = b - A @ x # 매 high-precision residual
|
||||
if np.linalg.norm(r) < tol:
|
||||
break
|
||||
d = np.linalg.solve(A_lo.astype(np.float32), r.astype(np.float32))
|
||||
x = x + d.astype(b.dtype)
|
||||
return x, k + 1
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### PyTorch AMP (Automatic Mixed Precision)
|
||||
```python
|
||||
import torch
|
||||
from torch.cuda.amp import autocast, GradScaler
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
scaler = GradScaler()
|
||||
for batch in loader:
|
||||
optim.zero_grad()
|
||||
with autocast(dtype=torch.float16):
|
||||
loss = model(batch).loss # 매 FP16 forward
|
||||
scaler.scale(loss).backward() # 매 FP32 grad scale
|
||||
scaler.step(optim) # 매 FP32 master weight update
|
||||
scaler.update()
|
||||
```
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
### FP8 inference + FP32 accumulation (H100)
|
||||
```python
|
||||
# Transformer Engine — Hopper FP8
|
||||
import transformer_engine.pytorch as te
|
||||
from transformer_engine.common.recipe import Format, DelayedScaling
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
fp8_recipe = DelayedScaling(
|
||||
margin=0, interval=1,
|
||||
fp8_format=Format.HYBRID, # 매 E4M3 fwd, E5M2 bwd
|
||||
)
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
|
||||
out = model(x) # FP8 GEMMs, FP32 reductions
|
||||
```
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### GMRES with iterative refinement
|
||||
```python
|
||||
from scipy.sparse.linalg import gmres
|
||||
|
||||
def gmres_ir(A, b, tol=1e-12, outer=5):
|
||||
"""매 outer IR loop, 매 inner GMRES low-prec."""
|
||||
x = np.zeros_like(b)
|
||||
A_lo = A.astype(np.float32)
|
||||
for _ in range(outer):
|
||||
r = b - A @ x
|
||||
if np.linalg.norm(r) < tol:
|
||||
return x
|
||||
d, _ = gmres(A_lo, r.astype(np.float32), atol=1e-6)
|
||||
x = x + d.astype(b.dtype)
|
||||
return x
|
||||
```
|
||||
|
||||
### Adam with FP32 master weights
|
||||
```python
|
||||
class MixedPrecisionAdam:
|
||||
def __init__(self, params, lr=1e-3):
|
||||
self.params_fp16 = params # 매 storage
|
||||
self.params_fp32 = [p.detach().clone().float() for p in params]
|
||||
self.m = [torch.zeros_like(p) for p in self.params_fp32]
|
||||
self.v = [torch.zeros_like(p) for p in self.params_fp32]
|
||||
self.lr = lr; self.t = 0
|
||||
def step(self):
|
||||
self.t += 1
|
||||
for p16, p32, m, v in zip(self.params_fp16, self.params_fp32, self.m, self.v):
|
||||
g = p16.grad.float()
|
||||
m.mul_(0.9).add_(g, alpha=0.1)
|
||||
v.mul_(0.999).addcmul_(g, g, value=0.001)
|
||||
p32.addcdiv_(m, v.sqrt().add_(1e-8), value=-self.lr)
|
||||
p16.data.copy_(p32.half()) # 매 sync back
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Strategy |
|
||||
|---|---|
|
||||
| 매 ill-conditioned linear system | GMRES-IR mixed precision |
|
||||
| 매 LLM training | AMP (FP16/BF16 + FP32 master) |
|
||||
| 매 Hopper / Blackwell inference | FP8 + FP32 accumulate |
|
||||
| 매 well-conditioned + FP64 needed | 매 single-precision solve OK |
|
||||
|
||||
**기본값**: 매 BF16 forward + FP32 master weights (training), FP8 inference (Hopper+).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Numerical-Methods]] · [[Mixed-Precision-Training]]
|
||||
- 변형: [[Iterative-Refinement]] · [[GMRES-IR]]
|
||||
- 응용: [[LLM-Training]] · [[Scientific-Computing]] · [[FP8-Inference]]
|
||||
- Adjacent: [[Floating-Point-Arithmetic]] · [[Condition-Number]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 numerical stability debugging, 매 mixed-precision recipe selection, 매 condition number analysis.
|
||||
**언제 X**: 매 integer / discrete optimization — 매 precision concept 무관.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Low-precision residual**: 매 cancellation error 폭발 → 매 refinement 무용.
|
||||
- **Ill-conditioned + low-prec**: 매 κ(A) > 10⁶ + FP16 → 매 발산.
|
||||
- **No master weights**: 매 FP16 weight update 매 underflow.
|
||||
- **Skip warmup**: 매 FP8 매 calibration 없이 → 매 NaN.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Higham 1997 *Accuracy and Stability*; Carson & Higham 2018 GMRES-IR; NVIDIA Transformer Engine docs 2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — iterative refinement + modern AMP/FP8 stack |
|
||||
|
||||
Reference in New Issue
Block a user