필사 모드: Weights & Biases (W&B) Experiment Management Practical Guide: From Experiment Tracking to Model Registry and Production Monitoring
EnglishIntroduction
ML 프로젝트에서 가장 흔히 발생하는 문제 중 하나는 "어떤 하이퍼파라미터 조합으로 학습한 모델이 가장 좋았는지 기억나지 않는다"는 것이다. 학습률, 배치 사이즈, 에포크 수, 모델 아키텍처 변경 등 수백 번의 실험을 진행하다 보면, 스프레드시트나 텍스트 파일로 관리하는 방식은 금세 한계에 도달한다. 재현 불가능한 실험, 유실된 메트릭, 팀원 간 실험 결과 공유의 어려움은 ML 팀의 생산성을 심각하게 저하시킨다.
**Weights & Biases(W&B)**는 이러한 ML 실험 관리 문제를 체계적으로 해결하기 위해 설계된 개발자 중심의 MLOps 플랫폼이다. 코드 몇 줄만 추가하면 모든 실험의 하이퍼파라미터, 메트릭, 시스템 자원 사용량, 모델 체크포인트를 자동으로 추적하고, 인터랙티브 대시보드에서 시각화할 수 있다. 2025년 기준 OpenAI, NVIDIA, Toyota Research 등 수천 개의 기업과 연구 기관에서 사용하고 있으며, PyTorch, TensorFlow, Keras, scikit-learn, Hugging Face Transformers 등 주요 프레임워크와 네이티브 통합을 제공한다.
이 글에서는 W&B의 핵심 기능인 Experiment Tracking, Sweeps, Artifacts, Model Registry, Tables, Reports를 실전 코드 예제와 함께 다룬다. 단순 사용법을 넘어, 팀 단위 협업 워크플로우, CI/CD 파이프라인 통합, 프로덕션 운영 시 주의사항, MLflow 등 경쟁 도구와의 비교까지 포괄적으로 살펴본다.
W&B 핵심 기능 개요
W&B 플랫폼은 ML 실험의 전체 라이프사이클을 커버하는 여러 컴포넌트로 구성된다. 각 컴포넌트는 독립적으로 사용할 수도 있고, 조합하여 완전한 MLOps 파이프라인을 구축할 수도 있다.
┌─────────────────────────────────────────────────────────────────┐
│ W&B Platform Architecture │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Experiment │ │ Sweeps │ │ Artifacts │ │
│ │ Tracking │──▶│ Hyperparams │──▶│ Data/Model Version │ │
│ │ (wandb.log) │ │ Tuning │ │ Control │ │
│ └──────┬───────┘ └──────────────┘ └──────────┬───────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Tables │ │ Reports │ │ Model Registry │ │
│ │ Data Viz │ │ Team Collab │ │ Production Staging │ │
│ │ Analysis │ │ Sharing │ │ Deployment │ │
│ └──────────────┘ └──────────────┘ └──────────┬───────────┘ │
│ │ │
│ ┌─────────▼──────────┐ │
│ │ W&B Launch / │ │
│ │ Webhooks / CI/CD │ │
│ │ Automation │ │
│ └────────────────────┘ │
│ │
│ Infrastructure: Cloud (SaaS) / Self-Hosted / Dedicated Cloud │
└─────────────────────────────────────────────────────────────────┘
**핵심 컴포넌트 요약:**
| 컴포넌트 | 역할 | 핵심 API |
| ------------------- | ---------------------------------------- | ---------------------------- |
| Experiment Tracking | 메트릭, 하이퍼파라미터, 시스템 자원 추적 | wandb.init(), wandb.log() |
| Sweeps | 자동 하이퍼파라미터 최적화 | wandb.sweep(), wandb.agent() |
| Artifacts | 데이터셋, 모델 체크포인트 버전 관리 | wandb.Artifact() |
| Model Registry | 모델 버전 스테이징, 프로덕션 배포 관리 | Registry UI / API |
| Tables | 예측 결과 시각화, 데이터 분석 | wandb.Table() |
| Reports | 실험 결과 문서화, 팀 공유 | Report Editor / SDK |
실험 추적(Experiment Tracking)
실험 추적은 W&B의 가장 기본이자 핵심 기능이다. 학습 스크립트에 몇 줄의 코드만 추가하면, 모든 실험 정보가 자동으로 기록되고 클라우드 대시보드에서 실시간으로 확인할 수 있다.
기본 설정과 메트릭 로깅
from torch.utils.data import DataLoader
1. W&B 초기화 - 프로젝트와 실험 이름 지정
wandb.init(
project="image-classifier",
name="resnet50-lr0.001-batch32",
config={
"architecture": "ResNet50",
"learning_rate": 0.001,
"batch_size": 32,
"epochs": 100,
"optimizer": "AdamW",
"weight_decay": 1e-4,
"scheduler": "CosineAnnealingLR",
"dataset": "CIFAR-100",
"augmentation": "RandAugment",
},
tags=["baseline", "resnet", "cifar100"],
notes="ResNet50 baseline with CosineAnnealing scheduler",
)
config = wandb.config # config 객체로 하이퍼파라미터 접근
2. 모델, 옵티마이저, 스케줄러 설정
model = build_model(config.architecture)
optimizer = torch.optim.AdamW(
model.parameters(),
lr=config.learning_rate,
weight_decay=config.weight_decay
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=config.epochs
)
3. W&B에서 모델 gradient 추적 (선택 사항)
wandb.watch(model, log="all", log_freq=100)
4. 학습 루프 - 메트릭 로깅
for epoch in range(config.epochs):
model.train()
train_loss = 0.0
correct = 0
total = 0
for batch_idx, (images, labels) in enumerate(train_loader):
images, labels = images.cuda(), labels.cuda()
outputs = model(images)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
train_loss += loss.item()
_, predicted = outputs.max(1)
total += labels.size(0)
correct += predicted.eq(labels).sum().item()
배치 단위 로깅 (선택적)
if batch_idx % 50 == 0:
wandb.log({
"batch/loss": loss.item(),
"batch/step": epoch * len(train_loader) + batch_idx,
})
에포크 단위 메트릭 로깅
train_acc = 100.0 * correct / total
val_loss, val_acc = evaluate(model, val_loader)
wandb.log({
"epoch": epoch,
"train/loss": train_loss / len(train_loader),
"train/accuracy": train_acc,
"val/loss": val_loss,
"val/accuracy": val_acc,
"learning_rate": scheduler.get_last_lr()[0],
"gpu/memory_allocated_gb": torch.cuda.memory_allocated() / 1e9,
"gpu/utilization": torch.cuda.utilization(),
})
scheduler.step()
최고 성능 모델 체크포인트 저장
if val_acc > best_val_acc:
best_val_acc = val_acc
torch.save(model.state_dict(), "best_model.pth")
wandb.save("best_model.pth")
wandb.run.summary["best_val_accuracy"] = best_val_acc
5. 실험 종료
wandb.finish()
위 코드를 실행하면 W&B 대시보드에서 다음을 실시간으로 확인할 수 있다:
- **학습/검증 손실과 정확도 곡선**: 에포크별 추이를 인터랙티브 차트로 확인
- **하이퍼파라미터 설정**: config에 지정한 모든 값이 자동 기록
- **시스템 메트릭**: GPU 사용률, 메모리, CPU, 디스크 I/O가 자동 수집
- **코드 버전**: Git 커밋 해시, diff, 실행 환경 정보가 자동 첨부
- **모델 그래디언트**: wandb.watch()로 파라미터 분포와 그래디언트 히스토그램 추적
프레임워크 통합
W&B는 주요 ML 프레임워크와의 네이티브 통합을 제공하여, 최소한의 코드 변경으로 실험 추적을 시작할 수 있다.
Hugging Face Transformers 통합 예시
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(
output_dir="./results",
report_to="wandb", # W&B 자동 연동
run_name="bert-finetune-v1",
logging_steps=10,
evaluation_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
metric_for_best_model="eval_f1",
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
compute_metrics=compute_metrics,
)
trainer.train() # 자동으로 W&B에 메트릭 로깅
PyTorch Lightning, Keras, scikit-learn, XGBoost, LightGBM 등 대부분의 프레임워크에서 유사한 방식으로 1-2줄의 코드 추가만으로 W&B 통합이 가능하다.
Sweeps: 하이퍼파라미터 최적화
수동으로 하이퍼파라미터를 조정하는 것은 시간이 많이 걸리고, 최적 조합을 놓칠 가능성이 높다. W&B Sweeps는 Grid Search, Random Search, Bayesian Optimization을 지원하며, Hyperband 기반의 Early Termination으로 비효율적인 실험을 자동 중단하여 GPU 시간을 절약한다.
Sweep 설정과 실행
1. Sweep 설정 정의
sweep_config = {
"method": "bayes", # grid, random, bayes 중 선택
"metric": {
"name": "val/accuracy",
"goal": "maximize"
},
"parameters": {
"learning_rate": {
"distribution": "log_uniform_values",
"min": 1e-5,
"max": 1e-2,
},
"batch_size": {
"values": [16, 32, 64, 128]
},
"optimizer": {
"values": ["adam", "adamw", "sgd"]
},
"weight_decay": {
"distribution": "log_uniform_values",
"min": 1e-6,
"max": 1e-2,
},
"dropout": {
"distribution": "uniform",
"min": 0.1,
"max": 0.5,
},
"architecture": {
"values": ["resnet18", "resnet34", "resnet50"]
},
},
Early Termination: 성능이 낮은 실험 자동 중단
"early_terminate": {
"type": "hyperband",
"min_iter": 5, # 최소 5 에포크 후 평가
"eta": 3, # 상위 1/3만 계속 진행
"max_iter": 50,
},
}
2. Sweep 생성
sweep_id = wandb.sweep(
sweep=sweep_config,
project="image-classifier"
)
3. 학습 함수 정의
def train():
wandb.init()
config = wandb.config
model = build_model(config.architecture, dropout=config.dropout)
optimizer = get_optimizer(
config.optimizer, model, config.learning_rate, config.weight_decay
)
for epoch in range(50):
train_loss = train_one_epoch(model, train_loader, optimizer)
val_loss, val_acc = evaluate(model, val_loader)
wandb.log({
"epoch": epoch,
"train/loss": train_loss,
"val/loss": val_loss,
"val/accuracy": val_acc,
})
wandb.finish()
4. Sweep Agent 실행 - 최대 50회 실험
wandb.agent(sweep_id, function=train, count=50)
Sweep 병렬 실행
여러 GPU나 머신에서 Sweep Agent를 병렬로 실행하여 탐색 속도를 높일 수 있다. 각 에이전트는 W&B 서버에서 다음 시도할 하이퍼파라미터 조합을 받아와 독립적으로 실행한다.
터미널 1 (GPU 0)
CUDA_VISIBLE_DEVICES=0 wandb agent your-entity/image-classifier/sweep_id
터미널 2 (GPU 1)
CUDA_VISIBLE_DEVICES=1 wandb agent your-entity/image-classifier/sweep_id
터미널 3 (다른 머신)
CUDA_VISIBLE_DEVICES=0 wandb agent your-entity/image-classifier/sweep_id
Bayesian Optimization은 이전 실험 결과를 기반으로 다음 탐색 지점을 선택하므로, Random Search 대비 더 적은 실험 횟수로 최적 하이퍼파라미터를 찾을 수 있다. 대시보드에서는 Parallel Coordinates Plot, Parameter Importance Plot 등을 통해 어떤 하이퍼파라미터가 성능에 가장 큰 영향을 미치는지 직관적으로 파악할 수 있다.
Artifacts: 데이터와 모델 버전 관리
W&B Artifacts는 데이터셋, 모델 체크포인트, 설정 파일 등의 버전을 관리하고, 각 실험에서 사용된 정확한 데이터 버전과 생성된 모델을 추적할 수 있게 해준다. 중복 파일은 자동으로 디듀플리케이션되어 저장 공간을 절약한다.
데이터셋 Artifact 생성과 사용
=== 데이터셋 업로드 ===
run = wandb.init(project="image-classifier", job_type="data-pipeline")
Artifact 생성
dataset_artifact = wandb.Artifact(
name="cifar100-processed",
type="dataset",
description="CIFAR-100 전처리 완료 데이터셋 (정규화, 증강 적용)",
metadata={
"num_classes": 100,
"train_size": 50000,
"val_size": 10000,
"preprocessing": "normalize_mean_std",
"augmentation": "randaugment_n2_m14",
"source": "torchvision.datasets.CIFAR100",
},
)
디렉토리 또는 파일 추가
dataset_artifact.add_dir("./data/processed/cifar100")
dataset_artifact.add_file("./data/metadata.json")
업로드 - 자동으로 v0, v1, v2... 버전 관리
run.log_artifact(dataset_artifact)
run.finish()
=== 학습 시 데이터셋 다운로드 ===
run = wandb.init(project="image-classifier", job_type="training")
특정 버전 또는 최신 버전 사용
dataset = run.use_artifact("cifar100-processed:latest")
data_dir = dataset.download() # 로컬에 캐시된 경로 반환
학습 진행...
train_loader = create_dataloader(data_dir, split="train")
=== 모델 체크포인트 저장 ===
model_artifact = wandb.Artifact(
name="resnet50-cifar100",
type="model",
description="ResNet50 trained on CIFAR-100",
metadata={
"val_accuracy": best_val_acc,
"architecture": "resnet50",
"framework": "pytorch",
"training_run": wandb.run.id,
},
)
model_artifact.add_file("best_model.pth")
model_artifact.add_file("model_config.json")
run.log_artifact(model_artifact)
run.finish()
Artifacts는 DAG(Directed Acyclic Graph) 형태의 Lineage를 자동으로 구성한다. 특정 모델이 어떤 데이터셋으로 학습되었는지, 어떤 전처리 파이프라인을 거쳤는지를 W&B UI에서 시각적으로 추적할 수 있다. 이는 모델 감사(auditing)와 재현성 확보에 필수적이다.
Model Registry
W&B Model Registry는 조직 차원에서 모델의 라이프사이클을 관리하는 중앙 저장소다. 개별 실험에서 생성된 모델 Artifact를 Registry에 등록하고, Staging, Production, Archived 등의 상태로 관리할 수 있다. 이를 통해 "현재 프로덕션에 배포된 모델이 무엇인지", "언제, 누가, 어떤 이유로 모델을 변경했는지"를 명확하게 추적할 수 있다.
Registry 워크플로우
1. 학습 완료 후 모델을 Registry에 등록
run = wandb.init(project="image-classifier", job_type="register-model")
기존 모델 Artifact 참조
model_artifact = run.use_artifact("resnet50-cifar100:v5")
Registry에 링크 - "Registered Model" 생성 또는 기존 모델에 새 버전 추가
run.link_artifact(
artifact=model_artifact,
target_path="model-registry/image-classifier-prod",
aliases=["candidate", "v2.1.0"],
)
run.finish()
2. 프로덕션 배포 시 Registry에서 모델 가져오기
run = wandb.init(project="image-classifier", job_type="deployment")
Registry에서 특정 alias로 모델 로드
model_artifact = run.use_artifact(
"model-registry/image-classifier-prod:production"
)
model_dir = model_artifact.download()
모델 로드 및 서빙
model = load_model(model_dir)
run.finish()
3. Webhook을 통한 자동화 - Registry 이벤트에 반응
W&B UI에서 설정하거나 API로 구성
새 모델이 "production" alias를 받으면 자동으로 배포 파이프라인 트리거
Registry 상태 관리 모범 사례
Registry에서 모델의 상태를 체계적으로 관리하려면 다음과 같은 alias 규칙을 정하는 것이 좋다:
- **candidate**: 학습 완료 후 평가 대기 중인 모델
- **staging**: 평가를 통과하여 스테이징 환경에서 테스트 중인 모델
- **production**: 현재 프로덕션에 배포된 모델
- **archived**: 더 이상 사용하지 않지만 기록 보존이 필요한 모델
W&B Registry는 모든 상태 변경에 대한 감사 로그를 자동으로 기록하므로, 규정 준수(compliance)와 거버넌스 요구 사항을 충족할 수 있다.
Tables: 데이터 시각화와 분석
W&B Tables는 모델 예측 결과, 데이터 분포, 오류 분석 등을 인터랙티브하게 시각화하고 분석할 수 있는 기능이다. 이미지, 텍스트, 오디오 등 다양한 미디어 타입을 지원하며, 필터링, 정렬, 그룹화, 계산 컬럼 등을 통해 데이터를 탐색할 수 있다.
run = wandb.init(project="image-classifier", job_type="evaluation")
예측 결과 테이블 생성
columns = ["image", "true_label", "predicted_label", "confidence", "correct"]
prediction_table = wandb.Table(columns=columns)
model.eval()
with torch.no_grad():
for images, labels in test_loader:
outputs = model(images.cuda())
probs = torch.softmax(outputs, dim=1)
confidences, predictions = probs.max(dim=1)
for i in range(len(images)):
is_correct = predictions[i].item() == labels[i].item()
prediction_table.add_data(
wandb.Image(images[i]), # 이미지
class_names[labels[i].item()], # 실제 라벨
class_names[predictions[i].item()], # 예측 라벨
confidences[i].item(), # 신뢰도
is_correct, # 정오답 여부
)
테이블 로깅
run.log({"predictions": prediction_table})
오분류 분석 테이블
error_table = wandb.Table(
columns=["image", "true", "predicted", "confidence", "loss"]
)
... 오분류 케이스만 필터링하여 추가
run.log({"error_analysis": error_table})
run.finish()
Tables를 활용하면 대시보드에서 "confidence가 낮은 예측", "특정 클래스의 오분류 패턴", "데이터셋의 분포 불균형" 등을 시각적으로 빠르게 파악할 수 있다. 특히 이미지 분류, 객체 탐지, NLP 태스크에서 모델의 약점을 분석하는 데 매우 유용하다.
Reports: 팀 협업과 공유
W&B Reports는 실험 결과를 문서화하고 팀과 공유하기 위한 인터랙티브 문서 도구다. 마크다운 텍스트, 실험 차트, 코드 블록, 미디어 등을 조합하여 재현 가능한 실험 보고서를 작성할 수 있다.
Reports의 주요 활용 사례는 다음과 같다:
- **주간 실험 진행 보고**: 이번 주 진행한 실험들의 결과와 인사이트 정리
- **모델 비교 분석**: A/B 테스트 결과, 아키텍처 비교 등의 정량적 분석
- **프로젝트 핸드오프**: 팀원이 변경될 때 실험 이력과 결론 전달
- **논문 재현 실험**: 논문의 결과를 재현한 실험 과정과 결과 공유
- **모델 리뷰**: 프로덕션 배포 전 모델 성능 검토 문서
Reports는 W&B UI에서 직접 작성할 수도 있고, Python SDK를 통해 프로그래매틱하게 생성할 수도 있다. 공유 시에는 이메일 초대 또는 Magic Link를 통해 W&B 계정 없는 이해관계자에게도 공유할 수 있어, ML 팀과 비즈니스 팀 간의 소통에 효과적이다.
팀 협업 모범 사례
효과적인 팀 협업을 위해 다음과 같은 규칙을 권장한다:
**1. 프로젝트 구조 표준화**
organization/
├── project-name-research/ # 탐색적 실험
├── project-name-staging/ # 배포 후보 모델 검증
└── project-name-production/ # 프로덕션 모니터링
**2. 실험 네이밍 규칙**
{모델아키텍처}-{데이터셋}-{핵심변경사항}-{날짜}
예: resnet50-cifar100-cosine_lr-20260308
**3. Tag 체계**
- 실험 목적: baseline, ablation, architecture-search
- 상태: wip, completed, failed
- 우선순위: p0-critical, p1-important, p2-nice-to-have
**4. 코드 리뷰 연동**
PR에 W&B Report 링크를 첨부하여, 코드 변경과 실험 결과를 함께 리뷰하는 문화를 만든다. 이를 통해 "이 코드 변경이 실제로 성능 향상을 가져왔는가"를 정량적으로 검증할 수 있다.
실험 관리 도구 비교 (W&B vs MLflow)
ML 실험 관리 도구를 선택할 때는 팀의 규모, 인프라 환경, 예산, 기술 스택을 종합적으로 고려해야 한다. 주요 도구들의 비교를 살펴보자.
| 기능 | W&B | MLflow | Neptune.ai | CometML |
| ----------------------- | ------------------------------------ | -------------------------------- | -------------------- | --------------- |
| **배포 방식** | SaaS / Self-hosted / Dedicated Cloud | Self-hosted / Databricks Managed | SaaS / Self-hosted | SaaS |
| **오픈소스 여부** | 부분 오픈소스 (서버 비공개) | 완전 오픈소스 (Apache 2.0) | 비공개 | 비공개 |
| **실험 추적** | 우수 (실시간, 자동 시스템 메트릭) | 양호 (기본 기능 충실) | 우수 (대규모 확장성) | 양호 |
| **하이퍼파라미터 튜닝** | Sweeps 내장 (Bayesian, Hyperband) | Optuna 등 외부 통합 필요 | Optuna 통합 | 내장 |
| **시각화 품질** | 최우수 (인터랙티브 대시보드) | 기본 수준 | 우수 | 양호 |
| **모델 레지스트리** | 내장 (alias 기반 상태 관리) | 내장 (Stage 기반) | 내장 | 내장 |
| **팀 협업** | Reports, 코멘트, 공유 링크 | 기본 수준 | 양호 | 양호 |
| **확장성** | 수만 runs 처리 가능 | 대규모 시 인프라 관리 필요 | 10만+ runs, 초대규모 | 중규모 |
| **프레임워크 통합** | PyTorch, TF, HF, Lightning 등 | PyTorch, TF, sklearn 등 | PyTorch, TF 등 | PyTorch, TF 등 |
| **가격 (팀)** | \$50/user/month (Pro) | 무료 (OSS) / Databricks 유료 | \$49/user/month | \$49/user/month |
| **러닝 커브** | 낮음 (코드 2줄로 시작) | 낮음-중간 | 중간 | 낮음 |
| **GPU/시스템 메트릭** | 자동 수집 | 수동 설정 필요 | 자동 수집 | 자동 수집 |
선택 기준 가이드
**W&B를 선택해야 할 때:**
- 시각화 품질과 개발자 경험(DX)이 최우선일 때
- 빠른 도입과 팀 간 협업이 중요할 때
- 하이퍼파라미터 튜닝이 빈번할 때
- Hugging Face, PyTorch Lightning 등과의 긴밀한 통합이 필요할 때
**MLflow를 선택해야 할 때:**
- 벤더 종속(vendor lock-in) 회피가 중요할 때
- 완전한 자체 호스팅과 데이터 주권(data sovereignty)이 필수일 때
- Databricks 생태계를 이미 사용 중일 때
- 라이선스 비용 없이 시작하고 싶을 때
**Neptune.ai를 선택해야 할 때:**
- 초대규모 실험 (10만+ runs, 수백만 데이터 포인트) 관리가 필요할 때
- Foundation 모델 학습 등 극한의 로깅 처리량이 요구될 때
- API 중심의 유연한 메타데이터 관리가 필요할 때
CI/CD 파이프라인 통합
W&B를 CI/CD 파이프라인에 통합하면, 모델 학습부터 평가, 레지스트리 등록, 배포까지의 전 과정을 자동화할 수 있다.
GitHub Actions 통합 예시
.github/workflows/model-training.yml
name: Model Training and Evaluation Pipeline
on:
push:
paths:
- 'src/models/**'
- 'configs/**'
workflow_dispatch:
inputs:
experiment_name:
description: 'Experiment name'
required: true
env:
WANDB_API_KEY: ${{ secrets.WANDB_API_KEY }}
WANDB_PROJECT: image-classifier
WANDB_ENTITY: your-team
jobs:
train:
runs-on: [self-hosted, gpu]
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -r requirements.txt
- name: Train model
run: |
python src/train.py \
--config configs/production.yaml \
--wandb-run-name "ci-${{ github.sha }}"
- name: Evaluate model
run: |
python src/evaluate.py \
--model-artifact "resnet50-cifar100:latest" \
--threshold-accuracy 0.92
- name: Register model to W&B Registry
if: success()
run: |
python src/register_model.py \
--artifact "resnet50-cifar100:latest" \
--registry "image-classifier-prod" \
--alias "candidate"
deploy:
needs: train
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Promote model to production
run: |
python src/promote_model.py \
--registry "image-classifier-prod" \
--from-alias "candidate" \
--to-alias "production"
W&B Webhook 자동화
W&B Registry에서 모델 상태가 변경될 때 자동으로 외부 시스템을 트리거할 수 있다. 예를 들어, 모델이 "production" alias를 받으면 자동으로 Kubernetes 배포 파이프라인을 시작하거나, Slack 알림을 보내는 식이다.
W&B Webhook 수신 서버 예시 (FastAPI)
from fastapi import FastAPI, Request
app = FastAPI()
@app.post("/wandb-webhook")
async def handle_wandb_webhook(request: Request):
payload = await request.json()
event_type = payload.get("event_type")
artifact_alias = payload.get("artifact_alias", "")
if event_type == "ADD_ARTIFACT_ALIAS" and "production" in artifact_alias:
프로덕션 배포 파이프라인 트리거
artifact_path = payload["artifact_version_string"]
subprocess.run([
"kubectl", "set", "image",
"deployment/model-server",
f"model-server=model-image:{artifact_path}",
])
Slack 알림
notify_slack(
f"New production model deployed: {artifact_path}"
)
return {"status": "ok"}
Troubleshooting
W&B를 사용하면서 자주 만나는 문제와 해결 방법을 정리한다.
1. 네트워크 오류로 로깅 실패
기업 방화벽이나 네트워크 불안정으로 W&B 서버에 연결하지 못하는 경우가 있다.
오프라인 모드로 실행 후 나중에 동기화
os.environ["WANDB_MODE"] = "offline"
wandb.init(project="my-project")
... 학습 진행 ...
wandb.finish()
나중에 인터넷 연결 시 수동 동기화
터미널에서 실행: wandb sync ./wandb/offline-run-*
2. 대용량 Artifact 업로드 타임아웃
대용량 데이터셋이나 모델을 업로드할 때 타임아웃이 발생할 수 있다.
참조 Artifact 사용 - 실제 파일을 업로드하지 않고 경로만 기록
artifact = wandb.Artifact("large-dataset", type="dataset")
artifact.add_reference(
"s3://my-bucket/datasets/imagenet/", # S3, GCS, Azure Blob 등 지원
name="imagenet"
)
run.log_artifact(artifact)
3. 메모리 부족 (Table 로깅 시)
대규모 테이블을 한 번에 로깅하면 메모리 부족이 발생할 수 있다.
배치 단위로 테이블 로깅
BATCH_SIZE = 1000
table = wandb.Table(columns=["id", "prediction", "label"])
for i in range(0, len(predictions), BATCH_SIZE):
batch = predictions[i:i + BATCH_SIZE]
for pred in batch:
table.add_data(pred["id"], pred["prediction"], pred["label"])
run.log({"predictions": table})
4. Sweep Agent가 중단된 경우
네트워크 장애 등으로 Sweep Agent가 중단된 경우, 동일한 sweep_id로 Agent를 다시 시작하면 중단된 지점부터 이어서 진행된다.
기존 sweep 재개
wandb agent your-entity/project/existing_sweep_id
5. Self-Hosted 환경에서의 성능 최적화
W&B Server를 자체 호스팅할 때는 다음 사항을 확인해야 한다:
- **데이터베이스**: MySQL 8.0 이상 권장, 충분한 연결 풀 설정
- **객체 저장소**: S3 호환 저장소 (MinIO 등) 사용 시 처리량 제한 확인
- **Redis**: 캐시 레이어로 Redis 설정하여 대시보드 응답 속도 개선
- **로드밸런서**: 다수의 동시 사용자가 있을 경우 Nginx/ALB로 로드밸런싱
Production Checklist
W&B를 프로덕션 환경에서 운영할 때 확인해야 할 항목들을 정리한다.
보안 및 접근 제어
- API Key를 환경 변수 또는 시크릿 매니저(AWS Secrets Manager, Vault 등)로 관리
- 팀별 프로젝트 접근 권한 설정 (Admin, Member, Viewer)
- Self-Hosted 배포 시 TLS/SSL 인증서 적용
- SAML/OIDC 기반 SSO 연동 (Enterprise 플랜)
- SCIM을 통한 프로그래매틱 사용자/역할 관리
비용 관리
W&B 비용은 크게 **사용자 수**, **저장 용량**, **추적 시간(Tracked Hours)**에 따라 결정된다:
- **Free 플랜**: 5 모델 시트, 5GB 저장, 개인 프로젝트에 적합
- **Pro 플랜**: \$50/user/month, 500 추적 시간, 100GB 저장, 추가 시간 \$1/hr
- **Enterprise**: 맞춤 가격, Self-hosted 옵션, SLA, 전담 지원
비용 최적화 팁:
- 불필요한 실험 데이터는 주기적으로 정리 (wandb.Api()로 자동화 가능)
- 대용량 Artifact는 Reference Artifact로 외부 저장소 활용
- Sweep 시 Early Termination을 적극 활용하여 추적 시간 절감
- 시스템 메트릭 로깅 빈도 조절 (기본 15초, 필요시 늘릴 수 있음)
모니터링과 알림
W&B Alert 설정 - 학습 이상 감지 시 알림
wandb.init(project="production-monitor")
학습 중 이상 감지 시 Slack/Email 알림
if val_loss > threshold:
wandb.alert(
title="Training Anomaly Detected",
text=f"Validation loss ({val_loss:.4f}) exceeded threshold ({threshold})",
level=wandb.AlertLevel.WARN,
)
NaN 감지
if torch.isnan(loss):
wandb.alert(
title="NaN Loss Detected",
text="Training diverged - NaN loss detected",
level=wandb.AlertLevel.ERROR,
)
wandb.finish(exit_code=1)
실패 사례와 대응
사례 1: 실험 메타데이터 혼란
**문제**: 팀원들이 각자 다른 네이밍 규칙과 태그를 사용하여, 수백 개의 실험 중 의미 있는 결과를 찾기 어려워졌다.
**대응**: 프로젝트 초기에 네이밍 컨벤션, 필수 태그 목록, config 스키마를 문서화하고, CI에서 검증하도록 pre-commit hook을 추가했다. W&B의 Group 기능을 활용하여 관련 실험을 묶고, Notes에 실험 목적과 가설을 반드시 기록하도록 팀 규칙을 정했다.
사례 2: Artifact 저장소 용량 폭증
**문제**: 모든 에포크의 체크포인트를 Artifact로 저장하여 저장 비용이 월 수백 달러로 급증했다.
**대응**: 체크포인트 저장 전략을 변경했다. 최고 성능 모델과 마지막 N개 체크포인트만 유지하고, 나머지는 자동 삭제하는 정책을 적용했다. 대용량 모델은 Reference Artifact로 S3에 직접 저장하고 W&B에는 메타데이터만 기록하도록 변경했다.
오래된 Artifact 버전 자동 정리 스크립트
api = wandb.Api()
artifact_type = api.artifact_type("model", "your-entity/your-project")
for artifact_collection in artifact_type.collections():
versions = artifact_collection.versions()
최신 5개 버전만 유지
for version in versions[5:]:
if "production" not in version.aliases and "staging" not in version.aliases:
version.delete()
print(f"Deleted: {version.name}")
사례 3: Sweep 무한 실행
**문제**: Bayesian Search Sweep을 실행한 후 명확한 종료 조건 없이 방치하여, GPU 리소스가 낭비되었다.
**대응**: 반드시 count 파라미터로 최대 실행 횟수를 설정하고, early_terminate를 활성화했다. 추가로 팀 Slack 채널에 Sweep 시작/종료 알림을 자동화하고, GPU 사용 시간 모니터링 대시보드를 구축했다.
사례 4: 프레임워크 버전 불일치
**문제**: 한 팀원의 환경에서 학습한 모델이 다른 팀원의 환경에서 로드되지 않았다. PyTorch 버전 차이가 원인이었다.
**대응**: wandb.config에 프레임워크 버전, CUDA 버전, 주요 라이브러리 버전을 명시적으로 기록하도록 래퍼 함수를 만들었다. Docker 이미지 태그를 config에 포함시키고, requirements.txt도 Artifact로 함께 저장하여 환경 재현성을 보장했다.
def init_wandb_with_env(project, name, config):
"""환경 정보를 자동으로 포함하는 wandb.init 래퍼"""
env_config = {
"python_version": sys.version,
"pytorch_version": torch.__version__,
"cuda_version": torch.version.cuda,
"cudnn_version": torch.backends.cudnn.version(),
"gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else "N/A",
"num_gpus": torch.cuda.device_count(),
}
config.update(env_config)
return wandb.init(
project=project,
name=name,
config=config,
save_code=True, # 실행한 코드 자동 저장
)
References
- [Weights & Biases 공식 문서 - Experiment Tracking](https://docs.wandb.ai/models/track)
- [Weights & Biases 공식 문서 - Sweeps](https://docs.wandb.ai/models/sweeps)
- [Weights & Biases 공식 문서 - Registry](https://docs.wandb.ai/models/registry)
- [Weights & Biases 공식 문서 - Tables](https://docs.wandb.ai/models/tables)
- [Weights & Biases 공식 문서 - Reports](https://docs.wandb.ai/models/reports)
- [Weights & Biases Artifacts](https://wandb.ai/site/artifacts/)
- [W&B Pricing](https://wandb.ai/site/pricing/)
- [W&B GitHub Repository](https://github.com/wandb/wandb)
- [The 2025 MLOps Landscape: MLflow vs W&B vs Neptune - Uplatz](https://uplatz.com/blog/the-2025-mlops-landscape-a-comparative-analysis-of-mlflow-weights-biases-and-neptune/)
- [Neptune.ai - W&B vs MLflow vs Neptune 비교](https://neptune.ai/vs/wandb-mlflow)
- [W&B 101 Course](https://wandb.ai/site/courses/101/)
- [Harvard Kempner Institute - W&B Sweeps Guide](https://handbook.eng.kempnerinstitute.harvard.edu/s5_ai_scaling_and_engineering/experiment_management/wandb_sweeps.html)
현재 단락 (1/516)
ML 프로젝트에서 가장 흔히 발생하는 문제 중 하나는 "어떤 하이퍼파라미터 조합으로 학습한 모델이 가장 좋았는지 기억나지 않는다"는 것이다. 학습률, 배치 사이즈, 에포크 수, 모...