You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Description
-----------
Started off with a simple code check, evolved to rewriting most of this
page.
Related issues
-----------
- Fixes https://wandb.atlassian.net/browse/DOCS-1695
<!-- preview-links-comment -->
📄 **[View preview links for changed
pages](#1518 (comment)
---------
Co-authored-by: Matt Linville <matt.linville@wandb.com>
@@ -8,19 +8,27 @@ title: Add W&B (wandb) to your code
8
8
weight: 2
9
9
---
10
10
11
-
There are numerous ways to add the W&B Python SDK to your script or notebook. This section provides a "best practice" example that shows how to integrate the W&B Python SDK into your own code.
11
+
This guide provides recommendations on how to integrate W&B into your Python training script or notebook.
12
12
13
-
###Original training script
13
+
## Original training script
14
14
15
-
Suppose you have the following code in a Python script. We define a function called `main`that mimics a typical training loop. For each epoch, the accuracy and loss is computed on the training and validation data sets. The values are randomly generated for the purpose of this example.
15
+
Suppose you have a Python scriptthat trains a model (see below). Your goal is to find the hyperparameters that maxmimizes the validation accuracy(`val_acc`).
16
16
17
-
We defined a dictionary called `config` where we store hyperparameters values. At the end of the cell, we call the `main` function to execute the mock training code.
17
+
In your Python script, you define two functions: `train_one_epoch` and `evaluate_one_epoch`. The `train_one_epoch` function simulates training for one epoch and returns the training accuracy and loss. The `evaluate_one_epoch` function simulates evaluating the model on the validation data set and returns the validation accuracy and loss.
18
+
19
+
You define a configuration dictionary (`config`) that contains hyperparameter values such as the learning rate (`lr`), batch size (`batch_size`), and number of epochs (`epochs`). The values in the configuration dictionary control the training process.
20
+
21
+
Next you define a function called `main` that mimics a typical training loop. For each epoch, the accuracy and loss is computed on the training and validation data sets.
22
+
23
+
{{< alert >}}
24
+
This code is a mock training script. It does not train a model, but simulates the training process by generating random accuracy and loss values. The purpose of this code is to demonstrate how to integrate W&B into your training script.
25
+
{{< /alert >}}
18
26
19
27
```python
20
28
import random
21
29
import numpy as np
22
30
23
-
deftrain_one_epoch(epoch, lr, bs):
31
+
deftrain_one_epoch(epoch, lr, batch_size):
24
32
acc =0.25+ ((epoch /30) + (random.random() /10))
25
33
loss =0.2+ (1- ((epoch -1) /10+ random.random() /5))
In the next section, you will add W&B to your Python script to track hyperparameters and metrics during training. You want to use W&B to find the best hyperparameters that maximize the validation accuracy (`val_acc`).
62
+
53
63
54
-
The following code examples demonstrate how to add the W&B Python SDK into your
55
-
code. If you start W&B Sweep jobs in the CLI, you will want to explore the CLI
56
-
tab. If you start W&B Sweep jobs within a Jupyter notebook or Python script,
57
-
explore the Python SDK tab.
64
+
## Training script with W&B Python SDK
58
65
59
-
{{< tabpane text=true >}} {{% tab header="Python script or notebook" %}} To
60
-
create a W&B Sweep, we added the following to the code example:
66
+
How you integrate W&B to your Python script or notebook depends on how you manage sweeps. You can start a sweep job within a Python notebook or script or from the command line.
61
67
62
-
1. Import the W&B Python SDK.
63
-
2. Create a dictionary object where the key-value pairs define the sweep configuration. In the proceeding example, the batch size (`batch_size`), epochs (`epochs`), and the learning rate (`lr`) hyperparameters are varied during each sweep. For more information, see [Define sweep configuration]({{< relref "/guides/models/sweeps/define-sweep-configuration/" >}}).
64
-
3. Pass the sweep configuration dictionary to [`wandb.sweep()`]({{< relref "/ref/python/sdk/functions/sweep.md" >}}). This initializes the sweep. This returns a sweep ID (`sweep_id`). For more information, see [Initialize sweeps]({{< relref "./initialize-sweeps.md" >}}).
65
-
4. Use the [`wandb.init()`]({{< relref "/ref/python/sdk/functions/init.md" >}}) API to generate a background process to sync and log data as a [W&B Run]({{< relref "/ref/python/sdk/classes/run.md" >}}).
66
-
5. (Optional) define values from `wandb.config` instead of defining hard coded values.
67
-
6. Log the metric you want to optimize with [`wandb.Run.log()`]({{< relref "/ref/python/sdk/classes/run.md/#method-runlog" >}}). You must log the metric defined in your configuration. Within the configuration dictionary (`sweep_configuration` in this example), you define the sweep to maximize the `val_acc` value.
68
-
7. Start the sweep with the [`wandb.agent`]({{< relref "/ref/python/sdk/functions/agent.md" >}}) API call. Provide the sweep ID and the name of the function the sweep will execute (`function=main`), and specify the maximum number of runs to try to four (`count=4`). For more informationp, see [Start sweep agents]({{< relref "./start-sweep-agents.md" >}}).
68
+
{{< tabpane text=true >}}
69
+
{{% tab header="Python script or notebook" %}}
69
70
71
+
Add the following to your Python script:
72
+
73
+
1. Create a dictionary object where the key-value pairs define a [sweep configuration]({{< relref "/guides/models/sweeps/define-sweep-configuration/" >}}). The sweep configuration defines the hyperparameters you want W&B to explore on your behalf along with the metric you want to optimize. Continuing from the previous example, the batch size (`batch_size`), epochs (`epochs`), and the learning rate (`lr`) are the hyperparameters to vary during each sweep. You want to maximize the accuracy of the validation score so you set `"goal": "maximize"` and the name of the variable you want to optimize for, in this case `val_acc` (`"name": "val_acc"`).
74
+
2. Pass the sweep configuration dictionary to [`wandb.sweep()`]({{< relref "/ref/python/sdk/functions/sweep.md" >}}). This initializes the sweep and returns a sweep ID (`sweep_id`). For more information, see [Initialize sweeps]({{< relref "./initialize-sweeps.md" >}}).
75
+
3. At the top of your script, import the W&B Python SDK (`wandb`).
76
+
4. Within your `main` function, use the [`wandb.init()`]({{< relref "/ref/python/sdk/functions/init.md" >}}) API to generate a background process to sync and log data as a [W&B Run]({{< relref "/ref/python/sdk/classes/run.md" >}}). Pass the project name as a parameter to the `wandb.init()` method. If you do not pass a project name, W&B uses the default project name.
77
+
5. Fetch the hyperparameter values from the `wandb.Run.config` object. This allows you to use the hyperparameter values defined in the sweep configuration dictionary instead of hard coded values.
78
+
6. Log the metric you are optimizing for to W&B using [`wandb.Run.log()`]({{< relref "/ref/python/sdk/classes/run.md/#method-runlog" >}}). You must log the metric defined in your configuration. For example, if you define the metric to optimize as `val_acc`, you must log `val_acc`. If you do not log the metric, W&B does not know what to optimize for. Within the configuration dictionary (`sweep_configuration` in this example), you define the sweep to maximize the `val_acc` value.
79
+
7. Start the sweep with [`wandb.agent()`]({{< relref "/ref/python/sdk/functions/agent.md" >}}). Provide the sweep ID and the name of the function the sweep will execute (`function=main`), and specify the maximum number of runs to try to four (`count=4`).
80
+
81
+
82
+
Putting this all together, your script might look similar to the following:
70
83
71
84
```python
72
-
import wandb
85
+
import wandb# Import the W&B Python SDK
73
86
import numpy as np
74
87
import random
88
+
import argparse
75
89
76
-
77
-
# Define training function that takes in hyperparameter
78
-
# values from `wandb.Run.config` and uses them to train a
79
-
# model and return the metrics
80
-
deftrain_one_epoch(epoch, lr, bs):
90
+
deftrain_one_epoch(epoch, lr, batch_size):
81
91
acc =0.25+ ((epoch /30) + (random.random() /10))
82
92
loss =0.2+ (1- ((epoch -1) /10+ random.random() /5))
83
93
return acc, loss
84
94
85
-
86
95
defevaluate_one_epoch(epoch):
87
96
acc =0.1+ ((epoch /20) + (random.random() /10))
88
97
loss =0.25+ (1- ((epoch -1) /10+ random.random() /6))
{{% alert %}} The preceding code snippet shows how to initialize a
144
-
[`wandb.init()`]({{< relref "/ref/python/sdk/functions/init.md" >}}) API within a `with`
145
-
context manager statement to generate a background process to sync and log data
146
-
as a [W&B Run]({{< relref "/ref/python/sdk/classes/run.md" >}}). This ensures the run is
147
-
properly terminated after uploading the logged values. An alternative approach
148
-
is to call `wandb.init()` and `wandb.Run.finish()` at the beginning and end of the
149
-
training script, respectively.
150
-
{{% /alert %}}
156
+
151
157
152
158
{{% /tab %}} {{% tab header="CLI" %}}
153
159
154
-
To create a W&B Sweep, we first create a YAML configuration file. The
155
-
configuration file contains the hyperparameters we want the sweep to explore. In
156
-
the proceeding example, the batch size (`batch_size`), epochs (`epochs`), and
160
+
Create a YAML configuration file with your sweep configuration. The
161
+
configuration file contains the hyperparameters you want the sweep to explore. In
162
+
the following example, the batch size (`batch_size`), epochs (`epochs`), and
157
163
the learning rate (`lr`) hyperparameters are varied during each sweep.
158
164
159
165
```yaml
@@ -179,13 +185,13 @@ For more information on how to create a W&B Sweep configuration, see [Define swe
179
185
You must provide the name of your Python script for the `program` key
180
186
in your YAML file.
181
187
182
-
Next, we add the following to the code example:
188
+
Next, add the following to the code example:
183
189
184
190
1. Import the W&B Python SDK (`wandb`) and PyYAML (`yaml`). PyYAML is used to read in our YAML configuration file.
185
191
2. Read in the configuration file.
186
-
3. Use the [`wandb.init()`]({{< relref "/ref/python/sdk/functions/init.md" >}}) API to generate a background process to sync and log data as a [W&B Run]({{< relref "/ref/python/sdk/classes/run.md" >}}). We pass the config object to the config parameter.
192
+
3. Use the [`wandb.init()`]({{< relref "/ref/python/sdk/functions/init.md" >}}) API to generate a background process to sync and log data as a [W&B Run]({{< relref "/ref/python/sdk/classes/run.md" >}}). Pass the config object to the config parameter.
187
193
4. Define hyperparameter values from `wandb.Run.config` instead of using hard coded values.
188
-
5. Log the metric we want to optimize with [`wandb.Run.log()`]({{< relref "/ref/python/sdk/classes/run.md/#method-runlog" >}}). You must log the metric defined in your configuration. Within the configuration dictionary (`sweep_configuration` in this example) we defined the sweep to maximize the `val_acc` value.
194
+
5. Log the metric you want to optimize with [`wandb.Run.log()`]({{< relref "/ref/python/sdk/classes/run.md/#method-runlog" >}}). You must log the metric defined in your configuration. Within the configuration dictionary (`sweep_configuration` in this example) you define the sweep to maximize the `val_acc` value.
Copy the sweep ID and replace `sweepID` in the proceeding code snippet to start
255
+
Copy the sweep ID and replace `sweepID` in the following code snippet to start
250
256
the sweep job with the [`wandb agent`]({{< relref "/ref/cli/wandb-agent.md" >}})
251
257
command:
252
258
@@ -258,84 +264,34 @@ For more information, see [Start sweep jobs]({{< relref "./start-sweep-agents.md
258
264
259
265
{{% /tab %}} {{< /tabpane >}}
260
266
261
-
## Consideration when logging metrics
262
267
263
-
Be sure to log the sweep's metric to W&B explicitly. Do not log metrics for your sweep inside a subdirectory.
264
-
265
-
For example, consider the following pseudocode. A user wants to log the validation loss (`"val_loss": loss`). First they pass the values into a dictionary. However, the dictionary passed to `wandb.Run.log()` does not explicitly access the key-value pair in the dictionary:
268
+
{{% alert title="Logging metrics to W&B in a sweep" %}}
269
+
You must log the metric you define and are optimizing for in both your sweep configuration and with `wandb.Run.log()`. For example, if you define the metric to optimize as `val_acc` within your sweep configuration, you must also log `val_acc` to W&B. If you do not log the metric, W&B does not know what to optimize for.
Instead, explicitly access the key-value pair within the Python dictionary. For example, the following code specifies the key-value pair when you pass the dictionary to the `wandb.Run.log()` method:
306
-
307
-
```python title="train.py"
308
-
# Import the W&B Python Library and log into W&B
309
-
import wandb
310
-
import random
311
-
282
+
The following is an incorrect example of logging the metric to W&B. The metric that is optimized for in the sweep configuration is `val_acc`, but the code logs `val_acc` within a nested dictionary under the key `validation`. You must log the metric directly, not within a nested dictionary.
0 commit comments