Skip to content

Design proposal for training - #3

Closed
mvsusp wants to merge 9 commits into
mvs/mvs-add-setupfrom
mvs-design-decisions-for-training
Closed

mvsusp wants to merge 9 commits into
mvs/mvs-add-setupfrom
mvs-design-decisions-for-training

Conversation

@mvsusp

@mvsusp mvsusp commented Apr 5, 2018 •

Copy link
Copy Markdown
Owner

Amazon SageMaker Containers

SageMaker Containers is the open source library that the SageMaker team uses to create the open source containers
that run on Amazon SageMaker:

You can use SageMaker Containers as a library with helper functions for your training script or to
create your own ML framework container compatible with SageMaker.

Install

Installing from source

pip install -U .

Getting started

Using it as a library

sagemaker_containers.training_environment contains information about the training container including:
hyperparameters, instance information (number of CPUs, GPUs, host name), input data information, environment
variables, etc.

Let's suppose that you want to train the Keras script below in SageMaker:
my_training_script.py

import argparse
import os

import numpy as np
import tensorflow as tf

parser = argparse.ArgumentParser()
parser.add_argument('--training-data-dir', type=str)
parser.add_argument('--batch-size', type=int)
parser.add_argument('--model-dir', type=str)

args = parser.parse_args()

data = np.load(os.path.join(args.training_data_dir, 'training_data.npz'))
x_train, y_train = data['features'], keras.utils.to_categorical(data['labels'])

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(64, activation='relu', input_dim=20))
model.add(tf.keras.layers.Dropout(0.5))

sgd = tf.keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

model.fit(x_train, y_train, epochs=20, batch_size=args.batch_size)

# saves the model in the end of training
model.save(os.path.join(args.model_dir, 'saved_model.h5'))

To be able to train the script above in SageMaker, you need to provide the parameters --training-data-dir,
--batch-size, --model-dir. training_environment makes this process very easy:

import sagemaker_containers.training_environment as env
...

# TODO (mvsusp) - create env.training_data_dir and env.evaluation_data_dir helpers
parser.add_argument('--training-data-dir', type=str, default=env.training_data_dir)
parser.add_argument('--batch-size', type=int, default=env.batch_size)
parser.add_argument('--model-dir', type=str, default=env.model_dir)

We can use SageMaker Python SDK to submit my_training_script.py to
trainining using the TensorFlow estimator:

# TODO (mvsusp) - allow sagemaker-python-sdk estimator to work in the scenario below
from sagemaker.tensorflow import TensorFlow

estimator = TensorFlow('train.py', role='SageMakerRole', 
                       train_instance_type='ml.p2.xlarge', train_instance_count = 1)
estimator.fit({'training': 's3://my/bucket/with/the/training/data'})

Creating a new ML framework container compatible with SageMaker Training

The core training structure of SageMaker Containers is Training. When training starts, e.g.
training.run(), the Training instance executes the following steps:

  1. install any required python dependencies
  2. start customs metrics that will be reported to CloudWatch Logs
  3. load SageMaker Training environment information, including default configuration files, directories,
    environment variables, and hyperparameters
  4. download the user script (or Python package) containing the functions required by the framework
  5. start the training process
  6. report success/failure

Let's suppose that we want to create a Keras Container that trains any Keras model provided by the user script.

Let's suppose that to be able to use our Containers, users need to submit a Python script containing a function with
the following signature:

def train(training_dir, hyperparameters):
    """Return a Keras model that will be trained by our SageMaker Keras container.
    
    Args:
        - training_dir (string): the path to the directory containing the training 
            data provided by the user.
        - hyperparameters (dict[string, object]): a map containing the hyperparameters 
            provided by the user.
         
    Returns:
        - (Keras.Model): the model that will be saved in the end of the training.
    """

Implementing our Keras Framework Container

Training will install the user provided script as a module, and prepare the training environment for us. All we
have to do is implement a function, training_process_fn, which implements the training process of our framework.

training_process_fn takes as parameters user module and the training environment, and is responsible to
save the trained model in end of training:

import os

from sagemaker_containers import Training

def keras_framework_training_process(user_module, training_environment):
    """This function implements our Keras Framework.
    
    Args:
        - user_module (module): the python script provided by the user loaded as a Python ```module```
        - training_environment (sagemaker_containers.TrainingEnvironment): the container's 
            training environment
    """
    # retrieves the training dir from training channels
    training_dir = training_environment.channel_input_dirs['training']
    
    # retrieves the hyperparameters submitted by the user
    hps = training_environment.hyperparameters
    
    # invokes user's ```train``` function
    model = user_module.train(training_dir, hps)
    
    # saves the model in the end of training
    model.save(os.path.join(training_environment.model_dir, 'saved_model.h5'))

