-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmnist_cnn_example.cpp
More file actions
221 lines (193 loc) · 6.85 KB
/
Copy pathmnist_cnn_example.cpp
File metadata and controls
221 lines (193 loc) · 6.85 KB
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
// mnist_cnn_example.cpp
// MNIST CNN learning example
// Download dataset from https://git-disl.github.io/GTDLBench/datasets/mnist_datasets/
// https://github.com/pytorch/examples/blob/main/mnist/main.py
#include <tt/data/dataset.h>
#include <tt/data/mnist.h>
#include <tt/device.h>
#include <tt/exception.h>
#include <tt/grad_mode.h>
#include <tt/nn/conv2d.h>
#include <tt/nn/dropout.h>
#include <tt/nn/linear.h>
#include <tt/nn/loss.h>
#include <tt/nn/module.h>
#include <tt/optim/adam.h>
#include <tt/random.h>
#include <tt/tensor.h>
#include <cstdint>
#include <format>
#include <iostream>
#include <ranges>
#include <string>
#include <utility>
using namespace tinytensor;
// Neural Net
// https://github.com/pytorch/examples/blob/main/mnist/main.py
class Net : public nn::Module {
public:
Net()
: conv1(1, 32, 3, 1, 0),
conv2(32, 64, 3, 1, 0),
linear1(9216, 128),
linear2(128, 10),
dropout1(0.25),
dropout2(0.5) {
register_module(conv1);
register_module(conv2);
register_module(linear1);
register_module(linear2);
register_module(dropout1);
register_module(dropout2);
}
[[nodiscard]] auto name() const -> std::string override {
return "Net";
}
[[nodiscard]] auto forward(Tensor input) -> Tensor {
Tensor result = relu(conv1.forward(input));
result = relu(conv2.forward(result));
result = max_pool2d(result, 2, 2, 0);
result = dropout1.forward(result);
result = result.flatten(1);
result = relu(linear1.forward(result));
result = dropout2.forward(result);
result = linear2.forward(result);
return result;
}
private:
nn::Conv2d conv1;
nn::Conv2d conv2;
nn::Linear linear1;
nn::Linear linear2;
nn::Dropout dropout1;
nn::Dropout dropout2;
};
#ifdef TT_CUDA
constexpr Device device = kCUDA;
#else
constexpr Device device = kCPU;
#endif
int main(int argc, char *argv[]) {
if (argc != 5) {
TT_EXCEPTION(
"Usage: ./mnist_cnn_example train-images-idx3-ubyte train-labels-idx1-ubyte t10k-images-idx3-ubyte "
"t10k-labels-idx1-ubyte"
);
}
const std::string train_img_path = argv[1]; // NOLINT(*-pointer-arithmetic)
const std::string train_label_path = argv[2]; // NOLINT(*-pointer-arithmetic)
const std::string test_img_path = argv[3]; // NOLINT(*-pointer-arithmetic)
const std::string test_label_path = argv[4]; // NOLINT(*-pointer-arithmetic)
constexpr double train_val_ratio = 0.7;
constexpr double lr = 3e-4;
constexpr int epochs = 2;
constexpr int batch_size = 256;
constexpr uint64_t seed = 0;
set_default_generator_seed(seed);
// Dataset and splits
data::MNISTDataset dataset_train(train_img_path, train_label_path, true);
data::MNISTDataset dataset_test(test_img_path, test_label_path, true);
int train_size = static_cast<int>(dataset_train.size() * train_val_ratio);
int val_size = dataset_train.size() - train_size;
auto [train_data, validate_data] = data::random_split(std::move(dataset_train), seed, train_size, val_size);
auto test_data = data::DatasetView(std::move(dataset_test));
auto train_loader = data::DataLoader(train_data, batch_size, true, seed);
auto validate_loader = data::DataLoader(validate_data, batch_size, false);
auto test_loader = data::DataLoader(test_data, batch_size, false);
Net net;
optim::Adam optim(net.parameters_for_optimizer(), lr);
net.to(device);
// Train/Validate
for ([[maybe_unused]] int epoch : std::views::iota(0, epochs)) {
// Train
net.train();
double epoch_train_loss = 0;
int i = -1;
for (auto [x, y] : train_loader) {
x = x.to(device);
y = y.to(device);
optim.zero_grad();
Tensor y_hat = net.forward(x);
Tensor loss = nn::cross_entropy_loss(y_hat, y.flatten());
auto loss_val = loss.item<double>();
epoch_train_loss += loss_val / train_loader.size();
loss.backward();
optim.step();
std::cout << std::format(
"Epoch: {:d}, train step: {:d}/{:d}, loss: {:f}",
epoch,
++i,
train_loader.size(),
loss_val
) << std::endl;
}
// Validate
net.eval();
double epoch_validate_loss = 0;
i = -1;
// Guard for no grads being tracked
{
const autograd::NoGradGuard guard;
for (auto [x, y] : validate_loader) {
x = x.to(device);
y = y.to(device);
Tensor y_hat = net.forward(x);
Tensor loss = nn::cross_entropy_loss(y_hat, y.flatten());
auto loss_val = loss.item<double>();
epoch_validate_loss += loss_val / validate_loader.size();
std::cout << std::format(
"Epoch: {:d}, val step step: {:d}/{:d}, loss: {:f}",
epoch,
++i,
validate_loader.size(),
loss_val
) << std::endl;
}
std::cout << std::format(
"Epoch: {:d}, Train Loss: {:f}, Validate Loss: {:f}",
epoch,
epoch_train_loss,
epoch_validate_loss
) << std::endl;
}
}
// Test net on held out set
// Demonstrate how to save and load model
net.save("model.pt");
Net net2;
net2.to(device);
net2.load("model.pt");
net2.eval();
int num_correct = 0;
int total_samples = 0;
for (auto [x, y] : test_loader) {
x = x.to(device);
y = y.to(device);
Tensor y_hat = net2.forward(x);
Tensor pred_labels = y_hat.argmax(-1, true);
num_correct += eq(pred_labels, y).sum().item<int>();
total_samples += y.numel();
}
double accuracy = (static_cast<double>(num_correct) / total_samples) * 100;
std::cout << std::format("Test Accuracy: {:d} / {:d} = {:.2f}%", num_correct, total_samples, accuracy) << std::endl;
// Test net on held out set
// Demonstrate how to serialize and deserialize model
net.save("model.pt");
Net net3;
net3.to(device);
net3.deserialize(net.serialize());
net3.eval();
num_correct = 0;
total_samples = 0;
for (auto [x, y] : test_loader) {
x = x.to(device);
y = y.to(device);
Tensor y_hat = net3.forward(x);
Tensor pred_labels = y_hat.argmax(-1, true);
num_correct += eq(pred_labels, y).sum().item<int>();
total_samples += y.numel();
}
accuracy = (static_cast<double>(num_correct) / total_samples) * 100;
std::cout << std::format("Test Accuracy: {:d} / {:d} = {:.2f}%", num_correct, total_samples, accuracy) << std::endl;
return 0;
}