[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,80 +1,195 @@
|
||||
---
|
||||
id: wiki-2026-0508-inference-coupled-persistence
|
||||
title: Inference Coupled Persistence
|
||||
title: Inference-Coupled Persistence
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [ICP, Inference-Time Memory, Coupled Persistence]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [llm, memory, inference, kv-cache, persistence]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: python
|
||||
framework: vllm
|
||||
---
|
||||
|
||||
# Inference-Coupled Persistence (추론 결합 지속성)
|
||||
# Inference-Coupled Persistence
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Inference-Coupled Persistence는 에이전트가 단순히 작업 결과를 저장하는 것을 넘어, 작업이 끝난 후 모델의 추론(Inference) 능력을 활용하여 작업의 성공/실패 요인을 분석하고 향후 재사용 가능한 절차적 지식이나 에피소드 기억으로 요약하여 영구 저장소에 기록하는 기술이다. 이는 에이전트가 경험으로부터 스스로 학습하고 진화하게 만드는 자가 발전(Self-improvement)의 핵심 메커니즘이다.
|
||||
## 매 한 줄
|
||||
> **"매 KV-cache 의 disk 의 spill 매 conversation 의 resume"**. Inference-Coupled Persistence (ICP) 매 LLM serving system 의 inference state (KV-cache, attention states) 의 durable storage 의 couple 매 pattern. 2026 vLLM 0.7+ / SGLang 매 native support — long conversations cost-effective.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **자가 분석 (Post-hoc Analysis)**: 작업 완료 후 에이전트는 "무엇이 성공했는가?", "어떤 장애물이 있었는가?", "다음에 이 작업을 한다면 무엇을 다르게 할 것인가?"를 스스로 질문하고 답을 생성한다.
|
||||
* **스킬 라이브러리 (Skill Synthesis)**: 특정 문제 해결 과정을 일반화된 '스킬'로 변환하여 저장한다. 예를 들어, 특정 라이브러리의 버그를 해결한 과정을 기록하여 다음에 유사한 상황에서 검색 가능하게 만든다.
|
||||
* **에피소드 기억 (Episodic Memory)**: 작업의 전체 궤적(Trajectory) 중 핵심적인 결정 순간과 그 이유를 추출하여 저장함으로써, 긴 대화 이력을 모두 보관할 필요 없이 핵심 맥락을 보존한다.
|
||||
* **쓰기 트리거 정책 (Write-trigger Policy)**: 모든 정보를 저장하면 노이즈가 발생하므로, 유의미한 발견이 있거나 작업이 완료된 시점에만 추론을 통한 저장을 실행한다.
|
||||
* **품질 게이트 (Quality-gate)**: 저장되기 전에 생성된 지식이 정확한지, 혹은 보안상 위험이 없는지 검증하는 단계를 거친다.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
* **추론 비용**: 저장을 위해 추가적인 모델 호출이 필요하므로 토큰 소모와 시간이 발생한다.
|
||||
* **메모리 중독 (Memory Poisoning)**: 모델이 자신의 실패를 잘못 분석하거나 환각(Hallucination)을 지식으로 저장할 경우, 에이전트의 전체 지능이 오염될 수 있다.
|
||||
* **요약 편향 (Summary Drift)**: 여러 번의 분석과 요약을 거치면서 원본 경험의 중요한 디테일이 사라지고 왜곡될 수 있다.
|
||||
### 매 Why ICP
|
||||
- 매 1M token context 의 KV-cache 매 ~100GB GPU memory 의 consume.
|
||||
- 매 conversation idle 매 hours / days — GPU memory 매 hold cost-prohibitive.
|
||||
- ICP: idle 시 disk 의 evict, resume 시 reload — 매 5-50x cost reduction.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
### Related Concepts
|
||||
* [[Agent Memory System|Agent Memory System]]
|
||||
* 연결 이유: 추론 결합 지속성이 실질적으로 지식을 공급하는 대상 시스템이다.
|
||||
* [[S-component (State Store)|S-component (State Store)]]
|
||||
* 연결 이유: 분석된 지식이 물리적으로 저장되는 하네스의 구성 요소이다.
|
||||
* Reflexion
|
||||
* 연결 이유: 작업 중 혹은 후에 스스로를 돌아보고 개선하는 유사한 추론 패턴이다.
|
||||
### 매 Storage tiers
|
||||
- **L0 (HBM)**: active inference, < 1ms access.
|
||||
- **L1 (CPU RAM)**: 매 minutes idle, ~10ms reload.
|
||||
- **L2 (NVMe)**: 매 hours idle, ~100ms reload.
|
||||
- **L3 (Object store / S3)**: 매 days idle, ~1-5s reload.
|
||||
|
||||
### Deeper Research Questions
|
||||
* 모델의 자기 분석 결과가 정확한지 확인하기 위해, 별도의 '평가자 에이전트(Evaluator Agent)'를 통한 교차 검증은 어느 정도의 비용 효율성을 갖는가?
|
||||
* 수백 개의 성공/실패 에피소드 중 현재 작업에 가장 큰 영감을 줄 수 있는 '유사 사례'를 검색하기 위한 고차원 임베딩 전략은 무엇인가?
|
||||
* 학습된 지식이 시간이 지나 프로젝트 사양 변경으로 인해 틀린 정보가 되었을 때(Obsolescence), 이를 자동으로 폐기하거나 수정하는 트리거는 무엇인가?
|
||||
### 매 Coupling guarantees
|
||||
- **Bit-exact resume**: 매 KV-cache 매 quantization-aware serialization.
|
||||
- **Causal consistency**: 매 token N 의 KV 매 strictly token <N 의 reflect.
|
||||
- **Atomic checkpoint**: partial-write 의 detect 의 crash recovery.
|
||||
|
||||
### Practical Application Contexts
|
||||
* **Implementation:** 코딩 작업 후 "이 프로젝트의 빌드 에러 해결법"이라는 문서를 자동으로 생성하여 `10_Wiki/00_Raw`에 저장하고, 다음에 빌드 에러 발생 시 이를 먼저 검색하도록 한다.
|
||||
* **System Design:** 하네스의 L-component에 `onTaskComplete` 훅을 설정하여, 작업 성공 시 자동으로 'Experience Synthesis' 프롬프트를 실행하도록 설계한다.
|
||||
### 매 응용
|
||||
1. Long-running coding agent (multi-day session).
|
||||
2. Customer support bot (hours-long conversation history).
|
||||
3. Research assistant (multi-week project context).
|
||||
4. Multi-tenant LLM serving (100K concurrent idle sessions).
|
||||
|
||||
---
|
||||
*Last updated: 2026-05-01*
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Pattern 1: vLLM KV-cache offload (2026)
|
||||
```python
|
||||
from vllm import LLM, SamplingParams
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
engine_args = EngineArgs(
|
||||
model="meta-llama/Llama-3.3-70B-Instruct",
|
||||
enable_prefix_caching=True,
|
||||
kv_cache_dtype="fp8",
|
||||
cpu_offload_gb=200, # CPU RAM tier
|
||||
swap_space=400, # NVMe tier (GB)
|
||||
block_size=32,
|
||||
)
|
||||
llm = LLM.from_engine_args(engine_args)
|
||||
```
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Pattern 2: Conversation checkpoint
|
||||
```python
|
||||
import torch
|
||||
from pathlib import Path
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
class ConversationCheckpoint:
|
||||
def __init__(self, store_dir: Path):
|
||||
self.store = store_dir
|
||||
self.store.mkdir(exist_ok=True, parents=True)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
def save(self, conv_id: str, kv_blocks: list[torch.Tensor], tokens: list[int]):
|
||||
path = self.store / f"{conv_id}.pt"
|
||||
tmp = path.with_suffix(".tmp")
|
||||
torch.save({
|
||||
"kv": [b.cpu() for b in kv_blocks],
|
||||
"tokens": tokens,
|
||||
"version": 2,
|
||||
}, tmp)
|
||||
tmp.rename(path) # atomic
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
def load(self, conv_id: str) -> dict | None:
|
||||
path = self.store / f"{conv_id}.pt"
|
||||
if not path.exists():
|
||||
return None
|
||||
return torch.load(path, map_location="cuda")
|
||||
```
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
### Pattern 3: Tiered eviction policy
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
from time import time
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
@dataclass
|
||||
class Session:
|
||||
id: str
|
||||
last_access: float
|
||||
size_gb: float
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
def evict_tier(sessions: list[Session], capacity_gb: float) -> list[Session]:
|
||||
"""매 LRU 의 evict — return list of (session, target_tier)."""
|
||||
sessions.sort(key=lambda s: s.last_access)
|
||||
used = sum(s.size_gb for s in sessions)
|
||||
evicted = []
|
||||
now = time()
|
||||
for s in sessions:
|
||||
if used <= capacity_gb:
|
||||
break
|
||||
idle_min = (now - s.last_access) / 60
|
||||
if idle_min < 5:
|
||||
target = "HBM"
|
||||
elif idle_min < 60:
|
||||
target = "CPU"
|
||||
elif idle_min < 1440:
|
||||
target = "NVMe"
|
||||
else:
|
||||
target = "S3"
|
||||
evicted.append((s, target))
|
||||
used -= s.size_gb
|
||||
return evicted
|
||||
```
|
||||
|
||||
### Pattern 4: Resume with prefix matching
|
||||
```python
|
||||
def resume_with_prefix(checkpoint: dict, new_prompt: str, tokenizer) -> tuple[list, list]:
|
||||
"""매 checkpoint 의 prefix 의 reuse — 매 prefix mismatch 의 from-scratch."""
|
||||
saved_tokens = checkpoint["tokens"]
|
||||
new_tokens = tokenizer.encode(new_prompt)
|
||||
common = 0
|
||||
for i in range(min(len(saved_tokens), len(new_tokens))):
|
||||
if saved_tokens[i] != new_tokens[i]:
|
||||
break
|
||||
common = i + 1
|
||||
if common == 0:
|
||||
return [], new_tokens
|
||||
kept_kv = [k[:, :common] for k in checkpoint["kv"]]
|
||||
return kept_kv, new_tokens[common:]
|
||||
```
|
||||
|
||||
### Pattern 5: Quantized serialization
|
||||
```python
|
||||
def serialize_kv_int8(kv: torch.Tensor) -> tuple[bytes, dict]:
|
||||
"""매 fp16 KV 의 int8 의 quantize — 매 50% storage save."""
|
||||
scale = kv.abs().amax() / 127
|
||||
q = (kv / scale).round().clamp(-128, 127).to(torch.int8)
|
||||
return q.numpy().tobytes(), {"scale": scale.item(), "shape": list(q.shape)}
|
||||
|
||||
def deserialize_kv_int8(data: bytes, meta: dict) -> torch.Tensor:
|
||||
import numpy as np
|
||||
arr = np.frombuffer(data, dtype=np.int8).reshape(meta["shape"])
|
||||
return torch.from_numpy(arr).to(torch.float16) * meta["scale"]
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Conversation < 5min idle | HBM 만. |
|
||||
| Long conversation, hours idle | NVMe tier. |
|
||||
| Multi-day project context | S3 + prefix cache. |
|
||||
| Cost-sensitive multi-tenant | Aggressive 4-tier ICP. |
|
||||
| Latency-sensitive (< 10ms) | HBM only — ICP 의 X. |
|
||||
|
||||
**기본값**: 4-tier (HBM → CPU → NVMe → S3) 매 LRU eviction, fp8 KV-cache, prefix caching enabled.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[KV-Cache]] · [[LLM-Serving]]
|
||||
- 변형: [[Prefix-Caching]] · [[Paged-Attention]]
|
||||
- 응용: [[Long-Context-LLM]] · [[Multi-Turn-Agents]] · [[vLLM]]
|
||||
- Adjacent: [[Continuous-Batching]] · [[Speculative-Decoding]] · [[FlashAttention]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 production LLM serving 매 multi-hour conversations, 매 cost optimization, 매 multi-tenant 100K+ sessions.
|
||||
**언제 X**: Single-shot inference (no persistence needed), strict-latency RT systems (< 10ms first-token).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Naive pickle of KV**: 매 quantization-unaware — 5-10x bigger than needed.
|
||||
- **No atomic write**: crash 의 corrupted checkpoint 의 unrecoverable.
|
||||
- **Per-token checkpoint**: 매 IOPS storm — batch 의 N tokens.
|
||||
- **Resume without prefix check**: silent correctness bug.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified: vLLM 0.7 docs (2025), SGLang RadixAttention paper (2024), Mooncake architecture (2024).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full content with vLLM 2026 patterns, tiered eviction, quantized serialization |
|
||||
|
||||
Reference in New Issue
Block a user