run-ab-test-models
정보
이 기술은 트래픽 분할과 통계 분석을 통해 프로덕션 환경의 ML 모델 A/B 테스트를 가능하게 합니다. 카나리 배포와 성능 측정을 지원하여 데이터 기반의 롤아웃 결정을 내릴 수 있습니다. 새로운 모델 버전 검증, 알고리즘 비교, 점진적 롤아웃 요구사항 충족에 활용하세요.
빠른 설치
Claude Code
추천npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/run-ab-test-modelsClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Run A/B Test for Models
See Extended Examples for complete configuration files and templates.
Execute controlled experiments comparing model versions using traffic splitting and statistical analysis.
Cuándo Usar
- Deploying new model version and want to validate improvement before full rollout
- Comparing multiple candidate models trained with different algorithms or features
- Testing impact of hyperparameter changes on business metrics
- Need to measure model performance in production without risking full traffic
- Regulatory requirements for gradual rollout (e.g., medical ML systems)
- Evaluating cost-performance tradeoffs between model sizes
Entradas
- Requerido: Champion model (current production version)
- Requerido: Challenger model(s) (new version to test)
- Requerido: Traffic allocation percentage (e.g., 5% to challenger)
- Requerido: Success metrics (business and ML metrics)
- Requerido: Minimum sample size or test duration
- Opcional: Guardrail metrics (latency, error rate thresholds)
- Opcional: User segments for stratified testing
Procedimiento
Paso 1: Design Experiment
Define test parameters, success criteria, and statistical requirements.
# ab_test/experiment_config.py
from dataclasses import dataclass
from typing import List, Dict
import numpy as np
from scipy.stats import norm
@dataclass
# ... (see EXAMPLES.md for complete implementation)
Esperado: Experiment configuration with statistically sound sample size calculation, typically 5-10k samples per variant for 5-10% MDE.
En caso de fallo: If required sample size too large, increase traffic allocation, extend test duration, or accept larger MDE; verify baseline metric estimate is accurate; consider sequential testing for continuous monitoring.
Paso 2: Implement Traffic Splitting
Set up routing logic to randomly assign requests to models.
# ab_test/traffic_router.py
import hashlib
import random
from typing import Dict, Optional
from dataclasses import dataclass
import logging
logger = logging.getLogger(__name__)
# ... (see EXAMPLES.md for complete implementation)
Esperado: Consistent user-to-variant assignment, accurate traffic split matching configured percentages, all assignments logged for analysis.
En caso de fallo: Verify hash function produces uniform distribution (test with 10k user IDs), check that user_id is stable across requests (not session_id), ensure logs capture all prediction events, validate traffic split in first 1000 requests.
Paso 3: Implement Shadow Deployment (Optional)
Run challenger model in parallel without affecting users (shadow mode).
# ab_test/shadow_deployment.py
import asyncio
from typing import Dict, Any
import logging
from concurrent.futures import ThreadPoolExecutor
import time
logger = logging.getLogger(__name__)
# ... (see EXAMPLES.md for complete implementation)
Esperado: Champion predictions served with normal latency, challenger predictions logged asynchronously without blocking, prediction differences captured for analysis.
En caso de fallo: Set challenger timeout < champion SLA to avoid blocking, handle challenger errors gracefully without affecting champion, monitor memory usage (two models loaded), consider sampling (log only 10% of shadow predictions).
Paso 4: Collect and Analyze Metrics
Gather experiment data and perform statistical tests.
# ab_test/analysis.py
import pandas as pd
import numpy as np
from scipy import stats
from typing import Dict, Tuple
import logging
logger = logging.getLogger(__name__)
# ... (see EXAMPLES.md for complete implementation)
Esperado: Statistical test results with p-values, confidence intervals, and clear decision (rollout/keep/inconclusive), typically after 7-14 days or reaching sample size.
En caso de fallo: Verify ground truth labels are available (may need delayed analysis), check for sample ratio mismatch (SRM) indicating assignment bugs, ensure sufficient sample size reached, look for novelty/primacy effects in early data, consider sequential testing if fixed-horizon test is too slow.
Paso 5: Monitor Guardrail Metrics
Continuously check that challenger doesn't violate safety thresholds.
# ab_test/guardrails.py
import pandas as pd
import logging
from typing import Dict, List
logger = logging.getLogger(__name__)
# ... (see EXAMPLES.md for complete implementation)
Esperado: Guardrail violations detected within 5-15 minutes, automated experiment stop if critical thresholds breached (latency, errors), alerts sent to team.
En caso de fallo: Verify guardrail thresholds are realistic (not too tight), ensure monitoring loop is running continuously, check that stop_experiment() function actually updates routing, test alert delivery channels.
Paso 6: Make Rollout Decision
Based on experiment results, decide whether to rollout challenger.
# ab_test/rollout_decision.py
import logging
from typing import Dict
from dataclasses import dataclass
logger = logging.getLogger(__name__)
# ... (see EXAMPLES.md for complete implementation)
Esperado: Clear decision (full/gradual rollout, keep champion, or extend test) with justification and action items.
En caso de fallo: If decision unclear, perform subgroup analysis (by user segment, time of day, device type), check for interaction effects, review business context (e.g., is 2% lift worth engineering cost?), consult with stakeholders.
Validación
- Traffic split matches configured percentages (within 1%)
- Same user always assigned to same variant (consistency check)
- Sample size calculation produces reasonable numbers (5-50k per variant)
- Statistical tests produce p-values consistent with manual calculation
- Guardrail violations trigger alerts within 5 minutes
- Shadow deployment shows <5% prediction divergence between models
- Experiment reports include confidence intervals
- Rollout decision documented with justification
Errores Comunes
- Sample ratio mismatch (SRM): If observed traffic split differs from configured (e.g., 95/5 becomes 92/8), indicates assignment bug; check hash function uniformity
- Peeking: Checking results before reaching sample size inflates Type I error; use sequential testing or wait for pre-determined end date
- Novelty effect: Users respond differently to new model initially; run for 2+ weeks to see steady-state behavior
- Carryover effects: Previous variant exposure affects current behavior; use new users or sufficient washout period
- Multiple testing: Testing many metrics increases false positive risk; correct with Bonferroni or focus on single primary metric
- Insufficient power: Small traffic allocation may require months to detect realistic effects; balance statistical power with risk tolerance
- Ignoring segments: Aggregate lift may hide negative impact on important user segments; perform subgroup analysis
- Attribution errors: Ensure outcome metrics correctly attributed to model predictions (not other system changes)
Habilidades Relacionadas
deploy-ml-model-serving- Model deployment infrastructure and versioningmonitor-model-drift- Ongoing performance monitoring post-rollout
GitHub 저장소
연관 스킬
evaluating-llms-harness
테스팅이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.
cloudflare-cron-triggers
테스팅이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.
webapp-testing
테스팅이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.
finishing-a-development-branch
테스팅이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.
