Lemorra commited on
Commit
ba9f758
·
1 Parent(s): 4d01c19

InternVL3-1B model app

Browse files
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from fastapi import FastAPI, Depends
3
+ from fastapi.responses import JSONResponse
4
+ from authenticator import authenticate_token
5
+ from payload_model import PayloadModel
6
+ from models import InternVL3
7
+ from internvl_utils import internvl_inference
8
+
9
+
10
+ app = FastAPI()
11
+
12
+ model = InternVL3("OpenGVLab/InternVL3-1B-Instruct")
13
+
14
+ @app.get("/healthcheck")
15
+ def healthcheck():
16
+ return JSONResponse(status_code=200, content={"status": "ok"})
17
+
18
+ @app.post("/internvl_inference")
19
+ async def inference(payload: PayloadModel, token: str = Depends(authenticate_token)):
20
+ try:
21
+ model_response = await internvl_inference(model, payload)
22
+ return JSONResponse(status_code=200, content={"status": "ok", "response": model_response})
23
+ except Exception as e:
24
+ print(f"Error: {e}")
25
+ return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})
authenticator.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Header, HTTPException
2
+ import os
3
+ import jwt
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+
8
+ secret_token = os.getenv("AUTH_TOKEN")
9
+
10
+ async def authenticate_token(authorization: str = Header(...)):
11
+ token_type, token = authorization.split()
12
+ if token_type != "Bearer":
13
+ raise HTTPException(status_code=401, detail="Unauthorized")
14
+ try:
15
+ return jwt.decode(token, secret_token, algorithms=["HS256"])
16
+ except jwt.ExpiredSignatureError:
17
+ raise HTTPException(status_code=401, detail="Token has expired") from None
18
+ except (jwt.InvalidTokenError, IndexError):
19
+ raise HTTPException(status_code=401, detail="Invalid token") from None
20
+
21
+
internvl_utils.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+ import torch
4
+ import torchvision.transforms as T
5
+ from torchvision.transforms.functional import InterpolationMode
6
+ from transformers import AutoConfig
7
+ from models import InternVL3
8
+ from payload_model import PayloadModel
9
+ from models.misc_utils import convert_base64_to_pil
10
+
11
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
12
+ IMAGENET_STD = (0.229, 0.224, 0.225)
13
+
14
+
15
+ def build_transform(input_size):
16
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
17
+ transform = T.Compose([
18
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
19
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
20
+ T.ToTensor(),
21
+ T.Normalize(mean=MEAN, std=STD)
22
+ ])
23
+ return transform
24
+
25
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
26
+ best_ratio_diff = float('inf')
27
+ best_ratio = (1, 1)
28
+ area = width * height
29
+ for ratio in target_ratios:
30
+ target_aspect_ratio = ratio[0] / ratio[1]
31
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
32
+ if ratio_diff < best_ratio_diff:
33
+ best_ratio_diff = ratio_diff
34
+ best_ratio = ratio
35
+ elif ratio_diff == best_ratio_diff:
36
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
37
+ best_ratio = ratio
38
+ return best_ratio
39
+
40
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
41
+ orig_width, orig_height = image.size
42
+ aspect_ratio = orig_width / orig_height
43
+
44
+ # calculate the existing image aspect ratio
45
+ target_ratios = set(
46
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
47
+ i * j <= max_num and i * j >= min_num)
48
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
49
+
50
+ # find the closest aspect ratio to the target
51
+ target_aspect_ratio = find_closest_aspect_ratio(
52
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
53
+
54
+ # calculate the target width and height
55
+ target_width = image_size * target_aspect_ratio[0]
56
+ target_height = image_size * target_aspect_ratio[1]
57
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
58
+
59
+ # resize the image
60
+ resized_img = image.resize((target_width, target_height))
61
+ processed_images = []
62
+ for i in range(blocks):
63
+ box = (
64
+ (i % (target_width // image_size)) * image_size,
65
+ (i // (target_width // image_size)) * image_size,
66
+ ((i % (target_width // image_size)) + 1) * image_size,
67
+ ((i // (target_width // image_size)) + 1) * image_size
68
+ )
69
+ # split the image
70
+ split_img = resized_img.crop(box)
71
+ processed_images.append(split_img)
72
+ assert len(processed_images) == blocks
73
+ if use_thumbnail and len(processed_images) != 1:
74
+ thumbnail_img = image.resize((image_size, image_size))
75
+ processed_images.append(thumbnail_img)
76
+ return processed_images
77
+
78
+ def load_image(image, input_size=448, max_num=12):
79
+ # image = Image.open(image_file).convert('RGB')
80
+ pil_image = convert_base64_to_pil(image)
81
+ transform = build_transform(input_size=input_size)
82
+ images = dynamic_preprocess(pil_image, image_size=input_size, use_thumbnail=True, max_num=max_num)
83
+ pixel_values = [transform(image) for image in images]
84
+ pixel_values = torch.stack(pixel_values)
85
+ pixel_values = pixel_values.to(torch.bfloat16).to("cuda")
86
+ return pixel_values
87
+
88
+ def split_model(model_name):
89
+ device_map = {}
90
+ world_size = torch.cuda.device_count()
91
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
92
+ num_layers = config.llm_config.num_hidden_layers
93
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
94
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
95
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
96
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
97
+ layer_cnt = 0
98
+ for i, num_layer in enumerate(num_layers_per_gpu):
99
+ for j in range(num_layer):
100
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
101
+ layer_cnt += 1
102
+ device_map['vision_model'] = 0
103
+ device_map['mlp1'] = 0
104
+ device_map['language_model.model.tok_embeddings'] = 0
105
+ device_map['language_model.model.embed_tokens'] = 0
106
+ device_map['language_model.output'] = 0
107
+ device_map['language_model.model.norm'] = 0
108
+ device_map['language_model.model.rotary_emb'] = 0
109
+ device_map['language_model.lm_head'] = 0
110
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
111
+
112
+ return device_map
113
+
114
+ async def internvl_inference(model: InternVL3, payload: PayloadModel):
115
+ return await model(payload)
models/InternVL3/__pycache__/intervl3.cpython-310.pyc ADDED
Binary file (2.62 kB). View file
 
models/InternVL3/intervl3.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModel, AutoTokenizer
2
+ import torch
3
+ from payload_model import PayloadModel
4
+ from internvl_utils import load_image
5
+ from pydantic import BaseModel, Field
6
+ from typing import Optional
7
+
8
+ class InternVL3(BaseModel):
9
+ model_name: str
10
+ model: Optional[AutoModel] = None
11
+ tokenizer: Optional[AutoTokenizer] = None
12
+ generation_config: dict = Field(default_factory=lambda: {"max_new_tokens": 1024, "do_sample": True})
13
+
14
+ model_config = {
15
+ "arbitrary_types_allowed": True,
16
+ "from_attributes": True
17
+ }
18
+
19
+ def __init__(self, model_name: str, **kwargs):
20
+ super().__init__(model_name=model_name, **kwargs)
21
+ self.model = AutoModel.from_pretrained(
22
+ self.model_name,
23
+ torch_dtype=torch.bfloat16,
24
+ load_in_8bit=False,
25
+ low_cpu_mem_usage=True,
26
+ use_flash_attn=True,
27
+ trust_remote_code=True,
28
+ device_map="auto",
29
+ ).eval()
30
+ self.tokenizer = AutoTokenizer.from_pretrained(
31
+ self.model_name,
32
+ trust_remote_code=True,
33
+ use_fast=False,
34
+ )
35
+
36
+ def get_query_prompt(self, prompt_keyword: str):
37
+ if prompt_keyword == "person_running":
38
+ query_prompt = """
39
+ <image>\nCheck if person is running or not? If they are running
40
+ respond with "Yes" else respond with "No". Limit your response to either "Yes" or "No"
41
+ """
42
+ else:
43
+ query_prompt = None
44
+ return query_prompt
45
+
46
+ def predict(self, payload: PayloadModel):
47
+ pixel_values = load_image(payload.image)
48
+ query_prompt = self.get_query_prompt(payload.prompt_keyword)
49
+ if query_prompt is None:
50
+ model_response = f"Invalid prompt keyword: {payload.prompt_keyword}"
51
+ else:
52
+ model_response = self.model.chat(
53
+ self.tokenizer,
54
+ pixel_values,
55
+ query_prompt,
56
+ generation_config=self.generation_config,
57
+ )
58
+
59
+ return model_response
60
+
61
+ def extract_model_response(self, model_response: str):
62
+ return "Yes" in model_response
63
+
64
+ async def __call__(self, payload: PayloadModel):
65
+ model_response = self.predict(payload)
66
+ extracted_response = self.extract_model_response(model_response)
67
+ return extracted_response
68
+
models/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .InternVL3.intervl3 import InternVL3
2
+ from .misc_utils import *
models/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (267 Bytes). View file
 
models/__pycache__/misc_utils.cpython-310.pyc ADDED
Binary file (830 Bytes). View file
 
models/misc_utils.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import base64
4
+ from PIL import Image
5
+
6
+
7
+ def convert_base64_to_cv2(base64_string: str):
8
+ return cv2.imdecode(np.frombuffer(base64.b64decode(base64_string), np.uint8), cv2.IMREAD_COLOR)
9
+
10
+ def convert_cv2_to_pil(image: np.ndarray):
11
+ return Image.fromarray(image).convert('RGB')
12
+
13
+ def convert_base64_to_pil(base64_string: str):
14
+ return convert_cv2_to_pil(convert_base64_to_cv2(base64_string))
15
+
payload_model.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+
3
+ class PayloadModel(BaseModel):
4
+ """Type check for payload parameters"""
5
+ image: str
6
+ prompt_keyword: str
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ transformers>=4.37.2
4
+ decord
5
+ numpy~=1.26.4
6
+ torch
7
+ torchvision
8
+ pillow
9
+ PyJWT
10
+ opencv-python==4.9.0.80
11
+ einops
12
+ timm
13
+ accelerate