Download main3.py from tqphu12421/tf-ddp: direct link, hf CLI and curl.
- Browser
- Download file 3.98 kB
-
https://huggingface.co/tqphu12421/tf-ddp/resolve/main/main3.py
- Command line
-
hf download hf://tqphu12421/tf-ddp/main3.py
-
curl -L -o main3.py https://huggingface.co/tqphu12421/tf-ddp/resolve/main/main3.py
3.98 kB
| # -*- coding: utf-8 -*- | |
| """flowers.ipynb | |
| Automatically generated by Colab. | |
| Original file is located at | |
| https://colab.research.google.com/drive/1B7pZ7W74ROe0QjtBbP4fJ3IvhZc0e7jl | |
| """ | |
| # Commented out IPython magic to ensure Python compatibility. | |
| import os | |
| import json | |
| import tensorflow as tf | |
| import tensorflow_hub as hub | |
| from tensorflow.keras import Sequential | |
| from tensorflow.keras.layers import Dense | |
| from tensorflow.keras.losses import SparseCategoricalCrossentropy | |
| from tensorflow.keras.layers import Rescaling | |
| from tensorflow.keras.callbacks import TensorBoard, EarlyStopping, LearningRateScheduler | |
| from pycocotools.coco import COCO | |
| import numpy as np | |
| import glob | |
| import logging | |
| logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ | |
| logging.FileHandler("{0}/{1}.log".format("logs", "tensorflow-ddp")), | |
| logging.StreamHandler() | |
| ]) | |
| def mnist_dataset(batch_size): | |
| (x_train, y_train), _ = tf.keras.datasets.mnist.load_data() | |
| # The `x` arrays are in uint8 and have values in the [0, 255] range. | |
| # You need to convert them to float32 with values in the [0, 1] range. | |
| x_train = x_train / np.float32(255) | |
| y_train = y_train.astype(np.int64) | |
| train_dataset = tf.data.Dataset.from_tensor_slices( | |
| (x_train, y_train)).shuffle(60000).repeat().batch(batch_size) | |
| return train_dataset | |
| def build_and_compile_cnn_model(): | |
| model = tf.keras.Sequential([ | |
| tf.keras.layers.InputLayer(input_shape=(28, 28)), | |
| tf.keras.layers.Reshape(target_shape=(28, 28, 1)), | |
| tf.keras.layers.Conv2D(32, 3, activation='relu'), | |
| tf.keras.layers.Flatten(), | |
| tf.keras.layers.Dense(128, activation='relu'), | |
| tf.keras.layers.Dense(10) | |
| ]) | |
| model.compile( | |
| loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), | |
| optimizer=tf.keras.optimizers.SGD(learning_rate=0.001), | |
| metrics=['accuracy']) | |
| return model | |
| def train_tf_distributed(tf_config, imgz, per_worker, num_workers, global_batch_size, epochs, train_dir, dataset_path): | |
| per_worker_batch_size = 2 | |
| tf_config = json.loads(os.environ['TF_CONFIG']) | |
| num_workers = len(tf_config['cluster']['worker']) | |
| strategy = tf.distribute.MultiWorkerMirroredStrategy() | |
| global_batch_size = per_worker_batch_size * num_workers | |
| multi_worker_dataset = mnist_dataset(global_batch_size) | |
| with strategy.scope(): | |
| # Model building/compiling need to be within `strategy.scope()`. | |
| multi_worker_model = build_and_compile_cnn_model() | |
| multi_worker_model.fit(multi_worker_dataset, epochs=epochs, steps_per_epoch=70) | |
| def main(): | |
| import argparse | |
| import ast | |
| parser = argparse.ArgumentParser(description='Train TensorFlow distributed model.') | |
| parser.add_argument('--tf_config', required=True, help='TF_CONFIG environment variable JSON string.') | |
| parser.add_argument('--imgz', type=str, required=True, help='Image size.') | |
| parser.add_argument('--per_worker', type=int, required=True, help='Number of images per worker.') | |
| parser.add_argument('--num_workers', type=int, required=True, help='Number of workers.') | |
| parser.add_argument('--global_batch_size', type=int, required=True, help='Global batch size.') | |
| parser.add_argument('--epochs', type=int, required=True, help='Number of epochs.') | |
| parser.add_argument('--train_dir', required=True, help='Directory to save the trained model.') | |
| parser.add_argument('--dataset_path', required=True, help='Directory to save the trained model.') | |
| args = parser.parse_args() | |
| tf_config_str = json.dumps(args.tf_config) # Chuyển đổi dict thành chuỗi JSON | |
| imgz_tuple = ast.literal_eval(args.imgz) | |
| train_tf_distributed( | |
| tf_config_str, | |
| imgz_tuple, | |
| args.per_worker, | |
| args.num_workers, | |
| args.global_batch_size, | |
| args.epochs, | |
| args.train_dir, | |
| args.dataset_path | |
| ) | |
| if __name__ == '__main__': | |
| main() | |