- 
                Notifications
    You must be signed in to change notification settings 
- Fork 6.9k
[New Example] Tensorflow Multi Worker Mirrored Strategy Distributed Training #4721
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            kandakji
  wants to merge
  14
  commits into
  aws:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
kandakji:master
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from 8 commits
      Commits
    
    
            Show all changes
          
          
            14 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      a821fa6
              
                Create mnist.py script
              
              
                kandakji aaa64d3
              
                Create mnist-distributed.py script
              
              
                kandakji 7034c2f
              
                Update mnist-distributed.py
              
              
                kandakji f01cd02
              
                Create tensorflow_multi_worker_mirrored_strategy.ipynb
              
              
                kandakji 332401e
              
                lint mnist-distributed.py
              
              
                kandakji e57404d
              
                Update tensorflow_multi_worker_mirrored_strategy.ipynb
              
              
                kandakji 30abe06
              
                Update distributed_training index.rst
              
              
                kandakji 08cec8f
              
                Update main README.md
              
              
                kandakji 9815556
              
                Update mnist.py dataset
              
              
                kandakji c3f22ce
              
                Update mnist-distributed.py dataset
              
              
                kandakji f9de3ce
              
                Update tensorflow_multi_worker_mirrored_strategy.ipynb dataset
              
              
                kandakji fd7f3f6
              
                Update tensorflow_multi_worker_mirrored_strategy.ipynb badges
              
              
                kandakji dd8a396
              
                Update sagemaker SDK in tensorflow_multi_worker_mirrored_strategy.ipynb
              
              
                kandakji 169c787
              
                downgrade TF version for PR test tensorflow_multi_worker_mirrored_str…
              
              
                kandakji File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            104 changes: 104 additions & 0 deletions
          
          104 
        
  training/distributed_training/tensorflow/multi_worker_mirrored_strategy/mnist-distributed.py
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"). You | ||
| # may not use this file except in compliance with the License. A copy of | ||
| # the License is located at | ||
| # | ||
| # http://aws.amazon.com/apache2.0/ | ||
| # | ||
| # or in the "license" file accompanying this file. This file 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 tensorflow as tf | ||
|  | ||
| import argparse | ||
| import json | ||
| import os | ||
|  | ||
| import numpy as np | ||
| import tensorflow as tf | ||
|  | ||
|  | ||
| def model(x_train, y_train, x_test, y_test, strategy): | ||
| """Generate a simple model""" | ||
| with strategy.scope(): | ||
|  | ||
| model = tf.keras.models.Sequential( | ||
| [ | ||
| tf.keras.layers.Flatten(), | ||
| tf.keras.layers.Dense(1024, activation=tf.nn.relu), | ||
| tf.keras.layers.Dropout(0.4), | ||
| tf.keras.layers.Dense(10, activation=tf.nn.softmax), | ||
| ] | ||
| ) | ||
|  | ||
| model.compile( | ||
| optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"] | ||
| ) | ||
|  | ||
| model.fit(x_train, y_train) | ||
| model.evaluate(x_test, y_test) | ||
|  | ||
| return model | ||
|  | ||
|  | ||
| def _load_training_data(base_dir): | ||
| """Load MNIST training data""" | ||
| x_train = np.load(os.path.join(base_dir, "train_data.npy")) | ||
| y_train = np.load(os.path.join(base_dir, "train_labels.npy")) | ||
| return x_train, y_train | ||
|  | ||
|  | ||
| def _load_testing_data(base_dir): | ||
| """Load MNIST testing data""" | ||
| x_test = np.load(os.path.join(base_dir, "eval_data.npy")) | ||
|         
                  kandakji marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| y_test = np.load(os.path.join(base_dir, "eval_labels.npy")) | ||