# Creates the training from the training process function and start training.
Training.from_train_fn(train_fn=keras_framework_training_process).run()

#TODO (mvsusp) - complete the example after implementing support for Docker containers.

An example of user provided script for training:

train.py

import os

import keras
import numpy as np

def train(training_dir, hyperparameters):
    data = np.load(os.path.join(training_dir, hyperparameters['training_data_file']))
    x_train, y_train = data['features'], keras.utils.to_categorical(data['labels'])

    model = keras.models.Sequential()
    model.add(keras.layers.Dense(64, activation='relu', input_dim=20))
    model.add(keras.layers.Dropout(0.5))

    sgd = keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

    model.fit(x_train, y_train, epochs=20, batch_size=128)
    return model

Submitting a Python script for training using our Keras container

We can use SageMaker Python SDK to submit a scripts to our
containers:

# TODO (mvsusp) - allow sagemaker-python-sdk estimator to work in the scenario below
from sagemaker.estimator import Estimator

estimator = Estimator('train.py', role='SageMakerRole', 
                      train_instance_type='ml.p2.xlarge', train_instance_count = 1)
estimator.fit({'training': 's3://my/bucket/with/the/training/data'})

You can look at more information on how to use SageMaker Python SDK here: https://github.com/aws/sagemaker-python-sdk#byo-docker-containers-with-sagemaker-estimators.

@jesterhazy

jesterhazy commented Apr 5, 2018 •

Copy link
Copy Markdown
Collaborator
  • framework code expects user code to return a model, but example user code doesn't return. actually user code isn't a function at all.
  • mxnet containers use return value from train to decide whether to call save function, and that function expects the value to be a Module/gluon network
  • save_model treats model as a dict... but this would usually be a model/network of some kind, at least for mxnet users
  • why do we need to set 'saved' key on model at all?

@mvsusp

mvsusp commented Apr 5, 2018

Copy link
Copy Markdown
Owner Author

About @jesterhazy considerations:

  1. user code actually returns a model. The user code example mentioned is:
def train(chanel_dirs, hps): 
    return {'trained': True, 'saved': False}
  1. you are correct that train should return model. That is not going to change. I will add more documentation and design pictures to explain better
  2. saving a model is framework specific. The example above is just a mock ML framework that saves a dict as a model
  3. that is framework specific as well. I will add another example in the docs to clarify your doubts.

@jesterhazy

Copy link
Copy Markdown
Collaborator

i was looking at training_module/train.py under User Module. what's the relation between that and user script?

@mvsusp

mvsusp commented Apr 5, 2018 •

Copy link
Copy Markdown
Owner Author

@jesterhazy
Users can provide a def train(...): that returns a model.
In addition to that, users can provide a python package, that will be executed in the container with the follow command: python -m {module_name}.
The latter option allows users to execute any arbitrary script they want in the container.
Customers can use the library API in their own scripts (freedom to opt-in and use the methods that they want).

@iquintero iquintero left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the overall design makes sense to me, just have some comments.

Comment thread src/sagemaker_containers/training.py Outdated


class Training(object):
def __init__(self, train_fn=None, module_name=None):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

