opensi·si

Last updated 2026-10-23

DeepSeek OCR Pipeline on SageMaker Training Jobs

Last updated 2026-10-23

📖 Context: This notebook is part of the VLM-OCR Recipes on GPU Infrastructure article, which explains the architecture and design decisions behind this pipeline.

This notebook runs a three-stage OCR pipeline using SageMaker Training Jobs:

  1. Extract - Run DeepSeek OCR over a dataset, save Markdown and crop detected figures
  2. Describe - Generate captions for extracted figures
  3. Assemble - Enrich Markdown with figure captions

This is the SageMaker equivalent of the HuggingFace Jobs pipeline. It uses SageMaker ModelTrainer V3 with a vLLM container to run GPU-accelerated inference.

Key difference from HF Jobs: This notebook saves datasets to S3 instead of HuggingFace Hub.

Prerequisites

  • AWS credentials configured
  • SageMaker execution role with S3 access
  • HuggingFace token for accessing source models and datasets
  • SageMaker SDK V3 installed (pip install sagemaker --upgrade)

📑 Table of Contents

  1. Setup
    • AWS SageMaker Training Jobs
    • How the pipeline code is shipped
    • The dataset
    • Inference Backend: vLLM
    • DeepSeek-OCR Prompts
  2. Authentication
  3. Configuration
  4. Bundle Pipeline Code
  5. Define Base Environment Variables
  6. Helper Functions
  7. Stage 1: Extract
    • Batch size optimization
  8. Stage 2: Describe
  9. Stage 3: Assemble
  10. Cost Analysis
  11. Pipeline Complete

⚙️ Setup

🔧 AWS SageMaker Training Jobs

SageMaker Training Jobs provide managed infrastructure for running compute-intensive workloads. While traditionally used for model training, they're equally well-suited for batch inference.

Why Training Jobs for batch OCR?

Training Jobs are the best option for accessing GPUs on SageMaker for offline/batch workloads:

  • Direct GPU access: Spin up powerful instances like ml.g6e.2xlarge (L40S GPU) or ml.p4d.24xlarge (8x A100) on demand
  • Pay per use: Billed per second only while the job runs - no idle costs
  • Automatic cleanup: Jobs terminate automatically on completion, releasing resources
  • S3 integration: Native support for reading/writing large datasets directly to S3
  • vLLM DLC: Pre-built Deep Learning Containers with vLLM for efficient inference
  • No infrastructure management: No cluster setup, scaling, or maintenance required

Alternative: SageMaker Endpoints

For different use cases, SageMaker Endpoints could be explored:

Aspect Training Jobs Endpoints
Best for Batch/offline processing Real-time inference
Billing Per-second while running Per-hour while deployed
Latency Minutes to start Always ready (when deployed)
Cost model Pay only during processing Pay for uptime
Scaling Single job, fixed resources Auto-scaling on demand

For this pipeline's batch OCR workload - processing thousands of documents in one go - Training Jobs are more cost-effective since we only pay for actual compute time rather than keeping an endpoint running.

📦 How the pipeline code is shipped

This notebook uses the SageMaker Python SDK v3 with the new ModelTrainer API to launch training jobs. The ModelTrainer class provides a simplified, declarative interface for configuring and running jobs.

For every SageMaker Training Job we launch, the logic is similar:

The pipeline code (entry.sh, sm_job_runner.py and the llm_ocr package) lives in the fgbelidji/llm-lab repository. We clone it (see the next section) rather than vendoring it here, then bundle and upload to S3:

  1. The entrypoint script (entry.sh + sm_job_runner.py)
  2. The pipeline code in llm_ocr/

SageMaker automatically makes this code available at /opt/ml/input/data/code inside the container.

Then we launch a SageMaker Training Job using ModelTrainer:

trainer = ModelTrainer(
    training_image=TRAINING_IMAGE,      # vLLM DLC from ECR
    source_code=SourceCode(source_dir), # Code bundle
    compute=Compute(instance_type, instance_count),
    hyperparameters={...},              # Environment variables
    output_data_config=OutputDataConfig(s3_output_path),
)
trainer.train(wait=False)  # Async execution

The job then:

  1. Pulls the vLLM Deep Learning Container from ECR
  2. Downloads the code bundle from S3
  3. Runs entry.sh which installs dependencies via uv and executes sm_job_runner.py
  4. The runner starts a vLLM server, then imports llm_ocr.cli and calls main() to run the pipeline stage
  5. Results are saved back to S3

📚 The dataset

This pipeline uses FineVision (HuggingFaceM4/FineVision) as a large, mixed image+text corpus for vision-language training/evaluation. FineVision aggregates many public sub-datasets into one unified interface, and you select a specific subset/config when loading.

  • Dataset: HuggingFaceM4/FineVision
  • Overview / exploration space: HuggingFaceM4/FineVision Space

