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

pytorch_example.py 8.2 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
  1. import numpy as np
  2. import os
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. import torch.optim as optim
  7. from filelock import FileLock
  8. from torch.utils.data import random_split
  9. import torchvision
  10. import torchvision.transforms as transforms
  11. import ray
  12. from ray import tune, air
  13. from ray.air import session
  14. from ray.air.checkpoint import Checkpoint
  15. from ray.air.integrations.dagshub import DagsHubLoggerCallback
  16. from ray.tune.schedulers import ASHAScheduler
  17. from config import bcolors, logger
  18. def load_data(data_dir="./data"):
  19. transform = transforms.Compose([
  20. transforms.ToTensor(),
  21. transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
  22. ])
  23. # We add FileLock here because multiple workers will want to
  24. # download data, and this may cause overwrites since
  25. # DataLoader is not threadsafe.
  26. with FileLock(os.path.expanduser("~/.data.lock")):
  27. trainset = torchvision.datasets.CIFAR10(
  28. root=data_dir, train=True, download=True, transform=transform)
  29. testset = torchvision.datasets.CIFAR10(
  30. root=data_dir, train=False, download=True, transform=transform)
  31. return trainset, testset
  32. class Net(nn.Module):
  33. def __init__(self, l1=120, l2=84):
  34. super(Net, self).__init__()
  35. self.conv1 = nn.Conv2d(3, 6, 5)
  36. self.pool = nn.MaxPool2d(2, 2)
  37. self.conv2 = nn.Conv2d(6, 16, 5)
  38. self.fc1 = nn.Linear(16 * 5 * 5, l1)
  39. self.fc2 = nn.Linear(l1, l2)
  40. self.fc3 = nn.Linear(l2, 10)
  41. def forward(self, x):
  42. x = self.pool(F.relu(self.conv1(x)))
  43. x = self.pool(F.relu(self.conv2(x)))
  44. x = x.view(-1, 16 * 5 * 5)
  45. x = F.relu(self.fc1(x))
  46. x = F.relu(self.fc2(x))
  47. x = self.fc3(x)
  48. return x
  49. def train_cifar(config):
  50. net = Net(config["l1"], config["l2"])
  51. device = "cpu"
  52. if torch.cuda.is_available():
  53. device = "cuda:0"
  54. if torch.cuda.device_count() > 1:
  55. net = nn.DataParallel(net)
  56. net.to(device)
  57. criterion = nn.CrossEntropyLoss()
  58. optimizer = optim.SGD(net.parameters(), lr=config["lr"], momentum=0.9)
  59. # To restore a checkpoint, use `session.get_checkpoint()`.
  60. loaded_checkpoint = session.get_checkpoint()
  61. if loaded_checkpoint:
  62. with loaded_checkpoint.as_directory() as loaded_checkpoint_dir:
  63. model_state, optimizer_state = torch.load(os.path.join(loaded_checkpoint_dir, "checkpoint.pt"))
  64. net.load_state_dict(model_state)
  65. optimizer.load_state_dict(optimizer_state)
  66. data_dir = os.path.abspath("./data")
  67. trainset, testset = load_data(data_dir)
  68. test_abs = int(len(trainset) * 0.8)
  69. train_subset, val_subset = random_split(
  70. trainset, [test_abs, len(trainset) - test_abs])
  71. trainloader = torch.utils.data.DataLoader(
  72. train_subset,
  73. batch_size=int(config["batch_size"]),
  74. shuffle=True,
  75. num_workers=8)
  76. valloader = torch.utils.data.DataLoader(
  77. val_subset,
  78. batch_size=int(config["batch_size"]),
  79. shuffle=True,
  80. num_workers=8)
  81. for epoch in range(10): # loop over the dataset multiple times
  82. running_loss = 0.0
  83. epoch_steps = 0
  84. for i, data in enumerate(trainloader, 0):
  85. # get the inputs; data is a list of [inputs, labels]
  86. inputs, labels = data
  87. inputs, labels = inputs.to(device), labels.to(device)
  88. # zero the parameter gradients
  89. optimizer.zero_grad()
  90. # forward + backward + optimize
  91. outputs = net(inputs)
  92. loss = criterion(outputs, labels)
  93. loss.backward()
  94. optimizer.step()
  95. # print statistics
  96. running_loss += loss.item()
  97. epoch_steps += 1
  98. if i % 2000 == 1999: # print every 2000 mini-batches
  99. print("[%d, %5d] loss: %.3f" % (epoch + 1, i + 1,
  100. running_loss / epoch_steps))
  101. running_loss = 0.0
  102. # Validation loss
  103. val_loss = 0.0
  104. val_steps = 0
  105. total = 0
  106. correct = 0
  107. for i, data in enumerate(valloader, 0):
  108. with torch.no_grad():
  109. inputs, labels = data
  110. inputs, labels = inputs.to(device), labels.to(device)
  111. outputs = net(inputs)
  112. _, predicted = torch.max(outputs.data, 1)
  113. total += labels.size(0)
  114. correct += (predicted == labels).sum().item()
  115. loss = criterion(outputs, labels)
  116. val_loss += loss.cpu().numpy()
  117. val_steps += 1
  118. # Here we save a checkpoint. It is automatically registered with
  119. # Ray Tune and can be accessed through `session.get_checkpoint()`
  120. # API in future iterations.
  121. os.makedirs("my_model", exist_ok=True)
  122. torch.save(
  123. (net.state_dict(), optimizer.state_dict()), "my_model/checkpoint.pt")
  124. checkpoint = Checkpoint.from_directory("my_model")
  125. session.report({"loss": (val_loss / val_steps), "accuracy": correct / total}, checkpoint=checkpoint)
  126. logger.info("Finished Training")
  127. def test_best_model(best_result):
  128. best_trained_model = Net(best_result.config["l1"], best_result.config["l2"])
  129. device = "cuda:0" if torch.cuda.is_available() else "cpu"
  130. best_trained_model.to(device)
  131. checkpoint_path = os.path.join(best_result.checkpoint.to_directory(), "checkpoint.pt")
  132. model_state, _ = torch.load(checkpoint_path)
  133. best_trained_model.load_state_dict(model_state)
  134. _, testset = load_data()
  135. testloader = torch.utils.data.DataLoader(
  136. testset, batch_size=4, shuffle=False, num_workers=2)
  137. correct = 0
  138. total = 0
  139. with torch.no_grad():
  140. for data in testloader:
  141. images, labels = data
  142. images, labels = images.to(device), labels.to(device)
  143. outputs = best_trained_model(images)
  144. _, predicted = torch.max(outputs.data, 1)
  145. total += labels.size(0)
  146. correct += (predicted == labels).sum().item()
  147. logger.info("Best trial test set accuracy: {}".format(correct / total))
  148. if __name__=="__main__":
  149. num_samples = 2
  150. max_num_epochs = 1
  151. gpus_per_trial = 0
  152. logger.info(
  153. f"{bcolors.BOLD}{bcolors.HEADER}--- Initialize Configuration ---{bcolors.ENDC}{bcolors.ENDC}"
  154. )
  155. config = {
  156. "l1": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)),
  157. "l2": tune.sample_from(lambda _: 2 ** np.random.randint(2, 9)),
  158. "lr": tune.loguniform(1e-4, 1e-1),
  159. "batch_size": tune.choice([2, 4, 8, 16])
  160. }
  161. logger.info(
  162. f"{bcolors.BOLD}{bcolors.HEADER}--- Initialize ASHAScheduler ---{bcolors.ENDC}{bcolors.ENDC}"
  163. )
  164. scheduler = ASHAScheduler(
  165. max_t=max_num_epochs,
  166. grace_period=1,
  167. reduction_factor=2)
  168. logger.info(
  169. f"{bcolors.BOLD}{bcolors.HEADER}--- Initialize Tuner ---{bcolors.ENDC}{bcolors.ENDC}"
  170. )
  171. tuner = tune.Tuner(
  172. tune.with_resources(
  173. tune.with_parameters(train_cifar),
  174. resources={"cpu": 2, "gpu": gpus_per_trial}
  175. ),
  176. tune_config=tune.TuneConfig(
  177. metric="loss",
  178. mode="min",
  179. scheduler=scheduler,
  180. num_samples=num_samples,
  181. ),
  182. run_config=air.RunConfig(
  183. name="dagshub",
  184. callbacks=[
  185. DagsHubLoggerCallback(
  186. tracking_uri="",
  187. experiment_name="ray_pytorch_exp",
  188. dagshub_repository="timho102003/ray_save_art_exp",
  189. log_mlflow_only=False,
  190. save_artifact=True,
  191. )
  192. ],
  193. ),
  194. param_space=config,
  195. )
  196. logger.info(
  197. f"{bcolors.BOLD}{bcolors.HEADER}--- Start Tuning ... ---{bcolors.ENDC}{bcolors.ENDC}"
  198. )
  199. results = tuner.fit()
  200. best_result = results.get_best_result("loss", "min")
  201. logger.info("Best trial config: {}".format(best_result.config))
  202. logger.info("Best trial final validation loss: {}".format(
  203. best_result.metrics["loss"]))
  204. logger.info("Best trial final validation accuracy: {}".format(
  205. best_result.metrics["accuracy"]))
  206. test_best_model(best_result)
Tip!

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

Comments

Loading...