Debian Codegraph @

docs/source/usage_guides/tracking.md

raw
1 <!--Copyright 2022 The HuggingFace Team. All rights reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4 the License. You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9 an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10 specific language governing permissions and limitations under the License.
11
12 ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
13 rendered properly in your Markdown viewer.
14 -->
15
16 # Experiment trackers
17
18 There are a large number of experiment tracking APIs available, however getting them all to work in a multi-processing environment can oftentimes be complex.
19 Accelerate provides a general tracking API that can be used to log useful items during your script through [`Accelerator.log`]
20
21 ## Integrated Trackers
22
23 Currently `Accelerate` supports eight trackers out-of-the-box:
24
25 - TensorBoard
26 - WandB
27 - Trackio
28 - CometML
29 - Aim
30 - MLFlow
31 - ClearML
32 - DVCLive
33
34 To use any of them, pass in the selected type(s) to the `log_with` parameter in [`Accelerate`]:
35 ```python
36 from accelerate import Accelerator
37 from accelerate.utils import LoggerType
38
39 accelerator = Accelerator(log_with="all") # For all available trackers in the environment
40 accelerator = Accelerator(log_with="wandb")
41 accelerator = Accelerator(log_with=["wandb", LoggerType.TENSORBOARD])
42 ```
43
44 At the start of your experiment [`Accelerator.init_trackers`] should be used to setup your project, and potentially add any experiment hyperparameters to be logged:
45 ```python
46 hps = {"num_iterations": 5, "learning_rate": 1e-2}
47 accelerator.init_trackers("my_project", config=hps)
48 ```
49
50 When you are ready to log any data, [`Accelerator.log`] should be used.
51 A `step` can also be passed in to correlate the data with a particular step in the training loop.
52 ```python
53 accelerator.log({"train_loss": 1.12, "valid_loss": 0.8}, step=1)
54 ```
55
56 Once you've finished training, make sure to run [`Accelerator.end_training`] so that all the trackers can run their finish functionalities if they have any.
57 ```python
58 accelerator.end_training()
59 ```
60
61
62 A full example is below:
63 ```python
64 from accelerate import Accelerator
65
66 accelerator = Accelerator(log_with="all")
67 config = {
68 "num_iterations": 5,
69 "learning_rate": 1e-2,
70 "loss_function": str(my_loss_function),
71 }
72
73 accelerator.init_trackers("example_project", config=config)
74
75 my_model, my_optimizer, my_training_dataloader = accelerator.prepare(my_model, my_optimizer, my_training_dataloader)
76 device = accelerator.device
77 my_model.to(device)
78
79 for iteration in range(config["num_iterations"]):
80 for step, batch in enumerate(my_training_dataloader):
81 my_optimizer.zero_grad()
82 inputs, targets = batch
83 inputs = inputs.to(device)
84 targets = targets.to(device)
85 outputs = my_model(inputs)
86 loss = my_loss_function(outputs, targets)
87 accelerator.backward(loss)
88 my_optimizer.step()
89 accelerator.log({"training_loss": loss}, step=step)
90 accelerator.end_training()
91 ```
92
93 If a tracker requires a directory to save data to, such as `TensorBoard`, then pass the directory path to `project_dir`. The `project_dir` parameter is useful
94 when there are other configurations to be combined with in the [`~utils.ProjectConfiguration`] data class. For example, you can save the TensorBoard data to `project_dir` and everything else can be logged in the `logging_dir` parameter of [`~utils.ProjectConfiguration`:
95
96 ```python
97 accelerator = Accelerator(log_with="tensorboard", project_dir=".")
98
99 # use with ProjectConfiguration
100 config = ProjectConfiguration(project_dir=".", logging_dir="another/directory")
101 accelerator = Accelerator(log_with="tensorboard", project_config=config)
102 ```
103
104 ## Implementing Custom Trackers
105
106 To implement a new tracker to be used in `Accelerator`, a new one can be made through implementing the [`GeneralTracker`] class.
107 Every tracker must implement three functions and have three properties:
108 - `__init__`:
109 - Should store a `run_name` and initialize the tracker API of the integrated library.
110 - If a tracker stores their data locally (such as TensorBoard), a `logging_dir` parameter can be added.
111 - `store_init_configuration`:
112 - Should take in a `values` dictionary and store them as a one-time experiment configuration
113 - `log`:
114 - Should take in a `values` dictionary and a `step`, and should log them to the run
115
116 - `name` (`str`):
117 - A unique string name for the tracker, such as `"wandb"` for the wandb tracker.
118 - This will be used for interacting with this tracker specifically
119 - `requires_logging_directory` (`bool`):
120 - Whether a `logging_dir` is needed for this particular tracker and if it uses one.
121 - `tracker`:
122 - This should be implemented as a `@property` function
123 - Should return the internal tracking mechanism the library uses, such as the `run` object for `wandb`.
124
125 Each method should also utilize the [`state.PartialState`] class if the logger should only be executed on the main process for instance.
126
127 A brief example can be seen below with an integration with Weights and Biases, containing only the relevant information and logging just on
128 the main process:
129 ```python
130 from accelerate.tracking import GeneralTracker, on_main_process
131 from typing import Optional
132
133 import wandb
134
135
136 class MyCustomTracker(GeneralTracker):
137 name = "wandb"
138 requires_logging_directory = False
139
140 @on_main_process
141 def __init__(self, run_name: str):
142 self.run_name = run_name
143 run = wandb.init(self.run_name)
144
145 @property
146 def tracker(self):
147 return self.run.run
148
149 @on_main_process
150 def store_init_configuration(self, values: dict):
151 wandb.config(values)
152
153 @on_main_process
154 def log(self, values: dict, step: Optional[int] = None):
155 wandb.log(values, step=step)
156 ```
157
158 When you are ready to build your `Accelerator` object, pass in an **instance** of your tracker to [`Accelerator.log_with`] to have it automatically
159 be used with the API:
160
161 ```python
162 tracker = MyCustomTracker("some_run_name")
163 accelerator = Accelerator(log_with=tracker)
164 ```
165
166 These also can be mixed with existing trackers, including with `"all"`:
167
168 ```python
169 tracker = MyCustomTracker("some_run_name")
170 accelerator = Accelerator(log_with=[tracker, "all"])
171 ```
172
173 ## Accessing the internal tracker
174
175 If some custom interactions with a tracker might be wanted directly, you can quickly access one using the
176 [`Accelerator.get_tracker`] method. Just pass in the string corresponding to a tracker's `.name` attribute
177 and it will return that tracker on the main process.
178
179 This example shows doing so with wandb:
180
181 ```python
182 wandb_tracker = accelerator.get_tracker("wandb")
183 ```
184
185 From there you can interact with `wandb`'s `run` object like normal:
186
187 ```python
188 wandb_tracker.log_artifact(some_artifact_to_log)
189 ```
190
191 <Tip>
192 Trackers built in Accelerate will automatically execute on the correct process,
193 so if a tracker is only meant to be ran on the main process it will do so
194 automatically.
195 </Tip>
196
197 If you want to truly remove Accelerate's wrapping entirely, you can
198 achieve the same outcome with:
199
200 ```python
201 wandb_tracker = accelerator.get_tracker("wandb", unwrap=True)
202 if accelerator.is_main_process:
203 wandb_tracker.log_artifact(some_artifact_to_log)
204 ```
205
206
207 ## When a wrapper cannot work
208
209 If a library has an API that does not follow a strict `.log` with an overall dictionary such as Neptune.AI, logging can be done manually under an `if accelerator.is_main_process` statement:
210 ```diff
211 from accelerate import Accelerator
212 + import neptune
213
214 accelerator = Accelerator()
215 + run = neptune.init_run(...)
216
217 my_model, my_optimizer, my_training_dataloader = accelerate.prepare(my_model, my_optimizer, my_training_dataloader)
218 device = accelerator.device
219 my_model.to(device)
220
221 for iteration in config["num_iterations"]:
222 for batch in my_training_dataloader:
223 my_optimizer.zero_grad()
224 inputs, targets = batch
225 inputs = inputs.to(device)
226 targets = targets.to(device)
227 outputs = my_model(inputs)
228 loss = my_loss_function(outputs, targets)
229 total_loss += loss
230 accelerator.backward(loss)
231 my_optimizer.step()
232 + if accelerator.is_main_process:
233 + run["logs/training/batch/loss"].log(loss)
234 ```