[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,65 +2,195 @@
|
||||
id: wiki-2026-0508-iteration
|
||||
title: Iteration
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-ITER-001]
|
||||
aliases: [Iterative Development, Loop, Iterate]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.96
|
||||
tags: [auto-reinforced, iteration, loops, recursion, computer-science, repetitive-tasks]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [methodology, agile, python, control-flow, generators]
|
||||
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: general
|
||||
---
|
||||
|
||||
# [[Iteration|Iteration]]
|
||||
# Iteration
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "기능의 되풀이, 지능의 축적: 복잡한 작업을 단순한 작은 단계로 나누어 목표를 달성할 때까지 끈질기게 반복 실행함으로써, 단 한 번의 시도로는 불가능한 정교한 결과물을 빚어내는 컴퓨팅적 인내."
|
||||
## 매 한 줄
|
||||
> **"매 small step, 매 feedback, 매 adjust, 매 repeat"**. Iteration 매 dual concept — (1) programming control flow (`for`, `while`, generators) 와 (2) development methodology (small increments + feedback loop). 2026 LLM-assisted 시대 매 iteration 매 even tighter — 매 minute 매 cycle 가능.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
반복(Iteration)은 동일한 절차를 여러 번 되풀이하는 컴퓨터 과학과 사고의 기본 원리입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **구현 방식**:
|
||||
* **Loops**: 정해진 횟수(for)나 조건(while)이 만족될 때까지 코드 블록 실행.
|
||||
* **Recursion**: 함수가 자기 자신을 호출하여 문제를 작게 쪼개어 해결.
|
||||
* **Convergence**: 값을 조금씩 수정하며 정답에 수렴함 ([[Gradient-Descent|Gradient-Descent]]와 연결).
|
||||
2. **왜 중요한가?**:
|
||||
* 인간은 수백만 번의 반복에 지치지만, 컴퓨터는 지치지 않고 반복하여 압도적인 데이터 처리와 수치 해석을 수행하기 때문임. ([[Efficiency|Efficiency]]와 연결)
|
||||
### 매 Programming iteration
|
||||
- **Eager**: `for x in list` — 매 list 매 fully materialized.
|
||||
- **Lazy**: generator, iterator — 매 on-demand pull.
|
||||
- **Async**: `async for x in stream` — 매 I/O 의 overlap.
|
||||
- **Parallel**: `joblib`, `multiprocessing.Pool.imap` — 매 CPU-bound iteration.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌**: 과거에는 단순히 '횟수 반복 정책'에 그쳤으나, 현대 정책은 반복할 때마다 이전 결과를 학습에 반영하여 더 나아지는 '피드백 기반 반복 정책'으로 지능화됨(RL Update). ([[Feedback-Loops|Feedback-Loops]]와 연결)
|
||||
- **정책 변화(RL Update)**: 거대 모델의 추론 정책에서 한 번에 답을 내기보다, 여러 번의 생각(Iteration)을 거쳐 정답을 다듬는 '가챠(Sampling)와 재시도 정책'이 성능의 핵심 지표가 됨.
|
||||
### 매 Methodology iteration
|
||||
- **Loop**: hypothesis → build → measure → learn.
|
||||
- **Cadence**: daily (LLM-assisted), weekly (sprint), monthly (release).
|
||||
- **Artifact per cycle**: shippable increment.
|
||||
- **Feedback source**: tests, users, metrics, code review.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Feedback-Loops|Feedback-Loops]], [[Gradient-Descent|Gradient-Descent]], [[Efficiency|Efficiency]], [[Incrementalism|Incrementalism]], [[Control-Theory|Control-Theory]]
|
||||
- **Modern Tech/Tools**: For loops, Multi-pass [[Reasoning|Reasoning]], Iterative [[Refinement|Refinement]], Self-Correction loops.
|
||||
---
|
||||
### 매 응용
|
||||
1. Data pipeline (process N rows lazily).
|
||||
2. ML hyperparameter search (iteratively narrow).
|
||||
3. Agile sprint (2-week cycle).
|
||||
4. LLM agentic loop (think → act → observe → repeat).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### Pattern 1: Generator (lazy iteration)
|
||||
```python
|
||||
def read_jsonl(path: str):
|
||||
"""매 1GB+ file 의 stream — 매 memory O(1)."""
|
||||
import json
|
||||
with open(path) as f:
|
||||
for line in f:
|
||||
yield json.loads(line)
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
for record in read_jsonl("events.jsonl"):
|
||||
process(record)
|
||||
```
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Pattern 2: Itertools combinators
|
||||
```python
|
||||
from itertools import islice, chain, groupby, accumulate
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
# 매 first 100 records 만
|
||||
head = list(islice(read_jsonl("big.jsonl"), 100))
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
# 매 multiple sources 의 concat
|
||||
combined = chain(read_jsonl("a.jsonl"), read_jsonl("b.jsonl"))
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
# 매 group by user
|
||||
sorted_records = sorted(combined, key=lambda r: r["user_id"])
|
||||
for user_id, group in groupby(sorted_records, key=lambda r: r["user_id"]):
|
||||
handle_user(user_id, list(group))
|
||||
```
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### Pattern 3: Async iteration (2026)
|
||||
```python
|
||||
import asyncio
|
||||
import httpx
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
async def fetch_pages(urls: list[str]):
|
||||
async with httpx.AsyncClient() as client:
|
||||
async def fetch(url):
|
||||
r = await client.get(url)
|
||||
return url, r.text
|
||||
for coro in asyncio.as_completed([fetch(u) for u in urls]):
|
||||
yield await coro
|
||||
|
||||
async def main():
|
||||
async for url, html in fetch_pages(URLS):
|
||||
print(url, len(html))
|
||||
```
|
||||
|
||||
### Pattern 4: Iterative refinement (algorithm)
|
||||
```python
|
||||
def newton_sqrt(n: float, tol: float = 1e-10, max_iter: int = 50) -> float:
|
||||
x = n / 2
|
||||
for _ in range(max_iter):
|
||||
x_new = 0.5 * (x + n / x)
|
||||
if abs(x_new - x) < tol:
|
||||
return x_new
|
||||
x = x_new
|
||||
return x
|
||||
```
|
||||
|
||||
### Pattern 5: LLM agentic loop (2026)
|
||||
```python
|
||||
from anthropic import Anthropic
|
||||
|
||||
client = Anthropic()
|
||||
|
||||
def agent_loop(task: str, max_iter: int = 10):
|
||||
history = [{"role": "user", "content": task}]
|
||||
for i in range(max_iter):
|
||||
msg = client.messages.create(
|
||||
model="claude-opus-4-7",
|
||||
max_tokens=4000,
|
||||
tools=TOOLS,
|
||||
messages=history,
|
||||
)
|
||||
history.append({"role": "assistant", "content": msg.content})
|
||||
if msg.stop_reason == "end_turn":
|
||||
return msg
|
||||
# tool_use → execute → observation → next iter
|
||||
observations = execute_tools(msg.content)
|
||||
history.append({"role": "user", "content": observations})
|
||||
raise RuntimeError("매 max_iter 의 reach")
|
||||
```
|
||||
|
||||
### Pattern 6: Sprint retrospective
|
||||
```python
|
||||
def retro(sprint_data: dict) -> dict:
|
||||
return {
|
||||
"what_worked": sprint_data["green_items"],
|
||||
"what_didnt": sprint_data["red_items"],
|
||||
"experiments_next": [
|
||||
f"Try {hypothesis}" for hypothesis in sprint_data["new_ideas"]
|
||||
],
|
||||
"metrics_delta": {
|
||||
k: sprint_data["after"][k] - sprint_data["before"][k]
|
||||
for k in sprint_data["before"]
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 7: Bounded iteration with timeout
|
||||
```python
|
||||
import time
|
||||
|
||||
def iterate_with_budget(items, budget_sec: float):
|
||||
start = time.time()
|
||||
for item in items:
|
||||
if time.time() - start > budget_sec:
|
||||
print(f"매 budget 매 expire — {item} 의 stop")
|
||||
return
|
||||
yield process(item)
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Large file processing | Generator (lazy). |
|
||||
| Multiple I/O calls | Async iteration. |
|
||||
| CPU-bound loop | `multiprocessing` 또는 vectorize. |
|
||||
| Numerical convergence | While + tolerance check. |
|
||||
| Product development | 2-week sprint + retrospective. |
|
||||
| LLM agent | think-act-observe loop with max_iter cap. |
|
||||
|
||||
**기본값**: Programming 매 generator-first; methodology 매 1-week iteration with measurable hypothesis.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Control-Flow]] · [[Agile]]
|
||||
- 변형: [[Recursion]] · [[Async-Iteration]] · [[Parallel-Iteration]]
|
||||
- 응용: [[Generator]] · [[Sprint]] · [[Agentic-Loop]] · [[Newton-Method]]
|
||||
- Adjacent: [[Itertools]] · [[Coroutine]] · [[Lean-Startup]] · [[Build-Measure-Learn]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Agentic systems (think-act-observe), iterative refinement of code via LLM feedback, sprint planning summaries.
|
||||
**언제 X**: Single-shot generation, tasks where each iteration is 1+ hours of human work (cycle too slow).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Eager when lazy works**: `list(huge_generator)` — 매 OOM.
|
||||
- **Unbounded loop**: no max_iter — 매 infinite loop bug.
|
||||
- **No feedback in iteration**: 매 build without measure — methodology 매 broken.
|
||||
- **Perfect first iteration**: 매 ship at 70% — feedback 의 wait.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: PEP 234 (iterators), Eric Ries "Lean Startup" (2011), "Continuous Delivery" (Humble & Farley).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content covering both programming and methodology iteration with LLM agentic loop |
|
||||
|
||||
Reference in New Issue
Block a user