[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,90 +1,245 @@
|
||||
---
|
||||
id: wiki-2026-0508-black-box-optimization
|
||||
title: Black Box Optimization
|
||||
title: Black-Box Optimization
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [BBO-001]
|
||||
aliases: [블랙박스 최적화, derivative-free optimization, BBO, Bayesian optimization, CMA-ES, gradient-free]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Optimization|[Optimization", algorithm, machine-learning, black-box, Heuristics]
|
||||
confidence_score: 0.92
|
||||
verification_status: applied
|
||||
tags: [optimization, bayesian-optimization, cma-es, hyperparameter-tuning, automl, gradient-free, derivative-free]
|
||||
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: Optuna / scikit-optimize / Ray Tune / BoTorch / nevergrad
|
||||
---
|
||||
|
||||
# Black-Box Optimization (블랙박스 최적화)
|
||||
# Black-Box Optimization
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "내부 원리는 몰라도, 입력과 출력만으로 최선의 답을 찾아내라" — 시스템의 내부 수학적 모델이나 기울기(Gradient) 정보를 알 수 없을 때, 관측된 데이터를 바탕으로 목적 함수를 최적화하는 기법.
|
||||
## 📌 한 줄 통찰
|
||||
> **"매 gradient X 의 best 의 search"**. 매 expensive function (1 trial = hour) 의 minimum sample 의 best. 매 hyperparameter / drug / robotics / circuit design 의 standard. 매 Bayesian Optimization (GP) 의 dominant.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 목적 함수의 미분값을 구할 수 없는 환경에서, 효율적인 샘플링과 전역 탐색 전략을 통해 최적의 파라미터 조합을 찾는 탐색 패턴.
|
||||
- **주요 기법:**
|
||||
- **Bayesian Optimization:** 가우시안 프로세스 등을 통해 목적 함수의 모양을 추정하고, 다음 샘플링 지점을 결정 (가장 널리 쓰임).
|
||||
- **Genetic Algorithms:** 자연 선택의 원리를 이용하여 해를 진화시킴.
|
||||
- **Simulated Annealing:** 확률적 탐색을 통해 지역 최적해 탈출.
|
||||
- **Random [[Search|Search]] / Grid Search:** 가장 단순한 형태의 탐색.
|
||||
- **응용 분야:** 하이퍼파라미터 튜닝(AutoML), 신약 설계, 로봇 제어 정책 최적화 등.
|
||||
## 📖 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 미분 가능한 환경에서의 경사 하강법에 의존하던 방식에서, 미분이 불가능하거나 연산 비용이 매우 비싼 실제 시스템 최적화로 영역 확장.
|
||||
- **정책 변화:** Antigravity 프로젝트의 에이전트 모델 하이퍼파라미터 최적화 시, 베이지안 최적화 기반의 블랙박스 기법을 사용하여 적은 시행횟수로 최적의 설정을 찾음.
|
||||
### 매 setting
|
||||
- 매 f(x): 매 expensive (분 ~ 일).
|
||||
- 매 gradient X 또는 매 noisy.
|
||||
- 매 budget 매 limited (10-1000 trial).
|
||||
- 매 goal: min/max f.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Bayesian-Inference, [[Evolutionary-Computation|Evolutionary-Computation]], [[Simulated-Annealing|Simulated-Annealing]], HyperParameter-Optimization
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/Black-Box-Optimization.md
|
||||
### 매 method
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
#### Random / Grid search
|
||||
- 매 simple, 매 baseline.
|
||||
- 매 random > grid (high-dim).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
#### Bayesian Optimization (BO)
|
||||
- 매 surrogate model (Gaussian Process / TPE) 의 fit.
|
||||
- 매 acquisition function (EI, UCB, PI) 의 next 결정.
|
||||
- ✅ 매 sample-efficient.
|
||||
- ❌ 매 GP scale O(N³).
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
#### Evolutionary
|
||||
- **CMA-ES**: 매 covariance matrix adaptation. 매 continuous.
|
||||
- **GA**: 매 discrete.
|
||||
- **Differential Evolution**: 매 robust.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
#### Simulated Annealing
|
||||
- 매 random walk + 매 cooling schedule.
|
||||
- 매 escape local min.
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
#### Population-based
|
||||
- **Particle Swarm** (PSO).
|
||||
- **Population-Based Training** (PBT, DeepMind).
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
#### TPE (Tree-structured Parzen Estimator)
|
||||
- 매 Optuna default.
|
||||
- 매 conditional parameter OK.
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
#### NES (Natural Evolution Strategy)
|
||||
- 매 OpenAI ES.
|
||||
- 매 distributed-friendly.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
### 매 acquisition function (BO)
|
||||
- **Expected Improvement (EI)**: 매 expected gain over best.
|
||||
- **UCB** (Upper Confidence Bound): 매 exploit + explore (κ).
|
||||
- **PI** (Probability of Improvement): 매 simple.
|
||||
- **TS** (Thompson Sampling): 매 sample posterior.
|
||||
- **q-EI**: 매 batch parallel.
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
### 매 응용
|
||||
1. **Hyperparameter tune**: 매 Optuna, 매 Ray Tune.
|
||||
2. **AutoML**: 매 architecture + hyperparam.
|
||||
3. **Drug discovery**: 매 molecule design.
|
||||
4. **Robotics**: 매 policy parameter.
|
||||
5. **A/B test**: 매 thompson sampling.
|
||||
6. **Material design**: 매 alloy composition.
|
||||
7. **Compiler**: 매 optimization flag.
|
||||
8. **NN architecture search**: NAS.
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
### 매 high-dim / structured
|
||||
- **Trust Region BO**: 매 local search.
|
||||
- **Multi-fidelity**: 매 cheap proxy.
|
||||
- **Constraint BO**: 매 feasibility constraint.
|
||||
- **Multi-objective**: 매 Pareto front.
|
||||
- **Categorical / mixed**: 매 SMAC, 매 TPE.
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
### 매 modern compute
|
||||
- **Parallel batch**: 매 q-acquisition.
|
||||
- **Async**: 매 worker 의 done 의 즉시 propose.
|
||||
- **Warm-start**: 매 prior task 의 transfer.
|
||||
- **Multi-fidelity** (Hyperband, BOHB): 매 budget allocation.
|
||||
|
||||
```text
|
||||
# TODO
|
||||
## 💻 패턴
|
||||
|
||||
### Optuna (TPE)
|
||||
```python
|
||||
import optuna
|
||||
|
||||
def objective(trial):
|
||||
lr = trial.suggest_float('lr', 1e-5, 1e-1, log=True)
|
||||
n_layers = trial.suggest_int('n_layers', 1, 5)
|
||||
optimizer = trial.suggest_categorical('optimizer', ['adam', 'sgd'])
|
||||
|
||||
model = build(n_layers, lr, optimizer)
|
||||
return train_and_eval(model)
|
||||
|
||||
study = optuna.create_study(direction='minimize')
|
||||
study.optimize(objective, n_trials=100, n_jobs=4)
|
||||
|
||||
print(study.best_params, study.best_value)
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### scikit-optimize (GP-BO)
|
||||
```python
|
||||
from skopt import gp_minimize
|
||||
from skopt.space import Real, Integer, Categorical
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
space = [
|
||||
Real(1e-5, 1e-1, prior='log-uniform', name='lr'),
|
||||
Integer(1, 10, name='depth'),
|
||||
Categorical(['relu', 'gelu'], name='activation'),
|
||||
]
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
result = gp_minimize(
|
||||
objective,
|
||||
space,
|
||||
n_calls=50,
|
||||
acq_func='EI',
|
||||
random_state=42,
|
||||
)
|
||||
print(f'best: {result.x}, value: {result.fun}')
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### CMA-ES (continuous)
|
||||
```python
|
||||
import cma
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def objective(x):
|
||||
return sum(xi**2 for xi in x) # 매 minimize
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
es = cma.CMAEvolutionStrategy(x0=[1.0]*10, sigma0=0.5)
|
||||
es.optimize(objective, iterations=100)
|
||||
print(es.result.xbest)
|
||||
```
|
||||
|
||||
### BoTorch (PyTorch BO)
|
||||
```python
|
||||
import torch
|
||||
from botorch.models import SingleTaskGP
|
||||
from botorch.fit import fit_gpytorch_mll
|
||||
from botorch.acquisition import ExpectedImprovement
|
||||
from botorch.optim import optimize_acqf
|
||||
from gpytorch.mlls import ExactMarginalLogLikelihood
|
||||
|
||||
# 매 X, Y 의 train data
|
||||
gp = SingleTaskGP(X, Y)
|
||||
mll = ExactMarginalLogLikelihood(gp.likelihood, gp)
|
||||
fit_gpytorch_mll(mll)
|
||||
|
||||
ei = ExpectedImprovement(model=gp, best_f=Y.max())
|
||||
candidate, _ = optimize_acqf(
|
||||
ei, bounds=bounds, q=1, num_restarts=10, raw_samples=512,
|
||||
)
|
||||
# 매 candidate 의 evaluate → 매 GP 의 update.
|
||||
```
|
||||
|
||||
### Hyperband / BOHB (multi-fidelity)
|
||||
```python
|
||||
from ray import tune
|
||||
from ray.tune.schedulers import HyperBandScheduler
|
||||
|
||||
scheduler = HyperBandScheduler(metric='loss', mode='min')
|
||||
analysis = tune.run(
|
||||
train_fn,
|
||||
config={'lr': tune.loguniform(1e-5, 1e-1)},
|
||||
scheduler=scheduler,
|
||||
num_samples=100,
|
||||
resources_per_trial={'gpu': 1},
|
||||
)
|
||||
```
|
||||
|
||||
→ 매 cheap (low epoch) 의 explore + 매 promising 의 더 exploit.
|
||||
|
||||
### Multi-objective (Pareto)
|
||||
```python
|
||||
import optuna
|
||||
|
||||
def objective(trial):
|
||||
x = trial.suggest_float('x', 0, 5)
|
||||
y = trial.suggest_float('y', 0, 5)
|
||||
return x**2, (x-2)**2 + y**2 # 매 둘 다 minimize
|
||||
|
||||
study = optuna.create_study(directions=['minimize', 'minimize'])
|
||||
study.optimize(objective, n_trials=100)
|
||||
# 매 Pareto front 의 visualize.
|
||||
optuna.visualization.plot_pareto_front(study).show()
|
||||
```
|
||||
|
||||
## 🤔 결정 기준
|
||||
| 상황 | Method |
|
||||
|---|---|
|
||||
| Hyperparam (medium budget) | Optuna (TPE) |
|
||||
| Hyperparam (small budget) | GP-BO (skopt / BoTorch) |
|
||||
| Continuous high-dim | CMA-ES |
|
||||
| Discrete + continuous | TPE / SMAC |
|
||||
| Multi-fidelity | BOHB / Hyperband |
|
||||
| Distributed / async | Ray Tune |
|
||||
| RL policy | CMA-ES / OpenAI ES |
|
||||
| Multi-objective | NSGA-II / qNEHVI |
|
||||
|
||||
**기본값**: Optuna 의 baseline. 매 small budget 가 BoTorch.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Optimization]] · [[AutoML]] · [[Hyperparameter-Tuning]]
|
||||
- 변형: [[Bayesian-Optimization]] · [[CMA-ES]] · [[Genetic-Algorithm]] · [[Simulated-Annealing]] · [[TPE]]
|
||||
- 응용: [[Optuna]] · [[Ray-Tune]] · [[BoTorch]] · [[scikit-optimize]] · [[nevergrad]]
|
||||
- 변형 (high-dim): [[Trust-Region-BO]] · [[BOHB]] · [[Hyperband]]
|
||||
- Adjacent: [[Gaussian-Process]] · [[Acquisition-Function]] · [[NAS]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 expensive function. 매 hyperparameter tune. 매 gradient 없는 system. 매 design space search.
|
||||
**언제 X**: 매 cheap function (gradient 더 fast). 매 closed-form solution.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Grid search high-dim**: 매 curse of dimensionality.
|
||||
- **Acquisition 의 always EI** (high-noise): 매 UCB 가 좋음.
|
||||
- **No warm-start (related task)**: 매 sample waste.
|
||||
- **GP 의 1000+ trial**: 매 cubic scale.
|
||||
- **No multi-fidelity** (cheap proxy 가능): 매 budget waste.
|
||||
- **Single objective (multi-criteria 의 case)**: 매 weight 의 wrong.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Snoek et al. BO, Hansen CMA-ES, Optuna paper).
|
||||
- 신뢰도 A.
|
||||
- Related: [[Bayesian-Optimization]] · [[CMA-ES]] · [[AutoML]] · [[Optuna]].
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — methods + acquisition + 매 Optuna / BoTorch / CMA-ES code |
|
||||
|
||||
Reference in New Issue
Block a user