train_fn and module_name are mutually exclusive. (As inferred from the existance of from_train_fn() and from_module(). This class needs to throw an exception if it is manually constructed and passed both.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/sagemaker_containers/training.py Outdated
raise e

def import_user_module(self, code_dir, user_script='user_script'):
return importlib.import_module(user_script)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

code_dir is not used, but it probably should right?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@property
def input_config_dir(self):
"""The directory where standard SageMaker configuration files are located."""
return os.path.join(self.base_dir, 'input/config')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rewrite this as

os.path.join(self.base_dir, 'input', 'config')

while I think os.path.join() will figure out the / in your string correctly (even on Windows), Windows only users can be confused as to why input/config is a path.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread src/sagemaker_containers/environment.py Outdated

@property
def model_dir(self):
return os.path.join(self.base_dir, 'model')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a big fan of having the getter function of the property calculate its value every time. Can we move to having:

def __init__(self):
    self._model_dir = os.path.join(self.base_dir, 'model')
     # ... other stuff here

@property
def model_dir(self):
    return self._model_dir

If someone else is strongly opposed to this Im fine discussing it though

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

moved all logic to the constructor.

return tmpdir


def test_training_from_train_fn(opt_ml, model_file):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a test to ensure that your class handles both a train_fn and a train_module being passed at the same time.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactored the classes so we do not have the edge case anymore.

Comment thread src/sagemaker_containers/training.py Outdated

self.train_fn(user_module, self.environment)
else:
subprocess.Popen(['python', '-m', self.module_name])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this asumes that the module is importing this as a library in order to figure out where to put stuff right? or the user just hardcoded all their paths but we don't care how they do it as long as it works right?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When the user provides a module, we will validate it before starting the training job.
The module will be saved to the code_dir. When a new Environment instance is created, it adds the code dir to PYTHONPATH.

@mvsusp

mvsusp commented Apr 5, 2018

Copy link
Copy Markdown
Owner Author

@iquintero thanks for the observations. The code here was simplified for design purposes. All your comments will be addressed in the following PRs with the real code implementation. Or would you prefer to address the changes here?

@mvsusp

mvsusp commented Apr 5, 2018

Copy link
Copy Markdown
Owner Author

@iquintero maybe I should not even push this PR since the code is not a real implementation?

@laurenyu laurenyu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are you planning a future PR that fleshes out the documentation in the README? (I'm guessing the current proposed README is just for showing what you're thinking)

also, my usual comments:

  • capitalize "Python"
  • import statements - I usually just ctrl/cmd-F on the Python Standard Library list to check what goes in the first group.

Comment thread src/sagemaker_containers/environment.py Outdated
@property
def code_dir(self):
"""The directory where user-supplied code will be staged."""
return os.path.join(self.base_dir, 'code')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'model' and 'code' can be constants with 'opt/ml'

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

created constants with just the base_names

Comment thread src/sagemaker_containers/training.py Outdated
self.environment.write_failure_file('Uncaught exception during training: %s' % e)
raise e

def import_user_module(self, code_dir, user_script='user_script'):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we be giving a default value to user_script? It seems a little strange to me to presume that, especially if code_dir is required. I'd be more inclined to follow the strategy in PythonSDK, where entry_point is required and source_dir defaults to None

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I agree that we should not. Just did that to reduce the prototype amount of lines and focus in the overall design.


@property
def channel_dirs(self):
""""""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why bother including the docstring at this point? 😂

@mvsusp

mvsusp commented Apr 6, 2018

Copy link
Copy Markdown
Owner Author

@laurenyu I agree with all your points here. I'm planning to not push this PR and just use it to gather design feedback.

@owen-t owen-t left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good - some of the implementations are missing though - let's get them filled out!

Great stuff!

Comment thread src/sagemaker_containers/environment.py Outdated

import sys

base_dir = 'opt/ml'

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be /opt/ml ?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed.

Comment thread src/sagemaker_containers/environment.py Outdated

import multiprocessing
import os

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whitespace?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added flake8 so we won't have these error again.

Comment thread src/sagemaker_containers/environment.py Outdated
@property
def available_gpus(self):
"""The number of gpus available in the current container."""
pass

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not provide a default here?

Try to invoke nvidia-smi (per Nacho's comment, probably not in the getter) and return the result or 0.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread src/sagemaker_containers/training.py Outdated


class Training(object):
def __init__(self, train_fn=None, module_name=None):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API docs! Particularly so for this class as it's a little esoteric.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@owen-t I added docstrings to the methods.


class Training(object):
def __init__(self, train_fn=None, module_name=None):
self.environment = env.TrainingEnvironment()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document the constraints on these arguments

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread src/sagemaker_containers/training.py Outdated

self.train_fn(user_module, self.environment)
else:
subprocess.Popen(['python', '-m', self.module_name])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Popen returns immediately and successfully if the process can be created. Should this be a check_call?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/sagemaker_containers/training.py Outdated
try:
if self.train_fn:

user_module = self.import_user_module(self.environment.code_dir)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we run the train_fn in a subprocess as well?

return os.path.join(self.base_dir, 'output')

@property
def resource_config(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we provide defaults for many of these?

""""""
pass

def load_training_parameters(self, fn):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Provide doc strings for these undocumented functions

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

@mvsusp

mvsusp commented Apr 8, 2018

Copy link
Copy Markdown
Owner Author

@jesterhazy I update the documentation and examples. Please let me know if you still have any
doubts/observations.

@mvsusp

mvsusp commented Apr 8, 2018 •

Copy link
Copy Markdown
Owner Author

@laurenyu I've found this flake8 extension that inspects the import order for us, so I stop messing up the import order: https://github.com/mvsusp/sagemaker-container-support/pull/3/files#diff-b91f3d5bd63fcd17221b267e851608e8R52

🎉 🍷

@mvsusp

mvsusp commented Apr 8, 2018

Copy link
Copy Markdown
Owner Author

@jesterhazy @owen-t @iquintero @laurenyu I updated the readme and added tox to this PR.
The next steps will be:

  • proposal design for training
  • setting up team city
  • additional missing features

@mvsusp
mvsusp requested a review from andremoeller April 8, 2018 15:47

@jesterhazy jesterhazy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good. added some nits. i think the readme docs will need another full pass once the design is settled.



# TODO (mvsusp) - create a shortcut decorator to allow get/set outside the class, e.g. env.model_dir = 'x'
base_dir = BASE_PATH

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are we exposing as model var at all? it's already a class attribute.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is temporary, just to reduce the size of the PR. But I added a TODO in the top to fix it.

self.environment = env.TrainingEnvironment()
self.training_process_fn = training_process_fn

# TODO(mvsusp) - add update_training_environment_fn to allow frameworks to update the training env.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does update mean? user can just update/attributes to the instance without adding a special function (b/c python)

@mvsusp mvsusp Apr 9, 2018 •

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for the following scenario:

    
def framework_train_fn(user_module, training_env):
    model = user_module.train(training_env.channel_input_dirs, training_env.hyperparameters)
    save_model(model, model_file)

def update_training_environment_fn(training_env):
    training_env.world_size = len(training_env.hosts * training_env.num_gpus)
    training_env.rank = 2
    return training_env


Training.from_train_fn(train_fn=framework_train_fn,  
                                      environment_fn=update_training_environment_fn)

Put it is outside the scope this PR. We can discuss implementation details later.



def write_user_module(tmpdir, code):
customer_module = tmpdir.mkdir('code', 'customer_module')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

customer_module*_path* etc.

Comment thread README.md
...

# TODO (mvsusp) - create env.training_data_dir and env.evaluation_data_dir helpers
parser.add_argument('--training-data-dir', type=str, default=env.training_data_dir)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this actually work with the code as is right now?

the training_environment module doesn't have training_data_dir, batch_size, etc. fields. You have to create an instance of TrainingEnvironment, right?

It's worth thinking about whether there's value in needing to create an instance of the class. The functions could all just live in the module rather than the class. Is there a strong reason one way or the other currently?

_PYTHONPATH = 'PYTHONPATH'


class Training(object):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two questions:

1). Can we design this so we don't lock users into this "framework"? I want to avoid the same problem we had with our original TensorFlow framework design.

What would it look like if framework authors were implementing their train entrypoint using library functions that we provide? How much complexity would remain that we would still want to abstract away, at the cost of flexibility? I'd like to see us design that "API" first, and see some example user code in that style.

We may still want to offer something like this, which enforces a specific workflow for the entirety of training, which lets us ensure that all of our frameworks behave the same way. Even in that case, I'd argue that that should be written purely by calling those library functions.

2). For the "framework", is a class like this the best implementation? Other potential alternatives:

  • A function which takes in a function/module
  • A class which can be subclassed

Are there reasons for going this direction over the others?

@mvsusp mvsusp closed this Apr 10, 2018
mvsusp added a commit that referenced this pull request Jul 26, 2018
* add container support code (#1)
* Add missing test dependencies to setup.py (#2)
* Add entry.py as script in setup.py so it can be invoked from our images (#3)
* Add data_files to setup.py to copy nginx config correctly + fix install_requires (#4)
* Move dependencies from extras_require to install_requires
* Copy in change from internal repo: support pip install requirements.txt (#5)
* Use package_data instead of data_files to package config files, refer to (#6)
* Add missing conf files (accidentally left out of previous commit) (aws#8)
* pip install requirements in training container (aws#11)
* Use container exit code to exit Trainer process. (aws#9)
* Add gunicorn and gevent as setup.py dependencies (aws#13)
* Specify version ranges for install_requires dependencies
* Add Apache license headers (aws#14)
* Add changelog (aws#15)
* Bump version to 1.0.0 (aws#16)
* Fix year in license headers (aws#18)
* Add README description (aws#20)
* Update version to 1.0.1 (aws#21)
* Read new TRAINING_JOB_NAME environment variable during training (aws#34)
* Bump version to 1.0.2 and update Changelog (aws#37)
* Move processing of requirements file out to the specific container. (aws#39)
* Bump version to 1.0.3 and update Changelog (aws#42)
* Change module name to string in __all__ (aws#50)
* Hardcode special case for tuning job hyperparameter (aws#54)
* Use strip() for more readability (aws#55)
This change is a small improvement upon aws#54
* Bump version to 1.0.4 (aws#56)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants