mcpField
W
weights-and-biases

weights-and-biases

github.com/kalarislabs数据与数据库7745 次安装4 天前更新
代码仓库

关于 weights-and-biases

面向机器学习项目的 Weights & Biases 技能,指导实验跟踪、训练可视化、超参数搜索和模型资产管理。适用于需要比较实验并协作管理运行与数据的团队。

主要功能

  1. 01记录实验配置与指标
  2. 02实时查看训练可视化
  3. 03比较不同实验运行
  4. 04自动化超参数搜索
  5. 05追踪数据集与模型资产

适用场景

  1. 01比较不同超参数配置的训练结果
  2. 02监控训练指标并生成图表
  3. 03管理模型与数据集版本及来源

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill weights-and-biases

安装后在 Claude Code 中输入/weights-and-biases确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
artifacts.md
hyperparameter-sweeps.md
integration-examples.md
integrations.md
sweeps.md

详细介绍

Weights & Biases:机器学习实验跟踪与 MLOps

何时使用此技能

在以下情况下使用 Weights & Biases(W&B):

  • 跟踪机器学习实验,并自动记录指标
  • 实时可视化训练过程
  • 跨超参数和配置比较运行
  • 通过自动化扫描优化超参数
  • 管理模型注册表,包含版本控制和沿袭信息
  • 通过团队工作区协作开展机器学习项目
  • 跟踪资源(数据集、模型、代码)及其沿袭信息

安装

# Install W&B
pip install wandb

# Login (creates API key)
wandb login

# Or set API key programmatically
export WANDB_API_KEY=your_api_key_here

快速入门

基本实验跟踪
import wandb

# Initialize a run
run = wandb.init(
    project="my-project",
    config={
        "learning_rate": 0.001,
        "epochs": 10,
        "batch_size": 32,
        "architecture": "ResNet50"
    }
)

# Training loop
for epoch in range(run.config.epochs):
    # Your training code
    train_loss = train_epoch()
    val_loss = validate()

    # Log metrics
    wandb.log({
        "epoch": epoch,
        "train/loss": train_loss,
        "val/loss": val_loss,
        "train/accuracy": train_acc,
        "val/accuracy": val_acc
    })

# Finish the run
wandb.finish()
使用 PyTorch
import torch
import wandb

# Initialize
wandb.init(project="pytorch-demo", config={
    "lr": 0.001,
    "epochs": 10
})

# Access config
config = wandb.config

# Training loop
for epoch in range(config.epochs):
    for batch_idx, (data, target) in enumerate(train_loader):
        # Forward pass
        output = model(data)
        loss = criterion(output, target)

        # Backward pass
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        # Log every 100 batches
        if batch_idx % 100 == 0:
            wandb.log({
                "loss": loss.item(),
                "epoch": epoch,
                "batch": batch_idx
            })

# Save model
torch.save(model.state_dict(), "model.pth")
wandb.save("model.pth")  # Upload to W&B

wandb.finish()

核心概念

1. 项目和运行

项目:相关实验的集合 运行:训练脚本的一次执行

# Create/use project
run = wandb.init(
    project="image-classification",
    name="resnet50-experiment-1",  # Optional run name
    tags=["baseline", "resnet"],    # Organize with tags
    notes="First baseline run"      # Add notes
)

# Each run has unique ID
print(f"Run ID: {run.id}")
print(f"Run URL: {run.url}")
2. 配置跟踪

自动跟踪超参数:

config = {
    # Model architecture
    "model": "ResNet50",
    "pretrained": True,

    # Training params
    "learning_rate": 0.001,
    "batch_size": 32,
    "epochs": 50,
    "optimizer": "Adam",

    # Data params
    "dataset": "ImageNet",
    "augmentation": "standard"
}

wandb.init(project="my-project", config=config)

# Access config during training
lr = wandb.config.learning_rate
batch_size = wandb.config.batch_size
3. 指标记录
# Log scalars
wandb.log({"loss": 0.5, "accuracy": 0.92})

# Log multiple metrics
wandb.log({
    "train/loss": train_loss,
    "train/accuracy": train_acc,
    "val/loss": val_loss,
    "val/accuracy": val_acc,
    "learning_rate": current_lr,
    "epoch": epoch
})

# Log with custom x-axis
wandb.log({"loss": loss}, step=global_step)

# Log media (images, audio, video)
wandb.log({"examples": [wandb.Image(img) for img in images]})

# Log histograms
wandb.log({"gradients": wandb.Histogram(gradients)})

# Log tables
table = wandb.Table(columns=["id", "prediction", "ground_truth"])
wandb.log({"predictions": table})
4. 模型检查点
import torch
import wandb

# Save model checkpoint
checkpoint = {
    'epoch': epoch,
    'model_state_dict': model.state_dict(),
    'optimizer_state_dict': optimizer.state_dict(),
    'loss': loss,
}

torch.save(checkpoint, 'checkpoint.pth')

# Upload to W&B
wandb.save('checkpoint.pth')

# Or use Artifacts (recommended)
artifact = wandb.Artifact('model', type='model')
artifact.add_file('checkpoint.pth')
wandb.log_artifact(artifact)

超参数扫描

详细信息、代码示例和参数表:references/hyperparameter-sweeps.md。在适用此步骤时阅读。

资源

跟踪数据集、模型和其他文件及其沿袭信息。

