How to use wandb.init in Python
Direct answer
Use
wandb.init() in Python to initialize a new run for experiment tracking, specifying parameters like project and entity to organize your runs.Setup
Install
pip install wandb Env vars
WANDB_API_KEY Imports
import wandb Examples
inwandb.init(project='my-project', entity='my-team')
outInitialized a new W&B run under project 'my-project' and entity 'my-team'.
inwandb.init(project='image-classification', config={'lr': 0.001, 'epochs': 10})
outStarted a run logging hyperparameters lr=0.001 and epochs=10.
inwandb.init(name='experiment-42', reinit=True)
outCreated a new run named 'experiment-42', allowing multiple runs in the same script.
Integration steps
- Install the wandb Python package via pip.
- Set your W&B API key in the environment variable WANDB_API_KEY.
- Import wandb in your Python script.
- Call wandb.init() with parameters like project, entity, and config to start a run.
- Log metrics and artifacts during training using wandb.log() and wandb.save().
- Finish the run automatically or call wandb.finish() to close it.
Full code
import os
import wandb
# Ensure your WANDB_API_KEY is set in environment variables
# os.environ['WANDB_API_KEY'] = 'your_api_key_here' # Do NOT hardcode in production
# Initialize a new W&B run
run = wandb.init(
project='my-sample-project',
entity='my-team',
config={
'learning_rate': 0.001,
'epochs': 5,
'batch_size': 32
},
name='experiment-001',
reinit=True
)
print(f"W&B run initialized with id: {run.id}")
# Example of logging metrics
for epoch in range(run.config.epochs):
loss = 0.1 * (run.config.epochs - epoch) # dummy loss
wandb.log({'epoch': epoch + 1, 'loss': loss})
# Finish the run explicitly (optional)
wandb.finish() output
W&B run initialized with id: 123abc456def # (followed by metrics logged to the W&B dashboard)
API trace
Request
{"project": "my-sample-project", "entity": "my-team", "config": {"learning_rate": 0.001, "epochs": 5, "batch_size": 32}, "name": "experiment-001", "reinit": true} Response
{"id": "123abc456def", "name": "experiment-001", "project": "my-sample-project", "entity": "my-team", "state": "running"} Extract
run.id or run.name for run identificationVariants
Streaming metrics logging ›
Use when you want to log metrics incrementally during training or evaluation.
import wandb
run = wandb.init(project='streaming-project')
for step in range(10):
metric = step * 2
wandb.log({'step': step, 'metric': metric})
wandb.finish() Async initialization with callback ›
Use when integrating W&B in asynchronous or multi-threaded environments.
import wandb
import threading
def on_run_start():
print('Run started asynchronously')
run = wandb.init(project='async-project', callbacks=[on_run_start])
wandb.finish() Initialize without project (default project) ›
Use when you want to log runs under your default project or when project is set in W&B settings.
import wandb
run = wandb.init(entity='my-team')
print(f"Run ID: {run.id}")
wandb.finish() Performance
Latency~100-300ms for wandb.init network handshake
CostFree for basic usage; check https://wandb.ai/pricing for enterprise features
Rate limitsNo strict rate limits for <code>wandb.init()</code>, but excessive logging may be throttled
- Log only essential metrics to reduce bandwidth and storage.
- Use <code>reinit=True</code> to manage multiple runs in one script efficiently.
- Batch metric logs with <code>wandb.log()</code> to minimize API calls.
| Approach | Latency | Cost/call | Best for |
|---|---|---|---|
Basic wandb.init() | ~100-300ms | Free | Standard experiment tracking |
| Streaming metrics logging | Low per log (~10-50ms) | Free | Real-time metric updates |
| Async initialization | ~100-300ms + threading overhead | Free | Concurrent or async workflows |
Quick tip
Always set your <code>WANDB_API_KEY</code> as an environment variable before calling <code>wandb.init()</code> to authenticate your runs securely.
Common mistake
Beginners often forget to set the <code>WANDB_API_KEY</code> environment variable, causing authentication failures when calling <code>wandb.init()</code>.