{"id":"weights-and-biases","name":"weights-and-biases","summary":"自動ログでML実験を追跡し、リアルタイムでトレーニングを可視化し、スイープでハイパーパラメータを最適化し、W&Bでモデルレジストリを管理する(MLOpsプラットフォームの共同作業)を行えます","body":"# Weights & Biases: ML Experiment Tracking & MLOps\n\n## When to Use This Skill\n\nUse Weights & Biases (W&B) when you need to:\n- **Track ML experiments** with automatic metric logging\n- **Visualize training** in real-time dashboards\n- **Compare runs** across hyperparameters and configurations\n- **Optimize hyperparameters** with automated sweeps\n- **Manage model registry** with versioning and lineage\n- **Collaborate on ML projects** with team workspaces\n- **Track artifacts** (datasets, models, code) with lineage\n\n**Users**: 200,000+ ML practitioners | **GitHub Stars**: 10.5k+ | **Integrations**: 100+\n\n## Installation\n\n```bash\n# Install W&B\npip install wandb\n\n# Login (creates API key)\nwandb login\n\n# Or set API key programmatically\nexport WANDB_API_KEY=your_api_key_here\n```\n\n## Quick Start\n\n### Basic Experiment Tracking\n\n```python\nimport wandb\n\n# Initialize a run\nrun = wandb.init(\n    project=\"my-project\",\n    config={\n        \"learning_rate\": 0.001,\n        \"epochs\": 10,\n        \"batch_size\": 32,\n        \"architecture\": \"ResNet50\"\n    }\n)\n\n# Training loop\nfor epoch in range(run.config.epochs):\n    # Your training code\n    train_loss = train_epoch()\n    val_loss = validate()\n\n    # Log metrics\n    wandb.log({\n        \"epoch\": epoch,\n        \"train/loss\": train_loss,\n        \"val/loss\": val_loss,\n        \"train/accuracy\": train_acc,\n        \"val/accuracy\": val_acc\n    })\n\n# Finish the run\nwandb.finish()\n```\n\n### With PyTorch\n\n```python\nimport torch\nimport wandb\n\n# Initialize\nwandb.init(project=\"pytorch-demo\", config={\n    \"lr\": 0.001,\n    \"epochs\": 10\n})\n\n# Access config\nconfig = wandb.config\n\n# Training loop\nfor epoch in range(config.epochs):\n    for batch_idx, (data, target) in enumerate(train_loader):\n        # Forward pass\n        output = model(data)\n        loss = criterion(output, target)\n\n        # Backward pass\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n        # Log every 100 batches\n        if batch_idx % 100 == 0:\n            wandb.log({\n                \"loss\": loss.item(),\n                \"epoch\": epoch,\n                \"batch\": batch_idx\n            })\n\n# Save model\ntorch.save(model.state_dict(), \"model.pth\")\nwandb.save(\"model.pth\")  # Upload to W&B\n\nwandb.finish()\n```\n\n## Core Concepts\n\n### 1. Projects and Runs\n\n**Project**: Collection of related experiments\n**Run**: Single execution of your training script\n\n```python\n# Create/use project\nrun = wandb.init(\n    project=\"image-classification\",\n    name=\"resnet50-experiment-1\",  # Optional run name\n    tags=[\"baseline\", \"resnet\"],    # Organize with tags\n    notes=\"First baseline run\"      # Add notes\n)\n\n# Each run has unique ID\nprint(f\"Run ID: {run.id}\")\nprint(f\"Run URL: {run.url}\")\n```\n\n### 2. Configuration Tracking\n\nTrack hyperparameters automatically:\n\n```python\nconfig = {\n    # Model architecture\n    \"model\": \"ResNet50\",\n    \"pretrained\": True,\n\n    # Training params\n    \"learning_rate\": 0.001,\n    \"batch_size\": 32,\n    \"epochs\": 50,\n    \"optimizer\": \"Adam\",\n\n    # Data params\n    \"dataset\": \"ImageNet\",\n    \"augmentation\": \"standard\"\n}\n\nwandb.init(project=\"my-project\", config=config)\n\n# Access config during training\nlr = wandb.config.learning_rate\nbatch_size = wandb.config.batch_size\n```\n\n### 3. Metric Logging\n\n```python\n# Log scalars\nwandb.log({\"loss\": 0.5, \"accuracy\": 0.92})\n\n# Log multiple metrics\nwandb.log({\n    \"train/loss\": train_loss,\n    \"train/accuracy\": train_acc,\n    \"val/loss\": val_loss,\n    \"val/accuracy\": val_acc,\n    \"learning_rate\": current_lr,\n    \"epoch\": epoch\n})\n\n# Log with custom x-axis\nwandb.log({\"loss\": loss}, step=global_step)\n\n# Log media (images, audio, video)\nwandb.log({\"examples\": [wandb.Image(img) for img in images]})\n\n# Log histograms\nwandb.log({\"gradients\": wandb.Histogram(gradients)})\n\n# Log tables\ntable = wandb.Table(columns=[\"id\", \"prediction\", \"ground_truth\"])\nwandb.log({\"predictions\": table})\n```\n\n### 4. Model Checkpointing\n\n```python\nimport torch\nimport wandb\n\n# Save model checkpoint\ncheckpoint = {\n    'epoch': epoch,\n    'model_state_dict': model.state_dict(),\n    'optimizer_state_dict': optimizer.state_dict(),\n    'loss': loss,\n}\n\ntorch.save(checkpoint, 'checkpoint.pth')\n\n# Upload to W&B\nwandb.save('checkpoint.pth')\n\n# Or use Artifacts (recommended)\nartifact = wandb.Artifact('model', type='model')\nartifact.add_file('checkpoint.pth')\nwandb.log_artifact(artifact)\n```\n\n## Hyperparameter Sweeps\n\nAutomatically search for optimal hyperparameters.\n\n### Define Sweep Configuration\n\n```python\nsweep_config = {\n    'method': 'bayes',  # or 'grid', 'random'\n    'metric': {\n        'name': 'val/accuracy',\n        'goal': 'maximize'\n    },\n    'parameters': {\n        'learning_rate': {\n            'distribution': 'log_uniform',\n            'min': 1e-5,\n            'max': 1e-1\n        },\n        'batch_size': {\n            'values': [16, 32, 64, 128]\n        },\n        'optimizer': {\n            'values': ['adam', 'sgd', 'rmsprop']\n        },\n        'dropout': {\n            'distribution': 'uniform',\n            'min': 0.1,\n            'max': 0.5\n        }\n    }\n}\n\n# Initialize sweep\nsweep_id = wandb.sweep(sweep_config, project=\"my-project\")\n```\n\n### Define Training Function\n\n```python\ndef train():\n    # Initialize run\n    run = wandb.init()\n\n    # Access sweep parameters\n    lr = wandb.config.learning_rate\n    batch_size = wandb.config.batch_size\n    optimizer_name = wandb.config.optimizer\n\n    # Build model with sweep config\n    model = build_model(wandb.config)\n    optimizer = get_optimizer(optimizer_name, lr)\n\n    # Training loop\n    for epoch in range(NUM_EPOCHS):\n        train_loss = train_epoch(model, optimizer, batch_size)\n        val_acc = validate(model)\n\n        # Log metrics\n        wandb.log({\n            \"train/loss\": train_loss,\n            \"val/accuracy\": val_acc\n        })\n\n# Run sweep\nwandb.agent(sweep_id, function=train, count=50)  # Run 50 trials\n```\n\n### Sweep Strategies\n\n```python\n# Grid search - exhaustive\nsweep_config = {\n    'method': 'grid',\n    'parameters': {\n        'lr': {'values': [0.001, 0.01, 0.1]},\n        'batch_size': {'values': [16, 32, 64]}\n    }\n}\n\n# Random search\nsweep_config = {\n    'method': 'random',\n    'parameters': {\n        'lr': {'distribution': 'uniform', 'min': 0.0001, 'max': 0.1},\n        'dropout': {'distribution': 'uniform', 'min': 0.1, 'max': 0.5}\n    }\n}\n\n# Bayesian optimization (recommended)\nsweep_config = {\n    'method': 'bayes',\n    'metric': {'name': 'val/loss', 'goal': 'minimize'},\n    'parameters': {\n        'lr': {'distribution': 'log_uniform', 'min': 1e-5, 'max': 1e-1}\n    }\n}\n```\n\n## Artifacts\n\nTrack datasets, models, and other files with lineage.\n\n### Log Artifacts\n\n```python\n# Create artifact\nartifact = wandb.Artifact(\n    name='training-dataset',\n    type='dataset',\n    description='ImageNet training split',\n    metadata={'size': '1.2M images', 'split': 'train'}\n)\n\n# Add files\nartifact.add_file('data/train.csv')\nartifact.add_dir('data/images/')\n\n# Log artifact\nwandb.log_artifact(artifact)\n```\n\n### Use Artifacts\n\n```python\n# Download and use artifact\nrun = wandb.init(project=\"my-project\")\n\n# Download artifact\nartifact = run.use_artifact('training-dataset:latest')\nartifact_dir = artifact.download()\n\n# Use the data\ndata = load_data(f\"{artifact_dir}/train.csv\")\n```\n\n### Model Registry\n\n```python\n# Log model as artifact\nmodel_artifact = wandb.Artifact(\n    name='resnet50-model',\n    type='model',\n    metadata={'architecture': 'ResNet50', 'accuracy': 0.95}\n)\n\nmodel_artifact.add_file('model.pth')\nwandb.log_artifact(model_artifact, aliases=['best', 'production'])\n\n# Link to model registry\nrun.link_artifact(model_artifact, 'model-registry/production-models')\n```\n\n## Integration Examples\n\n### HuggingFace Transformers\n\n```python\nfrom transformers import Trainer, TrainingArguments\nimport wandb\n\n# Initialize W&B\nwandb.init(project=\"hf-transformers\")\n\n# Training arguments with W&B\ntraining_args = TrainingArguments(\n    output_dir=\"./results\",\n    report_to=\"wandb\",  # Enable W&B logging\n    run_name=\"bert-finetuning\",\n    logging_steps=100,\n    save_steps=500\n)\n\n# Trainer automatically logs to W&B\ntrainer = Trainer(\n    model=model,\n    args=training_args,\n    train_dataset=train_dataset,\n    eval_dataset=eval_dataset\n)\n\ntrainer.train()\n```\n\n### PyTorch Lightning\n\n```python\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.loggers import WandbLogger\nimport wandb\n\n# Create W&B logger\nwandb_logger = WandbLogger(\n    project=\"lightning-demo\",\n    log_model=True  # Log model checkpoints\n)\n\n# Use with Trainer\ntrainer = Trainer(\n    logger=wandb_logger,\n    max_epochs=10\n)\n\ntrainer.fit(model, datamodule=dm)\n```\n\n### Keras/TensorFlow\n\n```python\nimport wandb\nfrom wandb.keras import WandbCallback\n\n# Initialize\nwandb.init(project=\"keras-demo\")\n\n# Add callback\nmodel.fit(\n    x_train, y_train,\n    validation_data=(x_val, y_val),\n    epochs=10,\n    callbacks=[WandbCallback()]  # Auto-logs metrics\n)\n```\n\n## Visualization & Analysis\n\n### Custom Charts\n\n```python\n# Log custom visualizations\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots()\nax.plot(x, y)\nwandb.log({\"custom_plot\": wandb.Image(fig)})\n\n# Log confusion matrix\nwandb.log({\"conf_mat\": wandb.plot.confusion_matrix(\n    probs=None,\n    y_true=ground_truth,\n    preds=predictions,\n    class_names=class_names\n)})\n```\n\n### Reports\n\nCreate shareable reports in W&B UI:\n- Combine runs, charts, and text\n- Markdown support\n- Embeddable visualizations\n- Team collaboration\n\n## Best Practices\n\n### 1. Organize with Tags and Groups\n\n```python\nwandb.init(\n    project=\"my-project\",\n    tags=[\"baseline\", \"resnet50\", \"imagenet\"],\n    group=\"resnet-experiments\",  # Group related runs\n    job_type=\"train\"             # Type of job\n)\n```\n\n### 2. Log Everything Relevant\n\n```python\n# Log system metrics\nwandb.log({\n    \"gpu/util\": gpu_utilization,\n    \"gpu/memory\": gpu_memory_used,\n    \"cpu/util\": cpu_utilization\n})\n\n# Log code version\nwandb.log({\"git_commit\": git_commit_hash})\n\n# Log data splits\nwandb.log({\n    \"data/train_size\": len(train_dataset),\n    \"data/val_size\": len(val_dataset)\n})\n```\n\n### 3. Use Descriptive Names\n\n```python\n# ✅ Good: Descriptive run names\nwandb.init(\n    project=\"nlp-classification\",\n    name=\"bert-base-lr0.001-bs32-epoch10\"\n)\n\n# ❌ Bad: Generic names\nwandb.init(project=\"nlp\", name=\"run1\")\n```\n\n### 4. Save Important Artifacts\n\n```python\n# Save final model\nartifact = wandb.Artifact('final-model', type='model')\nartifact.add_file('model.pth')\nwandb.log_artifact(artifact)\n\n# Save predictions for analysis\npredictions_table = wandb.Table(\n    columns=[\"id\", \"input\", \"prediction\", \"ground_truth\"],\n    data=predictions_data\n)\nwandb.log({\"predictions\": predictions_table})\n```\n\n### 5. Use Offline Mode for Unstable Connections\n\n```python\nimport os\n\n# Enable offline mode\nos.environ[\"WANDB_MODE\"] = \"offline\"\n\nwandb.init(project=\"my-project\")\n# ... your code ...\n\n# Sync later\n# wandb sync <run_directory>\n```\n\n## Team Collaboration\n\n### Share Runs\n\n```python\n# Runs are automatically shareable via URL\nrun = wandb.init(project=\"team-project\")\nprint(f\"Share this URL: {run.url}\")\n```\n\n### Team Projects\n\n- Create team account at wandb.ai\n- Add team members\n- Set project visibility (private/public)\n- Use team-level artifacts and model registry\n\n## Pricing\n\n- **Free**: Unlimited public projects, 100GB storage\n- **Academic**: Free for students/researchers\n- **Teams**: $50/seat/month, private projects, unlimited storage\n- **Enterprise**: Custom pricing, on-prem options\n\n## Resources\n\n- **Documentation**: https://docs.wandb.ai\n- **GitHub**: https://github.com/wandb/wandb (10.5k+ stars)\n- **Examples**: https://github.com/wandb/examples\n- **Community**: https://wandb.ai/community\n- **Discord**: https://wandb.me/discord\n\n## See Also\n\n- `references/sweeps.md` - Comprehensive hyperparameter optimization guide\n- `references/artifacts.md` - Data and model versioning patterns\n- `references/integrations.md` - Framework-specific examples","author":"@Orchestra-Research","ownerProfile":null,"authorContacts":null,"sourceUrl":"https://github.com/Orchestra-Research/AI-Research-SKILLs/tree/main/13-mlops/weights-and-biases","license":"MIT","category":"coding","lang":"en","tokens":3158,"stars":0,"calls30d":2,"claimed":false,"visibility":"public","origin":"crawler","version":"0.1.0","createdAt":"2026-08-22","updatedAt":"2026-08-22","files":[{"path":"references/artifacts.md","size":13425,"sha256":"3e4c2ebe70b310e74fdadb5e08af9822eba5b585ef6ad1e66012016b8fc6d461"},{"path":"references/integrations.md","size":16219,"sha256":"b11f806e19002e589d959d6f56d9d03986520923ee89ee4328822a6fff190251"},{"path":"references/sweeps.md","size":17675,"sha256":"c59012acf49ec73b0bbf4b2ff7713d0611d1372ba92a9e21337ae76d153a1f0d"}],"requires":{"mcp":[],"tools":[]},"safety":{"flags":[{"code":"code.eval","kind":"dangerous-code","where":"references/artifacts.md:256","excerpt":"eval(","message":"evaluates code at runtime","severity":"warn"},{"code":"code.eval","kind":"dangerous-code","where":"references/integrations.md:593","excerpt":"eval(","message":"evaluates code at runtime","severity":"warn"},{"code":"code.eval","kind":"dangerous-code","where":"references/sweeps.md:492","excerpt":"eval(","message":"evaluates code at runtime","severity":"warn"}],"scannedAt":"2026-08-22","hasScripts":false,"networkEndpoints":["docs.wandb.ai","wandb.ai","wandb.me"]}}