model.py 3.18 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging
17
from typing import Any, Dict, List, Optional
18
19

import torch
20
from transformers import AutoModel
21

22
logger = logging.getLogger(__name__)
23
24


25
26
27
28
29
30
class SupportedModels:
    """Supported multimodal model identifiers"""

    LLAVA_1_5_7B = "llava-hf/llava-1.5-7b-hf"
    QWEN_2_5_VL_7B = "Qwen/Qwen2.5-VL-7B-Instruct"
    LLAVA_NEXT_VIDEO_7B = "llava-hf/LLaVA-NeXT-Video-7B-hf"
31
    QWEN_2_AUDIO_7B = "Qwen/Qwen2-Audio-7B-Instruct"
32
33
34
35
36
37


def load_vision_model(model_id: str) -> torch.nn.Module:
    """
    Load a vision model from a HuggingFace model ID.
    """
38
39
    model = AutoModel.from_pretrained(
        model_id, device_map="auto", torch_dtype=torch.float16, trust_remote_code=True
40
    )
41
    return model
42
43
44
45
46


def construct_mm_data(
    model: str,
    embeddings_dtype: torch.dtype,
47
48
49
    image_embeds: Optional[torch.Tensor] = None,
    video_numpy: Optional[Any] = None,
    image_grid_thw: Optional[List[Any]] = None,
50
    audio_embeds: Optional[torch.Tensor] = None,
51
52
) -> Dict[str, torch.Tensor | Dict[str, Any]]:
    """Construct multimodal data for a vLLM request for models that require additional parameters alongside the embeddings"""
53
54
55
56
    if model == SupportedModels.QWEN_2_AUDIO_7B:
        audio_embeds = audio_embeds.to(torch.bfloat16)
        assert audio_embeds.ndim == 2, "Audio embeddings must be 2D"
        return {"audio": [audio_embeds]}
57
58
59
60
61
62
63
64
65
66
    # Handle video models
    if model == SupportedModels.LLAVA_NEXT_VIDEO_7B:
        if video_numpy is None:
            raise ValueError("No video frames provided.")
        return {"video": video_numpy}

    # Handle image models - validate image embeddings first
    if image_embeds is None:
        raise ValueError("No image embeddings provided.")

67
    image_embeds = image_embeds.to(embeddings_dtype)
68
69

    # Model-specific image handling
70
    if model == SupportedModels.QWEN_2_5_VL_7B:
71
        return _construct_qwen_image_data(image_embeds, image_grid_thw)
72
    else:
73
        # Default image handling for other models (e.g., LLAVA_1_5_7B)
74
        return {"image": image_embeds}
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91


def _construct_qwen_image_data(
    image_embeds: torch.Tensor, image_grid_thw: Optional[List[Any]]
) -> Dict[str, Dict[str, torch.Tensor]]:
    """Construct image data specifically for Qwen models."""
    if image_grid_thw is None or len(image_grid_thw) == 0:
        raise ValueError("No image grid provided for Qwen model.")

    grid_thw_tensor = torch.tensor(image_grid_thw)

    return {
        "image": {
            "image_embeds": image_embeds.squeeze(0),
            "image_grid_thw": grid_thw_tensor,
        }
    }