The olmOCR subsets

The olmOCR-mix-0225 dataset from Allen AI contains 260,000 crawled PDF pages from over 100,000 diverse PDFs - academic papers, legal documents, public domain books, brochures, and more. It includes challenging content: graphics, handwritten text, multi-column layouts, tables, equations, and poor quality scans.

Available configs:

  • olmOCR-mix-0225-documents - general documents
  • olmOCR-mix-0225-books - book pages

📄 Note: In this pipeline, one document = one page of a PDF.

These mirror real-world enterprise use cases: contracts, invoices, reports, forms, and scanned documents that organizations need to digitize and extract structured information from.

Licensing note: FineVision is a collection of many datasets, each with its own license/terms. Make sure the subset you use is compatible with your intended downstream use (see the dataset card for details).

⚡ Inference Backend: vLLM

This pipeline uses vLLM as the inference backend for DeepSeek-OCR. vLLM provides:

  • High throughput via continuous batching and PagedAttention
  • OpenAI-compatible API - easy to integrate with existing code
  • Efficient memory management - run large models on limited GPU memory

The SageMaker Training Job uses the official AWS vLLM Deep Learning Container (vllm:0.12.0-gpu-py312-cu129-ubuntu22.04-sagemaker). The pipeline sends batched requests (64 concurrent) to saturate the GPU and maximize throughput (~70 docs/min on ml.g6e.2xlarge).

📝 DeepSeek-OCR Prompts

DeepSeek-OCR supports different prompts for various OCR tasks. See the official config.py for examples:

Use Case Prompt
Document → Markdown <image>\n<|grounding|>Convert the document to markdown.
General OCR <image>\n<|grounding|>OCR this image.
Free OCR (no layout) <image>\nFree OCR.
Parse figures <image>\nParse the figure.
Describe image <image>\nDescribe this image in detail.

We configure these prompts via environment variables DOC_PROMPT and FIGURE_PROMPT in our job configuration, re-using the special tokens from the official DeepSeek-OCR config.

!pip3 install datasets ipython ipywidgets --quiet
# Preview 3 random document images
from datasets import load_dataset
from itertools import islice
from IPython.display import display

ds = load_dataset("HuggingFaceM4/FineVision", "olmOCR-mix-0225-documents", split="train", streaming=True).shuffle(
    seed=123
)
for i, s in enumerate(islice(ds, 3)):
    print(f"--- Doc {i} ---")
    img = s["images"][0]
    img.thumbnail((500, 500))  # Resize to max 500px
    display(img)

🔐 Authentication

🔑 AWS Authentication

Before running this notebook, ensure your AWS credentials are configured. You can authenticate using one of these methods:

Option 1: AWS SSO (recommended for organizations)

aws configure sso
aws sso login --profile your-profile-name

Option 2: IAM credentials via environment variables

export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
export AWS_DEFAULT_REGION=us-east-1

Option 3: AWS CLI configuration

aws configure

For more details, see the AWS CLI Configuration Guide.

Note: When running on SageMaker Studio or EC2 with an IAM role attached, credentials are automatically available via the instance metadata service.

!pip3 install "sagemaker>=3.0.0" --upgrade --quiet
!pip install -U "datasets>=4.0.0" "openai" --quiet
# 🔑 Authenticate with Hugging Face
# Required for accessing private datasets and pushing results
# Get your token at: https://huggingface.co/settings/tokens
import os
from huggingface_hub import login, get_token

login()

# Store token in env var for SageMaker Jobs
HF_TOKEN = get_token()
os.environ["HF_TOKEN"] = HF_TOKEN
print(f"HF_TOKEN set: {HF_TOKEN[:8]}...")
import os
import json
import shutil
import tempfile
import time
from pathlib import Path

import boto3
import sagemaker
from sagemaker.train.model_trainer import ModelTrainer
from sagemaker.train.configs import SourceCode, Compute, StoppingCondition, OutputDataConfig
from sagemaker.core.helper.session_helper import Session, get_execution_role

⚙️ Configuration

# Initialize SageMaker session
sagemaker_session = Session()
iam = boto3.client("iam")
role = iam.get_role(RoleName="sagemaker_execution_role")["Role"]["Arn"]
region = sagemaker_session.boto_region_name
account_id = boto3.client("sts").get_caller_identity()["Account"]

print(f"Region: {region}")
print(f"Account: {account_id}")
print(f"Role: {role}")
# Pipeline Configuration
PROJECT_NAME = "deepseek-ocr-sagemaker"
BUCKET_NAME = sagemaker_session.default_bucket()
S3_PREFIX = f"{PROJECT_NAME}"

# S3 output path (single location for all stages - dataset gets updated in place)
S3_OUTPUT_URI = f"s3://{BUCKET_NAME}/{S3_PREFIX}"

