Commit ·
aad164c
1
Parent(s): d28bb20
Add DeepSeek-OCR-2 vLLM script (rewrite from fixed v1 pattern)
Browse filesRewrites the broken draft (base64/llm.chat/resolution modes) to use the
proven v1 pattern: llm.generate() with PIL images + NGramPerReqLogitsProcessor.
Key v2 change: limit_mm_per_prompt={"image": 1} for the new architecture.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
23 unmodified lines24252627272829303132333435343637383 unmodified lines4243444445464748495050515253542 unmodified lines575859606162636464656667686970717273747576776566676813 unmodified lines82838497989910010110285868710488891069091108929394951121131141151161171181191201211221231241251261271281291309697984 unmodified lines10310410514114214314410610710829 unmodified lines1381391401801811821831411421431 unmodified line14514614719119219319419519619719819914814915015115220220320420520620720820921021121221321421515315415515615715815916016129 unmodified lines1911921932511941951962 unmodified lines1992002012602022032042051 unmodified line20720820926821021127027127227321221321419 unmodified lines23423523629930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832923723823933324024124224325 unmodified lines2692702713652722732742753692762772782792802812822833762842852862873802882892902912922932942952962972983853863872993893003013023035 unmodified lines3093103114014023123133143153163173183194044053203213223233242 unmodified lines32732832941433033133226 unmodified lines3593603614474484494503623633643 unmodified lines36836937046037137237337416 unmodified lines39139239348348448548639439539639739839949340040149540240340440511 unmodified lines4174184195134204214224234245194254265214274285234294305254314325275285295305314334345334354364374385375385395404394404415434424434447 unmodified lines4524534545575585595605615625634554564572 unmodified lines46046146257246346446557557657757857958046646746858446947047147258858959059147347447547647747847948048148248348415 unmodified lines50050150261661761861962062162262362462562662762862963063163263363463563650350450554 unmodified lines56056156269769869970056356456523 unmodified lineswith Visual Causal Flow architecture) to extract text and structure as markdown,using vLLM for efficient batch processing.
Tested with vLLM 0.8.5+, PyTorch 2.6.0, Transformers 4.46.3+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:- Visual Causal Flow architecture for enhanced visual encoding- 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 presets - v2 optimized for 768×768 tilesRESOLUTION_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": 768, "crop_mode": False}, # v2 optimized "large": {"base_size": 1280, "image_size": 1024, "crop_mode": False}, "gundam": { "base_size": 1024, "image_size": 768, # v2 optimized "crop_mode": True, }, # Dynamic resolution}
# Prompt mode presets (compatible with both v1 and v2)# Prompt mode presets (from DeepSeek-OCR GitHub)PROMPT_MODES = { "document": "<image>\n<|grounding|>Convert the document to markdown.", "image": "<image>\n<|grounding|>OCR this image.",13 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-2 is a 3B parameter vision-language model featuring Visual CausalFlow architecture for more human-like visual encoding. Building on DeepSeek-OCRv1, it offers enhanced document understanding with dynamic resolution up to(0-6)×768×768 + 1×1024×1024 patches.
### Key Improvements (v2)- 🧠 **Visual Causal Flow** - More human-like visual encoding architecture- 🎯 **Enhanced multi-patch** - Better processing of 768×768 tiles- 📝 **Improved structure** - Superior document hierarchy preservation- 📐 **Better layouts** - Enhanced handling of complex multi-column documentsFlow architecture for more human-like visual encoding. Building on DeepSeek-OCR v1,it offers enhanced document understanding with dynamic resolution up to(0-6)x768x768 + 1x1024x1024 patches.
### Capabilities- 📐 **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×768): High quality, ~192 vision tokens ⭐ v2 optimized- **Large** (1280×1024): Maximum quality, ~328 vision tokens- **Gundam** (dynamic): Adaptive multi-tile with 768×768 patches (default)- 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-ocr2-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 batch_size: int = 8, model: str = "deepseek-ai/DeepSeek-OCR-2", 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,19 unmodified lines 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 = prompt logger.info(f"Using custom prompt") logger.info("Using custom prompt") elif prompt_mode in PROMPT_MODES: final_prompt = PROMPT_MODES[prompt_mode] logger.info(f"Using prompt mode: {prompt_mode}")25 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-2 compatibility llm = LLM( model=model, trust_remote_code=True, max_model_len=max_model_len, gpu_memory_utilization=gpu_memory_utilization, enable_prefix_caching=False, mm_processor_cache_gb=0, limit_mm_per_prompt={"image": 1}, enforce_eager=False, # Use torch.compile instead of eager execution 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,3 unmodified lines "script": "deepseek-ocr2-vllm.py", "script_version": "1.0.0", "script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr2-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, )
card = DatasetCard(card_content) card.push_to_hub(output_dataset, token=HF_TOKEN) logger.info("✅ Dataset card created and pushed!") logger.info("Dataset card created and pushed!")
logger.info("✅ OCR conversion complete!") logger.info("OCR conversion complete!") logger.info( f"Dataset available at: https://huggingface.co/datasets/{output_dataset}" )11 unmodified lines print("with vLLM for efficient batch processing.") print("\nFeatures:") print("- Visual Causal Flow architecture for enhanced encoding") 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-ocr2-vllm.py document-images markdown-docs") print("\n2. High quality mode (Large - 1280×1024):") print("\n2. Parse figures from documents:") print( " uv run deepseek-ocr2-vllm.py scanned-pdfs extracted-text --resolution-mode large" " uv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure" ) print("\n3. Fast processing (Tiny - 512×512):") print(" uv run deepseek-ocr2-vllm.py quick-test output --resolution-mode tiny") print("\n4. Parse figures from documents:") print(" uv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure") print("\n5. Free OCR without layout:") print("\n3. Free OCR without layout:") print(" uv run deepseek-ocr2-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-ocr2-vllm.py large-dataset test-output --max-samples 10" ) print("\n7. Custom resolution:") print(" uv run deepseek-ocr2-vllm.py dataset output \\") print(" --base-size 1024 --image-size 768 --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-ocr2-vllm.py \\" )7 unmodified lines description="OCR images to markdown using DeepSeek-OCR-2 (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×768 pixels, high quality (~192 vision tokens) ⭐ v2 optimized large 1280×1024 pixels, maximum quality (~328 vision tokens) gundam Dynamic multi-tile with 768×768 patches (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-ocr2-vllm.py my-images-dataset ocr-results
# High quality processing uv run deepseek-ocr2-vllm.py documents extracted-text --resolution-mode large
# Fast processing for testing uv run deepseek-ocr2-vllm.py dataset output --resolution-mode tiny --max-samples 100
# Parse figures from a document dataset uv run deepseek-ocr2-vllm.py scientific-papers figures --prompt-mode figure
# Free OCR without layout (fastest) # Free OCR without layout uv run deepseek-ocr2-vllm.py images text --prompt-mode free
# Custom prompt for specific task uv run deepseek-ocr2-vllm.py dataset output --prompt "<image>\nExtract all table data."
# Custom resolution settings uv run deepseek-ocr2-vllm.py dataset output --base-size 1024 --image-size 768 --crop-mode uv run deepseek-ocr2-vllm.py dataset output --prompt "<image>\\nExtract all table data."
# With custom batch size for performance tuning uv run deepseek-ocr2-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-ocr2-vllm.py \\ my-dataset my-output --max-samples 10 """, )
15 unmodified lines default="deepseek-ai/DeepSeek-OCR-2", help="Model to use (default: deepseek-ai/DeepSeek-OCR-2)", ) 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-ocr2-vllm.py+62-200