|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Read MNIST data and feed it to a neural network. For a tutorial with |
| 15 | +explanations see: https://google.github.io/sedpack/tutorials/mnist |
| 16 | +
|
| 17 | +Inspired by https://flax.readthedocs.io/en/latest/mnist_tutorial.html |
| 18 | +
|
| 19 | +Example use: |
| 20 | + python mnist_save.py -d "~/Datasets/my_new_dataset/" |
| 21 | + python mnist_read_jax.py -d "~/Datasets/my_new_dataset/" |
| 22 | +""" |
| 23 | +import argparse |
| 24 | +from functools import partial |
| 25 | +from typing import Any |
| 26 | + |
| 27 | +from jax import Array |
| 28 | +from jax.typing import ArrayLike |
| 29 | +from flax import nnx |
| 30 | +import jax.numpy as jnp |
| 31 | +import optax |
| 32 | +from tqdm import tqdm |
| 33 | + |
| 34 | +from sedpack.io import Dataset |
| 35 | + |
| 36 | + |
| 37 | +def process_batch(d: Any) -> dict[str, Array]: |
| 38 | + """Turn the NumPy arrays into JAX arrays and reshape the input to have a |
| 39 | + channel. |
| 40 | + """ |
| 41 | + batch_size: int = d["input"].shape[0] |
| 42 | + return { |
| 43 | + "input": jnp.array(d["input"]).reshape(batch_size, 28, 28, 1), |
| 44 | + "digit": jnp.array(d["digit"], jnp.int32), |
| 45 | + } |
| 46 | + |
| 47 | + |
| 48 | +class CNN(nnx.Module): # type: ignore[misc] |
| 49 | + """FLAX CNN model. |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self, *, rngs: nnx.Rngs) -> None: |
| 53 | + self.conv1 = nnx.Conv(1, 32, kernel_size=(3, 3), rngs=rngs) |
| 54 | + self.conv2 = nnx.Conv(32, 64, kernel_size=(3, 3), rngs=rngs) |
| 55 | + self.avg_pool = partial(nnx.avg_pool, |
| 56 | + window_shape=(2, 2), |
| 57 | + strides=(2, 2)) |
| 58 | + self.linear1 = nnx.Linear(3_136, 256, rngs=rngs) |
| 59 | + self.linear2 = nnx.Linear(256, 10, rngs=rngs) |
| 60 | + |
| 61 | + def __call__(self, x: Array) -> Array: |
| 62 | + x = self.avg_pool(nnx.relu(self.conv1(x))) |
| 63 | + x = self.avg_pool(nnx.relu(self.conv2(x))) |
| 64 | + x = x.reshape(x.shape[0], -1) # flatten |
| 65 | + x = nnx.relu(self.linear1(x)) |
| 66 | + x = self.linear2(x) |
| 67 | + return x |
| 68 | + |
| 69 | + |
| 70 | +def loss_fn(model: CNN, batch: dict[str, Array]) -> tuple[Array, Array]: |
| 71 | + logits = model(batch["input"]) |
| 72 | + loss = optax.softmax_cross_entropy_with_integer_labels( |
| 73 | + logits=logits, labels=batch["digit"]).mean() |
| 74 | + return loss, logits |
| 75 | + |
| 76 | + |
| 77 | +@nnx.jit # type: ignore[misc] |
| 78 | +def train_step(model: CNN, optimizer: nnx.Optimizer, metrics: nnx.MultiMetric, |
| 79 | + batch: dict[str, ArrayLike]) -> None: |
| 80 | + """Train for a single step. |
| 81 | + """ |
| 82 | + grad_fn = nnx.value_and_grad(loss_fn, has_aux=True) |
| 83 | + (loss, logits), grads = grad_fn(model, batch) |
| 84 | + metrics.update(loss=loss, logits=logits, labels=batch["digit"]) |
| 85 | + optimizer.update(grads) |
| 86 | + |
| 87 | + |
| 88 | +@nnx.jit # type: ignore[misc] |
| 89 | +def eval_step( |
| 90 | + model: CNN, |
| 91 | + metrics: nnx.MultiMetric, |
| 92 | + batch: dict[str, Array], |
| 93 | +) -> None: |
| 94 | + loss, logits = loss_fn(model, batch) |
| 95 | + metrics.update(loss=loss, logits=logits, labels=batch["digit"]) |
| 96 | + |
| 97 | + |
| 98 | +def main() -> None: |
| 99 | + """Train a neural network on the MNIST dataset saved in the sedpack |
| 100 | + format. |
| 101 | + """ |
| 102 | + parser = argparse.ArgumentParser( |
| 103 | + description= |
| 104 | + "Read MNIST in dataset-lib format and train a small neural network.") |
| 105 | + parser.add_argument("--dataset_directory", |
| 106 | + "-d", |
| 107 | + help="Where to load the dataset", |
| 108 | + required=True) |
| 109 | + parser.add_argument("--ascii_evaluations", |
| 110 | + "-e", |
| 111 | + help="How many images to print and evaluate", |
| 112 | + type=int, |
| 113 | + default=10) |
| 114 | + args = parser.parse_args() |
| 115 | + |
| 116 | + model = CNN(rngs=nnx.Rngs(0)) |
| 117 | + nnx.display(model) |
| 118 | + |
| 119 | + learning_rate: float = 0.005 |
| 120 | + momentum: float = 0.9 |
| 121 | + optimizer = nnx.Optimizer(model, optax.adamw(learning_rate, momentum)) |
| 122 | + metrics = nnx.MultiMetric( |
| 123 | + accuracy=nnx.metrics.Accuracy(), |
| 124 | + loss=nnx.metrics.Average("loss"), |
| 125 | + ) |
| 126 | + nnx.display(optimizer) |
| 127 | + |
| 128 | + metrics_history: dict[str, list[Array]] = { |
| 129 | + "train_loss": [], |
| 130 | + "train_accuracy": [], |
| 131 | + "test_loss": [], |
| 132 | + "test_accuracy": [], |
| 133 | + } |
| 134 | + |
| 135 | + dataset = Dataset(args.dataset_directory) # Load the dataset |
| 136 | + batch_size = 32 |
| 137 | + train_data = dataset.as_tfdataset( |
| 138 | + "train", |
| 139 | + batch_size=batch_size, |
| 140 | + shuffle=1_000, |
| 141 | + ) |
| 142 | + validation_data = dataset.as_tfdataset( |
| 143 | + "test", # validation split |
| 144 | + batch_size=batch_size, |
| 145 | + shuffle=1_000, |
| 146 | + repeat=False, |
| 147 | + ) |
| 148 | + train_steps: int = 1_200 |
| 149 | + eval_every: int = 200 |
| 150 | + |
| 151 | + for step, batch in enumerate(tqdm(train_data)): |
| 152 | + if step > train_steps: |
| 153 | + break |
| 154 | + |
| 155 | + # Run the optimization for one step and make a stateful update to the |
| 156 | + # following: |
| 157 | + # - The train state's model parameters |
| 158 | + # - The optimizer state |
| 159 | + # - The training loss and accuracy batch metrics |
| 160 | + batch = process_batch(batch) |
| 161 | + train_step(model, optimizer, metrics, batch) |
| 162 | + |
| 163 | + if step > 0 and (step % eval_every == 0 or step |
| 164 | + == train_steps - 1): # One training epoch has passed. |
| 165 | + # Log the training metrics. |
| 166 | + # Compute the metrics. |
| 167 | + for metric, value in metrics.compute().items(): |
| 168 | + # Record the metrics. |
| 169 | + metrics_history[f"train_{metric}"].append(value) |
| 170 | + print(f"{metric} = {value}", end=" ") |
| 171 | + metrics.reset() # Reset the metrics for the test set. |
| 172 | + print() |
| 173 | + |
| 174 | + # Compute the metrics on the test set after each training epoch. |
| 175 | + for test_batch in validation_data.as_numpy_iterator(): |
| 176 | + test_batch = process_batch(test_batch) |
| 177 | + eval_step(model, metrics, test_batch) |
| 178 | + |
| 179 | + # Log the test metrics. |
| 180 | + for metric, value in metrics.compute().items(): |
| 181 | + metrics_history[f"test_{metric}"].append(value) |
| 182 | + print(f"test {metric} = {value}", end=" ") |
| 183 | + metrics.reset() # Reset the metrics for the next training epoch. |
| 184 | + print() |
| 185 | + |
| 186 | + |
| 187 | +if __name__ == "__main__": |
| 188 | + main() |
0 commit comments