Microsoft Florence-2 with Python: Build a Unified Multitask Vision-Language Pipeline on CPU

AI tutorial - IT technology blog
AI tutorial - IT technology blog

Real-World Problem: The Spaghetti Infrastructure of Computer Vision Pipelines

Last quarter, our infrastructure hit a breaking point. We were processing roughly 180,000 customer-uploaded documents, identity cards, and catalog photos every day. Every uploaded file required three distinct operations:

  • Extracting plain text, invoice totals, and serial numbers through Optical Character Recognition (OCR).
  • Locating product badges, signatures, and faces with Object Detection (OD).
  • Generating descriptive metadata for Elasticsearch indexing via Detailed Image Captioning.

Our initial architecture grew organically, one tool at a time. Tesseract pulled text from images. A YOLOv8 container handled bounding box extraction. Across the network, a BLIP-2 service produced descriptive captions. Individually, each tool worked well. Together in production, they created an operational nightmare.

Container sizes ballooned first. The three container images consumed 14.8 GB of disk space on our worker nodes. Next came the memory footprint. Keeping three separate runtimes resident required 11.2 GB of RAM, triggering constant Out-Of-Memory (OOM) alerts. Whenever ingest volume spiked past 50 images per second, queue latencies soared. To keep up, we spun up three g4dn.xlarge GPU instances on AWS. That single band-aid pushed our monthly inference bill past $2,800.

We needed a simpler setup. The goal: replace three disconnected tools with one lightweight vision-language model that could run reliably on standard multi-core CPU instances.

Root Cause Analysis: Why Vision Microservices Break at Scale

Why do traditional multi-model vision pipelines degrade under load? The core bottleneck is rarely raw compute. It is architectural friction:

  1. Redundant Tensor Calculations: Tesseract, YOLO, and BLIP-2 each decode raw pixels independently. Each library builds separate feature representations and runs distinct forward passes. Your servers end up recalculating visual geometry three times for the exact same 2 MB JPEG.
  2. Memory Footprint and Cold Starts: Stacking three models multiplies idle memory consumption. Kubernetes autoscaling suffered as a result. Pulling 15 GB container layers and loading distinct weight files into RAM pushed node cold starts past four minutes.
  3. Dependency Conflicts: Each vision library brought competing native requirements. We juggled incompatible OpenCV builds, conflicting PyTorch runtime targets, and fragile native C++ bindings for Leptonica.

End-to-end processing dragged out between 4.2 and 7.8 seconds per document on 8-vCPU nodes. Ingestion queues regularly backed up by tens of thousands of tasks during peak hours.

Solutions Compared: Benchmarking the Alternatives

Before committing to a rewrite, we benchmarked four architectures against four key metrics: CPU latency, RAM usage, maintenance burden, and cloud spend.

Option 1: The Multi-Model Microservice Stack (Status Quo)

  • Architecture: Tesseract 5.3 + YOLOv8m + BLIP-base.
  • Resource footprint: 11.2 GB RAM across three containers; 14.8 GB image size.
  • CPU Performance: 5.2 seconds per image on an 8-vCPU AWS c6i.2xlarge instance.
  • Verdict: Fragile. Inter-service networking added latency, and container coordination failures caused frequent retries.

Option 2: Commercial Vision APIs (AWS Rekognition & Google Cloud Vision)

  • Architecture: Managed REST endpoints for text, labels, and moderation.
  • Resource footprint: Zero local runtime memory.
  • CPU Performance: 400ms to 900ms round-trip latency per image over HTTPS.
  • Verdict: Clean, but costly. At 5.4 million images a month across three separate API features, our projected monthly bill exceeded $7,500. Enterprise data compliance restrictions also limited cloud transmission.

Option 3: 7B Multimodal LLMs (LLaVA-1.5 & CogVLM)

  • Architecture: Large autoregressive vision-language models.
  • Resource footprint: 16 GB+ VRAM on GPU, or 32 GB RAM on CPU.
  • CPU Performance: 28 to 45 seconds per image on CPU.
  • Verdict: Impractical. These models are powerful conversational engines, but running them without GPUs is far too slow for transactional document queues.

Option 4: Microsoft Florence-2 (Unified Vision Foundation Model)

  • Architecture: Sequence-to-sequence vision-language foundation model using a DaViT vision encoder and a standard language decoder (0.23B parameters for base, 0.77B for large).
  • Resource footprint: 1.6 GB RAM for base in FP32 on CPU. Container image size sits comfortably under 3.2 GB.
  • CPU Performance: 650ms to 1.1 seconds total per task on standard 4-vCPU to 8-vCPU machines.
  • Verdict: The clear winner. A single compact weight file covers OCR, bounding box proposals, and dense captioning through prompt tokens.

Best Approach: Deploying Microsoft Florence-2 on CPU with Python

Florence-2 frames all visual tasks as prompt-driven sequence-to-sequence translation. Pass an image alongside a task token like <OCR_WITH_REGION> or <OD>. The model responds with text tokens that describe sentences, coordinates, or structured labels.

We migrated our production ingestion pipeline to Florence-2 on standard four-core CPU nodes. The results were immediate. Baseline memory consumption dropped from 11.2 GB down to 1.6 GB. Ingestion queue latency fell by 68%, and our monthly compute bill plummeted from $2,800 to $620.

Step 1: Setting Up the Python Environment

Install PyTorch with CPU-only wheels first. This keeps your build lean by stripping out multi-gigabyte CUDA libraries you will not use.

# Create and activate an isolated virtual environment
python3 -m venv venv
source venv/bin/activate

# Install PyTorch CPU build
pip install --upgrade pip
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu

