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-cnn.py

91 lines · 3296 bytes Raw Blame History
1#!/usr/bin/env python3
2import sys
3from time import time
4import gguf
5import numpy as np
6import tensorflow as tf
7from tensorflow import keras
8from tensorflow.keras import layers
9
10
11def train(model_path):
12 # Model / data parameters
13 num_classes = 10
14 input_shape = (28, 28, 1)
15
16 # Load the data and split it between train and test sets
17 (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
18
19 # Scale images to the [0, 1] range
20 x_train = x_train.astype("float32") / 255
21 x_test = x_test.astype("float32") / 255
22 x_train = np.expand_dims(x_train, -1)
23 x_test = np.expand_dims(x_test, -1)
24 print("x_train shape:", x_train.shape)
25 print(x_train.shape[0], "train samples")
26 print(x_test.shape[0], "test samples")
27
28 # convert class vectors to binary class matrices
29 y_train = keras.utils.to_categorical(y_train, num_classes)
30 y_test = keras.utils.to_categorical(y_test, num_classes)
31
32 model = keras.Sequential(
33 [
34 keras.Input(shape=input_shape, dtype=tf.float32),
35 layers.Conv2D(8, kernel_size=(3, 3), padding="same", activation="relu", dtype=tf.float32),
36 layers.MaxPooling2D(pool_size=(2, 2)),
37 layers.Conv2D(16, kernel_size=(3, 3), padding="same", activation="relu", dtype=tf.float32),
38 layers.MaxPooling2D(pool_size=(2, 2)),
39 layers.Flatten(),
40 layers.Dense(num_classes, activation="softmax", dtype=tf.float32),
41 ]
42 )
43
44 model.summary()
45 batch_size = 1000
46 epochs = 30
47 model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
48
49 t_start = time()
50 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)
51 print(f"Training took {time()-t_start:.2f}s")
52
53 score = model.evaluate(x_test, y_test, verbose=0)
54 print(f"Test loss: {score[0]:.6f}")
55 print(f"Test accuracy: {100*score[1]:.2f}%")
56
57 gguf_writer = gguf.GGUFWriter(model_path, "mnist-cnn")
58
59 conv1_kernel = model.layers[0].weights[0].numpy()
60 conv1_kernel = np.moveaxis(conv1_kernel, [2, 3], [0, 1])
61 gguf_writer.add_tensor("conv1.kernel", conv1_kernel, raw_shape=(8, 1, 3, 3))
62
63 conv1_bias = model.layers[0].weights[1].numpy()
64 gguf_writer.add_tensor("conv1.bias", conv1_bias, raw_shape=(1, 8, 1, 1))
65
66 conv2_kernel = model.layers[2].weights[0].numpy()
67 conv2_kernel = np.moveaxis(conv2_kernel, [0, 1, 2, 3], [2, 3, 1, 0])
68 gguf_writer.add_tensor("conv2.kernel", conv2_kernel, raw_shape=(16, 8, 3, 3))
69
70 conv2_bias = model.layers[2].weights[1].numpy()
71 gguf_writer.add_tensor("conv2.bias", conv2_bias, raw_shape=(1, 16, 1, 1))
72
73 dense_weight = model.layers[-1].weights[0].numpy()
74 dense_weight = dense_weight.transpose()
75 gguf_writer.add_tensor("dense.weight", dense_weight, raw_shape=(10, 7*7*16))
76
77 dense_bias = model.layers[-1].weights[1].numpy()
78 gguf_writer.add_tensor("dense.bias", dense_bias)
79
80 gguf_writer.write_header_to_file()
81 gguf_writer.write_kv_data_to_file()
82 gguf_writer.write_tensors_to_file()
83 gguf_writer.close()
84 print(f"GGUF model saved to '{model_path}'")
85
86
87if __name__ == '__main__':
88 if len(sys.argv) != 2:
89 print(f"Usage: {sys.argv[0]} <model_path>")
90 sys.exit(1)
91 train(sys.argv[1])