|
| 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 | +# flake8: noqa |
| 15 | + |
| 16 | +import os |
| 17 | +os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' |
| 18 | +import tensorflow_datasets as tfds |
| 19 | +import tensorflow as tf |
| 20 | +import keras |
| 21 | +import glob |
| 22 | + |
| 23 | +datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True) |
| 24 | + |
| 25 | +mnist_train, mnist_test = datasets['train'], datasets['test'] |
| 26 | + |
| 27 | +print('******************') |
| 28 | +print('MNIST TRAINING JOB') |
| 29 | +print('******************') |
| 30 | + |
| 31 | +strategy = tf.distribute.MirroredStrategy() |
| 32 | +print('Number of devices: {}'.format(strategy.num_replicas_in_sync)) |
| 33 | +num_train_examples = info.splits['train'].num_examples |
| 34 | +num_test_examples = info.splits['test'].num_examples |
| 35 | + |
| 36 | +BUFFER_SIZE = 10000 |
| 37 | + |
| 38 | +BATCH_SIZE_PER_REPLICA = 64 |
| 39 | +BATCH_SIZE = BATCH_SIZE_PER_REPLICA * strategy.num_replicas_in_sync |
| 40 | + |
| 41 | +def scale(image, label): |
| 42 | + image = tf.cast(image, tf.float32) |
| 43 | + image /= 255 |
| 44 | + |
| 45 | + return image, label |
| 46 | + |
| 47 | +train_dataset = mnist_train.map(scale).cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE) |
| 48 | +eval_dataset = mnist_test.map(scale).batch(BATCH_SIZE) |
| 49 | + |
| 50 | +with strategy.scope(): |
| 51 | + model = keras.Sequential([ |
| 52 | + keras.Input(shape=(28, 28, 1)), |
| 53 | + keras.layers.Conv2D(32, kernel_size=(3, 3), activation="relu"), |
| 54 | + keras.layers.MaxPooling2D(), |
| 55 | + keras.layers.Flatten(), |
| 56 | + keras.layers.Dense(64, activation='relu'), |
| 57 | + keras.layers.Dense(10) |
| 58 | + ]) |
| 59 | + |
| 60 | + model.compile(loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), |
| 61 | + optimizer=keras.optimizers.Adam(), |
| 62 | + metrics=['accuracy']) |
| 63 | + |
| 64 | +# Define the checkpoint directory to store the checkpoints. |
| 65 | +checkpoint_dir = './training_checkpoints' |
| 66 | +# Define the name of the checkpoint files. |
| 67 | +checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}.weights.h5") |
| 68 | + |
| 69 | +def decay(epoch): |
| 70 | + if epoch < 3: |
| 71 | + return 1e-3 |
| 72 | + elif epoch >= 3 and epoch < 7: |
| 73 | + return 1e-4 |
| 74 | + else: |
| 75 | + return 1e-5 |
| 76 | + |
| 77 | +# Define a callback for printing the learning rate at the end of each epoch. |
| 78 | +class PrintLR(keras.callbacks.Callback): |
| 79 | + def on_epoch_end(self, epoch, logs=None): |
| 80 | + print('\nLearning rate for epoch {} is {}'.format(epoch + 1, |
| 81 | + model.optimizer.learning_rate.numpy())) |
| 82 | + |
| 83 | +callbacks = [ |
| 84 | + tf.keras.callbacks.TensorBoard(log_dir='./logs'), |
| 85 | + tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_prefix, |
| 86 | + save_weights_only=True), |
| 87 | + tf.keras.callbacks.LearningRateScheduler(decay), |
| 88 | + PrintLR() |
| 89 | +] |
| 90 | + |
| 91 | +EPOCHS = 12 |
| 92 | + |
| 93 | +model.fit(train_dataset, epochs=EPOCHS, callbacks=callbacks) |
| 94 | + |
| 95 | +# Function to find the latest .h5 file |
| 96 | +def find_latest_h5_checkpoint(checkpoint_dir): |
| 97 | + list_of_files = glob.glob(f'{checkpoint_dir}/*.h5') |
| 98 | + if list_of_files: |
| 99 | + latest_file = max(list_of_files, key=os.path.getctime) |
| 100 | + return latest_file |
| 101 | + else: |
| 102 | + return None |
| 103 | + |
| 104 | +model.load_weights(find_latest_h5_checkpoint(checkpoint_dir)) |
| 105 | + |
| 106 | +eval_loss, eval_acc = model.evaluate(eval_dataset) |
| 107 | + |
| 108 | +print('Eval loss: {}, Eval accuracy: {}'.format(eval_loss, eval_acc)) |
| 109 | + |
| 110 | +path = '/data/mnist_saved_model' |
| 111 | +os.makedirs(path, exist_ok=True) |
| 112 | + |
| 113 | +model_file = '/data/mnist_saved_model/mnist.keras' |
| 114 | +model.save(model_file) |
| 115 | + |
| 116 | +print('Training finished. Model saved') |
| 117 | + |
0 commit comments