Spot Instances
Manejo de interrupciones, checkpointing y flujos batch mixtos
Las Spot Instances son capacidad sobrante de AWS que se vende con descuento de hasta 90%. El trade-off es que AWS puede reclamarlas con 2 minutos de aviso cuando necesita la capacidad. Son perfectas para jobs que: (1) pueden interrumpirse y resumirse, (2) tienen duración corta o definida, (3) no sirven tráfico en tiempo real. Los casos de uso más comunes son entrenamiento de modelos ML, procesamiento batch, análisis de datos, y renderizado.
El mecanismo de interrupción funciona así: AWS envía una notificación de interrupción 2 minutos antes de terminar la instancia. Tu código debe escuchar esta señal (SIGTERM en Linux, o consultar el endpoint de metadatos EC2) y guardar el estado de progreso (checkpoint) antes de que la instancia sea terminada. Sin checkpoint, perderías todo el progreso.
Para entrenamiento de ML, el checkpoint consiste en guardar los pesos del modelo y el estado del optimizador en S3. Al reiniciar (en otra Spot instance o On-Demand), cargas el checkpoint y continúas desde donde quedaste. SageMaker tiene soporte nativo para Spot training: gestiona automáticamente los checkpoints y el reintento en caso de interrupción.
La estrategia mixed On-Demand + Spot es la más robusta para Auto Scaling Groups: defines un porcentaje de capacidad On-Demand como baseline (ej. 20%) y el resto como Spot de múltiples tipos de instancia. Al diversificar tipos de instancia (m5.large, m5a.large, t3.large), reduces la probabilidad de que todas las instancias sean interrumpidas simultáneamente, ya que diferentes pools de Spot tienen disponibilidades distintas.
import boto3
import signal
import json
import sys
import time
import urllib.request
s3 = boto3.client('s3')
CHECKPOINT_BUCKET = 'my-training-checkpoints'
CHECKPOINT_KEY = 'model/latest_checkpoint.json'
# === Interruption handler: save checkpoint before termination ===
def save_checkpoint(step: int, model_state: dict) -> None:
checkpoint = {
'step': step,
'model_state': model_state,
'timestamp': int(time.time())
}
# Save to local file
with open('/tmp/checkpoint.json', 'w') as f:
json.dump(checkpoint, f)
# Upload to S3
s3.upload_file('/tmp/checkpoint.json', CHECKPOINT_BUCKET, CHECKPOINT_KEY)
print(f'Checkpoint saved at step {step}')
def load_checkpoint() -> dict | None:
try:
s3.download_file(CHECKPOINT_BUCKET, CHECKPOINT_KEY, '/tmp/checkpoint.json')
with open('/tmp/checkpoint.json') as f:
return json.load(f)
except Exception:
return None # no checkpoint, start from scratch
# Handle SIGTERM (sent 2 minutes before interruption)
def handle_interruption(step_ref):
def handler(signum, frame):
print('SIGTERM received — spot interruption imminent. Saving checkpoint...')
save_checkpoint(step_ref['current'], step_ref['model_state'])
sys.exit(0)
return handler
# Check interruption via metadata service (poll every 5 seconds)
def check_spot_interruption() -> bool:
try:
url = 'http://169.254.169.254/latest/meta-data/spot/termination-time'
urllib.request.urlopen(url, timeout=1)
return True # termination-time endpoint only exists if interrupted
except Exception:
return False # not interrupted
# Training loop with checkpoint support
def train_with_checkpointing(total_steps: int = 1000):
step_ref = {'current': 0, 'model_state': {}}
signal.signal(signal.SIGTERM, handle_interruption(step_ref))
# Resume from checkpoint if exists
checkpoint = load_checkpoint()
start_step = checkpoint['step'] + 1 if checkpoint else 0
print(f'Starting from step {start_step}')
for step in range(start_step, total_steps):
step_ref['current'] = step
# ... training logic ...
if check_spot_interruption():
print('Interruption detected via metadata service')
save_checkpoint(step, step_ref['model_state'])
sys.exit(0)
# Save checkpoint every 100 steps (not just on interruption)
if step % 100 == 0:
save_checkpoint(step, step_ref['model_state'])
# === Auto Scaling Group: mixed On-Demand + Spot ===
ec2 = boto3.client('ec2')
autoscaling = boto3.client('autoscaling')
# Create mixed instance policy
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='ml-training-asg',
MixedInstancesPolicy={
'InstancesDistribution': {
'OnDemandPercentageAboveBaseCapacity': 20, # 20% On-Demand baseline
'SpotAllocationStrategy': 'lowest-price',
},
'LaunchTemplate': {
'LaunchTemplateSpecification': {'LaunchTemplateName': 'ml-training'},
'Overrides': [
{'InstanceType': 'm5.large'},
{'InstanceType': 'm5a.large'},
{'InstanceType': 't3.large'},
{'InstanceType': 't3a.large'}, # multiple types = less interruption risk
]
}
},
MinSize=1, MaxSize=10, DesiredCapacity=5
)Debugging lab
Detecta y corrige el error en el código.
- 01
# Training on Spot instance without interruption handler for epoch in range(100): train_epoch() # No checkpoint, no SIGTERM handler # If Spot is interrupted at epoch 87, all work is lost
- 02
# Spot instance without metadata polling # SIGTERM arrives 2 minutes before termination # But if training step takes 3 minutes, checkpoint is lost def handle_sigterm(s, f): save_checkpoint() # may not finish in 2 minutes
- 03
# Auto Scaling Group using only one Spot instance type autoscaling.create_auto_scaling_group( AutoScalingGroupName='ml-asg', LaunchTemplate={'LaunchTemplateName': 'm5.large'}, MinSize=1, MaxSize=10 # Only m5.large pool — if it's depleted, all instances interrupted