-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtrain.py
165 lines (136 loc) · 5.52 KB
/
train.py
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
import argparse
import statistics
import time
from concurrent.futures import ThreadPoolExecutor
from typing import Dict
import torch
import torch.nn as nn
from lightning.pytorch.demos import WikiText2
from torch.utils.data import DataLoader
from dataflux_pytorch.dataflux_checkpoint import DatafluxCheckpoint
class TextClassifier(nn.Module):
"""Basic implementation of a Text Classifier model."""
def __init__(self, vocab_size: int, embedding_dim: int, hidden_dim: int,
output_dim: int):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.rnn = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, output_dim)
def forward(self, x: torch.Tensor):
embedded = self.embedding(x)
output, (hidden, cell) = self.rnn(embedded)
last_hidden = hidden[-1]
logits = self.fc(last_hidden)
return logits.type(torch.FloatTensor)
class CheckpointHelper:
"""A wrapper class around DatafluxCheckpoint that allows the checkpoint
save to be called asynchronously."""
def __init__(self, project_name: str, bucket_name: str):
self._ckpt = DatafluxCheckpoint(project_name, bucket_name)
self._executor = ThreadPoolExecutor(max_workers=1)
def save_checkpoint(self,
path: str,
state_dict: Dict[str, torch.Tensor],
use_async: bool = False):
def _save():
# TODO: error handling
with self._ckpt.writer(path) as writer:
torch.save(state_dict, writer)
if use_async:
self._executor.submit(_save)
else:
_save()
def teardown(self):
self._executor.shutdown(wait=True)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Configuration for single-node async checkpoint demo.")
# User config
parser.add_argument("--project",
type=str,
required=True,
help="GCS project ID.")
parser.add_argument("--bucket",
type=str,
required=True,
help="GCS bucket for saving checkpoints.")
parser.add_argument("--use-async",
action="store_true",
default=False,
help="If checkpoint save should use async.")
# Hyper parameters
parser.add_argument("--embedding-dim",
type=int,
default=100,
help="The size of each embedding vector.")
parser.add_argument("--hidden-dim",
type=int,
default=128,
help="The number of features in the hidden state.")
parser.add_argument("--output-dim",
type=int,
default=35,
help="The size of each output sample.")
parser.add_argument("--batch-size",
type=int,
default=32,
help="How many samples per batch to load.")
parser.add_argument("--num-epochs",
type=int,
default=10,
help="The number of full passes through training.")
parser.add_argument(
"--learning-rate",
type=float,
default=0.001,
help=
"The size of the optimizer steps taken during the training process.")
return parser.parse_args()
def main(args: argparse.Namespace):
"""
Typical usage example:
python3 -u demo/checkpointing/train.py \
--project=<gcs_project_id> \
--bucket=<bucket_name> \
--embedding-dim=100 \
--use-async
"""
# Load dataset and create a Dataloader
dataset = WikiText2()
dataloader = DataLoader(dataset, batch_size=args.batch_size, num_workers=1)
# Create Model
model = TextClassifier(dataset.vocab_size, args.embedding_dim,
args.hidden_dim, args.output_dim)
ckpt = CheckpointHelper(args.project, args.bucket)
# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
save_checkpoint_times = []
total_time = time.time()
# Training workload
for epoch in range(args.num_epochs):
model.train()
for inputs, labels in dataloader:
optimizer.zero_grad()
outputs = model(inputs)
labels = labels.type(torch.FloatTensor)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
print(f"Epoch {epoch+1}/{args.num_epochs}, Train Loss: {loss:.4f}")
# Save checkpoint
save_time = time.time()
ckpt_path = f'single-node/async/checkpoint_{epoch}.pth'
ckpt.save_checkpoint(ckpt_path, model.state_dict(), args.use_async)
save_checkpoint_times.append(time.time() - save_time)
# Clean up and report measurements.
ckpt.teardown()
use_async_str = 'async' if args.use_async else ''
print(f'Average checkpoint {use_async_str} save time: '
f'{statistics.mean(save_checkpoint_times):.4f} seconds '
f'(stdev {statistics.stdev(save_checkpoint_times):.4f})')
duration = int(time.time() - total_time)
print(f'Total run time: {duration//60}m{duration%60}s')
if __name__ == '__main__':
args = parse_args()
main(args)