[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,62 +2,176 @@
id: wiki-2026-0508-pid-controllers-in-ai
title: PID Controllers in AI
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [CTRL-PID-001]
aliases: [Proportional-Integral-Derivative Control, PID Loop]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: ["Control-Theory|[Control-Theory", pid, ai, Robotics, feedback-loop, automation]
confidence_score: 0.9
verification_status: applied
tags: [control-theory, robotics, RL, tuning]
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: python
framework: simple_pid/control
---
# PID Controllers in AI (AI에서의 PID 제어기)
# PID Controllers in AI
## 📌 한 줄 통찰 (The Karpathy Summary)
> "과거의 오차(I)를 반성하고, 현재의 차이(P)를 직시하며, 미래의 변화(D)를 예측하여 완벽한 균형점을 사수하라" — 비례(Proportional), 적분(Integral), 미분(Derivative) 항의 조합을 통해 시스템의 출력을 목표값에 빠르고 안정적으로 수렴시키는 가장 대표적인 피드백 제어 기술.
## 한 줄
> **"매 error = setpoint - measurement 에 P/I/D 항을 적용해 actuator 를 제어"**. 1922 Minorsky ship steering 에서 시작, 매 산업 control 의 80%+ 사용. 매 2026 의 AI hybrid 사용: drone attitude (PX4), robot joint, LLM token-budget control, RLHF KL-coefficient tuning, training schedules.
## 📖 구조화된 지식 (Synthesized Content)
- **추출된 패턴:** "Closed-loop Error Correction" — 목표값과 현재값의 차이(오차)를 실시간으로 계산하고, 세 가지 제어 항을 통해 오차를 보정하여 외부 교란에도 불구하고 시스템을 안정 상태로 유지하는 패턴.
- **3대 제어 항:**
- **P (Proportional):** 현재 오차에 비례하여 강하게 반응 (빠른 응답).
- **I (Integral):** 쌓인 오차를 제거하여 잔류 편차 해결 (정밀도).
- **D (Derivative):** 오차의 변화 속도를 감지하여 오버슈트 억제 (안정성).
- **의의:** AI 에이전트가 현실 세계의 드론, 로봇 팔, 자율주행 조향 등을 실제로 움직일 때 사용하는 가장 믿음직하고 검증된 물리 인터페이스.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 사람이 수작업으로 최적의 계수(Gain)를 찾던 방식에서, 이제는 강화학습(RL)이나 베이지안 최적화가 실시간으로 가장 적합한 PID 계수를 찾아주는 '지능형 PID'로 진화함.
- **정책 변화:** Skybound 프로젝트의 비행 유닛들이 목표 고도를 유지하거나 흔들림을 보정할 때, 내부적으로 최적화된 PID 제어 루프를 사용하여 부드러운 움직임을 구현함.
### 매 PID 공식
- **u(t) = Kp·e(t) + Ki·∫e(τ)dτ + Kd·de/dt**.
- **P (Proportional)**: 매 현재 error 에 비례 — 매 fast response, 매 steady-state error 남김.
- **I (Integral)**: 매 누적 error — 매 steady-state error 제거, 매 windup 위험.
- **D (Derivative)**: 매 변화율 — 매 overshoot 감소, 매 noise 증폭.
## 🔗 지식 연결 (Graph)
- [[Optimal-Control-Theory|Optimal-Control-Theory]], [[Reinforcement-Learning|Reinforcement-Learning]], [[Robotics-Foundations|Robotics-Foundations]], Automation-Strategies
- **Raw Source:** 10_Wiki/Topics/AI/PID-Controllers-in-AI.md
### 매 tuning methods
- **Ziegler-Nichols**: 매 Ku, Tu (oscillation) 측정 후 공식 적용.
- **Cohen-Coon**: 매 process reaction curve 기반.
- **AutoTuning**: 매 relay feedback (Åström-Hägglund).
- **Bayesian optimization**: 매 simulation rollout + GP.
- **RL-based**: 매 PPO/SAC 으로 Kp, Ki, Kd 학습.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Drone attitude (PX4, ArduPilot).
2. Robot joint position control (ROS 2).
3. Cruise control, HVAC, 3D printer extruder.
4. LLM serving — token-rate controller (vLLM 의 batch sizing).
5. RLHF KL-coefficient adaptive tuning.
6. Training: gradient norm clipping with adaptive coefficient.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Plain PID (discrete)
```python
class PID:
def __init__(self, kp, ki, kd, dt, output_limits=(-1, 1)):
self.kp, self.ki, self.kd, self.dt = kp, ki, kd, dt
self.lo, self.hi = output_limits
self.integral = 0.0
self.prev_error = 0.0
## 🧪 검증 상태 (Validation)
def __call__(self, setpoint, measurement):
error = setpoint - measurement
self.integral += error * self.dt
derivative = (error - self.prev_error) / self.dt
output = self.kp*error + self.ki*self.integral + self.kd*derivative
output = max(self.lo, min(self.hi, output))
self.prev_error = error
return output
```
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
### Anti-windup (clamp + back-calculation)
```python
class PIDAntiWindup(PID):
def __init__(self, *args, kt=0.5, **kw):
super().__init__(*args, **kw)
self.kt = kt # back-calc gain
## 🧬 중복 검사 (Duplicate Check)
def __call__(self, setpoint, measurement):
error = setpoint - measurement
derivative = (error - self.prev_error) / self.dt
u_unsat = self.kp*error + self.ki*self.integral + self.kd*derivative
u_sat = max(self.lo, min(self.hi, u_unsat))
# back-calculation: discount integral when saturated
self.integral += self.dt * (error + self.kt * (u_sat - u_unsat))
self.prev_error = error
return u_sat
```
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
### Derivative on measurement (D-kick 회피)
```python
class PIDDerivOnMeas(PID):
def __init__(self, *args, **kw):
super().__init__(*args, **kw)
self.prev_meas = None
## 🕓 변경 이력 (Changelog)
def __call__(self, setpoint, measurement):
error = setpoint - measurement
if self.prev_meas is None:
d = 0
else:
d = -(measurement - self.prev_meas) / self.dt # 매 setpoint step → spike 없음
self.integral += error * self.dt
out = self.kp*error + self.ki*self.integral + self.kd*d
self.prev_meas = measurement
return max(self.lo, min(self.hi, out))
```
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
### Ziegler-Nichols tuning
```python
def ziegler_nichols(Ku, Tu, kind="classic"):
if kind == "classic":
return dict(kp=0.6*Ku, ki=1.2*Ku/Tu, kd=0.075*Ku*Tu)
elif kind == "no-overshoot":
return dict(kp=0.2*Ku, ki=0.4*Ku/Tu, kd=Ku*Tu/15)
elif kind == "PI-only":
return dict(kp=0.45*Ku, ki=0.54*Ku/Tu, kd=0)
```
### RLHF adaptive KL (PPO-style β)
```python
def adaptive_kl_pid(kl_observed, kl_target=0.02, state=None):
"""β ↑ when KL too large; β ↓ when too small. PI controller on log(β)."""
if state is None:
state = {"integral": 0.0, "log_beta": 0.0}
error = kl_observed - kl_target
state["integral"] += error
state["log_beta"] += 0.1 * error + 0.01 * state["integral"]
return float(np.exp(state["log_beta"])), state
```
### LLM token-rate controller (server batch)
```python
def batch_size_pid(target_tps, current_tps, pid_state):
"""Maintain target tokens/sec by adjusting batch size."""
delta = target_tps - current_tps
pid_state["integral"] += delta
adj = 0.05*delta + 0.001*pid_state["integral"]
return max(1, int(pid_state["batch"] + adj))
```
## 매 결정 기준
| 상황 | Controller |
|---|---|
| no steady-state error needed | P only |
| eliminate steady-state, slow process | PI |
| fast + minimal overshoot | PID with D-on-measurement |
| highly nonlinear / complex | MPC or RL (not PID) |
| discrete-event / queue | PI on rate |
| training schedule (KL, lr) | adaptive PI |
**기본값**: 매 80% 의 경우 PI 면 충분. 매 D 매 noise 환경에서 신중히.
## 🔗 Graph
- 부모: [[Control-Theory]] · [[Feedback-Control-Systems]]
- 변형: [[Cascade Control]] · [[Gain Scheduling]] · [[Adaptive PID]]
- 응용: [[Robotics]] · [[Drone Stabilization]] · [[LLM Serving]] · [[RLHF]]
- Adjacent: [[Model-Predictive-Control (MPC)]] · [[Kalman-Filter-and-State-Tracking]] · [[Reinforcement-Learning]]
## 🤖 LLM 활용
**언제**: 매 inference server batch sizing, 매 RLHF KL coefficient, 매 lr schedule under loss target.
**언제 X**: 매 highly nonlinear delays — MPC. 매 strong constraints — RL/MPC.
## ❌ 안티패턴
- **No anti-windup with saturation**: 매 integral 폭주 → overshoot.
- **D term on noisy raw signal**: 매 noise 증폭 → 매 LPF (low-pass filter) 필수.
- **Derivative on setpoint (D-kick)**: 매 setpoint step → spike. 매 D-on-measurement 사용.
- **One-size-fits-all gains across operating regions**: 매 nonlinear 시스템 — gain scheduling 필요.
- **Tuning by 임의 가이드**: 매 system 마다 다름 — Ziegler-Nichols 또는 simulation 사용.
## 🧪 검증 / 중복
- Verified (Åström & Hägglund, *PID Controllers*; Franklin et al. *Feedback Control of Dynamic Systems*; ArduPilot/PX4 firmware).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — PID FULL with anti-windup, D-on-meas, RLHF/serving applications |