pingsutw commented on a change in pull request #700: URL: https://github.com/apache/submarine/pull/700#discussion_r695522589
########## File path: dev-support/examples/mnist-tensorflow/ParameterServerStrategy/mnist_keras_distributed.py ########## @@ -0,0 +1,92 @@ +""" + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +""" +import os +import random +import tensorflow as tf +import json +from tensorflow.keras.layers.experimental import preprocessing +import tensorflow_datasets as tfds +import tensorboard + +print(tf.__version__) + +TF_CONFIG = os.environ.get('TF_CONFIG', '') +NUM_PS = len(json.loads(TF_CONFIG)['cluster']['ps']) +cluster_resolver = tf.distribute.cluster_resolver.TFConfigClusterResolver() + +variable_partitioner = ( + tf.distribute.experimental.partitioners.MinSizePartitioner( + min_shard_bytes=(256 << 10), + max_shards=NUM_PS)) + +strategy = tf.distribute.experimental.ParameterServerStrategy( + cluster_resolver, + variable_partitioner=variable_partitioner) + +def dataset_fn(input_context): + global_batch_size = 64 + batch_size = input_context.get_per_replica_batch_size(global_batch_size) + + x = tf.random.uniform((10, 10)) + y = tf.random.uniform((10,)) + + dataset = tf.data.Dataset.from_tensor_slices((x, y)).shuffle(10).repeat() + dataset = dataset.shard( + input_context.num_input_pipelines, + input_context.input_pipeline_id) + dataset = dataset.batch(batch_size) + dataset = dataset.prefetch(2) + + return dataset + +dc = tf.keras.utils.experimental.DatasetCreator(dataset_fn) + +with strategy.scope(): + model = tf.keras.models.Sequential([tf.keras.layers.Dense(10)]) + +model.compile(tf.keras.optimizers.SGD(), loss='mse', steps_per_execution=10) + +working_dir = '/tmp/my_working_dir' +log_dir = os.path.join(working_dir, 'log') +ckpt_filepath = os.path.join(working_dir, 'ckpt') +backup_dir = os.path.join(working_dir, 'backup') + +callbacks = [ + tf.keras.callbacks.TensorBoard(log_dir=log_dir), + tf.keras.callbacks.ModelCheckpoint(filepath=ckpt_filepath), + tf.keras.callbacks.experimental.BackupAndRestore(backup_dir=backup_dir), +] + +model.fit(dc, epochs=5, steps_per_epoch=20, callbacks=callbacks) +if __name__ == "__main__": + modelClient = ModelsClient() + with modelClient.start() as run: + EPOCHS = 5 + hist = model.fit(dc, epochs=EPOCHS, steps_per_epoch=20, callbacks=callbacks) + for i in range(EPOCHS): + modelClient.log_metric("val_loss", hist.history['loss'][i]) + modelClient.log_metric("Val_accuracy", hist.history['accuracy'][i]) + model.load_weights(tf.train.latest_checkpoint(checkpoint_dir)) + # eval_loss, eval_acc = model.evaluate(eval_dataset) + # print('Eval loss: {}, Eval accuracy: {}'.format(eval_loss, eval_acc)) + # modelClient.log_param("loss", eval_loss) + # modelClient.log_param("acc", eval_acc) Review comment: Could we remove these lines? ########## File path: dev-support/examples/mnist-tensorflow/MultiWorkerMirroredStrategy/mnist_keras_distributed.py ########## @@ -0,0 +1,98 @@ +""" + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +""" +from submarine import ModelsClient +import json +import os +import sys +import tensorflow as tf +import numpy as np +import tensorflow_datasets as tfds + +BUFFER_SIZE = 10000 +BATCH_SIZE = 32 + +strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() + +def make_datasets_unbatched(): + #Scaling MNIST data from (0, 255] to (0., 1.] + def scale(image, label): + image = tf.cast(image, tf.float32) + image /= 255 + return image, label + + datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True) + + return datasets['train'].map(scale, num_parallel_calls=tf.data.experimental.AUTOTUNE).cache().shuffle(BUFFER_SIZE) + +def build_and_compile_cnn_model(): + model = tf.keras.Sequential([ + tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)), + tf.keras.layers.MaxPooling2D(), + tf.keras.layers.Flatten(), + tf.keras.layers.Dense(64, 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 + +#single_worker_model = build_and_compile_cnn_model() +#single_worker_model.fit(x=train_datasets, epochs=3, steps_per_epoch=5) Review comment: Could we remove these lines? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
