File size: 9,054 Bytes
54ff1bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | # -*- 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()
])
# %load_ext tensorboard
"""# Multi-worker configuration"""
# gpu_devices = tf.config.list_physical_devices('GPU')
# if len(gpu_devices) == 0: raise SystemError('GPU device not found')
# for gpu in gpu_devices:
# tf.config.experimental.set_memory_growth(gpu, True)
# tf_config = {
# 'cluster': {
# 'worker': ['127.0.0.1:12345']
# },
# 'task': {'type': 'worker', 'index': 0}
# }
# os.environ.pop('TF_CONFIG', None)
# os.environ['TF_CONFIG'] = json.dumps(tf_config)
# IMAGE_SIZE = (224, 224)
# PER_WORKER_BATCH_SIZE = 32
# NUM_WORKERS = len(tf_config['cluster']['worker'])
# GLOBAL_BATCH_SIZE = PER_WORKER_BATCH_SIZE * NUM_WORKERS
# EPOCHS = 100
def train_tf_distributed(tf_config, imgz, per_worker, num_workers, global_batch_size, epochs, train_dir, dataset_path):
strategy = tf.distribute.MultiWorkerMirroredStrategy(
communication_options = tf.distribute.experimental.CommunicationOptions(
implementation = tf.distribute.experimental.CollectiveCommunication.RING
))
# dataset_path = "/app/datasets/20240626-100113"
if not dataset_path or dataset_path=="data":
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(f'{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)
else:
train_images_dir = f'{dataset_path}/train'
train_annotations_file = f'{dataset_path}/train/_annotations.coco.json'
valid_images_dir = f'{dataset_path}/valid'
valid_annotations_file = f'{dataset_path}/val/_annotations.coco.json'
if not os.path.exists(valid_images_dir):
valid_images_dir = f'{dataset_path}/test'
valid_annotations_file = f'{dataset_path}/test/_annotations.coco.json'
category_index = create_category_index(train_annotations_file)
ds_train = load_coco_dataset(train_annotations_file, train_images_dir, imgz, category_index, global_batch_size)
ds_val = load_coco_dataset(valid_annotations_file, valid_images_dir, imgz, category_index, global_batch_size)
strategy = tf.distribute.MultiWorkerMirroredStrategy(
communication_options = tf.distribute.experimental.CommunicationOptions(
implementation = tf.distribute.experimental.CollectiveCommunication.RING
))
with strategy.scope():
model = build_and_compile_model(imgz)
model.summary()
class PrintLR(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
print(f'\nLearning rate for epoch {epoch + 1} is {model.optimizer.lr.numpy()}')
logging.info(f'\nLearning rate for epoch {epoch + 1} is {model.optimizer.lr.numpy()}')
callbacks = [
TensorBoard(log_dir='./logs'),
EarlyStopping(monitor='val_loss', patience=3, verbose=1),
LearningRateScheduler(decay),
PrintLR()
]
"""# Training"""
# Commented out IPython magic to ensure Python compatibility.
history = model.fit(
ds_train,
validation_data = ds_val,
callbacks = callbacks,
epochs = epochs,
verbose = 1,
)
model.save(f"{train_dir}/model.hdf5")
def get_dataset(batch_size, subset, data_length, data_root, imgz):
shuffle = False
length = data_length
# if subset == 'validation': length = int(data_length * 1)
# elif subset == 'training':
# length = data_length#int(data_length * 1)
# shuffle = True
# else:
# raise NameError("subset must be 'training' or 'validation'")
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 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
"""## Callbacks"""
def decay(epoch):
if epoch < 3: return 1e-3
elif epoch >= 3 and epoch < 7: return 1e-4
return 1e-5
def create_category_index(coco_annotation_file):
coco = COCO(coco_annotation_file)
category_ids = coco.getCatIds()
category_ids.sort()
category_index = {cat_id: idx for idx, cat_id in enumerate(category_ids)}
return category_index
def load_coco_dataset(coco_annotation_file, img_dir, img_size, category_index, batch_size=32):
coco = COCO(coco_annotation_file)
img_ids = coco.getImgIds()
img_info = coco.loadImgs(img_ids)
def load_image(img_info):
img_path = os.path.join(img_dir, img_info['file_name'])
img = tf.io.read_file(img_path)
img = tf.image.decode_jpeg(img, channels=3)
img = tf.image.resize(img, img_size)
img = img / 255.0
return img
def load_annotations(img_info):
ann_ids = coco.getAnnIds(imgIds=img_info['id'])
anns = coco.loadAnns(ann_ids)
# Assume single annotation per image for simplicity
if anns:
category_id = anns[0]['category_id']
label = category_index.get(category_id, -1)
if label != -1 and label < 5: # Ensure label is within valid range
return label
return -1
def data_generator():
for info in img_info:
img = load_image(info)
label = load_annotations(info)
if label != -1: # Skip images without valid annotations
yield img, label
dataset = tf.data.Dataset.from_generator(
data_generator,
output_signature=(
tf.TensorSpec(shape=img_size + (3,), dtype=tf.float32),
tf.TensorSpec(shape=(), dtype=tf.int64)
)
)
dataset = dataset.shuffle(len(img_info))
dataset = dataset.batch(batch_size)
return dataset
# Define a callback for printing the learning rate at the end of each epoch.
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()
|