Table of Contents

    Multimodal Models (Vision-Language)

    Generative AI and Large Language Models

    Multimodal Models: Vision-Language

    Learn how Vision-Language Models combine visual perception with natural-language understanding to analyze images, answer visual questions, generate captions, interpret documents and charts, compare images with text, locate visual evidence, and support multimodal applications.

    Introduction

    Traditional language models process text. Traditional computer vision models process images. Many real-world tasks require both. A support engineer may need to analyze a screenshot together with a defect report. A learner may ask a question about a diagram. A business user may need information extracted from a chart, scanned form, receipt, or presentation slide.

    A Vision-Language Model, commonly abbreviated as VLM, combines visual information with natural language. Depending on its architecture and training, a VLM may accept an image and text prompt and generate a textual answer, caption, classification, structured record, or grounded description.

    Vision-language capability does not mean that a model sees exactly as a human does. Images are resized, normalized, divided into patches or regions, and converted into learned representations. These visual representations are aligned or integrated with the language model so that the system can generate text conditioned on visual content.

    Core principle: A Vision-Language Model connects visual representations with language representations so that the system can reason and communicate across images and text.

    Learning Objectives

    By the End of This Lesson

    • Define multimodal AI and Vision-Language Models
    • Distinguish modalities, encoders, adapters, and decoders
    • Explain how an image becomes visual tokens
    • Understand patch embeddings
    • Explain cross-modal alignment
    • Understand contrastive image-text learning
    • Distinguish dual-encoder and generative VLM architectures
    • Understand cross-attention and projection layers
    • Identify common VLM task categories
    • Generate image captions
    • Perform visual question answering
    • Extract information from documents and screenshots
    • Understand OCR and VLM responsibilities
    • Analyze tables, charts, and diagrams
    • Understand visual grounding
    • Run a local VLM with Hugging Face
    • Prepare images safely for inference
    • Evaluate visual and textual quality separately
    • Identify multimodal hallucination and security risks
    • Create a VLM production-readiness checklist

    Prerequisites

    Recommended Knowledge

    • Python programming
    • PyTorch fundamentals
    • Convolutional Neural Networks
    • Transformer architecture
    • Attention and cross-attention
    • Tokenization and embeddings
    • Hugging Face Transformers
    • Image preprocessing
    • Prompt engineering
    • LLM evaluation
    • Responsible AI fundamentals

    Example Packages

    • PyTorch
    • Transformers
    • Accelerate
    • Pillow
    • Requests for approved remote-image workflows
    • scikit-learn
    python -m pip install \
      torch \
      transformers \
      accelerate \
      pillow \
      requests \
      scikit-learn
    Compatibility requirement: Validate the selected model, processor, package versions, image formats, accelerator, precision, memory, license, and permitted usage before processing real content.

    What Is a Modality?

    A modality is a form in which information is expressed or observed. Multimodal systems process two or more modalities.

    Modality Example Inputs Possible Representations
    Text Questions, documents, code, and conversations Text tokens and embeddings
    Image Photographs, diagrams, screenshots, and scans Pixels, patches, regions, and visual tokens
    Audio Speech, calls, music, and environmental sounds Waveforms, spectrograms, and audio tokens
    Video Frames, motion, scenes, and events Frame, spatial, and temporal representations
    Structured Data Tables, measurements, and records Fields, values, and serialized tokens

    What Is Multimodal AI?

    Multimodal AI processes information from multiple modalities and learns relationships across them.

    Multimodal System
    Text + Image + Other Supported Modalities → Integrated Representation → Output
    Input Output Example Pattern
    Image Text Generate an image caption
    Image and Question Text Answer a question about an image
    Text Image Generate an image from a description
    Image and Text Similarity Score Measure image-text alignment
    Document Image and Prompt Structured Data Extract fields into JSON
    Video and Question Text Describe an observed event

    What Is a Vision-Language Model?

    A Vision-Language Model is a multimodal model designed to process visual and textual information together. Some VLMs focus on matching images and text. Others generate language conditioned on one or more images.

    VLM Category Main Behavior
    Image-Text Dual Encoder Encodes images and text separately into a shared vector space
    Vision Encoder with Text Decoder Generates text conditioned on encoded visual content
    Vision Encoder with LLM Connects image representations to a pretrained language model
    Unified Multimodal Transformer Processes compatible multimodal tokens through an integrated architecture
    Grounding Model Connects language expressions to image regions or coordinates

    Simplified VLM Architecture

    Vision-Language Flow
    Image → Image Processor → Vision Encoder → Projector or Adapter → Language Model → Text Output
    Component Responsibility
    Image Processor Resizes, normalizes, and prepares visual input
    Vision Encoder Transforms the image into learned visual representations
    Projector Maps visual representations into a space compatible with the language model
    Cross-Attention Allows text representations to attend to visual information
    Language Model Processes multimodal context and generates text
    Tokenizer Converts text into model tokens
    Decoder Generates the output sequence token by token
    Architecture variation: VLM implementations differ. Some use a linear projector, some use cross-attention, and others use more deeply integrated multimodal token processing.

    Image Representation

    A digital image can be represented as a tensor containing height, width, and channel dimensions.

    Image Tensor
    \[ I \in \mathbb{R}^{H \times W \times C} \]
    Symbol Meaning
    \(H\) Image height
    \(W\) Image width
    \(C\) Number of image channels

    The image processor may resize the input, normalize pixel values, convert color channels, and create the tensor format expected by the selected model.

    Image Patches and Visual Tokens

    A Vision Transformer commonly divides an image into fixed-size patches. Each patch is flattened and projected into an embedding.

    Number of Patches
    \[ N = \frac{H}{P} \times \frac{W}{P} \]

    Here, \(P\) is the patch height and width when square patches are used.

    Patch Embedding
    \[ \mathbf{z}_i = \mathbf{x}_i E + \mathbf{p}_i \]

    \(\mathbf{x}_i\) is a flattened image patch, \(E\) is a learned projection, and \(\mathbf{p}_i\) is positional information.

    Visual-token cost: Image resolution, patching strategy, cropping, tiling, and the number of images influence visual-token count, memory, latency, and cost.

    Cross-Modal Alignment

    Cross-modal alignment places related visual and textual concepts into representations that can be compared or combined.

    Aligned Representations
    \[ f_{\text{vision}} \left( I \right) \approx f_{\text{text}} \left( T \right) \]

    The approximation indicates that a matching image \(I\) and text description \(T\) should have compatible or nearby representations under the trained alignment objective.

    Alignment Enables

    • Text-to-image retrieval
    • Image-to-text retrieval
    • Zero-shot image classification
    • Visual question answering
    • Caption generation
    • Cross-modal reasoning

    Contrastive Image-Text Learning

    Contrastive learning teaches a model to assign higher similarity to matching image-text pairs and lower similarity to non-matching pairs.

    Cosine Similarity
    \[ s \left( \mathbf{v}, \mathbf{t} \right) = \frac{ \mathbf{v} \cdot \mathbf{t} }{ \lVert \mathbf{v} \rVert_2 \lVert \mathbf{t} \rVert_2 } \]
    Simplified Image-to-Text Loss
    \[ \mathcal{L}_{I \rightarrow T} = - \frac{1}{B} \sum_{i=1}^{B} \log \frac{ \exp \left( s_{ii}/\tau \right) }{ \sum_{j=1}^{B} \exp \left( s_{ij}/\tau \right) } \]

    \(B\) is the batch size, \(s_{ii}\) is the similarity of a matching image-text pair, \(s_{ij}\) represents comparisons with other text entries, and \(\tau\) is a temperature parameter.

    Training objective: Contrastive alignment supports retrieval and classification. Generative VLMs generally require additional components or training to produce detailed textual responses.

    Dual Encoder vs Generative VLM

    Area Dual Encoder Generative VLM
    Vision Processing Creates an image embedding Creates visual representations for language generation
    Text Processing Creates an independent text embedding Processes prompts and generates text
    Typical Output Similarity score or ranking Caption, answer, explanation, or structured output
    Typical Use Retrieval and zero-shot classification Visual question answering and image reasoning
    Retrieval Efficiency Corpus embeddings can be precomputed Usually requires generative inference per request

    Cross-Attention

    Cross-attention allows one representation stream to attend to another. In a VLM, textual queries may attend to visual keys and values.

    Cross-Attention
    \[ \operatorname{Attention} \left( Q, K, V \right) = \operatorname{softmax} \left( \frac{ QK^{T} }{ \sqrt{d_k} } \right) V \]
    Input Possible Source
    Queries \(Q\) Language-model hidden states
    Keys \(K\) Visual representations
    Values \(V\) Visual representations

    Common Vision-Language Tasks

    Task Input Output
    Image Captioning Image Natural-language description
    Visual Question Answering Image and question Answer grounded in the image
    Image-Text Retrieval Image or text query Ranked matching content
    Document Understanding Document image and prompt Fields, summary, or answer
    Chart Understanding Chart and question Data interpretation or answer
    Visual Grounding Image and referring phrase Region, box, point, or coordinates
    Visual Classification Image and candidate labels Selected label or scores
    Screenshot Analysis Application screenshot and instruction UI description, issue, or structured observation
    Image Comparison Two or more images Similarities and differences

    Image Captioning

    Image captioning produces a textual description of visual content. The desired level of detail depends on the use case.

    Caption Type Purpose
    Short Caption Provides a brief description
    Dense Caption Describes multiple objects and relationships
    Region Caption Describes a specified visual area
    Accessibility Description Communicates task-relevant visual information
    Domain Caption Uses approved domain terminology
    Captioning caution: A fluent caption may omit visual details or invent objects, attributes, relationships, or identities. Evaluate claims against the original image.

    Visual Question Answering

    Visual Question Answering, or VQA, provides an image and a natural-language question and asks the model to answer using visual evidence.

    VQA
    \[ \hat{y} = f \left( I, Q \right) \]

    \(I\) is the image, \(Q\) is the question, and \(\hat{y}\) is the generated answer.

    VQA May Require

    • Object recognition
    • Attribute recognition
    • Spatial reasoning
    • Counting
    • Text reading
    • Relationship reasoning
    • Chart interpretation
    • Comparison across images

    Document Understanding

    Document images may contain text, tables, logos, signatures, diagrams, handwriting, and spatial layouts. VLMs can analyze these elements together, but specialized OCR or document parsers may remain valuable.

    Document Task Example
    Text Extraction Read visible text from a scan
    Field Extraction Extract invoice number, date, and total
    Layout Understanding Associate a label with the correct nearby value
    Table Understanding Interpret rows, columns, headers, and totals
    Document Question Answering Answer a question using visible document evidence
    Document Classification Identify an approved document category
    Visual Consistency Compare document content with a structured record

    OCR vs Vision-Language Models

    Area OCR System Vision-Language Model
    Primary Goal Convert visible text into machine-readable text Understand and respond using visual and textual context
    Output Characters, words, lines, boxes, and confidence Answer, description, extraction, or reasoning output
    Deterministic Structure Often provides explicit coordinates and confidence May produce flexible natural-language output
    Reasoning Generally limited Can combine text, layout, and broader context
    Best Combined Through OCR extraction plus VLM interpretation and validation
    Architecture principle: Use deterministic OCR or document extraction when precise text, coordinates, or confidence values are required. Use a VLM for interpretation where its measured capabilities add value.

    Chart and Diagram Understanding

    Relevant Visual Elements

    • Chart title
    • Axes and units
    • Legend
    • Data labels
    • Series colors and markers
    • Annotations
    • Scale and baseline
    • Arrows and flow direction
    • Diagram nodes and connectors
    • Tables embedded in the visualization
    Numerical caution: Do not assume that a VLM has read small labels or exact chart values correctly. Use underlying structured data or deterministic extraction when numerical precision is important.

    Visual Grounding

    Visual grounding connects a text phrase with a location or region in an image.

    Bounding Box
    \[ b = \left( x_{\min}, y_{\min}, x_{\max}, y_{\max} \right) \]
    Grounding Output Use
    Bounding Box Encloses an object or region
    Point Identifies a target location
    Segmentation Mask Represents the precise pixels of an object
    Region Identifier References a pre-detected region
    Text Span to Region Links a phrase with corresponding visual evidence

    Load and Validate an Image

    from pathlib import Path
    
    from PIL import Image
    from PIL import UnidentifiedImageError
    
    
    def load_validated_image(
        image_path,
        maximum_pixels=20_000_000
    ):
        image_path = Path(
            image_path
        )
    
        if not image_path.is_file():
    
            raise FileNotFoundError(
                f"Image not found: {image_path}"
            )
    
        try:
            with Image.open(
                image_path
            ) as opened_image:
    
                opened_image.verify()
    
            image = Image.open(
                image_path
            ).convert(
                "RGB"
            )
    
        except UnidentifiedImageError as error:
    
            raise ValueError(
                "Unsupported or invalid image."
            ) from error
    
        width, height = image.size
    
        if (
            width
            *
            height
            >
            maximum_pixels
        ):
            raise ValueError(
                "Image exceeds the approved "
                "pixel limit."
            )
    
        return image
    Input-security rule: Validate file type, decoded content, dimensions, pixel count, size, source, and authorization. Do not trust a file merely because its extension appears to be an image format.

    Resize Images Safely

    from PIL import Image
    
    
    def resize_with_aspect_ratio(
        image,
        maximum_width,
        maximum_height
    ):
        if (
            maximum_width <= 0
            or maximum_height <= 0
        ):
            raise ValueError(
                "Maximum dimensions must "
                "be positive."
            )
    
        resized_image = image.copy()
    
        resized_image.thumbnail(
            (
                maximum_width,
                maximum_height
            ),
            Image.Resampling.LANCZOS
        )
    
        return resized_image
    Preprocessing consistency: Use the processor supplied for the selected model whenever possible. Arbitrary resizing or cropping can remove small text, objects, chart labels, or spatial relationships.

    Load a Vision-Language Model

    import torch
    from transformers import AutoProcessor
    from transformers import AutoModelForVision2Seq
    
    
    model_id = (
        "replace-with-approved-vision-language-model"
    )
    
    
    processor = AutoProcessor.from_pretrained(
        model_id
    )
    
    
    model = (
        AutoModelForVision2Seq
        .from_pretrained(
            model_id,
            torch_dtype=(
                torch.bfloat16
                if torch.cuda.is_available()
                and torch.cuda.is_bf16_supported()
                else torch.float16
            ),
            device_map="auto"
        )
    )
    
    
    model.eval()
    Model-access requirement: Replace the placeholder with an approved model. Review its model card, architecture, processor, supported modalities, image limits, prompt format, license, languages, intended use, and safety limitations.

    Create a Multimodal Prompt

    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "image": image
                },
                {
                    "type": "text",
                    "text": (
                        "Describe only the visible "
                        "content. If a detail cannot "
                        "be verified from the image, "
                        "state that it is unclear."
                    )
                }
            ]
        }
    ]
    
    
    prompt = processor.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True
    )
    Prompt principle: Ask for observable evidence, specify the required detail, define uncertainty behavior, and prohibit unsupported inference when the use case demands faithful visual analysis.

    Run Vision-Language Inference

    model_inputs = processor(
        text=[
            prompt
        ],
        images=[
            image
        ],
        return_tensors="pt"
    )
    
    
    model_inputs = {
        key: value.to(
            model.device
        )
        if hasattr(
            value,
            "to"
        )
        else value
        for key, value
        in model_inputs.items()
    }
    
    
    with torch.inference_mode():
    
        generated_ids = model.generate(
            **model_inputs,
            max_new_tokens=256,
            do_sample=False
        )
    
    
    generated_text = processor.batch_decode(
        generated_ids,
        skip_special_tokens=True
    )[
        0
    ]
    
    
    print(
        generated_text
    )
    API compatibility: Processing and generation interfaces differ among model families and Transformers versions. Use the usage instructions supplied for the exact model and installed package version.

    Request Structured Extraction

    Analyze the supplied document image.
    
    Return only valid JSON using this schema:
    
    {
      "document_type": "",
      "visible_fields": [
        {
          "field_name": "",
          "value": "",
          "evidence": ""
        }
      ],
      "unclear_fields": [],
      "warnings": []
    }
    
    Rules:
    1. Use only information visible in the image.
    2. Do not guess missing or unreadable values.
    3. Put uncertain fields in unclear_fields.
    4. Do not invent document identifiers.
    5. Preserve the visible wording.
    Structured-output requirement: Validate generated JSON against a schema. A text instruction asking for JSON does not guarantee syntactically or semantically valid output.

    Validate Structured VLM Output

    import json
    
    from pydantic import BaseModel
    from pydantic import Field
    from pydantic import ValidationError
    
    
    class ExtractedField(
        BaseModel
    ):
        field_name: str = Field(
            min_length=1
        )
    
        value: str
    
        evidence: str
    
    
    class DocumentExtraction(
        BaseModel
    ):
        document_type: str
    
        visible_fields: list[
            ExtractedField
        ]
    
        unclear_fields: list[
            str
        ]
    
        warnings: list[
            str
        ]
    
    
    def validate_vlm_json(
        generated_output
    ):
        try:
            parsed_output = json.loads(
                generated_output
            )
    
            validated_output = (
                DocumentExtraction
                .model_validate(
                    parsed_output
                )
            )
    
            return {
                "valid": True,
                "data": (
                    validated_output.model_dump()
                ),
                "error": None
            }
    
        except (
            json.JSONDecodeError,
            ValidationError
        ) as error:
    
            return {
                "valid": False,
                "data": None,
                "error": str(
                    error
                )
            }

    Multiple-Image Reasoning

    Some VLMs can receive multiple images in a single request. This can support comparison, change detection, visual sequence analysis, and cross-document reasoning.

    Multi-Image Tasks

    • Compare before-and-after screenshots
    • Identify differences between document versions
    • Compare a reference design with an implementation
    • Analyze several pages of a document
    • Follow a visual process across frames
    • Match a product image with a specification
    Image-reference rule: Label images clearly in the prompt and require the model to identify which image supports each observation.

    Memory and Compute Requirements

    VLM inference uses memory for model weights, visual representations, text tokens, key-value cache, generation, and temporary operations.

    Simplified Inference Memory
    \[ M_{\text{total}} \approx M_{\text{weights}} + M_{\text{visual tokens}} + M_{\text{text context}} + M_{\text{KV cache}} + M_{\text{temporary}} \]

    Resource Drivers

    • Model parameter count
    • Model precision or quantization
    • Image resolution
    • Number of images
    • Visual-token strategy
    • Prompt length
    • Generated-token length
    • Batch size
    • Attention implementation
    • Accelerator and runtime

    VLM Evaluation Dimensions

    Dimension Evaluation Question
    Visual Correctness Are claims supported by visible evidence?
    Text Recognition Was visible text read correctly?
    Spatial Reasoning Are positions and relationships correct?
    Counting Are visible objects counted correctly?
    Grounding Is the described region localized correctly?
    Answer Relevance Does the response address the visual question?
    Completeness Are all required visual details covered?
    Uncertainty Does the model acknowledge unreadable or ambiguous evidence?
    Safety Does the application avoid prohibited visual inferences?
    Operational Quality Does the system satisfy latency, memory, and cost requirements?

    Build a VLM Evaluation Dataset

    {
      "case_id": "chart-001",
      "image_id": "approved-image-reference",
      "question": "Which category has the highest visible value?",
      "reference_answer": "Category B",
      "required_evidence": [
        "Category labels",
        "Visible bar heights"
      ],
      "task": "chart-question-answering",
      "difficulty": "medium",
      "language": "en",
      "risk_level": "standard",
      "expected_behavior": {
        "must_use_visual_evidence": true,
        "must_not_invent_exact_values": true
      }
    }

    Include in the Evaluation Set

    • High-quality and low-quality images
    • Small and large objects
    • Dense and sparse scenes
    • Multiple aspect ratios
    • Rotated or skewed documents
    • Small text and handwriting
    • Charts, tables, diagrams, and screenshots
    • Ambiguous and partially occluded content
    • No-answer cases
    • Adversarial visual instructions
    • Required languages and scripts
    • Regression cases from real failures

    Evaluate Grounding with Intersection over Union

    Intersection over Union, or IoU, measures overlap between a predicted region and a reference region.

    Intersection over Union
    \[ \operatorname{IoU} = \frac{ \operatorname{Area} \left( B_{\text{pred}} \cap B_{\text{true}} \right) }{ \operatorname{Area} \left( B_{\text{pred}} \cup B_{\text{true}} \right) } \]
    def calculate_iou(
        predicted_box,
        reference_box
    ):
        pred_x1, pred_y1, pred_x2, pred_y2 = (
            predicted_box
        )
    
        ref_x1, ref_y1, ref_x2, ref_y2 = (
            reference_box
        )
    
        intersection_x1 = max(
            pred_x1,
            ref_x1
        )
    
        intersection_y1 = max(
            pred_y1,
            ref_y1
        )
    
        intersection_x2 = min(
            pred_x2,
            ref_x2
        )
    
        intersection_y2 = min(
            pred_y2,
            ref_y2
        )
    
        intersection_width = max(
            0,
            intersection_x2
            -
            intersection_x1
        )
    
        intersection_height = max(
            0,
            intersection_y2
            -
            intersection_y1
        )
    
        intersection_area = (
            intersection_width
            *
            intersection_height
        )
    
        predicted_area = max(
            0,
            pred_x2
            -
            pred_x1
        ) * max(
            0,
            pred_y2
            -
            pred_y1
        )
    
        reference_area = max(
            0,
            ref_x2
            -
            ref_x1
        ) * max(
            0,
            ref_y2
            -
            ref_y1
        )
    
        union_area = (
            predicted_area
            +
            reference_area
            -
            intersection_area
        )
    
        if union_area == 0:
    
            raise ValueError(
                "Bounding boxes must have "
                "a positive union area."
            )
    
        return (
            intersection_area
            /
            union_area
        )

    Evaluate Extracted Fields

    def calculate_field_metrics(
        predicted_fields,
        reference_fields
    ):
        predicted_keys = set(
            predicted_fields
        )
    
        reference_keys = set(
            reference_fields
        )
    
        correctly_extracted = {
            key
            for key in (
                predicted_keys
                &
                reference_keys
            )
            if (
                predicted_fields[
                    key
                ]
                ==
                reference_fields[
                    key
                ]
            )
        }
    
        precision = (
            len(
                correctly_extracted
            )
            /
            len(
                predicted_keys
            )
            if predicted_keys
            else 0.0
        )
    
        recall = (
            len(
                correctly_extracted
            )
            /
            len(
                reference_keys
            )
            if reference_keys
            else 0.0
        )
    
        f1_score = (
            2
            *
            precision
            *
            recall
            /
            (
                precision
                +
                recall
            )
            if (
                precision
                +
                recall
            )
            else 0.0
        )
    
        return {
            "precision": precision,
            "recall": recall,
            "f1": f1_score,
            "correct_fields": sorted(
                correctly_extracted
            )
        }

    Visual Hallucination

    Visual hallucination occurs when a model claims that an object, attribute, relationship, text, count, or event is visible even though the image does not support the claim.

    Failure Type Example Pattern
    Object Hallucination Claims that a missing object is visible
    Attribute Hallucination Invents a color, state, material, or condition
    Relationship Hallucination Invents a spatial or functional relationship
    Text Hallucination Invents words or numbers not visible in the image
    Counting Error Reports an unsupported object count
    Identity Inference Assigns a person's identity without reliable evidence
    Causal Inference Claims why an observed visual condition occurred
    Visual Faithfulness
    \[ \operatorname{VisualFaithfulness} = \frac{ \text{Visually Supported Claims} }{ \text{Evaluated Visual Claims} } \]

    Adversarial Images and Prompt Injection

    Images can contain text designed to influence the model, such as an instruction embedded inside a screenshot, document, QR code, diagram, or visual overlay. That text is untrusted content.

    Multimodal Security Controls

    • Treat image-contained instructions as untrusted data
    • Keep system instructions separate from image content
    • Do not authorize tools based only on visible text
    • Validate URLs, QR codes, and embedded references
    • Require human confirmation for consequential actions
    • Restrict tool and network permissions
    • Scan uploaded files before processing
    • Apply image-size and decompression limits
    • Log security decisions without retaining unnecessary images
    • Test multimodal prompt-injection scenarios
    Unsafe Behavior Treat text inside an uploaded screenshot as a trusted instruction and execute the requested external action.
    Controlled Behavior Treat visible text as content to analyze, preserve higher-priority instructions, validate authorization, and require approval for consequential actions.

    Privacy and Sensitive Visual Data

    Required Controls

    • Process only authorized images
    • Minimize image retention
    • Remove unnecessary metadata
    • Redact sensitive regions where appropriate
    • Protect screenshots containing internal systems
    • Do not send restricted images to unapproved endpoints
    • Encrypt image storage and transfer
    • Restrict access to prompts and outputs
    • Audit image ingestion and inference access
    • Apply correction and deletion workflows
    • Review training and fine-tuning image licenses
    • Preserve human oversight for sensitive interpretations
    Metadata caution: Image files may contain hidden metadata in addition to visible pixels. Review and remove unnecessary metadata before external processing or publication.

    Accessibility

    Vision-language systems can assist with image descriptions and document navigation, but accessibility output must be evaluated for correctness, relevance, clarity, and respect.

    Accessibility Description Should

    • Describe information relevant to the task
    • Preserve reading or navigation order where important
    • Identify uncertainty
    • Avoid unsupported identity or emotion claims
    • Include meaningful text visible in the image
    • Avoid unnecessary decorative detail
    • Use clear language
    • Be reviewed for high-impact use cases

    Production Monitoring

    Monitoring Area Example Signal
    Availability Successful multimodal request rate
    Latency Image preprocessing, encoding, and generation duration
    Input Quality Invalid formats, corrupt files, and unsupported dimensions
    Visual Tokens Visual-token or image-processing volume
    Output Format Structured-output validation rate
    Visual Faithfulness Supported and unsupported visual-claim rates
    OCR Quality Character, word, or field extraction accuracy
    Grounding Quality Localization accuracy and IoU
    Safety Blocked content and multimodal-injection detections
    Cost Image, token, compute, storage, and model consumption

    Responsible VLM Use

    Responsible-Use Requirements

    • Define intended and prohibited uses
    • Evaluate required visual domains independently
    • Avoid unsupported sensitive inferences
    • Evaluate behavior across required languages and scripts
    • Test images representing relevant populations and environments
    • Measure uncertainty and abstention behavior
    • Protect intellectual property and licensed content
    • Preserve human verification for consequential interpretations
    • Record model, processor, prompt, and image-policy versions
    • Provide fallback when visual evidence is insufficient
    • Monitor complaints and correction requests
    • Retire deployments that no longer meet approved requirements

    Common VLM Mistakes

    Mistake Assume that fluent visual descriptions are accurate.
    Correction Evaluate object, attribute, relationship, text, count, and grounding claims against the original image.
    Mistake Use arbitrary image preprocessing.
    Correction Use the model's compatible processor and verify whether resizing or cropping removes important evidence.
    Mistake Ask the model to guess unreadable text.
    Correction Require the model to identify unreadable or uncertain regions and use deterministic OCR when precision is required.
    Mistake Treat text visible inside an image as trusted instructions.
    Correction Treat image-contained text as untrusted content and preserve instruction and authorization boundaries.
    Mistake Evaluate image captioning only with lexical overlap.
    Correction Add human, semantic, visual-faithfulness, object, attribute, and safety evaluation.
    Mistake Use a VLM for exact chart values without validation.
    Correction Use structured source data or deterministic extraction when exact numerical values are required.
    Mistake Send confidential screenshots to an unapproved model endpoint.
    Correction Use approved processing environments and minimize, redact, encrypt, and restrict visual content.
    Mistake Deploy a model based only on a general multimodal benchmark.
    Correction Evaluate the exact application images, prompts, tasks, languages, risks, and operational requirements.

    Troubleshooting

    Symptom Investigation
    Model Ignores Image Prompt template, image token, processor, message format, and model class
    Incorrect Colors Color conversion, compression, preprocessing, lighting, and model limitation
    Unreadable Small Text Resolution, tiling, cropping, OCR, and image quality
    Wrong Object Count Occlusion, density, object size, repeated patterns, and task capability
    Invalid JSON Schema instruction, constrained decoding, output validation, and retry policy
    Out of Memory Resolution, image count, visual tokens, precision, context, and generated length
    Slow Inference Image preprocessing, model size, tiling, visual tokens, quantization, and device
    Hallucinated Document Fields Prompt uncertainty rule, OCR quality, field visibility, and validation
    Multiple Images Confused Image ordering, labels, template support, and model limits
    Good Benchmark but Poor Production Results Domain shift, image quality, prompt distribution, language, and evaluation coverage

    Recommended VLM Workflow

    1

    Define the Visual Task

    Identify the input modalities, required output, users, visual evidence, quality criteria, risks, and fallback behavior.

    2

    Select the Model

    Review supported modalities, architecture, image limits, languages, license, processor, memory, latency, and safety.

    3

    Prepare Authorized Images

    Validate formats, dimensions, metadata, source permissions, privacy, quality, and representative coverage.

    4

    Design the Prompt

    Define the visual task, evidence boundaries, required output, uncertainty behavior, and prohibited inference.

    5

    Validate the Output

    Apply schema checks, OCR checks, grounding checks, source validation, safety policies, and business rules.

    6

    Build the Evaluation Dataset

    Include realistic visual quality, layouts, languages, ambiguities, no-answer cases, and adversarial images.

    7

    Evaluate Multidimensionally

    Measure visual correctness, OCR, grounding, relevance, completeness, safety, latency, memory, and cost.

    8

    Apply Security and Privacy Controls

    Enforce access, redaction, scanning, prompt-injection protection, retention, and restricted tool use.

    9

    Deploy Through Controlled Environments

    Use staging, canary, fallback, human review, and rollback for the exact model and processor combination.

    10

    Monitor and Improve

    Track production quality, image characteristics, hallucination, safety, latency, cost, complaints, and regression cases.

    Hands-On Practice

    1

    Inspect Image Properties

    Load an approved or synthetic image and inspect its dimensions, mode, format, and pixel count.

    2

    Generate a Caption

    Ask a VLM to describe visible content and verify every claim against the image.

    3

    Perform Visual Question Answering

    Create factual, spatial, counting, and no-answer questions for one image.

    4

    Extract Structured Fields

    Request JSON from a synthetic document image and validate the output using Pydantic.

    5

    Compare OCR and VLM Results

    Compare deterministic OCR text with the VLM's interpretation and identify which component produced each error.

    6

    Evaluate Grounding

    Compare a predicted bounding box with a reference box using IoU.

    7

    Test Visual Hallucination

    Ask about objects and text that are both present and absent and measure unsupported visual claims.

    8

    Test Multimodal Prompt Injection

    Use a safe synthetic image containing instruction-like text and verify that the application treats it as untrusted content.

    Knowledge Check

    1

    What is a modality?

    Explain a form of information such as text, image, audio, or video.

    2

    What is a Vision-Language Model?

    Explain how it processes visual and textual information together.

    3

    What does a vision encoder do?

    Explain how it transforms image content into learned visual representations.

    4

    What is cross-modal alignment?

    Explain how related image and text representations are placed into compatible spaces.

    5

    How does a dual encoder differ from a generative VLM?

    Explain independent similarity embeddings compared with image-conditioned text generation.

    6

    What is visual question answering?

    Explain how the model answers a language question using supplied image evidence.

    7

    What is visual grounding?

    Explain how a phrase is linked to an image location or region.

    8

    What is visual hallucination?

    Explain unsupported claims about visible objects, text, attributes, relationships, or counts.

    9

    Why can OCR and VLMs be used together?

    Explain precise text extraction followed by contextual interpretation and reasoning.

    10

    Why is image-contained text untrusted?

    Explain how visible text can contain malicious or unauthorized instructions that must not override application policy.

    VLM Readiness Checklist

    Confirm Before Production Use

    • The visual task and intended use are documented
    • Prohibited visual inferences are documented
    • The model and immutable revision are recorded
    • The processor and tokenizer versions are recorded
    • The model license is reviewed
    • Supported image formats are defined
    • File-size and pixel limits are enforced
    • Image content is validated after decoding
    • Unnecessary image metadata is removed
    • Authorized processing locations are selected
    • The image preprocessing policy is versioned
    • The prompt template is versioned
    • Uncertainty behavior is defined
    • No-answer behavior is tested
    • Structured outputs are schema validated
    • OCR quality is independently evaluated where relevant
    • Visual question answering is evaluated
    • Object and attribute claims are evaluated
    • Counting behavior is evaluated
    • Spatial reasoning is evaluated
    • Grounding is evaluated where applicable
    • Chart and table interpretation is evaluated
    • Required languages and scripts are evaluated
    • Low-quality and ambiguous images are included
    • Visual hallucination is measured
    • Multimodal prompt injection is tested
    • Restricted image data is protected
    • Human review is applied where required
    • Latency and peak memory are measured
    • Image and token costs are measured
    • Version-specific monitoring is configured
    • Fallback behavior is available
    • Rollback restores model, processor, prompt, and policy versions
    • Correction and deletion workflows are documented
    • Accessibility output is reviewed
    • Known model limitations are documented

    Lesson Summary

    Concept Main Outcome
    Modality Represents a form of information such as text or image
    Multimodal AI Processes and combines multiple information modalities
    Vision-Language Model Integrates visual and language understanding
    Vision Encoder Transforms images into learned visual representations
    Visual Tokens Provide token-like representations of image information
    Projector or Adapter Connects visual representations to the language model
    Cross-Attention Allows language states to attend to visual information
    Contrastive Learning Aligns matching images and text in a shared space
    Image Captioning Generates descriptions of visual content
    Visual Question Answering Answers language questions using visual evidence
    Document Understanding Combines text, layout, and visual interpretation
    Visual Grounding Links language to image regions or coordinates
    Visual Hallucination Describes unsupported claims about image content
    Multimodal Security Protects against malicious files and image-contained instructions
    Production Evaluation Measures visual correctness, safety, latency, memory, and cost

    Key Takeaway

    Vision-Language Models connect visual perception with natural-language understanding. An image processor prepares visual input, a vision encoder creates visual representations, and an adapter, projector, cross-attention mechanism, or unified architecture connects those representations to language generation. This enables image captioning, visual question answering, document and chart understanding, image-text retrieval, structured extraction, and visual grounding. However, VLMs can misread text, overlook small details, count incorrectly, confuse spatial relationships, and hallucinate objects or attributes. Production use therefore requires model-compatible preprocessing, representative multimodal evaluation, structured-output validation, visual-faithfulness checks, privacy protection, prompt-injection defenses, accessibility review, human oversight, monitoring, fallback, and rollback. A fluent answer is not sufficient. Every important visual claim must be verified against the supplied visual evidence.

    Get Machine Learning updates by email

    Short, practical lessons and course updates from Rumman Ansari. No spam.