|
| 1 | +import argparse |
| 2 | +import numpy as np |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import logging |
| 6 | +import json |
| 7 | +import shutil |
| 8 | +import torch |
| 9 | +import torch.nn as nn |
| 10 | +from torch.utils.data import DataLoader, TensorDataset |
| 11 | +from pytorch_model_def import get_model |
| 12 | + |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | +logger.setLevel(logging.DEBUG) |
| 16 | +logger.addHandler(logging.StreamHandler(sys.stdout)) |
| 17 | + |
| 18 | + |
| 19 | +def parse_args(): |
| 20 | + """ |
| 21 | + Parse arguments passed from the SageMaker API |
| 22 | + to the container |
| 23 | + """ |
| 24 | + |
| 25 | + parser = argparse.ArgumentParser() |
| 26 | + |
| 27 | + # Hyperparameters sent by the client are passed as command-line arguments to the script |
| 28 | + parser.add_argument("--epochs", type=int, default=1) |
| 29 | + parser.add_argument("--batch_size", type=int, default=64) |
| 30 | + parser.add_argument("--learning_rate", type=float, default=0.1) |
| 31 | + |
| 32 | + # Data directories |
| 33 | + parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAIN")) |
| 34 | + parser.add_argument("--test", type=str, default=os.environ.get("SM_CHANNEL_TEST")) |
| 35 | + |
| 36 | + # Model directory: we will use the default set by SageMaker, /opt/ml/model |
| 37 | + parser.add_argument("--model_dir", type=str, default=os.environ.get("SM_MODEL_DIR")) |
| 38 | + |
| 39 | + return parser.parse_known_args() |
| 40 | + |
| 41 | + |
| 42 | +def get_train_data(train_dir): |
| 43 | + """ |
| 44 | + Get the training data and convert to tensors |
| 45 | + """ |
| 46 | + |
| 47 | + x_train = np.load(os.path.join(train_dir, "x_train.npy")) |
| 48 | + y_train = np.load(os.path.join(train_dir, "y_train.npy")) |
| 49 | + logger.info(f"x train: {x_train.shape}, y train: {y_train.shape}") |
| 50 | + |
| 51 | + return torch.from_numpy(x_train), torch.from_numpy(y_train) |
| 52 | + |
| 53 | + |
| 54 | +def get_test_data(test_dir): |
| 55 | + """ |
| 56 | + Get the testing data and convert to tensors |
| 57 | + """ |
| 58 | + |
| 59 | + x_test = np.load(os.path.join(test_dir, "x_test.npy")) |
| 60 | + y_test = np.load(os.path.join(test_dir, "y_test.npy")) |
| 61 | + logger.info(f"x test: {x_test.shape}, y test: {y_test.shape}") |
| 62 | + |
| 63 | + return torch.from_numpy(x_test), torch.from_numpy(y_test) |
| 64 | + |
| 65 | + |
| 66 | +def model_fn(model_dir): |
| 67 | + """ |
| 68 | + Load the model for inference |
| 69 | + """ |
| 70 | + |
| 71 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 72 | + model = get_model() |
| 73 | + model.load_state_dict(torch.load(model_dir + "/model.pth")) |
| 74 | + model.eval() |
| 75 | + return model.to(device) |
| 76 | + |
| 77 | + |
| 78 | +def input_fn(request_body, request_content_type): |
| 79 | + """ |
| 80 | + Deserialize and prepare the prediction input |
| 81 | + """ |
| 82 | + |
| 83 | + if request_content_type == "application/json": |
| 84 | + request = json.loads(request_body) |
| 85 | + train_inputs = torch.tensor(request) |
| 86 | + return train_inputs |
| 87 | + |
| 88 | + |
| 89 | +def predict_fn(input_data, model): |
| 90 | + """ |
| 91 | + Apply model to the incoming request |
| 92 | + """ |
| 93 | + |
| 94 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 95 | + model.to(device) |
| 96 | + model.eval() |
| 97 | + with torch.no_grad(): |
| 98 | + return model(input_data.float()).numpy()[0] |
| 99 | + |
| 100 | + |
| 101 | +def train(): |
| 102 | + """ |
| 103 | + Train the PyTorch model |
| 104 | + """ |
| 105 | + |
| 106 | + x_train, y_train = get_train_data(args.train) |
| 107 | + x_test, y_test = get_test_data(args.test) |
| 108 | + train_ds = TensorDataset(x_train, y_train) |
| 109 | + |
| 110 | + batch_size = args.batch_size |
| 111 | + epochs = args.epochs |
| 112 | + learning_rate = args.learning_rate |
| 113 | + logger.info( |
| 114 | + "batch_size = {}, epochs = {}, learning rate = {}".format( |
| 115 | + batch_size, epochs, learning_rate |
| 116 | + ) |
| 117 | + ) |
| 118 | + |
| 119 | + train_dl = DataLoader(train_ds, batch_size, shuffle=True) |
| 120 | + |
| 121 | + model = get_model() |
| 122 | + model = model.to(device) |
| 123 | + criterion = nn.MSELoss() |
| 124 | + optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) |
| 125 | + |
| 126 | + for epoch in range(epochs): |
| 127 | + for x_train_batch, y_train_batch in train_dl: |
| 128 | + y = model(x_train_batch.float()) |
| 129 | + loss = criterion(y.flatten(), y_train_batch.float()) |
| 130 | + optimizer.zero_grad() |
| 131 | + loss.backward() |
| 132 | + optimizer.step() |
| 133 | + epoch += 1 |
| 134 | + logger.info(f"epoch: {epoch} -> loss: {loss}") |
| 135 | + |
| 136 | + # evalutate on test set |
| 137 | + with torch.no_grad(): |
| 138 | + y = model(x_test.float()).flatten() |
| 139 | + mse = ((y - y_test) ** 2).sum() / y_test.shape[0] |
| 140 | + print("\nTest MSE:", mse.numpy()) |
| 141 | + |
| 142 | + torch.save(model.state_dict(), args.model_dir + "/model.pth") |
| 143 | + # PyTorch requires that the inference script must |
| 144 | + # be in the .tar.gz model file and Step Functions SDK doesn't do this. |
| 145 | + inference_code_path = args.model_dir + "/code/" |
| 146 | + |
| 147 | + if not os.path.exists(inference_code_path): |
| 148 | + os.mkdir(inference_code_path) |
| 149 | + logger.info("Created a folder at {}!".format(inference_code_path)) |
| 150 | + |
| 151 | + shutil.copy("train_deploy_pytorch_without_dependencies.py", inference_code_path) |
| 152 | + shutil.copy("pytorch_model_def.py", inference_code_path) |
| 153 | + logger.info("Saving models files to {}".format(inference_code_path)) |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + |
| 158 | + args, _ = parse_args() |
| 159 | + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 160 | + |
| 161 | + train() |
0 commit comments