SageMaker
Amazon SageMaker
AWS's fully managed machine learning platform. Supports the entire MLOps pipeline from data preparation, model training, deployment, to monitoring, and foundation models can also be used through JumpStart.
Amazon SageMaker
AWS's fully managed machine learning platform. Supports the entire MLOps pipeline from data preparation, model training, deployment, to monitoring, and foundation models can also be used through JumpStart.
Amazon SageMaker is a fully managed machine learning service first announced at AWS re:Invent in 2017. It is designed to help developers and data scientists quickly build, train, and deploy ML models. Its strength is deep integration with the AWS ecosystem, and it works naturally with S3, Lambda, Step Functions, CloudWatch, and more.
SageMaker has a variety of core components. Studio is a web-based IDE that provides notebooks, experiment management, and model debugging in one place. Processing runs large-scale data preprocessing in a distributed manner. Training runs training on a variety of instance types, and costs can be reduced by using Spot Instances. Inference supports real-time endpoints, batch transform, and serverless inference.
Recently, support for generative AI has been significantly strengthened. JumpStart can deploy open-source foundation models such as Llama, Falcon, and FLAN-T5 with one click, and they can be fine-tuned with your own data. When integrated with Bedrock, managed LLM APIs such as Claude and Titan can also be used.
In terms of MLOps, SageMaker Pipelines defines and automates ML workflows as code. Model Registry manages model versions, and Model Monitor monitors deployed models for data drift and performance degradation. Feature Store centrally manages the features used for training and inference.
# Amazon SageMaker를 활용한 ML 파이프라인 예제
import sagemaker
from sagemaker import get_execution_role
from sagemaker.estimator import Estimator
from sagemaker.processing import ScriptProcessor
from sagemaker.workflow.pipeline import Pipeline
from sagemaker.workflow.steps import ProcessingStep, TrainingStep, CreateModelStep
from sagemaker.workflow.parameters import ParameterString
from sagemaker.model import Model
from sagemaker.predictor import Predictor
# 세션 초기화
session = sagemaker.Session()
role = get_execution_role()
bucket = session.default_bucket()
# ==========================================
# 1. 데이터 전처리 (Processing)
# ==========================================
from sagemaker.sklearn.processing import SKLearnProcessor
sklearn_processor = SKLearnProcessor(
framework_version="1.2-1",
role=role,
instance_type="ml.m5.xlarge",
instance_count=1
)
# 전처리 실행
sklearn_processor.run(
code="preprocessing.py",
inputs=[
sagemaker.processing.ProcessingInput(
source="s3://my-bucket/raw-data/",
destination="/opt/ml/processing/input"
)
],
outputs=[
sagemaker.processing.ProcessingOutput(
output_name="train",
source="/opt/ml/processing/output/train",
destination=f"s3://{bucket}/processed/train"
),
sagemaker.processing.ProcessingOutput(
output_name="test",
source="/opt/ml/processing/output/test",
destination=f"s3://{bucket}/processed/test"
)
]
)
# ==========================================
# 2. 모델 학습 (Training)
# ==========================================
# PyTorch Estimator 예제
from sagemaker.pytorch import PyTorch
pytorch_estimator = PyTorch(
entry_point="train.py",
source_dir="./code",
role=role,
instance_count=1,
instance_type="ml.p3.2xlarge",
framework_version="2.1",
py_version="py310",
hyperparameters={
"epochs": 10,
"batch-size": 32,
"learning-rate": 0.001
},
use_spot_instances=True, # Spot 인스턴스로 비용 절감
max_run=3600,
max_wait=7200
)
# 학습 실행
pytorch_estimator.fit({
"train": f"s3://{bucket}/processed/train",
"test": f"s3://{bucket}/processed/test"
})
# ==========================================
# 3. 모델 배포 (Real-time Inference)
# ==========================================
predictor = pytorch_estimator.deploy(
initial_instance_count=1,
instance_type="ml.g4dn.xlarge",
endpoint_name="my-pytorch-endpoint"
)
# 추론 실행
import numpy as np
result = predictor.predict(np.array([[1.0, 2.0, 3.0, 4.0]]))
print(f"Prediction: {result}")
# ==========================================
# 4. SageMaker Pipelines (MLOps)
# ==========================================
from sagemaker.workflow.pipeline_context import PipelineSession
pipeline_session = PipelineSession()
# 파이프라인 파라미터
input_data = ParameterString(name="InputData", default_value=f"s3://{bucket}/raw-data")
instance_type = ParameterString(name="TrainingInstance", default_value="ml.m5.xlarge")
# 전처리 단계
processing_step = ProcessingStep(
name="DataPreprocessing",
processor=sklearn_processor,
inputs=[
sagemaker.processing.ProcessingInput(
source=input_data,
destination="/opt/ml/processing/input"
)
],
outputs=[
sagemaker.processing.ProcessingOutput(
output_name="train",
source="/opt/ml/processing/output/train"
)
],
code="preprocessing.py"
)
# 학습 단계
training_step = TrainingStep(
name="ModelTraining",
estimator=pytorch_estimator,
inputs={
"train": sagemaker.inputs.TrainingInput(
s3_data=processing_step.properties.ProcessingOutputConfig.Outputs["train"].S3Output.S3Uri
)
}
)
# 파이프라인 정의
pipeline = Pipeline(
name="ml-training-pipeline",
parameters=[input_data, instance_type],
steps=[processing_step, training_step]
)
# 파이프라인 생성 및 실행
pipeline.upsert(role_arn=role)
execution = pipeline.start()
# ==========================================
# 5. JumpStart로 LLM 배포
# ==========================================
from sagemaker.jumpstart.model import JumpStartModel
# Llama 2 모델 배포
llm_model = JumpStartModel(
model_id="meta-textgeneration-llama-2-7b",
role=role
)
llm_predictor = llm_model.deploy(
initial_instance_count=1,
instance_type="ml.g5.2xlarge",
endpoint_name="llama2-endpoint"
)
# LLM 추론
response = llm_predictor.predict({
"inputs": "What is machine learning?",
"parameters": {
"max_new_tokens": 256,
"temperature": 0.7
}
})
print(response)
ML Lead: "Training is taking too long. Should we move up to p3.8xlarge?"
Engineer: "Let's apply Spot Instances first. If you set max_wait, training can resume from a checkpoint even if it's interrupted. It can cut costs by up to 70%."
ML Lead: "Sounds good. And let's also check GPU utilization with SageMaker Debugger. It could be a batch size issue."
Interviewer: "Please explain the differences between model deployment options in SageMaker."
Candidate: "Real-time Inference is for APIs that need millisecond-level responses, and Batch Transform is suited to processing large volumes of data in bulk. Serverless Inference is cost-effective when traffic is irregular and you can tolerate cold starts, and Async Inference is used for large models whose response times take anywhere from several seconds to minutes."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: "data_capture_config is missing when deploying the endpoint. It's required if you want to use Model Monitor in production."
Author: "Ah, I'll add the inference data capture configuration and generate the baseline at the same time."