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 lines23242526272829303132333 unmodified lines37383940414243444546474849502 unmodified lines535455565758596061626364656667686970717273747514 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281294 unmodified lines13413513613713813914014114214329 unmodified lines1731741751761771781791801811821 unmodified line18418518618718818919019119219319419519619719819920020120220329 unmodified lines2332342352362372382392 unmodified lines2422432442452462472481 unmodified line25025125225325425525625725825926026114 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932029 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793805 unmodified lines3863873883893903913923933943953962 unmodified lines39940040140240340440526 unmodified lines4324334344354364374384394404411 unmodified line44344444544644744844945045116 unmodified lines46846947047147247347447547647718 unmodified lines4964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315327 unmodified lines5405415425435445455465475485495505515522 unmodified lines55555655755855956056156256356456556656756856957057157257357457557657757857958058158258315 unmodified lines59960060160260360460560660760860961061161261361461561661761861962062162262362462554 unmodified lines68068168268368468568668768868922 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.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 datetimeimport torchfrom datasets import load_dataset2 unmodified linesfrom toolz import partition_allfrom tqdm.auto import tqdmfrom vllm import LLM, SamplingParamslogging.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 lineslogger.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 neededif isinstance(image, Image.Image):pil_img = imageelif isinstance(image, dict) and "bytes" in image:pil_img = Image.open(io.BytesIO(image["bytes"]))elif isinstance(image, str):pil_img = Image.open(image)else:raise ValueError(f"Unsupported image type: {type(image)}")# Convert to RGBpil_img = pil_img.convert("RGB")# Convert to base64 data URIbuf = io.BytesIO()pil_img.save(buf, format="PNG")data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"# Return message in vLLM formatreturn [{"role": "user","content": [{"type": "image_url", "image_url": {"url": data_uri}},{"type": "text", "text": prompt},],}]def create_dataset_card(source_dataset: str,4 unmodified linesmax_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 InformationDeepSeek-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## Dataset Structure29 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)"""1 unmodified lineinput_dataset: str,output_dataset: str,image_column: str = "image",batch_size: int = 8, # Smaller batch size to avoid potential memory issues with DeepSeek-OCRmodel: 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 timestart_time = datetime.now()# Enable high-performance Xet downloadsos.environ["HF_XET_HIGH_PERFORMANCE"] = "1"# Login to HF if token providedHF_TOKEN = hf_token or os.environ.get("HF_TOKEN")if HF_TOKEN:login(token=HF_TOKEN)# Determine resolution settingsif 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 parametersif 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_sizefinal_image_size = image_sizefinal_crop_mode = crop_moderesolution_mode = "custom"logger.info(f"Resolution: base_size={final_base_size}, "f"image_size={final_image_size}, crop_mode={final_crop_mode}")# Determine promptif prompt is not None:final_prompt = prompt29 unmodified linesdataset = dataset.select(range(min(max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# Initialize vLLMlogger.info(f"Initializing vLLM with model: {model}")logger.info("This may take a few minutes on first run...")# Add specific parameters for DeepSeek-OCR compatibilityllm = 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)sampling_params = SamplingParams(temperature=0.0, # Deterministic for OCRmax_tokens=max_tokens,)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 batchesall_markdown = []for batch_indices in tqdm(5 unmodified linesbatch_images = [dataset[i][image_column] for i in batch_indices]try:# Create messages for batchbatch_messages = [make_ocr_message(img, final_prompt) for img in batch_images]# Process with vLLMoutputs = llm.chat(batch_messages, sampling_params)# Extract outputsfor output in outputs:2 unmodified linesexcept Exception as e:logger.error(f"Error processing batch: {e}")# Add error placeholders for failed batchall_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_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py","implementation": "vllm (batch processing)",}existing_info.append(new_info)16 unmodified linesmax_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 linesprint("\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("\nExample usage:")print("\n1. Basic OCR conversion (Gundam mode - dynamic resolution):")print(" uv run deepseek-ocr-vllm.py document-images markdown-docs")print("\n2. High quality mode (Large - 1280×1280):")print(" uv run deepseek-ocr-vllm.py scanned-pdfs extracted-text --resolution-mode large")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(" uv run deepseek-ocr-vllm.py images text --prompt-mode free")print("\n6. 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(" 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 linesdescription="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 linesdescribe Generate detailed image descriptionsExamples:# Basic usage with default Gundam modeuv run deepseek-ocr-vllm.py my-images-dataset ocr-results# High quality processinguv run deepseek-ocr-vllm.py documents extracted-text --resolution-mode large# Fast processing for testinguv run deepseek-ocr-vllm.py dataset output --resolution-mode tiny --max-samples 100# Parse figures from a document datasetuv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure# Free OCR without layout (fastest)uv run deepseek-ocr-vllm.py images text --prompt-mode free# Custom prompt for specific taskuv run deepseek-ocr-vllm.py dataset output --prompt "<image>\nExtract all table data."# Custom resolution settingsuv run deepseek-ocr-vllm.py dataset output --base-size 1024 --image-size 640 --crop-mode# With custom batch size for performance tuninguv run deepseek-ocr-vllm.py dataset output --batch-size 16 --max-model-len 16384""",)15 unmodified linesdefault="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 linesimage_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,22 unmodified lines23242526272829303132333435363 unmodified lines404142434445464748495051522 unmodified lines555657585960616263646514 unmodified lines80818283848586878889909192939495964 unmodified lines10110210310410510629 unmodified lines1361371381391401411 unmodified line14314414514614714814915015115215315429 unmodified lines1841851861871881892 unmodified lines1921931941951961971981 unmodified line20020120220320420520620714 unmodified lines22222322422522622722822923023123229 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942955 unmodified lines3013023033043053063073083093103113123133143153162 unmodified lines31932032132232332426 unmodified lines3513523533543553561 unmodified line35835936036136236336436536616 unmodified lines38338438538638738818 unmodified lines4074084094104114124134144154164174184194204214224234244254264274284294304314324334347 unmodified lines4424434444454464472 unmodified lines45045145245345445545645745845946046146246346446546646746846947047147247347415 unmodified lines49049149249349449554 unmodified lines55055155255355455522 unmodified linesThis script processes images through the DeepSeek-OCR model to extracttext and structure as markdown, using vLLM for efficient batch processing.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.htmlNOTE: Uses vLLM nightly wheels. First run may take a few minutes to downloadand install dependencies.Features:- LaTeX equation recognition- Table extraction and formatting- Document structure preservation3 unmodified lines"""import argparseimport ioimport jsonimport loggingimport osimport sysfrom datetime import datetimefrom typing import Any, Dict, Unionimport 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 NGramPerReqLogitsProcessorlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Prompt mode presets (from DeepSeek-OCR GitHub)PROMPT_MODES = {"document": "<image>\n<|grounding|>Convert the document to markdown.",14 unmodified lineslogger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:"""Convert various image formats to PIL Image."""if isinstance(image, Image.Image):return imageelif isinstance(image, dict) and "bytes" in image:return Image.open(io.BytesIO(image["bytes"]))elif isinstance(image, str):return Image.open(image)else:raise ValueError(f"Unsupported image type: {type(image)}")def create_dataset_card(source_dataset: str,4 unmodified linesmax_model_len: int,max_tokens: int,gpu_memory_utilization: float,image_column: str = "image",split: str = "train",) -> str:29 unmodified lines- **Output Column**: `markdown`- **Dataset Split**: `{split}`- **Batch Size**: {batch_size}- **Max Model Length**: {max_model_len:,} tokens- **Max Output Tokens**: {max_tokens:,}- **GPU Memory Utilization**: {gpu_memory_utilization:.1%}1 unmodified line## Model InformationDeepSeek-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## Dataset Structure29 unmodified linesuv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\\\{source_dataset} \\\\<output-dataset> \\\\--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)"""1 unmodified lineinput_dataset: str,output_dataset: str,image_column: str = "image",batch_size: int = 8,model: str = "deepseek-ai/DeepSeek-OCR",max_model_len: int = 8192,max_tokens: int = 8192,gpu_memory_utilization: float = 0.8,14 unmodified lines# Track processing start timestart_time = datetime.now()# Login to HF if token providedHF_TOKEN = hf_token or os.environ.get("HF_TOKEN")if HF_TOKEN:login(token=HF_TOKEN)# Determine promptif prompt is not None:final_prompt = prompt29 unmodified linesdataset = dataset.select(range(min(max_samples, len(dataset))))logger.info(f"Limited to {len(dataset)} samples")# 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...")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,logits_processors=[NGramPerReqLogitsProcessor],)sampling_params = SamplingParams(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}")# Process images in batches using llm.generate() with PIL imagesall_markdown = []for batch_indices in tqdm(5 unmodified linesbatch_images = [dataset[i][image_column] for i in batch_indices]try:# 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 generate APIoutputs = llm.generate(model_inputs, sampling_params)# Extract outputsfor output in outputs:2 unmodified linesexcept Exception as e:logger.error(f"Error processing batch: {e}")all_markdown.extend(["[OCR FAILED]"] * len(batch_images))# Calculate processing time26 unmodified lines"column_name": "markdown","model_id": model,"processing_date": datetime.now().isoformat(),"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": "2.0.0","script_url": "https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py","implementation": "vllm (batch processing, llm.generate + NGramPerReqLogitsProcessor)",}existing_info.append(new_info)16 unmodified linesmax_model_len=max_model_len,max_tokens=max_tokens,gpu_memory_utilization=gpu_memory_utilization,image_column=image_column,split=split,)18 unmodified linesprint("\nThis script converts document images to markdown using")print("DeepSeek-OCR with vLLM for efficient batch processing.")print("\nFeatures:")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")print("\nExample usage:")print("\n1. Basic OCR conversion (document mode with grounding):")print(" uv run deepseek-ocr-vllm.py document-images markdown-docs")print("\n2. Parse figures from documents:")print(" uv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure")print("\n3. Free OCR without layout:")print(" uv run deepseek-ocr-vllm.py images text --prompt-mode free")print("\n4. Process a subset for testing:")print(" uv run deepseek-ocr-vllm.py large-dataset test-output --max-samples 10")print("\n5. Running on HF Jobs:")print(" hf jobs uv run --flavor l4x1 \\")print(" -s HF_TOKEN \\")print(" https://huggingface.co/datasets/uv-scripts/ocr/raw/main/deepseek-ocr-vllm.py \\")7 unmodified linesdescription="OCR images to markdown using DeepSeek-OCR (vLLM)",formatter_class=argparse.RawDescriptionHelpFormatter,epilog="""Prompt Modes:document Convert document to markdown with grounding (default)image OCR any image with grounding2 unmodified linesdescribe Generate detailed image descriptionsExamples:# Basic usageuv run deepseek-ocr-vllm.py my-images-dataset ocr-results# Parse figures from a document datasetuv run deepseek-ocr-vllm.py scientific-papers figures --prompt-mode figure# Free OCR without layoutuv run deepseek-ocr-vllm.py images text --prompt-mode free# Custom prompt for specific taskuv run deepseek-ocr-vllm.py dataset output --prompt "<image>\\nExtract all table data."# With custom batch size for performance tuninguv run deepseek-ocr-vllm.py dataset output --batch-size 16 --max-model-len 16384# Running on HF Jobshf 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 linesdefault="deepseek-ai/DeepSeek-OCR",help="Model to use (default: deepseek-ai/DeepSeek-OCR)",)parser.add_argument("--max-model-len",type=int,54 unmodified linesimage_column=args.image_column,batch_size=args.batch_size,model=args.model,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