Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

train.py 9.8 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
  1. import datetime
  2. import json
  3. from typing import Tuple
  4. import numpy as np
  5. import ray
  6. import ray.train as train
  7. import torch
  8. import torch.nn as nn
  9. import torch.nn.functional as F
  10. import typer
  11. from ray.air import session
  12. from ray.air.config import (
  13. CheckpointConfig,
  14. DatasetConfig,
  15. RunConfig,
  16. ScalingConfig,
  17. )
  18. from ray.air.integrations.mlflow import MLflowLoggerCallback
  19. from ray.data import Dataset
  20. from ray.train.torch import TorchCheckpoint, TorchTrainer
  21. from transformers import BertModel
  22. from typing_extensions import Annotated
  23. from madewithml import data, models, utils
  24. from madewithml.config import MLFLOW_TRACKING_URI, logger
  25. # Initialize Typer CLI app
  26. app = typer.Typer()
  27. def train_step(
  28. ds: Dataset,
  29. batch_size: int,
  30. model: nn.Module,
  31. num_classes: int,
  32. loss_fn: torch.nn.modules.loss._WeightedLoss,
  33. optimizer: torch.optim.Optimizer,
  34. ) -> float: # pragma: no cover, tested via train workload
  35. """Train step.
  36. Args:
  37. ds (Dataset): dataset to iterate batches from.
  38. batch_size (int): size of each batch.
  39. model (nn.Module): model to train.
  40. num_classes (int): number of classes.
  41. loss_fn (torch.nn.loss._WeightedLoss): loss function to use between labels and predictions.
  42. optimizer (torch.optimizer.Optimizer): optimizer to use for updating the model's weights.
  43. Returns:
  44. float: cumulative loss for the dataset.
  45. """
  46. model.train()
  47. loss = 0.0
  48. ds_generator = ds.iter_torch_batches(batch_size=batch_size, collate_fn=utils.collate_fn)
  49. for i, batch in enumerate(ds_generator):
  50. optimizer.zero_grad() # reset gradients
  51. z = model(batch) # forward pass
  52. targets = F.one_hot(batch["targets"], num_classes=num_classes).float() # one-hot (for loss_fn)
  53. J = loss_fn(z, targets) # define loss
  54. J.backward() # backward pass
  55. optimizer.step() # update weights
  56. loss += (J.detach().item() - loss) / (i + 1) # cumulative loss
  57. return loss
  58. def eval_step(
  59. ds: Dataset, batch_size: int, model: nn.Module, num_classes: int, loss_fn: torch.nn.modules.loss._WeightedLoss
  60. ) -> Tuple[float, np.array, np.array]: # pragma: no cover, tested via train workload
  61. """Eval step.
  62. Args:
  63. ds (Dataset): dataset to iterate batches from.
  64. batch_size (int): size of each batch.
  65. model (nn.Module): model to train.
  66. num_classes (int): number of classes.
  67. loss_fn (torch.nn.loss._WeightedLoss): loss function to use between labels and predictions.
  68. Returns:
  69. Tuple[float, np.array, np.array]: cumulative loss, ground truths and predictions.
  70. """
  71. model.eval()
  72. loss = 0.0
  73. y_trues, y_preds = [], []
  74. ds_generator = ds.iter_torch_batches(batch_size=batch_size, collate_fn=utils.collate_fn)
  75. with torch.inference_mode():
  76. for i, batch in enumerate(ds_generator):
  77. z = model(batch)
  78. targets = F.one_hot(batch["targets"], num_classes=num_classes).float() # one-hot (for loss_fn)
  79. J = loss_fn(z, targets).item()
  80. loss += (J - loss) / (i + 1)
  81. y_trues.extend(batch["targets"].cpu().numpy())
  82. y_preds.extend(torch.argmax(z, dim=1).cpu().numpy())
  83. return loss, np.vstack(y_trues), np.vstack(y_preds)
  84. def train_loop_per_worker(config: dict) -> None: # pragma: no cover, tested via train workload
  85. """Training loop that each worker will execute.
  86. Args:
  87. config (dict): arguments to use for training.
  88. """
  89. # Hyperparameters
  90. dropout_p = config["dropout_p"]
  91. lr = config["lr"]
  92. lr_factor = config["lr_factor"]
  93. lr_patience = config["lr_patience"]
  94. batch_size = config["batch_size"]
  95. num_epochs = config["num_epochs"]
  96. num_classes = config["num_classes"]
  97. # Get datasets
  98. utils.set_seeds()
  99. train_ds = session.get_dataset_shard("train")
  100. val_ds = session.get_dataset_shard("val")
  101. # Model
  102. llm = BertModel.from_pretrained("allenai/scibert_scivocab_uncased", return_dict=False)
  103. model = models.FinetunedLLM(llm=llm, dropout_p=dropout_p, embedding_dim=llm.config.hidden_size, num_classes=num_classes)
  104. model = train.torch.prepare_model(model)
  105. # Training components
  106. loss_fn = nn.BCEWithLogitsLoss()
  107. optimizer = torch.optim.Adam(model.parameters(), lr=lr)
  108. scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=lr_factor, patience=lr_patience)
  109. # Training
  110. batch_size_per_worker = batch_size // session.get_world_size()
  111. for epoch in range(num_epochs):
  112. # Step
  113. train_loss = train_step(train_ds, batch_size_per_worker, model, num_classes, loss_fn, optimizer)
  114. val_loss, _, _ = eval_step(val_ds, batch_size_per_worker, model, num_classes, loss_fn)
  115. scheduler.step(val_loss)
  116. # Checkpoint
  117. metrics = dict(epoch=epoch, lr=optimizer.param_groups[0]["lr"], train_loss=train_loss, val_loss=val_loss)
  118. checkpoint = TorchCheckpoint.from_model(model=model)
  119. session.report(metrics, checkpoint=checkpoint)
  120. @app.command()
  121. def train_model(
  122. experiment_name: Annotated[str, typer.Option(help="name of the experiment for this training workload.")] = None,
  123. dataset_loc: Annotated[str, typer.Option(help="location of the dataset.")] = None,
  124. train_loop_config: Annotated[str, typer.Option(help="arguments to use for training.")] = None,
  125. num_workers: Annotated[int, typer.Option(help="number of workers to use for training.")] = 1,
  126. cpu_per_worker: Annotated[int, typer.Option(help="number of CPUs to use per worker.")] = 1,
  127. gpu_per_worker: Annotated[int, typer.Option(help="number of GPUs to use per worker.")] = 0,
  128. num_samples: Annotated[int, typer.Option(help="number of samples to use from dataset.")] = None,
  129. num_epochs: Annotated[int, typer.Option(help="number of epochs to train for.")] = 1,
  130. batch_size: Annotated[int, typer.Option(help="number of samples per batch.")] = 256,
  131. results_fp: Annotated[str, typer.Option(help="filepath to save results to.")] = None,
  132. ) -> ray.air.result.Result:
  133. """Main train function to train our model as a distributed workload.
  134. Args:
  135. experiment_name (str): name of the experiment for this training workload.
  136. dataset_loc (str): location of the dataset.
  137. train_loop_config (str): arguments to use for training.
  138. num_workers (int, optional): number of workers to use for training. Defaults to 1.
  139. cpu_per_worker (int, optional): number of CPUs to use per worker. Defaults to 1.
  140. gpu_per_worker (int, optional): number of GPUs to use per worker. Defaults to 0.
  141. num_samples (int, optional): number of samples to use from dataset.
  142. If this is passed in, it will override the config. Defaults to None.
  143. num_epochs (int, optional): number of epochs to train for.
  144. If this is passed in, it will override the config. Defaults to None.
  145. batch_size (int, optional): number of samples per batch.
  146. If this is passed in, it will override the config. Defaults to None.
  147. results_fp (str, optional): filepath to save results to. Defaults to None.
  148. Returns:
  149. ray.air.result.Result: training results.
  150. """
  151. # Set up
  152. train_loop_config = json.loads(train_loop_config)
  153. train_loop_config["num_samples"] = num_samples
  154. train_loop_config["num_epochs"] = num_epochs
  155. train_loop_config["batch_size"] = batch_size
  156. # Scaling config
  157. scaling_config = ScalingConfig(
  158. num_workers=num_workers,
  159. use_gpu=bool(gpu_per_worker),
  160. resources_per_worker={"CPU": cpu_per_worker, "GPU": gpu_per_worker},
  161. _max_cpu_fraction_per_node=0.8,
  162. )
  163. # Checkpoint config
  164. checkpoint_config = CheckpointConfig(
  165. num_to_keep=1,
  166. checkpoint_score_attribute="val_loss",
  167. checkpoint_score_order="min",
  168. )
  169. # MLflow callback
  170. mlflow_callback = MLflowLoggerCallback(
  171. tracking_uri=MLFLOW_TRACKING_URI,
  172. experiment_name=experiment_name,
  173. save_artifact=True,
  174. )
  175. # Run config
  176. run_config = RunConfig(
  177. callbacks=[mlflow_callback],
  178. checkpoint_config=checkpoint_config,
  179. )
  180. # Dataset
  181. ds = data.load_data(dataset_loc=dataset_loc, num_samples=train_loop_config["num_samples"])
  182. train_ds, val_ds = data.stratify_split(ds, stratify="tag", test_size=0.2)
  183. tags = train_ds.unique(column="tag")
  184. train_loop_config["num_classes"] = len(tags)
  185. # Dataset config
  186. dataset_config = {
  187. "train": DatasetConfig(fit=False, transform=False, randomize_block_order=False),
  188. "val": DatasetConfig(fit=False, transform=False, randomize_block_order=False),
  189. }
  190. # Preprocess
  191. preprocessor = data.CustomPreprocessor()
  192. train_ds = preprocessor.fit_transform(train_ds)
  193. val_ds = preprocessor.transform(val_ds)
  194. train_ds = train_ds.materialize()
  195. val_ds = val_ds.materialize()
  196. # Trainer
  197. trainer = TorchTrainer(
  198. train_loop_per_worker=train_loop_per_worker,
  199. train_loop_config=train_loop_config,
  200. scaling_config=scaling_config,
  201. run_config=run_config,
  202. datasets={"train": train_ds, "val": val_ds},
  203. dataset_config=dataset_config,
  204. preprocessor=preprocessor,
  205. )
  206. # Train
  207. results = trainer.fit()
  208. d = {
  209. "timestamp": datetime.datetime.now().strftime("%B %d, %Y %I:%M:%S %p"),
  210. "run_id": utils.get_run_id(experiment_name=experiment_name, trial_id=results.metrics["trial_id"]),
  211. "params": results.config["train_loop_config"],
  212. "metrics": utils.dict_to_list(results.metrics_dataframe.to_dict(), keys=["epoch", "train_loss", "val_loss"]),
  213. }
  214. logger.info(json.dumps(d, indent=2))
  215. if results_fp: # pragma: no cover, saving results
  216. utils.save_dict(d, results_fp)
  217. return results
  218. if __name__ == "__main__": # pragma: no cover, application
  219. if ray.is_initialized():
  220. ray.shutdown()
  221. ray.init()
  222. app()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...