# Install Hugging Face Transformers, flash-attn fallback dependencies, and Pillow
pip install transformers timm einops pillow requests

Step 2: Building the Unified Multitask Pipeline

Here is an end-to-end Python pipeline class. It loads Florence-2 once, holds it in host RAM, and switches between OCR, detection, and captioning based on the prompt token you provide.

import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForCausalLM

class FlorenceVisionPipeline:
    def __init__(self, model_id: str = "microsoft/Florence-2-base"):
        self.device = torch.device("cpu")
        self.torch_dtype = torch.float32

        print(f"Loading {model_id} onto CPU...")
        # Florence-2 uses custom modeling code hosted on the Hugging Face hub
        self.model = AutoModelForCausalLM.from_pretrained(
            model_id,
            torch_dtype=self.torch_dtype,
            trust_remote_code=True
        ).to(self.device)

        self.processor = AutoProcessor.from_pretrained(
            model_id,
            trust_remote_code=True
        )
        print("Model loaded successfully.")

    def process_task(self, image: Image.Image, task_prompt: str, text_input: str = None) -> dict:
        """
        Executes visual inference for a designated task prompt.
        Supported task prompts include:
          - '<CAPTION>'
          - '<DETAILED_CAPTION>'
          - '<MORE_DETAILED_CAPTION>'
          - '<OD>' (Object Detection)
          - '<OCR>' (Plain text extraction)
          - '<OCR_WITH_REGION>' (Text extraction with bounding coordinates)
        """
        prompt = task_prompt if text_input is None else f"{task_prompt} {text_input}"
        
        # Prepare tensors for CPU processing
        inputs = self.processor(
            text=prompt,
            images=image,
            return_tensors="pt"
        )
        
        # Keep token IDs as torch.long while casting pixel data to FP32
        input_ids = inputs["input_ids"].to(self.device)
        pixel_values = inputs["pixel_values"].to(self.device, self.torch_dtype)

        with torch.no_grad():
            generated_ids = self.model.generate(
                input_ids=input_ids,
                pixel_values=pixel_values,
                max_new_tokens=1024,
                num_beams=3,
                early_stopping=False
            )

        # Decode generated token IDs into string format
        generated_text = self.processor.batch_decode(
            generated_ids, 
            skip_special_tokens=False
        )[0]

        # Rescale location tokens directly to original image pixel coordinates
        parsed_result = self.processor.post_process_generation(
            generated_text,
            task=task_prompt,
            image_size=(image.width, image.height)
        )
        
        return parsed_result


if __name__ == "__main__":
    pipeline = FlorenceVisionPipeline(model_id="microsoft/Florence-2-base")

    # Test with a local document or generate a blank canvas fallback
    try:
        image = Image.open("sample_receipt.jpg").convert("RGB")
    except FileNotFoundError:
        image = Image.new("RGB", (800, 600), color=(245, 245, 245))

    # 1. Generate descriptive search metadata
    caption = pipeline.process_task(image, "<MORE_DETAILED_CAPTION>")
    print("\n--- Detailed Caption ---")
    print(caption.get("<MORE_DETAILED_CAPTION>"))

    # 2. Extract bounding boxes for UI entities
    detections = pipeline.process_task(image, "<OD>")
    print("\n--- Detected Objects ---")
    print(detections.get("<OD>"))

    # 3. Extract text lines and coordinates
    ocr_data = pipeline.process_task(image, "<OCR_WITH_REGION>")
    print("\n--- Extracted Text and Coordinates ---")
    print(ocr_data.get("<OCR_WITH_REGION>"))

Step 3: Transforming Coordinate Outputs into Normalized Data

Florence-2 represents bounding boxes internally as discrete <loc_0> to <loc_1000> tokens. The Hugging Face processor converts these into absolute pixel coordinates [x1, y1, x2, y2] automatically. A quick helper function transforms that raw output into clean JSON for your database:

def extract_detected_entities(detection_result: dict) -> list:
    od_data = detection_result.get("<OD>", {})
    boxes = od_data.get("bboxes", [])
    labels = od_data.get("labels", [])
    
    structured_items = []
    for box, label in zip(boxes, labels):
        structured_items.append({
            "label": label,
            "coordinates": {
                "x_min": round(box[0], 1),
                "y_min": round(box[1], 1),
                "x_max": round(box[2], 1),
                "y_max": round(box[3], 1)
            }
        })
    return structured_items

These structured records pipe directly into search engines and downstream relational tables. No manual coordinate math. No custom post-processing heuristics.

Step 4: Operational Tuning for Production CPU Workers

Running neural network inference reliably on CPU instances requires deliberate threading control. You can extract maximum throughput with three production adjustments:

  • Prevent Thread Contention: PyTorch defaults to using all detected virtual cores for linear algebra kernels. If you run multiple worker processes on one host, set torch.set_num_threads(4) or export OMP_NUM_THREADS=4. This prevents processes from thrashing over identical CPU cycles.
  • Pick the Right Weight Checkpoint: Stick with microsoft/Florence-2-base (232M parameters) for high-throughput queues. It completes single-task inferences in roughly 750ms on modern AMD EPYC cores. Switch to microsoft/Florence-2-large (771M parameters) only when deciphering messy cursive handwriting or dense legal forms.
  • Pre-scale Ingestion Dimensions: Florence-2 processes images at 768×768 internally. Downsample 12-megapixel smartphone uploads (4032×3024) to a maximum dimension of 1024px before inference. In our benchmarks, this shaved 320ms off image preprocessing per item with zero degradation in OCR accuracy.

Consolidating vision workloads into Florence-2 eliminates inter-service HTTP hops and slashes image sizes. You get a reliable, maintainable vision stack that runs on everyday cloud CPUs.

Share: