[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,89 +2,157 @@
id: wiki-2026-0508-determinism-in-computing
title: Determinism in Computing
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DET-COMP-001]
aliases: [Reproducibility, Bit-Exact, 결정론적 실행]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [computer-science, determinism, simulation, Physics-engine, skybound]
confidence_score: 0.93
verification_status: applied
tags: [determinism, reproducibility, concurrency, ML, distributed-systems]
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: unspecified
framework: unspecified
language: python
framework: pytorch/cuda
---
# Determinism in Computing (계산의 결정론)
# Determinism in Computing
## 📌 한 줄 통찰 (The Karpathy Summary)
> "동일한 입력과 초기 상태가 주어지면, 언제 어디서나 반드시 동일한 결과를 보장하라" — 시스템의 내부 상태와 연산 과정에서 무작위성을 배제하여, 프로그램의 실행 결과가 100% 예측 가능하고 재현 가능하도록 설계하는 원칙.
## 한 줄
> **"매 same input + same code = same output, every run, every machine"**. 매 1936 Turing 의 deterministic state machine 부터 매 2026 ML training 의 bit-exact reproducibility, 매 distributed consensus (Raft), 매 blockchain virtual machines 까지 — 매 trust 와 debugging 의 foundation.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** 부동 소수점 연산 오차, 멀티스레딩의 비결정적 실행 순서, 네트워크 지연 등 결과를 뒤흔들 수 있는 변수들을 제어하여 시스템의 일관성을 확보하는 설계 패턴.
- **핵심 요소:**
- **Fixed-point Arithmetic:** 부동 소수점 오차로 인한 결과 차이를 방지하기 위해 정수 기반 연산 사용.
- **Deterministic Lockstep:** 멀티플레이어 환경에서 모든 클라이언트가 동일한 타임라인에서 동일한 연산을 수행하도록 동기화.
- **[[Seed|Seed]]ed Randomness:** 난수 생성 시 항상 동일한 시드(Seed)를 사용하여 무작위 패턴을 재현 가능하게 함.
- **No Side Effects:** 함수가 외부 상태를 변경하지 않고 입력값에 의해서만 결과가 결정되도록 함 (순수 함수).
- **의의:** 디버깅 용이성, 멀티플레이어 게임의 동기화, 과학 시뮬레이션의 신뢰성 확보에 필수적.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 단순히 '작동'하는 것에 집중하던 방식에서, 분산 시스템과 복잡한 시뮬레이션이 늘어남에 따라 '재현 가능성'이 소프트웨어 품질의 핵심 지표로 부상.
- **정책 변화:** Skybound 프로젝트는 리플레이 시스템과 멀티플레이 동기화를 위해 모든 물리 연산과 확률 이벤트를 결정론적으로 설계하며, 부동 소수점 오차 누적을 방지하는 알고리즘을 적용함.
### 매 등급
- **Bit-exact**: 매 byte-level identical output. 매 cryptographic hash 동일.
- **Numerically reproducible**: 매 within ε tolerance — 매 floating-point order 차이.
- **Statistically reproducible**: 매 same distribution, different sample (RNG seed only).
- **Behaviorally reproducible**: 매 high-level outcome 동일 (test passes/fails 동일).
## 🔗 지식 연결 (Graph)
- Time-Step-Logic-in-Games, Physics-Engine, [[Distributed-Computing|Distributed-Computing]], Simulation-[[Principles|Principles]]
- **Raw Source:** 10_Wiki/Topics/AI/Determinism-in-Computing.md
### 매 nondeterminism 원인
- **FP non-associativity**: 매 (a+b)+c ≠ a+(b+c) — 매 reduction order matter.
- **GPU atomic ops**: 매 CUDA atomicAdd 의 ordering 비결정적.
- **Thread scheduling**: 매 OS scheduler 의 race condition.
- **Hash randomization**: 매 Python `PYTHONHASHSEED`, Go map iteration.
- **Wall-clock dependency**: 매 timestamps, `time.time()`, `random()`.
- **Hardware**: 매 cosmic ray bit flips, TLB/cache state.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. **ML training reproduction**: 매 paper benchmark 의 reproducibility crisis.
2. **Blockchain consensus**: 매 nodes must reach identical state.
3. **Distributed log replay**: 매 event sourcing 의 deterministic projection.
4. **Game engine replays**: 매 lockstep multiplayer (RTS, fighting games).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### PyTorch Bit-Exact Setup
```python
import torch, random, numpy as np, os
## 🧪 검증 상태 (Validation)
def set_full_determinism(seed=42):
os.environ['PYTHONHASHSEED'] = str(seed)
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # CUDA 10.2+
random.seed(seed); np.random.seed(seed)
torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
torch.use_deterministic_algorithms(True, warn_only=False)
- **정보 상태:** 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
set_full_determinism()
```
## 🤔 의사결정 기준 (Decision Criteria)
### Deterministic DataLoader
```python
def seed_worker(worker_id):
s = torch.initial_seed() % 2**32
np.random.seed(s); random.seed(s)
**선택 A를 써야 할 때:**
- *(TODO)*
g = torch.Generator(); g.manual_seed(42)
loader = DataLoader(ds, batch_size=64, shuffle=True,
num_workers=4, worker_init_fn=seed_worker, generator=g)
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Lockstep Game Loop (Fixed-Point Math)
```rust
// All clients run identical sim → only inputs synchronized.
const FIXED_DT: Fixed<i64, 16> = Fixed::from_num(1.0 / 60.0);
**기본값:**
> *(TODO)*
fn tick(state: &mut GameState, inputs: &[Input]) {
for input in inputs.iter().sorted_by_key(|i| i.player_id) {
state.apply(input, FIXED_DT); // fixed-point, no f32!
}
state.tick += 1;
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Content-Addressable Build (Bazel-style)
```python
def build_artifact(sources, deps, command):
h = hashlib.sha256()
for src in sorted(sources):
h.update(open(src, 'rb').read())
for d in sorted(deps): h.update(d.hash.encode())
h.update(command.encode())
cache_key = h.hexdigest()
if cache_key in cache: return cache[cache_key]
return run_and_cache(command, cache_key)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Deterministic Hash for Sets
```python
# Avoid Python set iteration order
def stable_hash_set(items):
return hashlib.sha256(
b'\n'.join(sorted(repr(x).encode() for x in items))
).hexdigest()
```
### Replay Test
```python
def test_replay_is_deterministic():
seed = 12345
out1 = run_simulation(seed)
out2 = run_simulation(seed)
assert out1 == out2, "Nondeterminism detected!"
# for ML: torch.testing.assert_close(out1, out2, atol=0, rtol=0)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| ML reproducibility paper | bit-exact (CUBLAS config + cudnn.deterministic) |
| Distributed sim / lockstep | fixed-point arithmetic |
| Build system | content-addressable hashing |
| Statistical study | seed-only (statistical determinism) |
| Performance critical | relax to "numerically close" |
**기본값**: 매 seed everything + log seeds in artifacts metadata.
## 🔗 Graph
- 부모: [[Theoretical-Computer-Science]] · [[Reproducibility]]
- 변형: [[Bit-Exact-Reproducibility]] · [[Statistical-Reproducibility]]
- 응용: [[ML Reproducibility]] · [[Blockchain Consensus]] · [[Lockstep-Networking]]
- Adjacent: [[Floating-Point-Arithmetic]] · [[Random Number Generation]] · [[Idempotency]]
## 🤖 LLM 활용
**언제**: 매 evaluation harness, 매 regression test 의 ground truth, 매 paper code release.
**언제 X**: 매 LLM sampling 자체 (temperature > 0) — 매 inherently nondeterministic; 매 fixed seed + temperature=0 만 reproducible.
## ❌ 안티패턴
- **Forgetting CUBLAS_WORKSPACE_CONFIG**: 매 CUDA matmul 비결정적, training 결과 매 run 다름.
- **Using `set()` in pipeline**: 매 Python <3.7 dict order 비결정적.
- **Wall-clock as seed**: 매 reproducibility 불가, debugging 불가.
- **Mixing CPU/GPU reductions**: 매 sum order 차이로 ε divergence 누적.
- **Ignoring hardware drift**: 매 different GPU arch (A100 vs H100) → different results 가능.
## 🧪 검증 / 중복
- Verified (PyTorch reproducibility docs 2026; Raft paper 2014; Bazel hermetic build docs).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with PyTorch, lockstep, build patterns |