Lesson 2 of 5 Training Models with SageMaker AI

Training Custom Code with Script Mode and Framework Containers

This lesson explains script mode, the usual way to train custom models on SageMaker AI, which runs a normal training script in an AWS-maintained framework container without building or maintaining images.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how a framework estimator runs an entry point script.
  • Write a training script that reads and writes the SageMaker paths.
  • Choose between built-in algorithms, script mode and custom containers.
  • Add libraries with a requirements file instead of a custom image.

How script mode works

A framework estimator in the SageMaker Python SDK, such as PyTorch, TensorFlow, SKLearn, XGBoost or HuggingFace, takes an entry_point script, an optional source_dir with helper modules and a requirements.txt, the framework and Python versions, the instance type and count, and hyperparameters. When fit() is called, SageMaker AI starts instances, pulls the framework image, downloads input channels and runs the script.

Inside the container, hyperparameters arrive as command-line arguments (and also as SM_HP_<NAME> environment variables), and paths arrive as environment variables: SM_CHANNEL_<NAME> for each input channel, SM_MODEL_DIR (/opt/ml/model) for the model, SM_OUTPUT_DATA_DIR for other outputs and SM_NUM_GPUS for the hardware. Anything saved to the model directory is packaged as model.tar.gz in S3 when training ends.

The following diagram shows how SageMaker AI runs a script-mode training job.

What happens when a script-mode estimator's fit() is called. SageMaker AI starts the instances, pulls the framework image, downloads each input channel and runs the entry-point script, passing hyperparameters as arguments and paths as environment variables. Whatever the script saves to SM_MODEL_DIR is packaged as model.tar.gz in S3 when training ends.
The paths are the standard SageMaker AI container paths.
Match the pairs

Script mode paths

Exam skills 2.2.2

Match each script mode environment variable with what it holds.

Log in to try this activity Interactive activities are free with an account.

A minimal example

# train.py
import argparse, os, joblib, pandas as pd
from sklearn.ensemble import RandomForestClassifier

p = argparse.ArgumentParser()
p.add_argument("--n-estimators", type=int, default=200)
args = p.parse_args()

df = pd.read_csv(os.path.join(os.environ["SM_CHANNEL_TRAIN"], "train.csv"))
model = RandomForestClassifier(n_estimators=args.n_estimators).fit(df.drop(columns="label"), df["label"])
joblib.dump(model, os.path.join(os.environ["SM_MODEL_DIR"], "model.joblib"))

# launcher (notebook or pipeline)
from sagemaker.sklearn import SKLearn
est = SKLearn(entry_point="train.py", framework_version="1.2-1", instance_type="ml.m5.xlarge",
              role=role, hyperparameters={"n-estimators": 300})
est.fit({"train": "s3://bucket/churn/train/"})

The same script runs locally for debugging and in SageMaker AI for scale. Local mode in the SDK can run the container on a notebook instance before using paid training instances.

Spot the bug

A script mode script that loses its model

Exam skills 2.2.2 · 3.3.3

Find the three lines that make this training script fail in SageMaker AI script mode.

Log in to try this activity Interactive activities are free with an account.

Script mode compared with other options

SageMaker AI offers three ways to train, with increasing flexibility and effort. Built-in algorithms need no code but offer fixed behaviour. Script mode adds the team's own training script to managed framework images; it keeps the framework optimisations AWS provides and works with distributed training libraries, SageMaker Debugger and automatic model tuning.

Extending a framework image with a Dockerfile, or bringing a fully custom container, is needed only for system-level dependencies that cannot be installed with pip from a requirements file, because custom images must then be built, scanned and maintained by the team. The following table summarises the choice.

OptionYour codeContainer workUse when
Built-in algorithmNoneNoneProblem matches an algorithm
Script modeTraining scriptNone (requirements.txt for packages)Custom logic on a supported framework
Extended framework imageScriptDockerfile based on AWS imageSystem libraries or special drivers
Fully custom imageEverythingFull containerUnsupported framework or language
Scenario questions

Built-in, script mode or BYOC?

Exam skills 2.2.2

Choose between a built-in algorithm, script mode and a custom container.

Log in to try this activity Interactive activities are free with an account.
Worked example

Adding a library

A team's PyTorch training script needs the timm and albumentations Python packages. A colleague proposes building a custom Docker image.

Listing both packages in requirements.txt inside source_dir is enough: the PyTorch framework container installs them before running the script. A custom image would add a build pipeline, ECR repository and patching work with no benefit, so it is not the least-effort answer.

The packages are downloaded from PyPI when the container starts, so this works only when the job can reach a package repository. With network isolation enabled, or in private subnets with no route to PyPI or an AWS CodeArtifact repository, the installation fails; in that case the packages must be built into an extended framework image instead.

Check yourself

Where does a script-mode training script save the model?

Show answer

In the directory given by SM_MODEL_DIR; input data is read from SM_CHANNEL_<NAME>.

Exam Tips

Remember for the exam

  • Custom code on a supported framework: script mode.
  • Extra Python packages: requirements.txt in source_dir (needs access to PyPI or CodeArtifact at start-up).
  • Read data from SM_CHANNEL_<NAME>; save the model to SM_MODEL_DIR.
  • Hyperparameters are passed as command-line arguments.
  • Extend or build images only for needs pip cannot satisfy.