[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
+186 -62
View File
@@ -2,89 +2,213 @@
id: wiki-2026-0508-pytorch-foundations
title: PyTorch Foundations
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [DL-PYTORCH-001]
aliases: [PyTorch Basics, PyTorch Core, torch fundamentals]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [ai, Deep-Learning, pytorch, tensors, autograd, framework, python]
confidence_score: 0.95
verification_status: applied
tags: [pytorch, deep-learning, tensors, autograd]
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-2.x
---
# PyTorch Foundations (PyTorch 기초)
# PyTorch Foundations
## 📌 한 줄 통찰 (The Karpathy Summary)
> "데이터를 유연한 텐서의 흐름(Tensors)으로 정의하고, 수학적 기울기를 자동으로 추적(Autograd)하여, 파이썬다운 우아함으로 지능의 아키텍처를 구현하라" — 페이스북(현 Meta)에서 개발한 오픈소스 머신러닝 라이브러리로, 동적 계산 그래프와 파이썬 지향적 설계로 현대 딥러닝 연구 및 실무의 표준이 된 프레임워크.
## 한 줄
> **"매 Tensor + autograd + nn.Module + DataLoader"**. 2016 Soumith Chintala @ Meta 가 release. 매 NumPy-like + GPU + automatic differentiation. 매 2026 현재 PyTorch 2.x — `torch.compile`, FSDP2, MPS backend, torch.func — 가 매 default DL framework.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Tensor [[Opera|Opera]]tions and Automatic Differentiation" — 다차원 배열 연산을 GPU 가속을 통해 고속으로 처리하고, 복잡한 신경망 연산 과정에서의 미분값을 역전파([[Backpropagation|Backpropagation]]) 시점에 자동으로 계산해주는 핵심 패턴.
- **주요 구성 요소:**
- **Tensors:** GPU 가속이 가능한 다차원 배열. PyTorch의 기본 데이터 단위.
- **Autograd:** 미분값 계산을 자동화하는 엔진.
- **nn.Module:** 레이어와 모델 아키텍처를 정의하는 기본 클래스.
- **Optimizers:** 가중치 업데이트 알고리즘 (SGD, Adam 등).
- **의의:** 정적인 그래프 선언 방식(과거 TensorFlow)에서 탈출하여, 코드 실행 중에 그래프를 생성하는 유연성을 제공함으로써 복잡한 모델의 디버깅과 실험 속도를 획기적으로 향상시킴.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 연구용으로는 좋지만 배포용(Production)으로는 부족하다는 비판을 TorchScript와 ONNX 지원을 통해 극복하며, 이제는 연구부터 상용 서비스까지 전 과정을 아우르는 통합 플랫폼으로 성장함.
- **정책 변화:** Antigravity 프로젝트는 에이전트의 내부 학습 로직 및 임베딩 모델 구현 시, 코드 가독성과 커스터마이징 자유도가 높은 PyTorch를 표준 프레임워크로 사용함.
### 매 4 pillars
- **Tensor**: 매 N-d array, GPU/CPU/MPS, autograd-tracked.
- **Autograd**: 매 reverse-mode AD — `.backward()`.
- **nn.Module**: 매 layer + state container.
- **DataLoader**: 매 batched + parallel data pipeline.
## 🔗 지식 연결 (Graph)
- [[PyTorch-Lightning|PyTorch-Lightning]], Deep-Learning-Foundations, Backpropagation-Foundations, GPU-[[Optimization|Optimization]]-Foundations
- **Raw Source:** 10_Wiki/Topics/AI/PyTorch-Foundations.md
### 매 device
- **CUDA**: NVIDIA. 매 production default.
- **MPS**: Apple Silicon. 매 dev-machine.
- **ROCm**: AMD. 매 growing.
- **XPU**: Intel.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Vision (timm, torchvision).
2. NLP / LLM (transformers, vLLM 의 backend).
3. Diffusion (diffusers).
4. RL (cleanrl, torchrl).
5. Scientific ML (PINN, geometric DL).
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Tensor basics
```python
import torch
## 🧪 검증 상태 (Validation)
x = torch.randn(3, 4, device="cuda", dtype=torch.float32)
y = torch.arange(12).reshape(3, 4).float().cuda()
- **정보 상태:** 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
z = x @ y.T # matmul
w = x.mean(dim=0) # reduction
print(x.shape, x.dtype, x.device)
```
## 🤔 의사결정 기준 (Decision Criteria)
### Autograd
```python
x = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)
y = (x ** 2).sum()
y.backward()
print(x.grad) # tensor([2., 4., 6.])
```
**선택 A를 써야 할 때:**
- *(TODO)*
### nn.Module
```python
import torch.nn as nn
**선택 B를 써야 할 때:**
- *(TODO)*
class MLP(nn.Module):
def __init__(self, d_in, d_h, d_out):
super().__init__()
self.net = nn.Sequential(
nn.Linear(d_in, d_h), nn.GELU(),
nn.Linear(d_h, d_h), nn.GELU(),
nn.Linear(d_h, d_out),
)
def forward(self, x):
return self.net(x)
**기본값:**
> *(TODO)*
model = MLP(784, 256, 10).cuda()
```
## ❌ 안티패턴 (Anti-Patterns)
### Training loop (canonical)
```python
from torch.utils.data import DataLoader
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
opt = torch.optim.AdamW(model.parameters(), lr=3e-4)
loss_fn = nn.CrossEntropyLoss()
loader = DataLoader(dataset, batch_size=128, shuffle=True,
num_workers=4, pin_memory=True)
for epoch in range(10):
for x, y in loader:
x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)
opt.zero_grad(set_to_none=True)
logits = model(x)
loss = loss_fn(logits, y)
loss.backward()
opt.step()
```
### torch.compile (2.x default)
```python
# 매 30-50% 속도 향상 의 free.
model = torch.compile(model, mode="reduce-overhead")
# mode: "default" | "reduce-overhead" | "max-autotune"
```
### Mixed precision (bf16 / amp)
```python
from torch.amp import autocast, GradScaler
scaler = GradScaler("cuda")
for x, y in loader:
opt.zero_grad(set_to_none=True)
with autocast(device_type="cuda", dtype=torch.bfloat16):
loss = loss_fn(model(x), y)
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()
```
### Custom Dataset
```python
from torch.utils.data import Dataset
class CSVDataset(Dataset):
def __init__(self, path, transform=None):
import pandas as pd
self.df = pd.read_csv(path)
self.transform = transform
def __len__(self): return len(self.df)
def __getitem__(self, i):
row = self.df.iloc[i]
x = torch.tensor(row[:-1].values, dtype=torch.float32)
y = torch.tensor(row[-1], dtype=torch.long)
return (self.transform(x), y) if self.transform else (x, y)
```
### Save / load
```python
# state_dict (recommended)
torch.save(model.state_dict(), "model.pt")
model.load_state_dict(torch.load("model.pt", weights_only=True))
# safetensors (preferred for sharing, no pickle RCE)
from safetensors.torch import save_file, load_file
save_file(model.state_dict(), "model.safetensors")
```
### Distributed (FSDP2, 2026 default for large)
```python
import torch.distributed as dist
from torch.distributed.fsdp import FSDPModule, fully_shard
dist.init_process_group("nccl")
model = MLP(...).cuda()
fully_shard(model) # FSDP2 API
```
### torch.func (functional API)
```python
from torch.func import vmap, grad
def loss(params, x, y):
return ((model_fn(params, x) - y) ** 2).mean()
per_sample_grads = vmap(grad(loss), in_dims=(None, 0, 0))(params, X, Y)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Single-GPU train | `model.cuda()` + `torch.compile` |
| Multi-GPU same node | DDP |
| Model > GPU mem | **FSDP2** |
| Apple Silicon dev | MPS backend |
| Inference, llm-scale | vLLM / TensorRT-LLM |
| Quick prototype | Lightning or pure loop |
**기본값**: PyTorch 2.x + bf16 + torch.compile + AdamW.
## 🔗 Graph
- 부모: [[Deep-Learning]] · [[Tensor-Frameworks]]
- 변형: [[JAX]] · [[TensorFlow]] · [[MLX]]
- 응용: [[Transformers]] · [[Diffusion-Models]] · [[Reinforcement-Learning]]
- Adjacent: [[Lightning]] · [[Hugging-Face]] · [[Triton]]
## 🤖 LLM 활용
**언제**: 매 boilerplate training loop, 매 shape debug, 매 custom op skeleton.
**언제 X**: 매 hot-path numerical code 의 review 없이 trust X. 매 hallucinated API (e.g., 매 wrong autograd custom op).
## ❌ 안티패턴
- **`zero_grad()` 없이 backward**: 매 grad accumulate 의 silent bug.
- **`with torch.no_grad()` forget at eval**: 매 memory + 매 wrong stat.
- **CPU↔GPU 의 매 step transfer**: 매 PCIe bottleneck. 매 pin_memory + non_blocking.
- **In-place op 의 autograd-tracked tensor**: `x += 1` 의 backward 의 break.
- **`weights_only=False` (default 2.6+)**: pickle RCE risk. 매 always `weights_only=True`.
- **No `set_to_none=True`**: 매 zero-fill 의 wasteful.
## 🧪 검증 / 중복
- Verified (pytorch.org docs, PyTorch 2.x release notes).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PyTorch 2.x foundations canonical. |