Commit ·
952354b
1
Parent(s): 0bc9b0a
Fix deepseek-ocr-vllm.py: use official vLLM offline pattern (P0)
Browse filesRewrote inference core to match the official vLLM DeepSeek-OCR recipe:
- llm.generate() with PIL images instead of llm.chat() with base64
- Added NGramPerReqLogitsProcessor to prevent repetition loops
- Added enable_prefix_caching=False, mm_processor_cache_gb=0
- Added skip_special_tokens=False and ngram/window sampling params
- Removed resolution modes (only apply to transformers API, not vLLM)
- Removed deprecated HF_XET_HIGH_PERFORMANCE env var
- Bumped script_version to 2.0.0
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
22 unmodified lines23242526272627282930313233303435363 unmodified lines4041424043444546474648495051522 unmodified lines55565758596061626061626364656667686970717263646514 unmodified lines80818293949596979883848510086871028889104909192931081091101111121131141151161171181191201211221231241251269495964 unmodified lines10110210313713813914010410510629 unmodified lines1361371381761771781791391401411 unmodified line14314414518718818919019119219319419519619719819920014614714814915015115215315429 unmodified lines1841851862361871881892 unmodified lines1921931942451951961971981 unmodified line20020120225320320425525625725820520620714 unmodified lines22222322427928028122522622722822928728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631723023123229 unmodified lines2622632643532652662672683572692702712722733633642742752762772782793682802812822832842852862872882892903733743752913772922932942955 unmodified lines3013023033893903043053063073083093103113923933123133143153162 unmodified lines31932032140232232332426 unmodified lines3513523534354364374383543553561 unmodified line35835936044636136244836336436536616 unmodified lines38338438547147247347438638738818 unmodified lines4074084094994104114124134145054154165074174185094194205114214225135145155165174234245194254264274285235245255264294304315294324334347 unmodified lines4424434445435445455465475485494454464472 unmodified lines45045145255845345445556156256356456556645645745857045946046146257457557657746346446546646746846947047147247347415 unmodified lines49049149260260360460560660760860961061161261361461561661761861962062162249349449554 unmodified lines55055155268368468568655355455522 unmodified linesThis script processes images through the DeepSeek-OCR model to extracttext and structure as markdown, using vLLM for efficient batch processing.
NOTE: Uses vLLM nightly wheels from main (PR #27247 now merged). First runmay take a few minutes to download and install dependencies.Uses the official vLLM offline pattern: llm.generate() with PIL imagesand NGramPerReqLogitsProcessor to prevent repetition on complex documents.See: https://docs.vllm.ai/projects/recipes/en/latest/DeepSeek/DeepSeek-OCR.html
NOTE: Uses vLLM nightly wheels. First run may take a few minutes to downloadand install dependencies.
Features:- Multiple resolution modes (Tiny/Small/Base/Large/Gundam)- LaTeX equation recognition- Table extraction and formatting- Document structure preservation3 unmodified lines"""
import argparseimport base64import ioimport jsonimport loggingimport osimport sysfrom typing import Any, Dict, List, Unionfrom datetime import datetimefrom typing import Any, Dict, Union
import torchfrom datasets import load_dataset2 unmodified linesfrom toolz import partition_allfrom tqdm.auto import tqdmfrom vllm import LLM, SamplingParamsfrom vllm.model_executor.models.deepseek_ocr import NGramPerReqLogitsProcessor
logging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Resolution mode presetsRESOLUTION_MODES = { "tiny": {"base_size": 512, "image_size": 512, "crop_mode": False}, "small": {"base_size": 640, "image_size": 640, "crop_mode": False}, "base": {"base_size": 1024, "image_size": 1024, "crop_mode": False}, "large": {"base_size": 1280, "image_size": 1280, "crop_mode": False}, "gundam": { "base_size": 1024, "image_size": 640, "crop_mode": True, }, # Dynamic resolution}
# Prompt mode presets (from DeepSeek-OCR GitHub)PROMPT_MODES = { "document": "<image>\n<|grounding|>Convert the document to markdown.",14 unmodified lines logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
def make_ocr_message( image: Union[Image.Image, Dict[str, Any], str], prompt: str = "<image>\n<|grounding|>Convert the document to markdown. ",) -> List[Dict]: """Create chat message for OCR processing.""" # Convert to PIL Image if neededdef to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image: """Convert various image formats to PIL Image.""" if isinstance(image, Image.Image): pil_img = image return image elif isinstance(image, dict) and "bytes" in image: pil_img = Image.open(io.BytesIO(image["bytes"])) return Image.open(io.BytesIO(image["bytes"])) elif isinstance(image, str): pil_img = Image.open(image) return Image.open(image) else: raise ValueError(f"Unsupported image type: {type(image)}")
# Convert to RGB pil_img = pil_img.convert("RGB")
# Convert to base64 data URI buf = io.BytesIO() pil_img.save(buf, format="PNG") data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
# Return message in vLLM format return [ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": data_uri}}, {"type": "text", "text": prompt}, ], } ]
def create_dataset_card( source_dataset: str,4 unmodified lines max_model_len: int, max_tokens: int, gpu_memory_utilization: float, resolution_mode: str, base_size: int, image_size: int, crop_mode: bool, image_column: str = "image", split: str = "train",) -> str:29 unmodified lines- **Output Column**: `markdown`- **Dataset Split**: `{split}`- **Batch Size**: {batch_size}- **Resolution Mode**: {resolution_mode}- **Base Size**: {base_size}- **Image Size**: {image_size}- **Crop Mode**: {crop_mode}- **Max Model Length**: {max_model_len:,} tokens- **Max Output Tokens**: {max_tokens:,}- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}1 unmodified line## Model Information
DeepSeek-OCR is a state-of-the-art document OCR model that excels at:- 📐 **LaTeX equations** - Mathematical formulas preserved in LaTeX format- 📊 **Tables** - Extracted and formatted as HTML/markdown- 📝 **Document structure** - Headers, lists, and formatting maintained- 🖼️ **Image grounding** - Spatial layout and bounding box information- 🔍 **Complex layouts** - Multi-column and hierarchical structures- 🌍 **Multilingual** - Supports multiple languages
### Resolution Modes
- **Tiny** (512×512): Fast processing, 64 vision tokens- **Small** (640×640): Balanced speed/quality, 100 vision tokens- **Base** (1024×1024): High quality, 256 vision tokens- **Large** (1280×1280): Maximum quality, 400 vision tokens- **Gundam** (dynamic): Adaptive multi-tile processing for large documents- LaTeX equations - Mathematical formulas preserved in LaTeX format- Tables - Extracted and formatted as HTML/markdown- Document structure - Headers, lists, and formatting maintained- Image grounding - Spatial layout and bounding box information- Complex layouts - Multi-column and hierarchical structures- Multilingual - Supports multiple languages
## Dataset Structure
29 unmodified linesuv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\\\ {source_dataset} \\\\ <output-dataset> \\\\ --resolution-mode {resolution_mode} \\\\ --image-column {image_column}```
2 unmodified lines- **Processing Speed**: ~{num_samples / (float(processing_time.split()[0]) * 60):.1f} images/second- **Processing Method**: Batch processing with vLLM (2-3x speedup over sequential)
Generated with 🤖 [UV Scripts](https://huggingface.co/uv-scripts)Generated with [UV Scripts](https://huggingface.co/uv-scripts)"""
1 unmodified line input_dataset: str, output_dataset: str, image_column: str = "image", batch_size: int = 8, # Smaller batch size to avoid potential memory issues with DeepSeek-OCR batch_size: int = 8, model: str = "deepseek-ai/DeepSeek-OCR", resolution_mode: str = "gundam", base_size: int = None, image_size: int = None, crop_mode: bool = None, max_model_len: int = 8192, max_tokens: int = 8192, gpu_memory_utilization: float = 0.8,14 unmodified lines # Track processing start time start_time = datetime.now()
# Enable high-performance Xet downloads os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
# Login to HF if token provided HF_TOKEN = hf_token or os.environ.get("HF_TOKEN") if HF_TOKEN: login(token=HF_TOKEN)
# Determine resolution settings if resolution_mode in RESOLUTION_MODES: mode_config = RESOLUTION_MODES[resolution_mode] final_base_size = ( base_size if base_size is not None else mode_config["base_size"] ) final_image_size = ( image_size if image_size is not None else mode_config["image_size"] ) final_crop_mode = ( crop_mode if crop_mode is not None else mode_config["crop_mode"] ) logger.info(f"Using resolution mode: {resolution_mode}") else: # Custom mode - require all parameters if base_size is None or image_size is None or crop_mode is None: raise ValueError( f"Invalid resolution mode '{resolution_mode}'. " f"Use one of {list(RESOLUTION_MODES.keys())} or specify " f"--base-size, --image-size, and --crop-mode manually." ) final_base_size = base_size final_image_size = image_size final_crop_mode = crop_mode resolution_mode = "custom"
logger.info( f"Resolution: base_size={final_base_size}, " f"image_size={final_image_size}, crop_mode={final_crop_mode}" )
# Determine prompt if prompt is not None: final_prompt = prompt29 unmodified lines dataset = dataset.select(range(min(max_samples, len(dataset)))) logger.info(f"Limited to {len(dataset)} samples")
# Initialize vLLM # Initialize vLLM (matches official DeepSeek-OCR vLLM recipe) logger.info(f"Initializing vLLM with model: {model}") logger.info("This may take a few minutes on first run...")
# Add specific parameters for DeepSeek-OCR compatibility llm = LLM( model=model, trust_remote_code=True, max_model_len=max_model_len, gpu_memory_utilization=gpu_memory_utilization, limit_mm_per_prompt={"image": 1}, enforce_eager=False, # Use torch.compile instead of eager execution enable_prefix_caching=False, mm_processor_cache_gb=0, logits_processors=[NGramPerReqLogitsProcessor], )
sampling_params = SamplingParams( temperature=0.0, # Deterministic for OCR temperature=0.0, max_tokens=max_tokens, skip_special_tokens=False, extra_args=dict( ngram_size=30, window_size=90, whitelist_token_ids={128821, 128822}, ), )
logger.info(f"Processing {len(dataset)} images in batches of {batch_size}") logger.info( "Using vLLM for batch processing - should be faster than sequential processing" )
# Process images in batches # Process images in batches using llm.generate() with PIL images all_markdown = []
for batch_indices in tqdm(5 unmodified lines batch_images = [dataset[i][image_column] for i in batch_indices]
try: # Create messages for batch batch_messages = [make_ocr_message(img, final_prompt) for img in batch_images] # Build model inputs with PIL images (official vLLM pattern) model_inputs = [] for img in batch_images: pil_img = to_pil(img).convert("RGB") model_inputs.append( {"prompt": final_prompt, "multi_modal_data": {"image": pil_img}} )
# Process with vLLM outputs = llm.chat(batch_messages, sampling_params) # Process with vLLM generate API outputs = llm.generate(model_inputs, sampling_params)
# Extract outputs for output in outputs:2 unmodified lines
except Exception as e: logger.error(f"Error processing batch: {e}") # Add error placeholders for failed batch all_markdown.extend(["[OCR FAILED]"] * len(batch_images))
# Calculate processing time26 unmodified lines "column_name": "markdown", "model_id": model, "processing_date": datetime.now().isoformat(), "resolution_mode": resolution_mode, "base_size": final_base_size, "image_size": final_image_size, "crop_mode": final_crop_mode, "prompt": final_prompt, "prompt_mode": prompt_mode if prompt is None else "custom", "batch_size": batch_size,1 unmodified line "gpu_memory_utilization": gpu_memory_utilization, "max_model_len": max_model_len, "script": "deepseek-ocr-vllm.py", "script_version": "1.0.0", "script_version": "2.0.0", "script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py", "implementation": "vllm (batch processing)", "implementation": "vllm (batch processing, llm.generate + NGramPerReqLogitsProcessor)", } existing_info.append(new_info)
16 unmodified lines max_model_len=max_model_len, max_tokens=max_tokens, gpu_memory_utilization=gpu_memory_utilization, resolution_mode=resolution_mode, base_size=final_base_size, image_size=final_image_size, crop_mode=final_crop_mode, image_column=image_column, split=split, )18 unmodified lines print("\nThis script converts document images to markdown using") print("DeepSeek-OCR with vLLM for efficient batch processing.") print("\nFeatures:") print("- Multiple resolution modes (Tiny/Small/Base/Large/Gundam)") print("- LaTeX equation recognition") print("- Table extraction and formatting") print("- Document structure preservation") print("- Image grounding and spatial layout") print("- Multilingual support") print("- ⚡ Fast batch processing with vLLM (2-3x speedup)") print("- Fast batch processing with vLLM") print("\nExample usage:") print("\n1. Basic OCR conversion (Gundam mode - dynamic resolution):") print("\n1. Basic OCR conversion (document mode with grounding):") print(" uv run deepseek-ocr-vllm.py document-images markdown-docs") print("\n2. High quality mode (Large - 1280×1280):") print("\n2. Parse figures from documents:") print( " uv run deepseek-ocr-vllm.py scanned-pdfs extracted-text --resolution-mode large" " uv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure" ) print("\n3. Fast processing (Tiny - 512×512):") print(" uv run deepseek-ocr-vllm.py quick-test output --resolution-mode tiny") print("\n4. Parse figures from documents:") print(" uv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure") print("\n5. Free OCR without layout:") print("\n3. Free OCR without layout:") print(" uv run deepseek-ocr-vllm.py images text --prompt-mode free") print("\n6. Process a subset for testing:") print("\n4. Process a subset for testing:") print( " uv run deepseek-ocr-vllm.py large-dataset test-output --max-samples 10" ) print("\n7. Custom resolution:") print(" uv run deepseek-ocr-vllm.py dataset output \\") print(" --base-size 1024 --image-size 640 --crop-mode") print("\n8. Running on HF Jobs:") print("\n5. Running on HF Jobs:") print(" hf jobs uv run --flavor l4x1 \\") print(" -s HF_TOKEN \\") print(" -e UV_TORCH_BACKEND=auto \\") print( " https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\" )7 unmodified lines description="OCR images to markdown using DeepSeek-OCR (vLLM)", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Resolution Modes: tiny 512×512 pixels, fast processing (64 vision tokens) small 640×640 pixels, balanced (100 vision tokens) base 1024×1024 pixels, high quality (256 vision tokens) large 1280×1280 pixels, maximum quality (400 vision tokens) gundam Dynamic multi-tile processing (adaptive)
Prompt Modes: document Convert document to markdown with grounding (default) image OCR any image with grounding2 unmodified lines describe Generate detailed image descriptions
Examples: # Basic usage with default Gundam mode # Basic usage uv run deepseek-ocr-vllm.py my-images-dataset ocr-results
# High quality processing uv run deepseek-ocr-vllm.py documents extracted-text --resolution-mode large
# Fast processing for testing uv run deepseek-ocr-vllm.py dataset output --resolution-mode tiny --max-samples 100
# Parse figures from a document dataset uv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure
# Free OCR without layout (fastest) # Free OCR without layout uv run deepseek-ocr-vllm.py images text --prompt-mode free
# Custom prompt for specific task uv run deepseek-ocr-vllm.py dataset output --prompt "<image>\nExtract all table data."
# Custom resolution settings uv run deepseek-ocr-vllm.py dataset output --base-size 1024 --image-size 640 --crop-mode uv run deepseek-ocr-vllm.py dataset output --prompt "<image>\\nExtract all table data."
# With custom batch size for performance tuning uv run deepseek-ocr-vllm.py dataset output --batch-size 16 --max-model-len 16384
# Running on HF Jobs hf jobs uv run --flavor l4x1 -s HF_TOKEN \\ https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\ my-dataset my-output --max-samples 10 """, )
15 unmodified lines default="deepseek-ai/DeepSeek-OCR", help="Model to use (default: deepseek-ai/DeepSeek-OCR)", ) parser.add_argument( "--resolution-mode", default="gundam", choices=list(RESOLUTION_MODES.keys()) + ["custom"], help="Resolution mode preset (default: gundam)", ) parser.add_argument( "--base-size", type=int, help="Base resolution size (overrides resolution-mode)", ) parser.add_argument( "--image-size", type=int, help="Image tile size (overrides resolution-mode)", ) parser.add_argument( "--crop-mode", action="store_true", help="Enable dynamic multi-tile cropping (overrides resolution-mode)", ) parser.add_argument( "--max-model-len", type=int,54 unmodified lines image_column=args.image_column, batch_size=args.batch_size, model=args.model, resolution_mode=args.resolution_mode, base_size=args.base_size, image_size=args.image_size, crop_mode=args.crop_mode if args.crop_mode else None, max_model_len=args.max_model_len, max_tokens=args.max_tokens, gpu_memory_utilization=args.gpu_memory_utilization,deepseek-ocr-vllm.py+59-193