| return x_test, y_test | ||
|  | ||
|  | ||
| def _parse_args(): | ||
| parser = argparse.ArgumentParser() | ||
|  | ||
| # Data, model, and output directories | ||
| # model_dir is always passed in from SageMaker. By default this is a S3 path under the default bucket. | ||
| parser.add_argument("--model_dir", type=str) | ||
| parser.add_argument("--sm-model-dir", type=str, default=os.environ.get("SM_MODEL_DIR")) | ||
| parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAINING")) | ||
| parser.add_argument("--hosts", type=list, default=json.loads(os.environ.get("SM_HOSTS"))) | ||
| parser.add_argument("--current-host", type=str, default=os.environ.get("SM_CURRENT_HOST")) | ||
|  | ||
| return parser.parse_known_args() | ||
|  | ||
|  | ||
| if __name__ == "__main__": | ||
| args, unknown = _parse_args() | ||
|  | ||
| train_data, train_labels = _load_training_data(args.train) | ||
| eval_data, eval_labels = _load_testing_data(args.train) | ||
|  | ||
| print("Tensorflow version: ", tf.__version__) | ||
| print("TF_CONFIG", os.environ.get("TF_CONFIG")) | ||
|  | ||
| communication_options = tf.distribute.experimental.CommunicationOptions( | ||
| implementation=tf.distribute.experimental.CommunicationImplementation.NCCL | ||
| ) | ||
| strategy = tf.distribute.MultiWorkerMirroredStrategy( | ||
| communication_options=communication_options | ||
| ) | ||
|  | ||
| print("Number of devices: {}".format(strategy.num_replicas_in_sync)) | ||
|  | ||
| mnist_classifier = model(train_data, train_labels, eval_data, eval_labels, strategy) | ||
|  | ||
| task_type, task_id = (strategy.cluster_resolver.task_type, strategy.cluster_resolver.task_id) | ||
|  | ||
| print("Task type: ", task_type) | ||
| print("Task id: ", task_id) | ||
|  | ||
| # Save the model on chief worker | ||
| if strategy.cluster_resolver.task_id == 0: | ||
| print("Saving model on chief") | ||
| mnist_classifier.save(os.path.join(args.sm_model_dir, "000000001")) | ||
| else: | ||
| print("Saving model in /tmp on worker") | ||
| mnist_classifier.save(f"/tmp/{strategy.cluster_resolver.task_id}") | ||
        
          
          
            79 changes: 79 additions & 0 deletions
          
          79 
        
  training/distributed_training/tensorflow/multi_worker_mirrored_strategy/mnist.py
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"). You | ||
| # may not use this file except in compliance with the License. A copy of | ||
| # the License is located at | ||
| # | ||
| # http://aws.amazon.com/apache2.0/ | ||
| # | ||
| # or in the "license" file accompanying this file. This file 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 tensorflow as tf | ||
|  | ||
| import argparse | ||
| import json | ||
| import os | ||
|  | ||
| import numpy as np | ||
| import tensorflow as tf | ||
|  | ||
|  | ||
| def model(x_train, y_train, x_test, y_test): | ||
| """Generate a simple model""" | ||
| model = tf.keras.models.Sequential( | ||
| [ | ||
| tf.keras.layers.Flatten(), | ||
| tf.keras.layers.Dense(1024, activation=tf.nn.relu), | ||
| tf.keras.layers.Dropout(0.4), | ||
| tf.keras.layers.Dense(10, activation=tf.nn.softmax), | ||
| ] | ||
| ) | ||
|  | ||
| model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) | ||
| model.fit(x_train, y_train) | ||
| model.evaluate(x_test, y_test) | ||
|  | ||
| return model | ||
|  | ||
|  | ||
| def _load_training_data(base_dir): | ||
| """Load MNIST training data""" | ||
| x_train = np.load(os.path.join(base_dir, "train_data.npy")) | ||
|         
                  kandakji marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| y_train = np.load(os.path.join(base_dir, "train_labels.npy")) | ||
| return x_train, y_train | ||
|  | ||
|  | ||
| def _load_testing_data(base_dir): | ||
| """Load MNIST testing data""" | ||
| x_test = np.load(os.path.join(base_dir, "eval_data.npy")) | ||
|         
                  kandakji marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| y_test = np.load(os.path.join(base_dir, "eval_labels.npy")) | ||
| return x_test, y_test | ||
|  | ||
|  | ||
| def _parse_args(): | ||
| parser = argparse.ArgumentParser() | ||
|  | ||
| # Data, model, and output directories | ||
| # model_dir is always passed in from SageMaker. By default this is a S3 path under the default bucket. | ||
| parser.add_argument("--model_dir", type=str) | ||
| parser.add_argument("--sm-model-dir", type=str, default=os.environ.get("SM_MODEL_DIR")) | ||
| parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAINING")) | ||
| parser.add_argument("--hosts", type=list, default=json.loads(os.environ.get("SM_HOSTS"))) | ||
| parser.add_argument("--current-host", type=str, default=os.environ.get("SM_CURRENT_HOST")) | ||
|  | ||
| return parser.parse_known_args() | ||
|  | ||
|  | ||
| if __name__ == "__main__": | ||
| args, unknown = _parse_args() | ||
|  | ||
| train_data, train_labels = _load_training_data(args.train) | ||
| eval_data, eval_labels = _load_testing_data(args.train) | ||
|  | ||
| mnist_classifier = model(train_data, train_labels, eval_data, eval_labels) | ||
|  | ||
| if args.current_host == args.hosts[0]: | ||
| # save model to an S3 directory with version number '00000001' in Tensorflow SavedModel Format | ||
| # To export the model as h5 format use model.save('my_model.h5') | ||
| mnist_classifier.save(os.path.join(args.sm_model_dir, "000000001")) | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.