MNIST offline mode with MXNet/PyTorch/TensorFlow (#1787)
* mnist train and test notebooks tested on local mode * added config.json for global config * training notebook requires user to be in the same region as the public s3 bucket * default to non-local mode * Website preview (#1764) * mnist train and test notebooks tested on local mode * added config.json for global config * training notebook requires user to be in the same region as the public s3 bucket * default to non-local mode * cleared output / added sym link to global config.json * minor fix * added swp file to gitignore; * added updated mxnet examples * train entry point tested * train notebook ready * train / inference tested * inference.py not needed * removed zombie cells / changed public model addr * cleared outputs * default to non-local mode * default to non-local mode * removed downloaded model * default to nonlocal mode * small bug fix * Pytorch vpc (#1780) * deleted training notebook * train / deployment notebook tested in local mode * default to non-local mode * added utils * changed rst * removed a trained model * Website preview (#1785) * Notebook cleaned and data on S3 - XGBoost (#1713) * Notebook cleaned and data on S3 * Cleared all cell outputs * formatting a cell * PR comments addressed * PR comments addressed * Instance type updated * Bucket changed to prod regions bucket and citation added * Deleted install instructions * Cleaned up Linear Learner notebook (#1709) * Cleaned up Linear Learner notebook * directory name changed on S3 * PR comments addressed * Updated instance type and kernel * Bucket changed to prod bucket and citation added * Changed parameter name as in SageMaker v2 * Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> * Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> * Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> * Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> * Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> * Update introduction_to_amazon_algorithms/linear_learner_abalone/Linear_Learner_Regression_csv_format.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> Co-authored-by: Aaron Markham <markhama@amazon.com> * Image classification notebook fix + data source on S3 (#1700) * Fixing notebooks * Cleared all outputs * PR comments addressed and code cleaned * Typo fix * Added kernel type in description * Fixed instance type to studio * Added instance type * Data bucket changed to prod bucket * Download links added * estimator parameter changed to be compatible with SageMaker v2 * Update introduction_to_amazon_algorithms/imageclassification_caltech/Image-classification-transfer-learning-highlevel.ipynb Co-authored-by: Aaron Markham <markhama@amazon.com> Co-authored-by: Aaron Markham <markhama@amazon.com> * Small fix, notebook formatting, data on S3 - PCA (#1715) * Small fix and notebook formatting * Variable name changed * Updated instance type and kernel * Bucket changed to prod bucket * Changed parameter name in Estimator as in SageMaker v2 * Added missing import Co-authored-by: Aaron Markham <markhama@amazon.com> * website: add getting started videos; rename featured examples to studio (#1758) * add getting started videos; rename featured examples to studio * vidoes for getting started; combine to same page * refactor byo algo with pipe mode to be python3 and sdk v2 (#1690) * Docs: Deleting working_with_redshift_data.ipynb New notebook will cover this topic in more depth. Deleting to remove duplication. https://github.com/aws/amazon-sagemaker-examples/issues/1447 * add GT video, fix links, update copyright notice (#1763) * train entry point tested * train notebook ready * train / inference tested * inference.py not needed * default to non-local mode * default to non-local mode * removed downloaded model * removed a trained model Co-authored-by: vivekmadan2 <53404938+vivekmadan2@users.noreply.github.com> Co-authored-by: Aaron Markham <markhama@amazon.com> Co-authored-by: Talia <31782251+TEChopra1000@users.noreply.github.com> * add a line break * editorial fix par style guide * removed swp file * fix json * fixed typos * bug fix * better way to upload data * deleted empty cell * tensorflow / pytorch tested * removed mxnet for more testing * cleared output * removed mxnet from rst * minor fixes Co-authored-by: vivekmadan2 <53404938+vivekmadan2@users.noreply.github.com> Co-authored-by: Aaron Markham <markhama@amazon.com> Co-authored-by: Talia <31782251+TEChopra1000@users.noreply.github.com>
This commit is contained in:
@@ -3,4 +3,5 @@
|
||||
**/__pycache__
|
||||
**/.aws-sam
|
||||
.DS_Store
|
||||
|
||||
**/_build
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"public_bucket": "sagemaker-sample-files"
|
||||
}
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../config.json
|
||||
@@ -0,0 +1,57 @@
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.addHandler(logging.StreamHandler(sys.stdout))
|
||||
|
||||
# Based on https://github.com/pytorch/examples/blob/master/mnist/main.py
|
||||
class Net(nn.Module):
|
||||
def __init__(self):
|
||||
super(Net, self).__init__()
|
||||
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
|
||||
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
|
||||
self.conv2_drop = nn.Dropout2d()
|
||||
self.fc1 = nn.Linear(320, 50)
|
||||
self.fc2 = nn.Linear(50, 10)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(F.max_pool2d(self.conv1(x), 2))
|
||||
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
|
||||
x = x.view(-1, 320)
|
||||
x = F.relu(self.fc1(x))
|
||||
x = F.dropout(x, training=self.training)
|
||||
x = self.fc2(x)
|
||||
return F.log_softmax(x, dim=1)
|
||||
|
||||
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
||||
|
||||
def model_fn(model_dir):
|
||||
model = Net().to(device)
|
||||
model.eval()
|
||||
return model
|
||||
|
||||
# data preprocessing
|
||||
def input_fn(request_body, request_content_type):
|
||||
assert request_content_type=='application/json'
|
||||
data = json.loads(request_body)['inputs']
|
||||
data = torch.tensor(data, dtype=torch.float32, device=device)
|
||||
return data
|
||||
|
||||
# inference
|
||||
def predict_fn(input_object, model):
|
||||
with torch.no_grad():
|
||||
prediction = model(input_object)
|
||||
return prediction
|
||||
|
||||
# postprocess
|
||||
def output_fn(predictions, content_type):
|
||||
assert content_type == 'application/json'
|
||||
res = predictions.cpu().numpy().tolist()
|
||||
return json.dumps(res)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
from inference import model_fn, input_fn, predict_fn, output_fn
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import boto3
|
||||
import botocore
|
||||
import tarfile
|
||||
import numpy as np
|
||||
import sagemaker
|
||||
|
||||
def fetch_model(model_data):
|
||||
""" Untar the model.tar.gz object either from local file system
|
||||
or a S3 location
|
||||
|
||||
Args:
|
||||
model_data (str): either a path to local file system starts with
|
||||
file:/// that points to the `model.tar.gz` file or an S3 link
|
||||
starts with s3:// that points to the `model.tar.gz` file
|
||||
|
||||
Returns:
|
||||
model_dir (str): the directory that contains the uncompress model
|
||||
checkpoint files
|
||||
"""
|
||||
|
||||
model_dir = "/tmp/model"
|
||||
if not os.path.exists(model_dir):
|
||||
os.makedirs(model_dir)
|
||||
|
||||
if model_data.startswith("file"):
|
||||
_check_model(model_data)
|
||||
shutil.copy2(os.path.join(model_dir, "model.tar.gz"),
|
||||
os.path.join(model_dir, "model.tar.gz"))
|
||||
elif model_data.startswith("s3"):
|
||||
# get bucket name and object key
|
||||
bucket_name = model_data.split("/")[2]
|
||||
key = "/".join(model_data.split("/")[3:])
|
||||
|
||||
s3 = boto3.resource("s3")
|
||||
try:
|
||||
s3.Bucket(bucket_name).download_file(
|
||||
key, os.path.join(model_dir, 'model.tar.gz'))
|
||||
except botocore.exceptions.ClientError as e:
|
||||
if e.response['Error']['Code'] == '404':
|
||||
print("the object does not exist.")
|
||||
else:
|
||||
raise
|
||||
|
||||
# untar the model
|
||||
tar = tarfile.open(os.path.join(model_dir, 'model.tar.gz'))
|
||||
tar.extractall(model_dir)
|
||||
tar.close()
|
||||
|
||||
return model_dir
|
||||
|
||||
|
||||
def test(model_data):
|
||||
# decompress the model.tar.gz file
|
||||
model_dir = fetch_model(model_data)
|
||||
|
||||
# load the model
|
||||
net = model_fn(model_dir)
|
||||
|
||||
# simulate some input data to test transform_fn
|
||||
|
||||
data = {
|
||||
"inputs": np.random.rand(16, 1, 28, 28).tolist()
|
||||
}
|
||||
|
||||
# encode numpy array to binary stream
|
||||
serializer = sagemaker.serializers.JSONSerializer()
|
||||
|
||||
jstr = serializer.serialize(data)
|
||||
jstr = json.dumps(data)
|
||||
|
||||
# "send" the bin_stream to the endpoint for inference
|
||||
# inference container calls transform_fn to make an inference
|
||||
# and get the response body for the caller
|
||||
|
||||
content_type='application/json'
|
||||
input_object = input_fn(jstr, content_type)
|
||||
predictions = predict_fn(input_object, net)
|
||||
res = output_fn(predictions, content_type)
|
||||
print(res)
|
||||
return
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
model_data = "s3://sagemaker-us-west-2-688520471316/mxnet/mnist/pytorch-training-2020-11-21-22-02-56-203/model.tar.gz"
|
||||
test(model_data)
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
from train import train, parse_args
|
||||
|
||||
import sys
|
||||
import os
|
||||
import boto3
|
||||
import json
|
||||
|
||||
dirname = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
with open(os.path.join(dirname, "config.json"), "r") as f:
|
||||
CONFIG = json.load(f)
|
||||
|
||||
def download_from_s3(data_dir='/tmp/data', train=True):
|
||||
"""Download MNIST dataset and convert it to numpy array
|
||||
|
||||
Args:
|
||||
data_dir (str): directory to save the data
|
||||
train (bool): download training set
|
||||
|
||||
Returns:
|
||||
tuple of images and labels as numpy arrays
|
||||
"""
|
||||
|
||||
if not os.path.exists(data_dir):
|
||||
os.makedirs(data_dir)
|
||||
|
||||
|
||||
if train:
|
||||
images_file = "train-images-idx3-ubyte.gz"
|
||||
labels_file = "train-labels-idx1-ubyte.gz"
|
||||
else:
|
||||
images_file = "t10k-images-idx3-ubyte.gz"
|
||||
labels_file = "t10k-labels-idx1-ubyte.gz"
|
||||
|
||||
# download objects
|
||||
s3 = boto3.client('s3')
|
||||
bucket = CONFIG["public_bucket"]
|
||||
for obj in [images_file, labels_file]:
|
||||
key = os.path.join("datasets/image/MNIST", obj)
|
||||
dest = os.path.join(data_dir, obj)
|
||||
if not os.path.exists(dest):
|
||||
s3.download_file(bucket, key, dest)
|
||||
return
|
||||
|
||||
class Env:
|
||||
def __init__(self):
|
||||
# simulate container env
|
||||
os.environ["SM_MODEL_DIR"] = "/tmp/model"
|
||||
os.environ["SM_CHANNEL_TRAINING"]="/tmp/data"
|
||||
os.environ["SM_CHANNEL_TESTING"]="/tmp/data"
|
||||
os.environ["SM_HOSTS"] = '["algo-1"]'
|
||||
os.environ["SM_CURRENT_HOST"]="algo-1"
|
||||
os.environ["SM_NUM_GPUS"] = "0"
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
Env()
|
||||
args = parse_args()
|
||||
train(args)
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import argparse
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import torch.optim as optim
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.DEBUG)
|
||||
logger.addHandler(logging.StreamHandler(sys.stdout))
|
||||
|
||||
# Based on https://github.com/pytorch/examples/blob/master/mnist/main.py
|
||||
class Net(nn.Module):
|
||||
def __init__(self):
|
||||
super(Net, self).__init__()
|
||||
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
|
||||
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
|
||||
self.conv2_drop = nn.Dropout2d()
|
||||
self.fc1 = nn.Linear(320, 50)
|
||||
self.fc2 = nn.Linear(50, 10)
|
||||
|
||||
def forward(self, x):
|
||||
x = F.relu(F.max_pool2d(self.conv1(x), 2))
|
||||
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
|
||||
x = x.view(-1, 320)
|
||||
x = F.relu(self.fc1(x))
|
||||
x = F.dropout(x, training=self.training)
|
||||
x = self.fc2(x)
|
||||
return F.log_softmax(x, dim=1)
|
||||
|
||||
|
||||
# Decode binary data from SM_CHANNEL_TRAINING
|
||||
# Decode and preprocess data
|
||||
# Create map dataset
|
||||
|
||||
|
||||
def normalize(x, axis):
|
||||
eps = np.finfo(float).eps
|
||||
mean = np.mean(x, axis=axis, keepdims=True)
|
||||
# avoid division by zero
|
||||
std = np.std(x, axis=axis, keepdims=True) + eps
|
||||
return (x - mean) / std
|
||||
|
||||
def convert_to_tensor(data_dir, images_file, labels_file):
|
||||
"""Byte string to torch tensor
|
||||
"""
|
||||
with gzip.open(os.path.join(data_dir, images_file), 'rb') as f:
|
||||
images = np.frombuffer(f.read(),
|
||||
np.uint8, offset=16).reshape(-1, 28, 28).astype(np.float32)
|
||||
|
||||
with gzip.open(os.path.join(data_dir, labels_file), 'rb') as f:
|
||||
labels = np.frombuffer(f.read(), np.uint8, offset=8).astype(
|
||||
np.int64)
|
||||
|
||||
# normalize the images
|
||||
images = normalize(images, axis=(1,2))
|
||||
|
||||
# add channel dimension (depth-major)
|
||||
images = np.expand_dims(images, axis=1)
|
||||
|
||||
# to torch tensor
|
||||
images = torch.tensor(images, dtype=torch.float32)
|
||||
labels = torch.tensor(labels, dtype=torch.int64)
|
||||
return images, labels
|
||||
|
||||
|
||||
class MNIST(Dataset):
|
||||
def __init__(self, data_dir, train=True):
|
||||
|
||||
if train:
|
||||
images_file="train-images-idx3-ubyte.gz"
|
||||
labels_file="train-labels-idx1-ubyte.gz"
|
||||
else:
|
||||
images_file="t10k-images-idx3-ubyte.gz"
|
||||
labels_file="t10k-labels-idx1-ubyte.gz"
|
||||
|
||||
self.images, self.labels = convert_to_tensor(
|
||||
data_dir, images_file, labels_file)
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return len(self.labels)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
return self.images[idx], self.labels[idx]
|
||||
|
||||
|
||||
def train(args):
|
||||
use_cuda = args.num_gpus > 0
|
||||
device = torch.device("cuda" if use_cuda > 0 else "cpu")
|
||||
|
||||
torch.manual_seed(args.seed)
|
||||
if use_cuda:
|
||||
torch.cuda.manual_seed(args.seed)
|
||||
|
||||
train_loader = DataLoader(MNIST(args.train, train=True),
|
||||
batch_size=args.batch_size, shuffle=True)
|
||||
test_loader = DataLoader(MNIST(args.test, train=False),
|
||||
batch_size=args.test_batch_size, shuffle=False)
|
||||
|
||||
net = Net().to(device)
|
||||
loss_fn = nn.CrossEntropyLoss()
|
||||
optimizer = optim.Adam(net.parameters(),
|
||||
betas=(args.beta_1, args.beta_2),
|
||||
weight_decay=args.weight_decay)
|
||||
|
||||
logger.info("Start training ...")
|
||||
for epoch in range(1, args.epochs+1):
|
||||
net.train()
|
||||
for batch_idx, (imgs, labels) in enumerate(train_loader, 1):
|
||||
imgs, labels = imgs.to(device), labels.to(device)
|
||||
output = net(imgs)
|
||||
loss = loss_fn(output, labels)
|
||||
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
if batch_idx % args.log_interval == 0:
|
||||
print('Train Epoch: {} [{}/{} ({:.0f}%)] Loss: {:.6f}'.format(
|
||||
epoch, batch_idx * len(imgs), len(train_loader.sampler),
|
||||
100. * batch_idx / len(train_loader), loss.item()))
|
||||
|
||||
# test the model
|
||||
test(net, test_loader, device)
|
||||
|
||||
# save model checkpoint
|
||||
save_model(net, args.model_dir)
|
||||
return
|
||||
|
||||
def test(model, test_loader, device):
|
||||
model.eval()
|
||||
test_loss = 0
|
||||
correct = 0
|
||||
with torch.no_grad():
|
||||
for imgs, labels in test_loader:
|
||||
imgs, labels = imgs.to(device), labels.to(device)
|
||||
output = model(imgs)
|
||||
test_loss+=F.cross_entropy(output, labels, reduction='sum').item()
|
||||
|
||||
pred = output.max(1, keepdim=True)[1]
|
||||
correct+=pred.eq(labels.view_as(pred)).sum().item()
|
||||
|
||||
test_loss /= len(test_loader.dataset)
|
||||
logger.info('Test set: Average loss: {:.4f}, Accuracy: {}/{}, {})\n'.format(
|
||||
test_loss, correct, len(test_loader.dataset),
|
||||
100.0 * correct / len(test_loader.dataset)
|
||||
))
|
||||
return
|
||||
|
||||
def save_model(model, model_dir):
|
||||
logger.info('Saving the model')
|
||||
path = os.path.join(model_dir, 'model.pth')
|
||||
torch.save(model.cpu().state_dict(), path)
|
||||
return
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
# Data and model checkpoints directories
|
||||
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
|
||||
help='input batch size for training (default: 64)')
|
||||
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
|
||||
help='input batch size for testing (default: 1000)')
|
||||
parser.add_argument('--epochs', type=int, default=1, metavar='N',
|
||||
help='number of epochs to train (default: 1)')
|
||||
parser.add_argument('--learning-rate', type=float, default=0.001, metavar='LR',
|
||||
help='learning rate (default: 0.01)')
|
||||
parser.add_argument('--beta_1', type=float, default=0.9, metavar='BETA1',
|
||||
help='beta1 (default: 0.9)')
|
||||
parser.add_argument('--beta_2', type=float, default=0.999, metavar='BETA2',
|
||||
help='beta2 (default: 0.999)')
|
||||
parser.add_argument('--weight-decay', type=float, default=1e-4, metavar='WD',
|
||||
help='L2 weight decay (default: 1e-4)')
|
||||
parser.add_argument('--seed', type=int, default=1, metavar='S',
|
||||
help='random seed (default: 1)')
|
||||
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
|
||||
help='how many batches to wait before logging training status')
|
||||
parser.add_argument('--backend', type=str, default=None,
|
||||
help='backend for distributed training (tcp, gloo on cpu and gloo, nccl on gpu)')
|
||||
|
||||
# Container environment
|
||||
parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS']))
|
||||
parser.add_argument('--current-host', type=str, default=os.environ['SM_CURRENT_HOST'])
|
||||
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
|
||||
parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
|
||||
parser.add_argument('--test', type=str, default=os.environ['SM_CHANNEL_TESTING'])
|
||||
parser.add_argument('--num-gpus', type=int, default=os.environ['SM_NUM_GPUS'])
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = parse_args()
|
||||
train(args)
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,379 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# MNIST training with PyTorch\n",
|
||||
"\n",
|
||||
"MNIST is a widely used dataset for handwritten digit classification. It consists of 70,000 labeled 28x28 pixel grayscale images of hand-written digits. The dataset is split into 60,000 training images and 10,000 test images. There are 10 classes (one for each of the 10 digits). This tutorial will show how to train and test an MNIST model on SageMaker using PyTorch. \n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"import json\n",
|
||||
"\n",
|
||||
"import sagemaker\n",
|
||||
"from sagemaker.pytorch import PyTorch\n",
|
||||
"from sagemaker import get_execution_role\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"sess = sagemaker.Session()\n",
|
||||
"\n",
|
||||
"role = get_execution_role()\n",
|
||||
"\n",
|
||||
"output_path='s3://' + sess.default_bucket() + '/mnist'"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## PyTorch Estimator\n",
|
||||
"\n",
|
||||
"The `PyTorch` class allows you to run your training script on SageMaker\n",
|
||||
"infrastracture in a containerized environment. In this notebook, we\n",
|
||||
"refer to this container as *training container*. \n",
|
||||
"\n",
|
||||
"You need to configure\n",
|
||||
"it with the following parameters to set up the environment:\n",
|
||||
"\n",
|
||||
"- entry_point: A user defined python file to be used by the training container as the \n",
|
||||
"instructions for training. We further discuss this file in the next subsection.\n",
|
||||
"\n",
|
||||
"- role: An IAM role to make AWS service requests\n",
|
||||
"\n",
|
||||
"- instance_type: The type of SageMaker instance to run your training script. \n",
|
||||
"Set it to `local` if you want to run the training job on \n",
|
||||
"the SageMaker instance you are using to run this notebook\n",
|
||||
"\n",
|
||||
"- instance count: The number of instances you need to run your training job. \n",
|
||||
"Multiple instances are needed for distributed training.\n",
|
||||
"\n",
|
||||
"- output_path: \n",
|
||||
"S3 bucket URI to save training output (model artifacts and output files)\n",
|
||||
"\n",
|
||||
"- framework_version: The version of PyTorch you need to use.\n",
|
||||
"\n",
|
||||
"- py_version: The python version you need to use\n",
|
||||
"\n",
|
||||
"For more information, see [the API reference](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase)\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Implement the entry point for training\n",
|
||||
"\n",
|
||||
"The entry point for training is a python script that provides all \n",
|
||||
"the code for training a PyTorch model. It is used by the SageMaker \n",
|
||||
"PyTorch Estimator (`PyTorch` class above) as the entry point for running the training job.\n",
|
||||
"\n",
|
||||
"Under the hood, SageMaker PyTorch Estimator creates a docker image\n",
|
||||
"with runtime environemnts \n",
|
||||
"specified by the parameters you used to initiated the\n",
|
||||
"estimator class and it injects the training script into the \n",
|
||||
"docker image to be used as the entry point to run the container.\n",
|
||||
"\n",
|
||||
"In the rest of the notebook, we use *training image* to refer to the \n",
|
||||
"docker image specified by the PyTorch Estimator and *training container*\n",
|
||||
"to refer to the container that runs the training image. \n",
|
||||
"\n",
|
||||
"This means your training script is very similar to a training script\n",
|
||||
"you might run outside Amazon SageMaker, but it can access the useful environment \n",
|
||||
"variables provided by the training image. Checkout [the short list of environment variables provided by the SageMaker service](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/using_mxnet.html?highlight=entry%20point) to see some common environment \n",
|
||||
"variables you might used. Checkout [the complete list of environment variables](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md) for a complete \n",
|
||||
"description of all environment variables your training script\n",
|
||||
"can access to. \n",
|
||||
"\n",
|
||||
"In this example, we use the training script `code/train.py`\n",
|
||||
"as the entry point for our PyTorch Estimator.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pygmentize 'code/train.py'"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Set hyperparameters\n",
|
||||
"\n",
|
||||
"In addition, PyTorch estimator allows you to parse command line arguments\n",
|
||||
"to your training script via `hyperparameters`.\n",
|
||||
"\n",
|
||||
"<span style=\"color:red\"> Note: local mode is not supported in SageMaker Studio </span>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# set local_mode to be True if you want to run the training script\n",
|
||||
"# on the machine that runs this notebook\n",
|
||||
"\n",
|
||||
"local_mode=True\n",
|
||||
"\n",
|
||||
"if local_mode:\n",
|
||||
" instance_type='local'\n",
|
||||
"else:\n",
|
||||
" instance_type='ml.c4.xlarge'\n",
|
||||
" \n",
|
||||
"est = PyTorch(\n",
|
||||
" entry_point='train.py',\n",
|
||||
" source_dir='code', # directory of your training script\n",
|
||||
" role=role,\n",
|
||||
" framework_version='1.5.0',\n",
|
||||
" py_version='py3',\n",
|
||||
" instance_type=instance_type,\n",
|
||||
" instance_count=1,\n",
|
||||
" output_path=output_path,\n",
|
||||
" hyperparameters={\n",
|
||||
" 'batch-size':128,\n",
|
||||
" 'epochs':20,\n",
|
||||
" 'learning-rate': 1e-3,\n",
|
||||
" 'log-interval':100\n",
|
||||
" }\n",
|
||||
")\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The training container executes your training script like\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"python train.py --batch-size 100 --epochs 10 --learning-rate 1e-3 \\\n",
|
||||
" --log-interval 100\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Set up channels for training and testing data\n",
|
||||
"\n",
|
||||
"You need to tell `PyTorch` estimator where to find your training and \n",
|
||||
"testing data. It can be a link to an S3 bucket or it can be a path\n",
|
||||
"in your local file system if you use local mode. In this example,\n",
|
||||
"we download the MNIST data from a public S3 bucket and upload it \n",
|
||||
"to your default bucket. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import logging\n",
|
||||
"import boto3\n",
|
||||
"from botocore.exceptions import ClientError\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Download training and testing data from a public S3 bucket\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def download_from_s3(data_dir='/tmp/data', train=True):\n",
|
||||
" \"\"\"Download MNIST dataset and convert it to numpy array\n",
|
||||
" \n",
|
||||
" Args:\n",
|
||||
" data_dir (str): directory to save the data\n",
|
||||
" train (bool): download training set\n",
|
||||
" \n",
|
||||
" Returns:\n",
|
||||
" None\n",
|
||||
" \"\"\"\n",
|
||||
" \n",
|
||||
" # Get global config\n",
|
||||
" with open('code/config.json', 'r') as f:\n",
|
||||
" CONFIG=json.load(f)\n",
|
||||
" \n",
|
||||
" if not os.path.exists(data_dir):\n",
|
||||
" os.makedirs(data_dir)\n",
|
||||
" \n",
|
||||
" if train:\n",
|
||||
" images_file = \"train-images-idx3-ubyte.gz\"\n",
|
||||
" labels_file = \"train-labels-idx1-ubyte.gz\"\n",
|
||||
" else:\n",
|
||||
" images_file = \"t10k-images-idx3-ubyte.gz\"\n",
|
||||
" labels_file = \"t10k-labels-idx1-ubyte.gz\"\n",
|
||||
"\n",
|
||||
" # download objects\n",
|
||||
" s3 = boto3.client('s3')\n",
|
||||
" bucket = CONFIG['public_bucket']\n",
|
||||
" for obj in [images_file, labels_file]:\n",
|
||||
" key = os.path.join(\"datasets/image/MNIST\", obj)\n",
|
||||
" dest = os.path.join(data_dir, obj)\n",
|
||||
" if not os.path.exists(dest):\n",
|
||||
" s3.download_file(bucket, key, dest)\n",
|
||||
" return\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"download_from_s3('/tmp/data', True)\n",
|
||||
"download_from_s3('/tmp/data', False)\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# upload to the default bucket\n",
|
||||
"\n",
|
||||
"prefix = 'mnist'\n",
|
||||
"bucket = sess.default_bucket()\n",
|
||||
"loc = sess.upload_data(path='/tmp/data', bucket=bucket, key_prefix=prefix)\n",
|
||||
"\n",
|
||||
"channels = {\n",
|
||||
" \"training\": loc,\n",
|
||||
" \"testing\": loc\n",
|
||||
"}\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The keys of the dictionary `channels` are parsed to the training image\n",
|
||||
"and it creates the environment variable `SM_CHANNEL_<key name>`. \n",
|
||||
"\n",
|
||||
"In this example, `SM_CHANNEL_TRAINING` and `SM_CHANNEL_TESTING` are created in the training image (checkout \n",
|
||||
"how `code/train.py` access these variables). For more information,\n",
|
||||
"see: [SM_CHANNEL_{channel_name}](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md#sm_channel_channel_name)\n",
|
||||
"\n",
|
||||
"If you want, you can create a channel for validation:\n",
|
||||
"```\n",
|
||||
"channels = {\n",
|
||||
" 'training': train_data_loc,\n",
|
||||
" 'validation': val_data_loc,\n",
|
||||
" 'test': test_data_loc\n",
|
||||
" }\n",
|
||||
"```\n",
|
||||
"You can then access this channel within your training script via\n",
|
||||
"`SM_CHANNEL_VALIDATION`\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Run the training script on SageMaker\n",
|
||||
"Now, the training container has everything to execute your training\n",
|
||||
"script. You can start the container by calling `fit` method."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"est.fit(inputs=channels)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Inspect and store model data\n",
|
||||
"\n",
|
||||
"Now, the training is finished, the model artifact has been saved in \n",
|
||||
"the `output_path`. We "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"pt_mnist_model_data = est.model_data\n",
|
||||
"print(\"Model artifact saved at:\\n\", pt_mnist_model_data)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We store the variable `model_data` in the current notebook kernel. \n",
|
||||
"In the [next notebook](get_started_with_mnist_deploy.ipynb), you will learn how to retrieve the model artifact and deploy to a SageMaker\n",
|
||||
"endpoint."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%store pt_mnist_model_data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Test and debug the entry point before executing the training container\n",
|
||||
"\n",
|
||||
"The entry point `code/train.py` provided here has been tested and it can be executed in the training container. \n",
|
||||
"When you do develop your own training script, it is a good practice to simulate the container environment \n",
|
||||
"in the local shell and test it before sending it to SageMaker, because debugging in a containerized environment\n",
|
||||
"is rather cumbersome. The following script shows how you can test your training script:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pygmentize code/test_train.py"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.6"
|
||||
},
|
||||
"notice": "Copyright 2017 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."
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../utils/
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../config.json
|
||||
@@ -0,0 +1,59 @@
|
||||
from train import train, parse_args
|
||||
|
||||
import sys
|
||||
import os
|
||||
import boto3
|
||||
import json
|
||||
|
||||
dirname = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
with open(os.path.join(dirname, "config.json"), "r") as f:
|
||||
CONFIG = json.load(f)
|
||||
|
||||
def download_from_s3(data_dir='/tmp/data', train=True):
|
||||
"""Download MNIST dataset and convert it to numpy array
|
||||
Args:
|
||||
data_dir (str): directory to save the data
|
||||
train (bool): download training set
|
||||
Returns:
|
||||
tuple of images and labels as numpy arrays
|
||||
"""
|
||||
|
||||
if not os.path.exists(data_dir):
|
||||
os.makedirs(data_dir)
|
||||
|
||||
if train:
|
||||
images_file = "train-images-idx3-ubyte.gz"
|
||||
labels_file = "train-labels-idx1-ubyte.gz"
|
||||
else:
|
||||
images_file = "t10k-images-idx3-ubyte.gz"
|
||||
labels_file = "t10k-labels-idx1-ubyte.gz"
|
||||
|
||||
# download objects
|
||||
s3 = boto3.client('s3')
|
||||
bucket = CONFIG["public_bucket"]
|
||||
for obj in [images_file, labels_file]:
|
||||
key = os.path.join("datasets/image/MNIST", obj)
|
||||
dest = os.path.join(data_dir, obj)
|
||||
if not os.path.exists(dest):
|
||||
s3.download_file(bucket, key, dest)
|
||||
return
|
||||
|
||||
class Env:
|
||||
def __init__(self):
|
||||
# simulate container env
|
||||
os.environ["SM_MODEL_DIR"] = "/tmp/tf/model"
|
||||
os.environ["SM_CHANNEL_TRAINING"]="/tmp/data"
|
||||
os.environ["SM_CHANNEL_TESTING"]="/tmp/data"
|
||||
os.environ["SM_HOSTS"] = '["algo-1"]'
|
||||
os.environ["SM_CURRENT_HOST"]="algo-1"
|
||||
os.environ["SM_NUM_GPUS"] = "0"
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
Env()
|
||||
download_from_s3()
|
||||
download_from_s3(train=False)
|
||||
args = parse_args()
|
||||
train(args)
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
from __future__ import print_function
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import json
|
||||
import gzip
|
||||
import numpy as np
|
||||
import traceback
|
||||
|
||||
import tensorflow as tf
|
||||
from tensorflow.keras.layers import Dense, Flatten, Conv2D
|
||||
from tensorflow.keras import Model
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
# Define the model object
|
||||
|
||||
class SmallConv(Model):
|
||||
def __init__(self):
|
||||
super(SmallConv, self).__init__()
|
||||
self.conv1 = Conv2D(32, 3, activation='relu')
|
||||
self.flatten = Flatten()
|
||||
self.d1 = Dense(128, activation='relu')
|
||||
self.d2 = Dense(10)
|
||||
|
||||
def call(self, x):
|
||||
x = self.conv1(x)
|
||||
x = self.flatten(x)
|
||||
x = self.d1(x)
|
||||
return self.d2(x)
|
||||
|
||||
|
||||
# Decode and preprocess data
|
||||
def convert_to_numpy(data_dir, images_file, labels_file):
|
||||
"""Byte string to numpy arrays"""
|
||||
with gzip.open(os.path.join(data_dir, images_file), 'rb') as f:
|
||||
images = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1, 28, 28)
|
||||
|
||||
with gzip.open(os.path.join(data_dir, labels_file), 'rb') as f:
|
||||
labels = np.frombuffer(f.read(), np.uint8, offset=8)
|
||||
|
||||
return (images, labels)
|
||||
|
||||
def mnist_to_numpy(data_dir, train):
|
||||
"""Load raw MNIST data into numpy array
|
||||
|
||||
Args:
|
||||
data_dir (str): directory of MNIST raw data.
|
||||
This argument can be accessed via SM_CHANNEL_TRAINING
|
||||
|
||||
train (bool): use training data
|
||||
|
||||
Returns:
|
||||
tuple of images and labels as numpy array
|
||||
"""
|
||||
|
||||
if train:
|
||||
images_file = "train-images-idx3-ubyte.gz"
|
||||
labels_file = "train-labels-idx1-ubyte.gz"
|
||||
else:
|
||||
images_file = "t10k-images-idx3-ubyte.gz"
|
||||
labels_file = "t10k-labels-idx1-ubyte.gz"
|
||||
|
||||
return convert_to_numpy(data_dir, images_file, labels_file)
|
||||
|
||||
|
||||
def normalize(x, axis):
|
||||
eps = np.finfo(float).eps
|
||||
|
||||
mean = np.mean(x, axis=axis, keepdims=True)
|
||||
# avoid division by zero
|
||||
std = np.std(x, axis=axis, keepdims=True) + eps
|
||||
return (x - mean) / std
|
||||
|
||||
# Training logic
|
||||
|
||||
def train(args):
|
||||
# create data loader from the train / test channels
|
||||
x_train, y_train = mnist_to_numpy(data_dir=args.train, train=True)
|
||||
x_test, y_test = mnist_to_numpy(data_dir=args.test, train=False)
|
||||
|
||||
x_train, x_test = x_train.astype(np.float32), x_test.astype(np.float32)
|
||||
|
||||
# normalize the inputs to mean 0 and std 1
|
||||
x_train, x_test = normalize(x_train, (1, 2)), normalize(x_test, (1, 2))
|
||||
|
||||
# expand channel axis
|
||||
# tf uses depth minor convention
|
||||
x_train, x_test = np.expand_dims(x_train, axis=3), np.expand_dims(x_test, axis=3)
|
||||
|
||||
# normalize the data to mean 0 and std 1
|
||||
train_loader = tf.data.Dataset.from_tensor_slices(
|
||||
(x_train, y_train)).shuffle(len(x_train)).batch(args.batch_size)
|
||||
|
||||
test_loader = tf.data.Dataset.from_tensor_slices(
|
||||
(x_test, y_test)).batch(args.batch_size)
|
||||
|
||||
model = SmallConv()
|
||||
model.compile()
|
||||
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
|
||||
optimizer = tf.keras.optimizers.Adam(
|
||||
learning_rate=args.learning_rate,
|
||||
beta_1=args.beta_1,
|
||||
beta_2=args.beta_2
|
||||
)
|
||||
|
||||
|
||||
train_loss = tf.keras.metrics.Mean(name='train_loss')
|
||||
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
|
||||
|
||||
test_loss = tf.keras.metrics.Mean(name='test_loss')
|
||||
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
|
||||
|
||||
|
||||
@tf.function
|
||||
def train_step(images, labels):
|
||||
with tf.GradientTape() as tape:
|
||||
predictions = model(images, training=True)
|
||||
loss = loss_fn(labels, predictions)
|
||||
grad = tape.gradient(loss, model.trainable_variables)
|
||||
optimizer.apply_gradients(zip(grad, model.trainable_variables))
|
||||
|
||||
train_loss(loss)
|
||||
train_accuracy(labels, predictions)
|
||||
return
|
||||
|
||||
@tf.function
|
||||
def test_step(images, labels):
|
||||
predictions = model(images, training=False)
|
||||
t_loss = loss_fn(labels, predictions)
|
||||
test_loss(t_loss)
|
||||
test_accuracy(labels, predictions)
|
||||
return
|
||||
|
||||
print("Training starts ...")
|
||||
for epoch in range(args.epochs):
|
||||
train_loss.reset_states()
|
||||
train_accuracy.reset_states()
|
||||
test_loss.reset_states()
|
||||
test_accuracy.reset_states()
|
||||
|
||||
for batch, (images, labels) in enumerate(train_loader):
|
||||
train_step(images, labels)
|
||||
|
||||
for images, labels in test_loader:
|
||||
test_step(images, labels)
|
||||
|
||||
print(
|
||||
f'Epoch {epoch + 1}, '
|
||||
f'Loss: {train_loss.result()}, '
|
||||
f'Accuracy: {train_accuracy.result() * 100}, '
|
||||
f'Test Loss: {test_loss.result()}, '
|
||||
f'Test Accuracy: {test_accuracy.result() * 100}'
|
||||
)
|
||||
|
||||
# Save the model
|
||||
# A version number is needed for the serving container
|
||||
# to load the model
|
||||
version = '00000000'
|
||||
ckpt_dir = os.path.join(args.model_dir, version)
|
||||
if not os.path.exists(ckpt_dir):
|
||||
os.makedirs(ckpt_dir)
|
||||
model.save(ckpt_dir)
|
||||
return
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument('--batch-size', type=int, default=32)
|
||||
parser.add_argument('--epochs', type=int, default=1)
|
||||
parser.add_argument('--learning-rate', type=float, default=1e-3)
|
||||
parser.add_argument('--beta_1', type=float, default=0.9)
|
||||
parser.add_argument('--beta_2', type=float, default=0.999)
|
||||
|
||||
# Environment variables given by the training image
|
||||
parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR'])
|
||||
parser.add_argument('--train', type=str, default=os.environ['SM_CHANNEL_TRAINING'])
|
||||
parser.add_argument('--test', type=str, default=os.environ['SM_CHANNEL_TESTING'])
|
||||
|
||||
parser.add_argument('--current-host', type=str, default=os.environ['SM_CURRENT_HOST'])
|
||||
parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS']))
|
||||
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = parse_args()
|
||||
train(args)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Deploy a Trained TensorFlow V2 Model\n",
|
||||
"\n",
|
||||
"In this notebook, we walk through the process of deploying a trained model to a SageMaker endpoint. If you recently ran [the notebook for training](get_started_mnist_deploy.ipynb) with %store% magic, the `model_data` can be restored. Otherwise, we retrieve the \n",
|
||||
"model artifact from a public S3 bucket."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# setups\n",
|
||||
"\n",
|
||||
"import os\n",
|
||||
"import json\n",
|
||||
"\n",
|
||||
"import sagemaker\n",
|
||||
"from sagemaker.tensorflow import TensorFlowModel\n",
|
||||
"from sagemaker import get_execution_role, Session\n",
|
||||
"import boto3\n",
|
||||
"\n",
|
||||
"# Get global config\n",
|
||||
"with open('code/config.json', 'r') as f:\n",
|
||||
" CONFIG=json.load(f)\n",
|
||||
"\n",
|
||||
"sess = Session()\n",
|
||||
"role = get_execution_role()\n",
|
||||
"\n",
|
||||
"%store -r tf_mnist_model_data\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"try: \n",
|
||||
" tf_mnist_model_data\n",
|
||||
"except NameError:\n",
|
||||
" import json\n",
|
||||
" # copy a pretrained model from a public public to your default bucket\n",
|
||||
" s3 = boto3.client('s3')\n",
|
||||
" bucket = CONFIG['public_bucket']\n",
|
||||
" key = 'datasets/image/MNIST/model/tensorflow-training-2020-11-20-23-57-13-077/model.tar.gz'\n",
|
||||
" s3.download_file(bucket, key, 'model.tar.gz')\n",
|
||||
" tf_mnist_model_data = sess.upload_data(\n",
|
||||
" path='model.tar.gz', bucket=sess.default_bucket(), key_prefix='model/tensorflow')\n",
|
||||
" os.remove('model.tar.gz')\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(tf_mnist_model_data)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## TensorFlow Model Object\n",
|
||||
"\n",
|
||||
"The `TensorFlowModel` class allows you to define an environment for making inference using your\n",
|
||||
"model artifact. Like `TensorFlow` estimator class we discussed \n",
|
||||
"[in this notebook for training an Tensorflow model](\n",
|
||||
"get_started_mnist_train.ipynb), it is high level API used to set up a docker image for your model hosting service.\n",
|
||||
"\n",
|
||||
"Once it is properly configured, it can be used to create a SageMaker\n",
|
||||
"endpoint on an EC2 instance. The SageMaker endpoint is a containerized environment that uses your trained model \n",
|
||||
"to make inference on incoming data via RESTful API calls. \n",
|
||||
"\n",
|
||||
"Some common parameters used to initiate the `TensorFlowModel` class are:\n",
|
||||
"- role: An IAM role to make AWS service requests\n",
|
||||
"- model_data: the S3 bucket URI of the compressed model artifact. It can be a path to a local file if the endpoint \n",
|
||||
"is to be deployed on the SageMaker instance you are using to run this notebook (local mode)\n",
|
||||
"- framework_version: version of the MXNet package to be used\n",
|
||||
"- py_version: python version to be used"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"\n",
|
||||
"model = TensorFlowModel(\n",
|
||||
" role=role,\n",
|
||||
" model_data=tf_mnist_model_data,\n",
|
||||
" framework_version='2.3.0',\n",
|
||||
")\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Execute the Inference Container\n",
|
||||
"Once the `TensorFlowModel` class is initiated, we can call its `deploy` method to run the container for the hosting\n",
|
||||
"service. Some common parameters needed to call `deploy` methods are:\n",
|
||||
"\n",
|
||||
"- initial_instance_count: the number of SageMaker instances to be used to run the hosting service.\n",
|
||||
"- instance_type: the type of SageMaker instance to run the hosting service. Set it to `local` if you want run the hosting service on the local SageMaker instance. Local mode are typically used for debugging. \n",
|
||||
"\n",
|
||||
"<span style=\"color:red\"> Note: local mode is not supported in SageMaker Studio </span>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from sagemaker.serializers import JSONSerializer\n",
|
||||
"from sagemaker.deserializers import JSONDeserializer\n",
|
||||
"\n",
|
||||
"# set local_mode to False if you want to deploy on a remote\n",
|
||||
"# SageMaker instance\n",
|
||||
"\n",
|
||||
"local_mode=False\n",
|
||||
"\n",
|
||||
"if local_mode:\n",
|
||||
" instance_type='local'\n",
|
||||
"else:\n",
|
||||
" instance_type='ml.c4.xlarge'\n",
|
||||
"\n",
|
||||
"predictor = model.deploy(\n",
|
||||
" initial_instance_count=1,\n",
|
||||
" instance_type=instance_type,\n",
|
||||
" )"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Making Predictions Against a SageMaker endpoint\n",
|
||||
"\n",
|
||||
"Once you have the `Predictor` instance returned by `model.deploy(...)`, you can send prediction requests to your endpoints. In this case, the model accepts normalized \n",
|
||||
"batch images in depth-minor convention. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# use some dummy inputs\n",
|
||||
"import numpy as np\n",
|
||||
"\n",
|
||||
"dummy_inputs = {\n",
|
||||
" 'instances': np.random.rand(4, 28, 28, 1)\n",
|
||||
"}\n",
|
||||
"\n",
|
||||
"res = predictor.predict(dummy_inputs)\n",
|
||||
"print(res)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The formats of the input and output data correspond directly to the request and response\n",
|
||||
"format of the `Predict` method in [TensorFlow Serving REST API](https://www.tensorflow.org/tfx/serving/api_rest), for example, the key of the array to be \n",
|
||||
"parsed to the model in the `dummy_inputs` needs to be called `instances`. Moreover, the input data needs to have a batch dimension. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# Uncomment the following lines to see an example that cannot be processed by the endpoint\n",
|
||||
"\n",
|
||||
"#dummy_data = {\n",
|
||||
"# 'instances': np.random.rand(28, 28, 1).tolist()\n",
|
||||
"#}\n",
|
||||
"#print(predictor.predict(inputs))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Now, let's use real MNIST test to test the endpoint. We use helper functions defined in `code.utils` to \n",
|
||||
"download MNIST data set and normalize the input data."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from utils.mnist import mnist_to_numpy, normalize\n",
|
||||
"import random\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"%matplotlib inline\n",
|
||||
"\n",
|
||||
"data_dir = '/tmp/data'\n",
|
||||
"X, _ = mnist_to_numpy(data_dir, train=False)\n",
|
||||
"\n",
|
||||
"# randomly sample 16 images to inspect\n",
|
||||
"mask = random.sample(range(X.shape[0]), 16)\n",
|
||||
"samples = X[mask]\n",
|
||||
"\n",
|
||||
"# plot the images \n",
|
||||
"fig, axs = plt.subplots(nrows=1, ncols=16, figsize=(16, 1))\n",
|
||||
"\n",
|
||||
"for i, splt in enumerate(axs):\n",
|
||||
" splt.imshow(samples[i])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"Since the model accepts normalized input, you will need to normalize the samples before \n",
|
||||
"sending it to the endpoint. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"samples = normalize(samples, axis=(1, 2))\n",
|
||||
"predictions = predictor.predict(\n",
|
||||
" np.expand_dims(samples, 3) # add channel dim\n",
|
||||
")['predictions'] \n",
|
||||
"\n",
|
||||
"# softmax to logit\n",
|
||||
"predictions = np.array(predictions, dtype=np.float32)\n",
|
||||
"predictions = np.argmax(predictions, axis=1)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(\"Predictions: \", predictions.tolist())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## (Optional) Clean up \n",
|
||||
"\n",
|
||||
"If you do not plan to use the endpoint, you should delete it to free up some computation \n",
|
||||
"resource. If you use local, you will need to manually delete the docker container bounded\n",
|
||||
"at port 8080 (the port that listens to the incoming request).\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"\n",
|
||||
"if not local_mode:\n",
|
||||
" predictor.delete_endpoint()\n",
|
||||
"else:\n",
|
||||
" os.system(\"docker container ls | grep 8080 | awk '{print $1}' | xargs docker container rm -f\")"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"instance_type": "ml.t3.medium",
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.6"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Training a Tensorflow Model on MNIST\n",
|
||||
"\n",
|
||||
"MNIST is a widely used dataset for handwritten digit classification. It consists of 70,000 labeled 28x28 pixel grayscale images of hand-written digits. The dataset is split into 60,000 training images and 10,000 test images. There are 10 classes (one for each of the 10 digits). This tutorial will show how to train a Tensorflow V2 model on MNIST model on SageMaker.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import os\n",
|
||||
"import json\n",
|
||||
"\n",
|
||||
"import sagemaker\n",
|
||||
"from sagemaker.tensorflow import TensorFlow\n",
|
||||
"from sagemaker import get_execution_role\n",
|
||||
"\n",
|
||||
"sess = sagemaker.Session()\n",
|
||||
"\n",
|
||||
"role = get_execution_role()\n",
|
||||
"\n",
|
||||
"output_path='s3://' + sess.default_bucket() + '/tensorflow/mnist'"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## TensorFlow Estimator\n",
|
||||
"\n",
|
||||
"The `TensorFlow` class allows you to run your training script on SageMaker\n",
|
||||
"infrastracture in a containerized environment. In this notebook, we\n",
|
||||
"refer to this container as *training container*. \n",
|
||||
"\n",
|
||||
"You need to configure\n",
|
||||
"it with the following parameters to set up the environment:\n",
|
||||
"\n",
|
||||
"- entry_point: A user defined python file to be used by the training container as the \n",
|
||||
"instructions for training. We will further discuss this file in the next subsection\n",
|
||||
"\n",
|
||||
"- role: An IAM role to make AWS service requests\n",
|
||||
"\n",
|
||||
"- instance_type: The type of SageMaker instance to run your training script. \n",
|
||||
"Set it to `local` if you want to run the training job on \n",
|
||||
"the SageMaker instance you are using to run this notebook\n",
|
||||
"\n",
|
||||
"- model_dir: S3 bucket URI where the checkpoint data and models can be exported to during training (default: None). \n",
|
||||
"To disable having model_dir passed to your training script, set `model_dir`=False\n",
|
||||
"\n",
|
||||
"- instance count: The number of instances you need to run your training job. \n",
|
||||
"Multiple instances are needed for distributed training\n",
|
||||
"\n",
|
||||
"- output_path: \n",
|
||||
"S3 bucket URI to save training output (model artifacts and output files)\n",
|
||||
"\n",
|
||||
"- framework_version: The version of TensorFlow you need to use.\n",
|
||||
"\n",
|
||||
"- py_version: The python version you need to use\n",
|
||||
"\n",
|
||||
"For more information, see [the API reference](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.EstimatorBase)\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Implement the entry point for training\n",
|
||||
"\n",
|
||||
"The entry point for training is a python script that provides all \n",
|
||||
"the code for training a TensorFlow model. It is used by the SageMaker \n",
|
||||
"TensorFlow Estimator (`TensorFlow` class above) as the entry point for running the training job.\n",
|
||||
"\n",
|
||||
"Under the hood, SageMaker TensorFlow Estimator downloads a docker image\n",
|
||||
"with runtime environemnts \n",
|
||||
"specified by the parameters you used to initiated the\n",
|
||||
"estimator class and it injects the training script into the \n",
|
||||
"docker image to be used as the entry point to run the container.\n",
|
||||
"\n",
|
||||
"In the rest of the notebook, we use *training image* to refer to the \n",
|
||||
"docker image specified by the TensorFlow Estimator and *training container*\n",
|
||||
"to refer to the container that runs the training image. \n",
|
||||
"\n",
|
||||
"This means your training script is very similar to a training script\n",
|
||||
"you might run outside Amazon SageMaker, but it can access the useful environment \n",
|
||||
"variables provided by the training image. Checkout [the short list of environment variables provided by the SageMaker service](https://sagemaker.readthedocs.io/en/stable/frameworks/mxnet/using_mxnet.html?highlight=entry%20point) to see some common environment \n",
|
||||
"variables you might used. Checkout [the complete list of environment variables](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md) for a complete \n",
|
||||
"description of all environment variables your training script\n",
|
||||
"can access to. \n",
|
||||
"\n",
|
||||
"In this example, we use the training script `code/train.py`\n",
|
||||
"as the entry point for our TensorFlow Estimator. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pygmentize 'code/train.py'"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### Set hyperparameters\n",
|
||||
"\n",
|
||||
"In addition, TensorFlow estimator allows you to parse command line arguments\n",
|
||||
"to your training script via `hyperparameters`.\n",
|
||||
"\n",
|
||||
"<span style=\"color:red\"> Note: local mode is not supported in SageMaker Studio. </span>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# set local_mode to be True if you want to run the training script\n",
|
||||
"# on the machine that runs this notebook\n",
|
||||
"\n",
|
||||
"local_mode=True\n",
|
||||
"\n",
|
||||
"if local_mode:\n",
|
||||
" instance_type='local'\n",
|
||||
"else:\n",
|
||||
" instance_type='ml.c4.xlarge'\n",
|
||||
" \n",
|
||||
"est = TensorFlow(\n",
|
||||
" entry_point='train.py',\n",
|
||||
" source_dir='code', # directory of your training script\n",
|
||||
" role=role,\n",
|
||||
" framework_version='2.3.0',\n",
|
||||
" model_dir=False, # don't pass --model_dir to your training script\n",
|
||||
" py_version='py37',\n",
|
||||
" instance_type=instance_type,\n",
|
||||
" instance_count=1,\n",
|
||||
" output_path=output_path,\n",
|
||||
" hyperparameters={\n",
|
||||
" 'batch-size':512,\n",
|
||||
" 'epochs':10,\n",
|
||||
" 'learning-rate': 1e-3,\n",
|
||||
" 'beta_1' : 0.9,\n",
|
||||
" 'beta_2' : 0.999\n",
|
||||
" \n",
|
||||
" }\n",
|
||||
")\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The training container executes your training script like\n",
|
||||
"\n",
|
||||
"```\n",
|
||||
"python train.py --batch-size 32 --epochs 10 --learning-rate 0.001\n",
|
||||
" --beta_1 0.9 --beta_2 0.999\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Set up channels for training and testing data\n",
|
||||
"\n",
|
||||
"You need to tell `TensorFlow` estimator where to find your training and \n",
|
||||
"testing data. It can be a link to an S3 bucket or it can be a path\n",
|
||||
"in your local file system if you use local mode. In this example,\n",
|
||||
"we download the MNIST data from a public S3 bucket and upload it \n",
|
||||
"to your default bucket. "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import logging\n",
|
||||
"import boto3\n",
|
||||
"from botocore.exceptions import ClientError\n",
|
||||
"# Download training and testing data from a public S3 bucket\n",
|
||||
"\n",
|
||||
"def download_from_s3(data_dir='/tmp/data', train=True):\n",
|
||||
" \"\"\"Download MNIST dataset and convert it to numpy array\n",
|
||||
" \n",
|
||||
" Args:\n",
|
||||
" data_dir (str): directory to save the data\n",
|
||||
" train (bool): download training set\n",
|
||||
" \n",
|
||||
" Returns:\n",
|
||||
" None\n",
|
||||
" \"\"\"\n",
|
||||
" \n",
|
||||
" if not os.path.exists(data_dir):\n",
|
||||
" os.makedirs(data_dir)\n",
|
||||
" \n",
|
||||
" if train:\n",
|
||||
" images_file = \"train-images-idx3-ubyte.gz\"\n",
|
||||
" labels_file = \"train-labels-idx1-ubyte.gz\"\n",
|
||||
" else:\n",
|
||||
" images_file = \"t10k-images-idx3-ubyte.gz\"\n",
|
||||
" labels_file = \"t10k-labels-idx1-ubyte.gz\"\n",
|
||||
" \n",
|
||||
" with open('code/config.json', 'r') as f:\n",
|
||||
" config = json.load(f)\n",
|
||||
"\n",
|
||||
" # download objects\n",
|
||||
" s3 = boto3.client('s3')\n",
|
||||
" bucket = config['public_bucket']\n",
|
||||
" for obj in [images_file, labels_file]:\n",
|
||||
" key = os.path.join(\"datasets/image/MNIST\", obj)\n",
|
||||
" dest = os.path.join(data_dir, obj)\n",
|
||||
" if not os.path.exists(dest):\n",
|
||||
" s3.download_file(bucket, key, dest)\n",
|
||||
" return\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"download_from_s3('/tmp/data', True)\n",
|
||||
"download_from_s3('/tmp/data', False)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# upload to the default bucket\n",
|
||||
"\n",
|
||||
"prefix = 'mnist'\n",
|
||||
"bucket = sess.default_bucket()\n",
|
||||
"loc = sess.upload_data(path='/tmp/data', bucket=bucket, key_prefix=prefix)\n",
|
||||
"\n",
|
||||
"channels = {\n",
|
||||
" \"training\": loc,\n",
|
||||
" \"testing\": loc\n",
|
||||
"}\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"The keys of the dictionary `channels` are parsed to the training image\n",
|
||||
"and it creates the environment variable `SM_CHANNEL_<key name>`. \n",
|
||||
"\n",
|
||||
"In this example, `SM_CHANNEL_TRAINING` and `SM_CHANNEL_TESTING` are created in the training image (checkout \n",
|
||||
"how `code/train.py` access these variables). For more information,\n",
|
||||
"see: [SM_CHANNEL_{channel_name}](https://github.com/aws/sagemaker-training-toolkit/blob/master/ENVIRONMENT_VARIABLES.md#sm_channel_channel_name)\n",
|
||||
"\n",
|
||||
"If you want, you can create a channel for validation:\n",
|
||||
"```\n",
|
||||
"channels = {\n",
|
||||
" 'training': train_data_loc,\n",
|
||||
" 'validation': val_data_loc,\n",
|
||||
" 'test': test_data_loc\n",
|
||||
" }\n",
|
||||
"```\n",
|
||||
"You can then access this channel within your training script via\n",
|
||||
"`SM_CHANNEL_VALIDATION`."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Run the training script on SageMaker\n",
|
||||
"Now, the training container has everything to execute your training\n",
|
||||
"script. You can start the container by calling `fit` method."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {
|
||||
"scrolled": true
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"est.fit(inputs=channels)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Inspect and store model data\n",
|
||||
"\n",
|
||||
"Now, the training is finished, the model artifact has been saved in \n",
|
||||
"the `output_path`. We "
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"tf_mnist_model_data = est.model_data\n",
|
||||
"print(\"Model artifact saved at:\\n\", tf_mnist_model_data)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We will store the variable `model_data` in the current notebook kernel. \n",
|
||||
"In the [next notebook](get_started_with_mnist_deploy.ipynb), you will learn how to retrieve the model artifact and deploy to a SageMaker\n",
|
||||
"endpoint."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%store tf_mnist_model_data"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Test and debug the entry point before executing the training container\n",
|
||||
"\n",
|
||||
"The entry point `code/train.py` provided here has been tested and it can be executed in the training container. \n",
|
||||
"When you develop your own training script, it is a good practice to simulate the container environment \n",
|
||||
"in the local shell and test it before sending it to SageMaker, because debugging in a containerized environment\n",
|
||||
"is rather cumbersome. The following script shows how you can test your training script:"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"!pygmentize code/test_train.py"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"In [the next notebook](get_started_mnist_deploy.ipynb) you will see how to deploy your \n",
|
||||
"trained model artifacts to a SageMaker endpoint. "
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"instance_type": "ml.t3.medium",
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (Data Science)",
|
||||
"language": "python",
|
||||
"name": "python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/datascience-1.0"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.7.6"
|
||||
},
|
||||
"notice": "Copyright 2017 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."
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 4
|
||||
}
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
../utils/
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"public_bucket": "sagemaker-sample-files"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import numpy as np
|
||||
from urllib import request
|
||||
import gzip
|
||||
import os
|
||||
import boto3
|
||||
import json
|
||||
|
||||
dirname = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
with open(os.path.join(dirname, "config.json"), "r") as f:
|
||||
CONFIG = json.load(f)
|
||||
|
||||
def mnist_to_numpy(data_dir='/tmp/data', train=True):
|
||||
"""Download MNIST dataset and convert it to numpy array
|
||||
|
||||
Args:
|
||||
data_dir (str): directory to save the data
|
||||
train (bool): download training set
|
||||
|
||||
Returns:
|
||||
tuple of images and labels as numpy arrays
|
||||
"""
|
||||
|
||||
if not os.path.exists(data_dir):
|
||||
os.makedirs(data_dir)
|
||||
|
||||
|
||||
if train:
|
||||
images_file = "train-images-idx3-ubyte.gz"
|
||||
labels_file = "train-labels-idx1-ubyte.gz"
|
||||
else:
|
||||
images_file = "t10k-images-idx3-ubyte.gz"
|
||||
labels_file = "t10k-labels-idx1-ubyte.gz"
|
||||
|
||||
# download objects
|
||||
s3 = boto3.client('s3')
|
||||
bucket = CONFIG["public_bucket"]
|
||||
for obj in [images_file, labels_file]:
|
||||
key = os.path.join("datasets/image/MNIST", obj)
|
||||
dest = os.path.join(data_dir, obj)
|
||||
if not os.path.exists(dest):
|
||||
s3.download_file(bucket, key, dest)
|
||||
|
||||
return _convert_to_numpy(data_dir, images_file, labels_file)
|
||||
|
||||
def _convert_to_numpy(data_dir, images_file, labels_file):
|
||||
"""Byte string to numpy arrays"""
|
||||
with gzip.open(os.path.join(data_dir, images_file), 'rb') as f:
|
||||
images = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1, 28, 28)
|
||||
|
||||
with gzip.open(os.path.join(data_dir, labels_file), 'rb') as f:
|
||||
labels = np.frombuffer(f.read(), np.uint8, offset=8)
|
||||
|
||||
return (images, labels)
|
||||
|
||||
def normalize(x, axis):
|
||||
eps = np.finfo(float).eps
|
||||
|
||||
mean = np.mean(x, axis=axis, keepdims=True)
|
||||
# avoid division by zero
|
||||
std = np.std(x, axis=axis, keepdims=True) + eps
|
||||
return (x - mean) / std
|
||||
|
||||
def adjust_to_framework(x, framework='pytorch'):
|
||||
"""Adjust a ``numpy.ndarray`` to be used as input for specified framework
|
||||
|
||||
Args:
|
||||
x (numpy.ndarray): Batch of images to be adjusted
|
||||
to follow the convention in pytorch / tensorflow / mxnet
|
||||
|
||||
framework (str): Framework to use. Takes value in
|
||||
``pytorch``, ``tensorflow`` or ``mxnet``
|
||||
Return:
|
||||
numpy.ndarray following the convention of tensors in the given
|
||||
framework
|
||||
"""
|
||||
|
||||
if x.ndim == 3:
|
||||
# input is gray-scale
|
||||
x = np.expand_dims(x, 1)
|
||||
|
||||
if framework in ['pytorch', 'mxnet']:
|
||||
# depth-major
|
||||
return x
|
||||
elif framework == 'tensorlfow':
|
||||
# depth-minor
|
||||
return np.transpose(x, (0, 2, 3, 1))
|
||||
elif framework == 'mxnet':
|
||||
return x
|
||||
else:
|
||||
raise ValueError('framework must be one of ' + \
|
||||
'[pytorch, tensorflow, mxnet], got {}'.format(framework))
|
||||
|
||||
if __name__ == '__main__':
|
||||
X, Y = mnist_to_numpy()
|
||||
X, Y = X.astype(np.float32), Y.astype(np.int8)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
+10
-6
@@ -22,8 +22,7 @@ from mxnet import autograd, gluon, nd
|
||||
from mxnet.test_utils import download
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
def main(args):
|
||||
# Function to get mnist iterator given a rank
|
||||
def get_mnist_iterator(rank):
|
||||
data_dir = "data-%d" % rank
|
||||
@@ -175,7 +174,7 @@ def main():
|
||||
device = context.device_type + str(num_workers)
|
||||
logging.info('Device info: %s', device)
|
||||
|
||||
if __name__ == "__main__":
|
||||
def parse_args():
|
||||
# Handling script arguments
|
||||
parser = argparse.ArgumentParser(description='MXNet MNIST Distributed Example')
|
||||
parser.add_argument('--batch-size', type=int, default=64,
|
||||
@@ -188,7 +187,8 @@ if __name__ == "__main__":
|
||||
help='learning rate (default: 0.01)')
|
||||
parser.add_argument('--momentum', type=float, default=0.9,
|
||||
help='SGD momentum (default: 0.9)')
|
||||
parser.add_argument('--no-cuda', action='store_true', help='disable training on GPU (default: False)')
|
||||
parser.add_argument('--no-cuda', type=bool, default=False,
|
||||
help='disable training on GPU (default: False)')
|
||||
|
||||
# Container Environment
|
||||
parser.add_argument('--hosts', type=list, default=json.loads(os.environ['SM_HOSTS']))
|
||||
@@ -203,8 +203,12 @@ if __name__ == "__main__":
|
||||
# Disable CUDA if there are no GPUs.
|
||||
if mx.context.num_gpus() == 0:
|
||||
args.no_cuda = True
|
||||
return args
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
args = parse_args()
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logging.info(args)
|
||||
|
||||
main()
|
||||
main(args)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
from train import train, parse_args
|
||||
|
||||
import sys
|
||||
import os
|
||||
import boto3
|
||||
import json
|
||||
|
||||
dirname = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
with open(os.path.join(dirname, "config.json"), "r") as f:
|
||||
CONFIG = json.load(f)
|
||||
|
||||
def download_from_s3(data_dir='/tmp/data', train=True):
|
||||
"""Download MNIST dataset and convert it to numpy array
|
||||
Args:
|
||||
data_dir (str): directory to save the data
|
||||
train (bool): download training set
|
||||
Returns:
|
||||
tuple of images and labels as numpy arrays
|
||||
"""
|
||||
|
||||
if not os.path.exists(data_dir):
|
||||
os.makedirs(data_dir)
|
||||
|
||||
if train:
|
||||
images_file = "train-images-idx3-ubyte.gz"
|
||||
labels_file = "train-labels-idx1-ubyte.gz"
|
||||
else:
|
||||
images_file = "t10k-images-idx3-ubyte.gz"
|
||||
labels_file = "t10k-labels-idx1-ubyte.gz"
|
||||
|
||||
# download objects
|
||||
s3 = boto3.client('s3')
|
||||
bucket = CONFIG["public_bucket"]
|
||||
for obj in [images_file, labels_file]:
|
||||
key = os.path.join("datasets/image/MNIST", obj)
|
||||
dest = os.path.join(data_dir, obj)
|
||||
if not os.path.exists(dest):
|
||||
s3.download_file(bucket, key, dest)
|
||||
return
|
||||
|
||||
class Env:
|
||||
def __init__(self):
|
||||
# simulate container env
|
||||
os.environ["SM_MODEL_DIR"] = "/tmp/tf/model"
|
||||
os.environ["SM_CHANNEL_TRAINING"]="/tmp/data"
|
||||
os.environ["SM_CHANNEL_TESTING"]="/tmp/data"
|
||||
os.environ["SM_HOSTS"] = '["algo-1"]'
|
||||
os.environ["SM_CURRENT_HOST"]="algo-1"
|
||||
os.environ["SM_NUM_GPUS"] = "0"
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
Env()
|
||||
download_from_s3()
|
||||
download_from_s3(train=False)
|
||||
args = parse_args()
|
||||
train(args)
|
||||
|
||||
+2
-2
@@ -317,7 +317,7 @@
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "conda_tensorflow_p36",
|
||||
"display_name": "Environment (conda_tensorflow_p36)",
|
||||
"language": "python",
|
||||
"name": "conda_tensorflow_p36"
|
||||
},
|
||||
@@ -331,7 +331,7 @@
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.6.5"
|
||||
"version": "3.6.10"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
|
||||
@@ -10,7 +10,6 @@ Apache MXNet
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
../sagemaker-python-sdk/mxnet_gluon_mnist/mxnet_mnist_with_gluon
|
||||
../sagemaker-python-sdk/mxnet_gluon_embedding_server/mxnet_embedding_server
|
||||
../sagemaker-python-sdk/mxnet_gluon_sentiment/mxnet_sentiment_analysis_with_gluon
|
||||
../introduction_to_applying_machine_learning/gluon_recommender_system/gluon_recommender_system
|
||||
@@ -45,7 +44,9 @@ PyTorch
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
../sagemaker-python-sdk/pytorch_mnist/pytorch_mnist
|
||||
../frameworks/pytorch/get_started_mnist_train
|
||||
../frameworks/pytorch/get_started_mnist_deploy
|
||||
../sagemaker-python-sdk/pytorch_lstm_word_language_model/pytorch_rnn
|
||||
../sagemaker-python-sdk/pytorch_lstm_word_language_model/pytorch_rnn
|
||||
|
||||
|
||||
@@ -86,6 +87,9 @@ TensorFlow
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
../frameworks/tensorflow/get_started_mnist_train
|
||||
../frameworks/tensorflow/get_started_mnist_deploy
|
||||
../sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode
|
||||
../sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode
|
||||
../sagemaker-python-sdk/tensorflow_script_mode_horovod/tensorflow_script_mode_horovod
|
||||
../sagemaker-python-sdk/tensorflow_script_mode_pipe_mode/tensorflow_script_mode_pipe_mode
|
||||
|
||||
Reference in New Issue
Block a user