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 8.0 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
  1. """Training Script."""
  2. import argparse
  3. import os
  4. import torch
  5. import torch.nn as nn
  6. from torch.optim import Adam
  7. from torch.utils.data import DataLoader
  8. from torchvision.models import vgg16
  9. from torchvision.models.feature_extraction import create_feature_extractor
  10. import matplotlib.pyplot as plt
  11. import mlflow
  12. from mlflow.tracking import MlflowClient
  13. from pathlib import Path
  14. from configs import config
  15. from models import StyleTransferNetwork, calc_content_loss, calc_style_loss, calc_tv_loss
  16. from utils.data_utils import ImageDataset, DataProcessor
  17. from utils.image_utils import imsave
  18. def plot_losses(losses, run_id):
  19. """Plot loss graphs and log them as artifacts."""
  20. plt.figure(figsize=(10, 5))
  21. plt.plot(losses['content'], label='Content Loss')
  22. plt.plot(losses['style'], label='Style Loss')
  23. plt.plot(losses['tv'], label='TV Loss')
  24. plt.plot(losses['total'], label='Total Loss')
  25. plt.xlabel('Iterations')
  26. plt.ylabel('Loss')
  27. plt.title('Losses Over Training')
  28. plt.legend()
  29. # Save the plot as an image file
  30. plot_path = 'losses.png'
  31. plt.savefig(plot_path)
  32. # Log the plot as an artifact
  33. mlflow.log_artifact(plot_path, artifact_path='plots', run_id=run_id)
  34. plt.close()
  35. def train(args):
  36. """Train Network."""
  37. device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
  38. # Set up MLflow
  39. mlflow.set_tracking_uri("https://dagshub.com/shatter-star/musical-octo-dollop.mlflow")
  40. os.environ["MLFLOW_TRACKING_USERNAME"] = "shatter-star"
  41. os.environ["MLFLOW_TRACKING_PASSWORD"] = "411996890a0df0c0ccf65dbd848d454f40ad3cbb"
  42. mlflow_client = MlflowClient()
  43. experiment_name = "StyleTransferExperiment"
  44. experiment = mlflow_client.get_experiment_by_name(experiment_name)
  45. if experiment:
  46. experiment_id = experiment.experiment_id
  47. else:
  48. experiment_id = mlflow_client.create_experiment(experiment_name)
  49. # data
  50. content_dataset = ImageDataset(dir_path=Path(args.content_path))
  51. style_dataset = ImageDataset(dir_path=Path(args.style_path))
  52. data_processor = DataProcessor(imsize=args.imsize,
  53. cropsize=args.cropsize,
  54. cencrop=args.cencrop)
  55. content_dataloader = DataLoader(dataset=content_dataset,
  56. batch_size=args.batch_size,
  57. shuffle=True,
  58. collate_fn=data_processor)
  59. style_dataloader = DataLoader(dataset=style_dataset,
  60. batch_size=args.batch_size,
  61. shuffle=True,
  62. collate_fn=data_processor)
  63. # loss network
  64. vgg = vgg16(pretrained=True).features # Load with ImageNet weights
  65. for param in vgg.parameters():
  66. param.requires_grad = False
  67. loss_network = create_feature_extractor(vgg, config.RETURN_NODES).to(device)
  68. # network
  69. model = StyleTransferNetwork(num_style=config.NUM_STYLE)
  70. model.train()
  71. model = model.to(device)
  72. # optimizer# Use DataParallel to leverage multiple GPUs
  73. if torch.cuda.device_count() > 1:
  74. print(f"Using {torch.cuda.device_count()} GPUs!")
  75. model = nn.DataParallel(model)
  76. optimizer = Adam(model.parameters(), lr=args.learning_rate)
  77. losses = {'content': [], 'style': [], 'tv': [], 'total': []}
  78. print("Start training...")
  79. with mlflow.start_run(experiment_id=experiment_id, run_name="StyleTransferRun") as run:
  80. run_id = run.info.run_id
  81. # Log parameters
  82. mlflow.log_params({
  83. "style_weight": args.style_weight,
  84. "tv_weight": args.tv_weight,
  85. "learning_rate": args.learning_rate,
  86. "batch_size": args.batch_size,
  87. "iterations": args.iterations,
  88. # ... (add other relevant parameters)
  89. })
  90. for i in range(1, 1+args.iterations):
  91. content_images, _ = next(iter(content_dataloader))
  92. style_images, style_indices = next(iter(style_dataloader))
  93. style_codes = torch.zeros(args.batch_size, config.NUM_STYLE, 1)
  94. for b, s in enumerate(style_indices):
  95. style_codes[b, s] = 1
  96. content_images = content_images.to(device)
  97. style_images = style_images.to(device)
  98. style_codes = style_codes.to(device)
  99. output_images = model(content_images, style_codes)
  100. if isinstance(model, nn.DataParallel):
  101. content_features = loss_network(content_images.repeat(torch.cuda.device_count(), 1, 1, 1))
  102. style_features = loss_network(style_images.repeat(torch.cuda.device_count(), 1, 1, 1))
  103. output_features = loss_network(output_images.repeat(torch.cuda.device_count(), 1, 1, 1))
  104. else:
  105. content_features = loss_network(content_images)
  106. style_features = loss_network(style_images)
  107. output_features = loss_network(output_images)
  108. style_loss = calc_style_loss(output_features,
  109. style_features,
  110. config.STYLE_NODES)
  111. content_loss = calc_content_loss(output_features,
  112. content_features,
  113. config.CONTENT_NODES)
  114. tv_loss = calc_tv_loss(output_images)
  115. total_loss = content_loss \
  116. + style_loss * args.style_weight \
  117. + tv_loss * args.tv_weight
  118. optimizer.zero_grad()
  119. total_loss.backward()
  120. optimizer.step()
  121. losses['content'].append(content_loss.item())
  122. losses['style'].append(style_loss.item())
  123. losses['tv'].append(tv_loss.item())
  124. losses['total'].append(total_loss.item())
  125. # Log metrics
  126. mlflow.log_metrics({
  127. "content_loss": content_loss.item(),
  128. "style_loss": style_loss.item(),
  129. "tv_loss": tv_loss.item(),
  130. "total_loss": total_loss.item(),
  131. }, step=i)
  132. if i % 100 == 0:
  133. log = f"iter.: {i}"
  134. for k, v in losses.items():
  135. # calculate a recent average value
  136. avg = sum(v[-50:]) / 50
  137. log += f", {k}: {avg:1.4f}"
  138. print(log)
  139. # Log the trained model as a PyTorch model
  140. model_path = "model"
  141. mlflow.pytorch.log_model(model.module, model_path, registered_model_name="StyleTransferModel")
  142. # Plot losses
  143. plot_losses(losses, run_id)
  144. if __name__ == "__main__":
  145. parser = argparse.ArgumentParser()
  146. # Training configurations
  147. parser.add_argument('--style_weight', type=float, default=config.STYLE_WEIGHT,
  148. help='Weight for style loss')
  149. parser.add_argument('--tv_weight', type=float, default=config.TV_WEIGHT,
  150. help='Weight for total variation loss')
  151. parser.add_argument('--learning_rate', type=float, default=config.LEARNING_RATE,
  152. help='Learning rate for optimizer')
  153. parser.add_argument('--batch_size', type=int, default=config.BATCH_SIZE,
  154. help='Batch size for training')
  155. parser.add_argument('--iterations', type=int, default=config.ITERATIONS,
  156. help='Number of training iterations')
  157. # Data configurations
  158. parser.add_argument('--content_path', type=str, required=True,
  159. help='Path to content images')
  160. parser.add_argument('--style_path', type=str, required=True,
  161. help='Path to style images')
  162. parser.add_argument('--imsize', type=int, default=config.IMSIZE,
  163. help='Input image size')
  164. parser.add_argument('--cropsize', type=int, default=config.CROPSIZE,
  165. help='Crop size for input images')
  166. parser.add_argument('--cencrop', action='store_true',
  167. help='Use center crop instead of random crop')
  168. args = parser.parse_args()
  169. train(args)
Tip!

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

Comments

Loading...