Download main2.py from tqphu12421/tf-ddp: direct link, hf CLI and curl.
- Browser
- Download file 7.07 kB
-
https://huggingface.co/tqphu12421/tf-ddp/resolve/main/main2.py
- Command line
-
hf download hf://tqphu12421/tf-ddp/main2.py
-
curl -L -o main2.py https://huggingface.co/tqphu12421/tf-ddp/resolve/main/main2.py
7.07 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 threading | |
| 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 tensorflow.keras.preprocessing.image import ImageDataGenerator | |
| import glob | |
| def build_and_compile_model(img_size): | |
| feature_extractor_layer = hub.KerasLayer( | |
| 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4', | |
| input_shape = img_size + (3,), | |
| trainable = True | |
| ) | |
| model = Sequential([feature_extractor_layer, Dense(5)]) | |
| model.compile( | |
| optimizer = 'adam', | |
| loss = SparseCategoricalCrossentropy(from_logits=True), | |
| metrics = ['accuracy'] | |
| ) | |
| return model | |
| def get_dataset(batch_size, subset, data_length, data_root, imgz): | |
| shuffle = False | |
| length = data_length | |
| dataset = tf.keras.utils.image_dataset_from_directory( | |
| str(data_root), | |
| validation_split = 0, | |
| # subset = subset, | |
| image_size = imgz, | |
| batch_size = batch_size, | |
| seed = 123, | |
| ) | |
| normalization_layer = Rescaling(1./127.5, offset=-1) | |
| dataset = dataset.map(lambda x, y: (normalization_layer(x), y)) | |
| # if shuffle: dataset = dataset.shuffle(buffer_size=length) | |
| # dataset = dataset.cache().prefetch(buffer_size=tf.data.AUTOTUNE) | |
| return dataset, length | |
| def decay(epoch): | |
| if epoch < 3: return 1e-3 | |
| elif epoch >= 3 and epoch < 7: return 1e-4 | |
| return 1e-5 | |
| import numpy as np | |
| 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_model(): | |
| model = tf.keras.Sequential([ | |
| tf.keras.layers.Flatten(), | |
| tf.keras.layers.Dense(10, activation=tf.nn.softmax) | |
| ]) | |
| model.compile( | |
| loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), | |
| optimizer=tf.keras.optimizers.SGD(), | |
| metrics=['accuracy']) | |
| return model | |
| # Define a callback for printing the learning rate at the end of each epoch. | |
| def train_tf_distributed(tf_config, imgz, per_worker, num_workers, global_batch_size, epochs, train_dir): | |
| # cluster_spec = tf.train.ClusterSpec({"worker": ["69.197.168.145:23456"], | |
| # "ps": ["204.12.205.28:23456"]}) | |
| print(tf_config) | |
| cluster_spec = tf.train.ClusterSpec({"worker": tf_config["cluster"]["worker"], | |
| "ps": tf_config["cluster"]["ps"]}) | |
| multi_worker_dataset = mnist_dataset(64) | |
| # data_url = 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz' | |
| # data_root = tf.keras.utils.get_file('flower_photos', data_url, untar=True) | |
| # # data_length = !find {data_root} -name *.jpg | wc -l | |
| # data=glob.glob('{data_root}/**/*.jpg', recursive=True) | |
| # data_length =data.count | |
| # ds_train, num_train = get_dataset(global_batch_size, 'training', data_length, data_root, imgz) | |
| # ds_val, num_val = get_dataset(global_batch_size, 'validation', data_length, data_root, imgz) | |
| cluster_resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(cluster_spec, task_type="ps",task_id=0) | |
| print("Server is prepare start ...") | |
| # Start a TensorFlow server and wait. | |
| server = tf.distribute.Server( | |
| cluster_resolver.cluster_spec(), | |
| job_name = cluster_resolver.task_type, | |
| task_index = cluster_resolver.task_id, | |
| start = True | |
| ) | |
| print("Server is active !!!") | |
| def sever_join(): | |
| server.join() | |
| thread = threading.Thread(target=sever_join, args=()) | |
| thread.start() | |
| if tf_config["task"]["type"] == "worker": | |
| print("Start worker") | |
| # cluster_spec = tf.train.ClusterSpec({"worker": ["69.197.168.145:23456"], | |
| # "ps": ["204.12.205.28:23456"]}) | |
| cluster_resolver = tf.distribute.cluster_resolver.SimpleClusterResolver(cluster_spec, task_type="worker",task_id=0) | |
| strategy = tf.distribute.experimental.ParameterServerStrategy(cluster_resolver) | |
| model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) | |
| with strategy.scope(): | |
| multi_worker_model = build_and_compile_model() | |
| print("chief gets called!") | |
| class PrintLR(tf.keras.callbacks.Callback): | |
| def on_epoch_end(self, epoch, logs=None): | |
| try: | |
| if model.optimizer and model.optimizer.lr: | |
| print(f'\nLearning rate for epoch {epoch + 1} is {model.optimizer.lr.numpy()}') | |
| except: | |
| print("training ...") | |
| callbacks = [ | |
| TensorBoard(log_dir='./logs'), | |
| EarlyStopping(monitor='val_loss', patience=3, verbose=1), | |
| LearningRateScheduler(decay), | |
| PrintLR() | |
| ] | |
| history = multi_worker_model.fit( | |
| multi_worker_dataset, | |
| # validation_data=ds_val, | |
| callbacks=callbacks, | |
| epochs=epochs, | |
| steps_per_epoch=12 | |
| ) | |
| multi_worker_model.save(f"{train_dir}/model.keras") | |
| 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.') | |
| args = parser.parse_args() | |
| tf_config_str = json.loads(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 | |
| ) | |
| if __name__ == '__main__': | |
| main() |