# vLLM Container - use SageMaker vLLM DLC
TRAINING_IMAGE = (
    f"763104351884.dkr.ecr.{region}.amazonaws.com/vllm:0.12.0-gpu-py312-cu129-ubuntu22.04-sagemaker-v1.0"  # GPU stages
)
LIGHTWEIGHT_IMAGE = f"763104351884.dkr.ecr.{region}.amazonaws.com/pytorch-training:2.4.0-cpu-py311-ubuntu22.04-sagemaker"  # CPU-only assemble

# Instance configuration
INSTANCE_TYPE = "ml.g6e.2xlarge"  # GPU instances for extract/describe stages
INSTANCE_TYPE_CPU = "ml.c5.xlarge"  # CPU-only instance for assemble stage (much cheaper)  # Single L40s GPU
# INSTANCE_TYPE = "ml.p4d.24xlarge"  # 8x A100 GPUs for larger scale
VOLUME_SIZE_GB = 100
MAX_RUNTIME_SECONDS = 3 * 60 * 60  # 3 hours

# Source dataset (from HuggingFace)
SOURCE_DATASET = "HuggingFaceM4/FineVision"
SOURCE_CONFIG = "olmOCR-mix-0225-documents"
MAX_SAMPLES = 1024  # Start small for testing

# HuggingFace token for accessing source datasets
HF_TOKEN = os.environ.get("HF_TOKEN", "")

print(f"S3 Bucket: s3://{BUCKET_NAME}/{S3_PREFIX}")
print(f"S3 Output URI: {S3_OUTPUT_URI}")
print(f"Instance: {INSTANCE_TYPE}")
print(f"Source: {SOURCE_DATASET}/{SOURCE_CONFIG} ({MAX_SAMPLES} samples)")

📦 Bundle Pipeline Code

SageMaker automatically uploads this bundle to S3 and makes it available at /opt/ml/input/data/code.

# Clone the pipeline code from the llm-lab repository
import subprocess
from pathlib import Path

REPO_DIR = Path("llm-lab")
if not REPO_DIR.exists():
    subprocess.run(
        ["git", "clone", "--depth", "1", "https://github.com/fgbelidji/llm-lab.git", str(REPO_DIR)],
        check=True,
    )

# Locations of the pipeline code within the cloned repo
PIPELINE_DIR = REPO_DIR / "batch-ocr-inference"  # contains the `llm_ocr` package
SAGEMAKER_DIR = PIPELINE_DIR / "sagemaker"  # contains entry.sh + sm_job_runner.py
print(f"Cloned pipeline code into: {PIPELINE_DIR.resolve()}")
# Paths to pipeline code
CODE_PATHS = [
    SAGEMAKER_DIR / "entry.sh",
    SAGEMAKER_DIR / "sm_job_runner.py",
    PIPELINE_DIR / "llm_ocr",
]

# Create a source directory bundle
source_dir = Path(tempfile.mkdtemp(prefix="sm-ocr-code-"))

for path in CODE_PATHS:
    src = Path.cwd() / path if not path.is_absolute() else path
    if src.is_dir():
        shutil.copytree(src, source_dir / path.name, dirs_exist_ok=True)
    else:
        shutil.copy2(src, source_dir / path.name)

print(f"Source directory: {source_dir}")
print(f"Contents: {list(source_dir.iterdir())}")
# Dependencies are declared in sm_job_runner.py inline metadata (PEP 723)
# entry.sh installs uv and runs: uv run sm_job_runner.py
# This automatically installs all dependencies

🔧 Define Base Environment Variables

# Base environment variables for all stages
# All configuration is passed via environment variables (same as HF Jobs)
BASE_ENV = {
    # vLLM configuration
    "MODEL_ID": "deepseek-ai/DeepSeek-OCR",
    "SERVED_MODEL_NAME": "deepseek-ocr",
    "HOST": "0.0.0.0",
    "PORT": "8000",
    "MAX_MODEL_LEN": "8192",
    "GPU_MEMORY_UTILIZATION": "0.90",
    "TENSOR_PARALLEL_SIZE": "1",
    # HuggingFace authentication (for source datasets)
    # Note: For production, consider using AWS Secrets Manager instead of env vars
    "HF_TOKEN": os.environ.get("HF_TOKEN", ""),
    "HF_HUB_ENABLE_HF_TRANSFER": "1",
    # Prompts
    "DOC_PROMPT": "<image>\n<|grounding|>Convert this document to Markdown.",
    "DOC_MAX_TOKENS": "4096",
    "DOC_TEMPERATURE": "0.1",
    "FIGURE_PROMPT": "<image>\nDescribe this image in detail.",
    "FIGURE_MAX_TOKENS": "512",
    "FIGURE_TEMPERATURE": "0.6",
}