interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / examples / mnist / mnist-train-fc.py

131 lines · 4537 bytes Raw Blame History
1import gguf
2import numpy as np
3import torch
4import torch.nn as nn
5import torchvision.datasets as dsets
6import torchvision.transforms as transforms
7from torch.autograd import Variable
8
9import sys
10from time import time
11
12input_size = 784 # img_size = (28,28) ---> 28*28=784 in total
13hidden_size = 500 # number of nodes at hidden layer
14num_classes = 10 # number of output classes discrete range [0,9]
15num_epochs = 30 # number of times which the entire dataset is passed throughout the model
16batch_size = 1000 # the size of input data used for one iteration
17lr = 1e-3 # size of step
18
19
20class Net(nn.Module):
21 def __init__(self, input_size, hidden_size, num_classes):
22 super(Net, self).__init__()
23 self.fc1 = nn.Linear(input_size, hidden_size)
24 self.relu = nn.ReLU()
25 self.fc2 = nn.Linear(hidden_size, num_classes)
26
27 def forward(self, x):
28 out = self.fc1(x)
29 out = self.relu(out)
30 out = self.fc2(out)
31 return out
32
33
34def train(model_path):
35 train_data = dsets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
36 test_data = dsets.MNIST(root='./data', train=False, transform=transforms.ToTensor())
37
38 assert len(train_data) == 60000
39 assert len(test_data) == 10000
40
41 kwargs_train_test = dict(batch_size=batch_size, num_workers=4, pin_memory=True)
42 train_gen = torch.utils.data.DataLoader(dataset=train_data, shuffle=True, **kwargs_train_test)
43 test_gen = torch.utils.data.DataLoader(dataset=test_data, shuffle=False, **kwargs_train_test)
44
45 net = Net(input_size, hidden_size, num_classes)
46
47 if torch.cuda.is_available():
48 net.cuda()
49
50 loss_function = nn.CrossEntropyLoss()
51 optimizer = torch.optim.Adam(net.parameters(), lr=lr)
52
53 t_start = time()
54 for epoch in range(num_epochs):
55 loss_history = []
56 ncorrect = 0
57
58 for i, (images, labels) in enumerate(train_gen):
59 images = Variable(images.view(-1, 28*28))
60 labels = Variable(labels)
61
62 if torch.cuda.is_available():
63 images = images.cuda()
64 labels = labels.cuda()
65
66 optimizer.zero_grad()
67 outputs = net(images)
68 loss = loss_function(outputs, labels)
69
70 loss_history.append(loss.cpu().data)
71 _, predictions = torch.max(outputs, 1)
72 ncorrect += (predictions == labels).sum()
73
74 loss.backward()
75 optimizer.step()
76
77 if (i + 1)*batch_size % 10000 == 0:
78 loss_mean = np.mean(loss_history)
79 accuracy = ncorrect / ((i + 1) * batch_size)
80 print(
81 f"Epoch [{epoch+1:02d}/{num_epochs}], "
82 f"Step [{(i+1)*batch_size:05d}/{len(train_data)}], "
83 f"Loss: {loss_mean:.4f}, Accuracy: {100*accuracy:.2f}%")
84 print()
85 print(f"Training took {time()-t_start:.2f}s")
86
87 loss_history = []
88 ncorrect = 0
89
90 for i, (images, labels) in enumerate(test_gen):
91 images = Variable(images.view(-1, 28*28))
92 labels = Variable(labels)
93
94 if torch.cuda.is_available():
95 images = images.cuda()
96 labels = labels.cuda()
97
98 outputs = net(images)
99 loss = loss_function(outputs, labels)
100
101 loss_history.append(loss.cpu().data)
102 _, predictions = torch.max(outputs, 1)
103 ncorrect += (predictions == labels).sum().cpu().numpy()
104
105 loss_mean = np.mean(loss_history)
106 loss_uncertainty = np.std(loss_history) / np.sqrt(len(loss_history) - 1)
107 accuracy_mean = ncorrect / (len(test_gen) * batch_size)
108 accuracy_uncertainty = np.sqrt(accuracy_mean * (1.0 - accuracy_mean) / (len(test_gen) * batch_size))
109 print()
110 print(f"Test loss: {loss_mean:.6f}+-{loss_uncertainty:.6f}, Test accuracy: {100*accuracy_mean:.2f}+-{100*accuracy_uncertainty:.2f}%")
111
112 gguf_writer = gguf.GGUFWriter(model_path, "mnist-fc")
113
114 print()
115 print(f"Model tensors saved to {model_path}:")
116 for tensor_name in net.state_dict().keys():
117 data = net.state_dict()[tensor_name].squeeze().cpu().numpy()
118 print(tensor_name, "\t", data.shape)
119 gguf_writer.add_tensor(tensor_name, data)
120
121 gguf_writer.write_header_to_file()
122 gguf_writer.write_kv_data_to_file()
123 gguf_writer.write_tensors_to_file()
124 gguf_writer.close()
125
126
127if __name__ == '__main__':
128 if len(sys.argv) != 2:
129 print(f"Usage: {sys.argv[0]} <model_path>")
130 sys.exit(1)
131 train(sys.argv[1])