记录资源
# Create artifact
artifact = wandb.Artifact(
    name='training-dataset',
    type='dataset',
    description='ImageNet training split',
    metadata={'size': '1.2M images', 'split': 'train'}
)

# Add files
artifact.add_file('data/train.csv')
artifact.add_dir('data/images/')

# Log artifact
wandb.log_artifact(artifact)
使用资源
# Download and use artifact
run = wandb.init(project="my-project")

# Download artifact
artifact = run.use_artifact('training-dataset:latest')
artifact_dir = artifact.download()

# Use the data
data = load_data(f"{artifact_dir}/train.csv")
模型注册表
# Log model as artifact
model_artifact = wandb.Artifact(
    name='resnet50-model',
    type='model',
    metadata={'architecture': 'ResNet50', 'accuracy': 0.95}
)

model_artifact.add_file('model.pth')
wandb.log_artifact(model_artifact, aliases=['best', 'production'])

# Link to model registry
run.link_artifact(model_artifact, 'model-registry/production-models')

集成示例

详细信息、代码示例和参数表:references/integration-examples.md。在适用此步骤时阅读。

可视化与分析

自定义图表
# Log custom visualizations
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(x, y)
wandb.log({"custom_plot": wandb.Image(fig)})

# Log confusion matrix
wandb.log({"conf_mat": wandb.plot.confusion_matrix(
    probs=None,
    y_true=ground_truth,
    preds=predictions,
    class_names=class_names
)})
报告

在 W&B UI 中创建可分享的报告:

  • 组合运行、图表和文本
  • 支持 Markdown
  • 可嵌入的可视化内容
  • 团队协作

最佳实践

1. 使用标签和分组进行整理
wandb.init(
    project="my-project",
    tags=["baseline", "resnet50", "imagenet"],
    group="resnet-experiments",  # Group related runs
    job_type="train"             # Type of job
)
2. 记录所有相关信息
# Log system metrics
wandb.log({
    "gpu/util": gpu_utilization,
    "gpu/memory": gpu_memory_used,
    "cpu/util": cpu_utilization
})

# Log code version
wandb.log({"git_commit": git_commit_hash})

# Log data splits
wandb.log({
    "data/train_size": len(train_dataset),
    "data/val_size": len(val_dataset)
})
3. 使用描述性名称
# ✅ Good: Descriptive run names
wandb.init(
    project="nlp-classification",
    name="bert-base-lr0.001-bs32-epoch10"
)

# ❌ Bad: Generic names
wandb.init(project="nlp", name="run1")
4. 保存重要资源
# Save final model
artifact = wandb.Artifact('final-model', type='model')
artifact.add_file('model.pth')
wandb.log_artifact(artifact)

# Save predictions for analysis
predictions_table = wandb.Table(
    columns=["id", "input", "prediction", "ground_truth"],
    data=predictions_data
)
wandb.log({"predictions": predictions_table})
5. 在连接不稳定时使用离线模式
import os

# Enable offline mode
os.environ["WANDB_MODE"] = "offline"

wandb.init(project="my-project")
# ... your code ...

# Sync later
# wandb sync <run_directory>

团队协作

分享运行
# Runs are automatically shareable via URL
run = wandb.init(project="team-project")
print(f"Share this URL: {run.url}")
团队项目
  • 在 wandb.ai 创建团队账户
  • 添加团队成员
  • 设置项目可见性(私有/公开)
  • 使用团队级资源和模型注册表

定价

  • 免费:无限量公开项目,100GB 存储空间
  • 学术:面向学生/研究人员免费
  • 团队:每席位每月 $50,私有项目,无限量存储空间
  • 企业:定制价格,提供本地部署选项

资源

另请参阅

  • references/sweeps.md - 全面的超参数优化指南
  • references/artifacts.md - 数据和模型版本控制模式
  • references/integrations.md - 特定框架的示例

Agent 操作流程

  1. 检查环境。 确认硬件、框架和服务版本、模型格式及预期负载。
  2. 明确输入。 根据数据或用户确认格式、标识符和参数。凡是会改变结果的值,不要猜测,应先询问。
  3. 先运行小规模版本。 扩大规模前,先提供或记录单个请求,或端到端运行一次。
  4. 按照上述说明和参考资料执行完整任务。
  5. 验证结果。 对照参考值测量延迟、吞吐量和输出正确性;检查资源使用情况和成本。
  6. 汇报。 说明运行了什么(版本、命令、参数)、检查了什么,以及仍有哪些不确定之处。
如果发生以下情况请采取以下措施
服务无法启动或发生 OOM检查模型大小与内存是否匹配,以及量化和并行设置。
这些说明中的函数、标志或端点在已安装的版本中不存在查看该版本自带的文档(help()、--help、官方文档),进行调整并告知用户。切勿臆造 API。
必需的输入、标识符或参数不明确询问用户,或在运行前明确说明所采用的假设。

诚信规则

  • 切勿伪造结果、参数、标识符、引文或统计数据。如果无法运行或验证某项内容,请明确说明。
  • 不要公开暴露服务或凭证;配置前确认云服务成本。
  • 此处与版本相关的细节可能已过时:请根据已安装版本的官方文档进行确认。
  • 对于涉及费用、占用共享 GPU 或云配额、处理个人或患者数据,或无法撤销的操作,请先征求同意。

评论

支持 Markdown