Files
2nd/10_Wiki/Topics/AI_and_ML/State-Space.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

177 lines
6.5 KiB
Markdown

---
id: wiki-2026-0508-state-space
title: State Space
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [ssm, state-space-model, mamba, s4, linear-rnn]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [state-space, control-theory, ssm, mamba, sequence-modeling]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: pytorch-mamba-jax
---
# State Space
## 매 한 줄
> **"매 hidden state evolves over time, observations emerge from it"**. State space 는 매 control theory / signal processing 의 핵심 representation: $x_{t+1}=Ax_t+Bu_t,\; y_t=Cx_t+Du_t$. 매 2024-2026 의 deep learning 의 SSM (S4, Mamba, Mamba-2) 가 매 Transformer 의 long-context alternative 로 부상.
## 매 핵심
### 매 control-theory origin
- **State** $x_t$: 매 system 의 internal memory.
- **Input** $u_t$: 매 external control / observation.
- **Output** $y_t$: 매 measurable.
- **Matrices** $A, B, C, D$: 매 dynamics, input mapping, observation, feedthrough.
- **Discrete vs continuous**: $\dot x = Ax + Bu$ (continuous) vs $x_{t+1}$ (discrete).
### 매 deep learning SSM 진화
- **HiPPO (2020)**: 매 long-range memory 의 polynomial 근사 — 매 A matrix 의 영리한 init.
- **S4 (2022)**: structured SSM, FFT-based convolution view, long-range arena SOTA.
- **H3, Hyena**: 매 SSM + gating 의 hybrid.
- **Mamba (2023)**: 매 selective SSM — 매 input-dependent A,B,C, hardware-aware parallel scan.
- **Mamba-2 (2024)**: 매 SSD (state-space duality) — 매 attention 과 의 unification.
- **Hybrid (2025+)**: 매 Jamba, Zamba, Samba — 매 Transformer + Mamba mix.
### 매 vs Transformer
| 측면 | Transformer | SSM (Mamba) |
|---|---|---|
| Train | O(N²) parallel | O(N) parallel scan |
| Infer | O(N) per token, KV cache | O(1) per token, fixed state |
| Memory at infer | grows with context | constant |
| Long context | quadratic cost | linear cost |
| In-context recall | strong | weaker (improving with hybrids) |
### 매 응용
1. **Control systems** — 매 robotics, aerospace, Kalman filter.
2. **Time series** — 매 Kalman / particle filter, dynamic factor model.
3. **Long-context LLM** — 매 Mamba-3B, Jamba-1.5 의 1M+ context.
4. **DNA / genomics** — 매 Caduceus, HyenaDNA 의 long sequence.
5. **Audio** — 매 SaShiMi 의 raw-waveform generation.
## 💻 패턴
### Classic discrete state space (control)
```python
import numpy as np
def simulate(A, B, C, D, u, x0):
x, ys = x0.copy(), []
for ut in u:
y = C @ x + D @ ut
x = A @ x + B @ ut
ys.append(y)
return np.array(ys)
```
### Kalman filter
```python
def kalman_step(x, P, u, z, A, B, C, Q, R):
# predict
x = A @ x + B @ u
P = A @ P @ A.T + Q
# update
K = P @ C.T @ np.linalg.inv(C @ P @ C.T + R)
x = x + K @ (z - C @ x)
P = (np.eye(len(x)) - K @ C) @ P
return x, P
```
### S4 convolutional view (PyTorch)
```python
import torch, torch.nn.functional as F
def s4_conv(u, A_bar, B_bar, C, L):
# K_l = C A_bar^l B_bar → conv kernel of length L
K = torch.stack([C @ torch.matrix_power(A_bar, l) @ B_bar for l in range(L)])
y = F.conv1d(u.unsqueeze(0), K.flip(0).unsqueeze(0).unsqueeze(0))
return y.squeeze()
```
### Mamba selective scan (mamba-ssm package)
```python
from mamba_ssm import Mamba
import torch
model = Mamba(d_model=512, d_state=16, d_conv=4, expand=2).cuda()
x = torch.randn(2, 1024, 512, device="cuda")
y = model(x) # [B, L, D] — O(L) parallel scan
```
### HiPPO initialization (LegS)
```python
def hippo_legs(N):
A = np.zeros((N, N))
for n in range(N):
for k in range(N):
if n > k: A[n, k] = -np.sqrt((2*n+1) * (2*k+1))
elif n == k: A[n, k] = -(n + 1)
return A
```
### Mamba-2 SSD block (simplified)
```python
def ssd_block(X, A, B, C, chunk=64):
# state-space duality: structured matrix multiply
# parallelizable as matmul, shows attention-SSM equivalence
L = X.shape[1]
Y = torch.zeros_like(X)
state = torch.zeros(...)
for s in range(0, L, chunk):
Y[:, s:s+chunk], state = ssd_chunk(X[:, s:s+chunk], A, B, C, state)
return Y
```
### Hybrid (Jamba-style: Mamba + attention)
```python
class JambaBlock(nn.Module):
def __init__(self, d, use_attn=False):
super().__init__()
self.layer = MultiheadAttention(d, 8) if use_attn else Mamba(d_model=d)
self.mlp = MoE(d) if use_moe else MLP(d)
def forward(self, x): return self.mlp(self.layer(x) + x) + x
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Control system 의 design | classical SSM + LQR / Kalman |
| Time-series filtering | Kalman / particle filter |
| Long-context language (>128k) | Mamba / Jamba hybrid |
| In-context recall heavy | Transformer or hybrid (not pure Mamba) |
| Genomics 1M token | HyenaDNA / Caduceus |
| Audio raw waveform | SaShiMi / Mamba-Audio |
**기본값**: 매 control 의 classical SSM. 매 long-context LM 의 Mamba-2 또는 Jamba 의 hybrid (pure Mamba 의 recall 약점 의 보완).
## 🔗 Graph
- 부모: [[Control-Theory]] · [[Sequence-to-Sequence-Models|Sequence-Modeling]]
- 변형: [[S4]] · [[Mamba]] · [[Linear-RNN]]
- 응용: [[Kalman-Filter-and-State-Tracking|Kalman-Filter]] · [[Time-Series-Analysis|Time-Series-Forecasting]]
- Adjacent: [[Transformer]] · [[데이터_사이언스_및_ML_엔지니어링|RNN]]
## 🤖 LLM 활용
**언제**: SSM literature 정리, mamba-ssm boilerplate, control-system identification 의 sympy / numpy code.
**언제 X**: real-time safety-critical control (aerospace, medical) — 매 verified controller / formal methods 의 영역.
## ❌ 안티패턴
- **HiPPO init 무시**: random init Mamba 의 long-range 성능 추락. 매 proper A init 필수.
- **Pure Mamba 의 in-context retrieval 기대**: needle-in-haystack 약함. Hybrid 권장.
- **No selective mechanism**: 매 vanilla S4 의 modern Mamba 보다 약함 — input-dependent param 필수.
- **Classical SSM 의 nonlinearity 무시**: 매 real system 의 nonlinear — EKF / UKF / particle filter 사용.
- **CUDA scan 미활용**: 매 naive Python loop 의 100배 slow. mamba-ssm 의 official kernel 사용.
## 🧪 검증 / 중복
- Verified (Kalman 1960, Gu et al. S4 2022, Gu & Dao Mamba 2023, Dao & Gu Mamba-2 2024, Jamba 2024).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — control SSM + modern Mamba/Mamba-2/Jamba |