A standardized Python framework for seamless integration between ML frameworks (TensorRT-LLM, vLLM) and Amazon SageMaker hosting.
Overview
This package simplifies model deployment by providing:
Unified Handler System: Consistent /ping and /invocations endpoints across frameworks
Flexible Configuration: Environment variables, decorators, or custom scripts
Automatic Dependency Installation: Installs requirements.txt from model artifacts before server startup
Framework Agnostic: Works with vLLM, TensorRT-LLM, and other ML frameworks
Production Ready: Comprehensive logging, error handling, and debugging tools
Quick Start
# Install
poetry install
# Framework integration (e.g., in vLLM server code)
import model_hosting_container_standards.sagemaker as sagemaker_standards
from fastapi import Request, Response
import json
@sagemaker_standards.register_ping_handler
async def ping(raw_request: Request) -> Response:
"""Ping check. Endpoint required for SageMaker"""
return Response(
content='{"status": "healthy", "source": "vllm_default"}',
media_type="application/json",
)
@sagemaker_standards.register_invocation_handler
@sagemaker_standards.inject_adapter_id("model")
async def invocations(raw_request: Request) -> Response:
"""Model invocations endpoint with LoRA adapter injection"""
body_bytes = await raw_request.body()
body = json.loads(body_bytes.decode()) if body_bytes else {}
# Adapter ID injected by decorator from SageMakerLoRAApiHeader
adapter_id = body.get("model", "base-model")
# Your model inference logic here
response_data = {
"predictions": ["Generated text response"],
"adapter_id": adapter_id,
}
return Response(
content=json.dumps(response_data),
media_type="application/json",
)
# Customer customization (in model.py)
@sagemaker_standards.custom_ping_handler
async def custom_ping(raw_request: Request):
return Response(status_code=200, content="Custom OK")
# Or simple functions (automatically discovered)
async def ping():
return {"status": "healthy"}
Installation
# Install with Poetry (development)
poetry install
# Build wheel for distribution
poetry build
Requirements: Python >= 3.10, FastAPI >= 0.117.1
Usage Patterns
1. Framework Integration
For framework developers (e.g., vLLM, TensorRT-LLM), use register decorators to automatically set up routes:
import model_hosting_container_standards.sagemaker as sagemaker_standards
from fastapi import Request, Response
# Register decorators - automatically create /ping and /invocations routes
@sagemaker_standards.register_ping_handler
async def ping(request: Request) -> Response:
"""Framework ping handler with automatic routing."""
return Response(status_code=200, content="OK")
@sagemaker_standards.register_invocation_handler
async def invocations(request: Request) -> dict:
"""Framework invocation handler with automatic routing."""
body = await request.json()
# Process your model inference here
return {"result": "processed"}
# Optional: Add LoRA adapter support
@sagemaker_standards.register_invocation_handler
@sagemaker_standards.inject_adapter_id("model") # Replace mode
async def invocations_with_lora(request: Request) -> dict:
"""Invocation handler with LoRA adapter ID injection."""
body = await request.json()
adapter_id = body.get("model", "base-model") # Injected from header
# Use adapter_id for model inference
return {"result": f"processed with {adapter_id}"}
2. Customer Script Customization
For customers customizing model behavior, put this in your model artifact folder as model.py:
import model_hosting_container_standards.sagemaker as sagemaker_standards
from fastapi import Request
from fastapi.responses import Response
# Override decorators - immediately register handlers
@sagemaker_standards.custom_ping_handler
async def custom_ping(request: Request) -> Response:
"""Custom ping handler."""
return Response(status_code=200, content="OK")
@sagemaker_standards.custom_invocation_handler
async def custom_invoke(request: Request) -> dict:
"""Custom invocation handler."""
body = await request.json()
# Process your model inference here
return {"result": "processed"}
# Or use simple functions (automatically discovered)
async def custom_sagemaker_ping_handler():
"""Simple ping function - automatically discovered."""
return {"status": "healthy"}
async def custom_sagemaker_invocation_handler(request: Request):
"""Simple invoke function - automatically discovered."""
body = await request.json()
return {"result": "processed"}
3. Environment Variable Configuration
# Point to custom handlers in your code
export CUSTOM_FASTAPI_PING_HANDLER="model.py:my_ping_function"
export CUSTOM_FASTAPI_INVOCATION_HANDLER="model.py:my_invoke_function"
# Or use absolute paths
export CUSTOM_FASTAPI_PING_HANDLER="/opt/ml/model/handlers.py:ping"
# Or use module
export CUSTOM_FASTAPI_INVOCATION_HANDLER="model:my_invoke_function" #`model` is alias to $SAGEMAKER_MODEL_PATH/$CUSTOM_SCRIPT_FILENAME
CUSTOM_FASTAPI_PING_HANDLER="vllm.entrypoints.openai.api_server:health"
4. Handler Resolution Priority
The system automatically resolves handlers in this order:
Environment variables always take priority over decorator-registered middleware:
# This decorator will be ignored if CUSTOM_FASTAPI_MIDDLEWARE_THROTTLE is set
@custom_middleware("throttle")
async def decorator_throttle(request, call_next):
return await call_next(request)
# Environment variable takes priority (can use module or file path)
# CUSTOM_FASTAPI_MIDDLEWARE_THROTTLE=throttle_module:ThrottleClass
# CUSTOM_FASTAPI_MIDDLEWARE_THROTTLE=env_throttle.py:env_throttle_func
The package provides centralized logging control using standard SageMaker environment variables.
By default, the package uses ERROR level logging, which effectively keeps it silent in production unless there are actual errors.
Log Level Configuration
# Set log level using SageMaker standard variable (recommended)
export SAGEMAKER_CONTAINER_LOG_LEVEL=DEBUG # or INFO, WARNING, ERROR (default)
# Alternative: Use generic LOG_LEVEL variable
export LOG_LEVEL=INFO # Falls back to this if SAGEMAKER_CONTAINER_LOG_LEVEL not set
Log Levels
ERROR (default): Only errors are logged - effectively silent in normal operation
WARNING: Errors and warnings
INFO: Informational messages, warnings, and errors
DEBUG: Detailed debug information including handler resolution
Log Format
All package logs use a consistent format:
[LEVEL] logger_name - filename:line: message
Examples
# Production: ERROR level by default (silent unless errors occur)
vllm serve model --dtype auto
# Development: Enable INFO level logging
SAGEMAKER_CONTAINER_LOG_LEVEL=INFO vllm serve model --dtype auto
# Debug mode: Enable detailed DEBUG logging
SAGEMAKER_CONTAINER_LOG_LEVEL=DEBUG vllm serve model --dtype auto
# Using alternative LOG_LEVEL variable
LOG_LEVEL=DEBUG vllm serve model --dtype auto
Note: These environment variables only control package logging. Your application's logging configuration is independent and unaffected.
Testing
Quick Endpoint Testing
# Start your service (example with vLLM)
vllm serve TinyLlama/TinyLlama-1.1B-Chat-v1.0 --dtype auto
# Test ping
curl -i http://127.0.0.1:8000/ping
# Test invocation
curl -X POST http://localhost:8000/invocations \
-H "Content-Type: application/json" \
-d '{"prompt": "Hello!", "max_tokens": 50}'
Development
Quick Development Setup
# Install dependencies and dev tools
make install
# Install pre-commit hooks (recommended)
make pre-commit-install
# Run all checks
make all
Development Commands
make install # Install dependencies
make format # Format code (black, isort)
make lint # Run linters (flake8, mypy)
make test # Run test suite
make all # Format, lint, and test
make clean # Clean build artifacts
Code Quality Tools
Black (88 char line length) + isort for formatting