Update handler.py
Browse files- handler.py +74 -49
handler.py
CHANGED
|
@@ -1,66 +1,91 @@
|
|
|
|
|
| 1 |
import torch
|
| 2 |
-
from transformers import
|
| 3 |
-
from peft import PeftModel
|
| 4 |
from PIL import Image
|
| 5 |
import requests
|
| 6 |
from io import BytesIO
|
| 7 |
import base64
|
| 8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
class EndpointHandler:
|
| 10 |
def __init__(self, path=""):
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
# Define the base model that your LoRA was trained on
|
| 14 |
-
base_model_id = "llava-hf/llava-1.5-7b-hf"
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
self.processor = AutoProcessor.from_pretrained(base_model_id, revision="a272c74")
|
| 19 |
-
|
| 20 |
-
print("Loading base model...")
|
| 21 |
-
# Load the base model in 4-bit for memory efficiency
|
| 22 |
-
self.model = LlavaForConditionalGeneration.from_pretrained(
|
| 23 |
-
base_model_id,
|
| 24 |
load_in_4bit=True,
|
| 25 |
-
|
| 26 |
-
|
|
|
|
| 27 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
image = Image.open(BytesIO(response.content))
|
| 45 |
-
elif image_b64:
|
| 46 |
-
image_bytes = base64.b64decode(image_b64)
|
| 47 |
-
image = Image.open(BytesIO(image_bytes))
|
| 48 |
-
else:
|
| 49 |
-
return {"error": "No image provided. Please use 'image_url' or 'image_b64'."}
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
output = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
|
| 60 |
|
| 61 |
-
#
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Any
|
| 2 |
import torch
|
| 3 |
+
from transformers import BitsAndBytesConfig
|
|
|
|
| 4 |
from PIL import Image
|
| 5 |
import requests
|
| 6 |
from io import BytesIO
|
| 7 |
import base64
|
| 8 |
|
| 9 |
+
from llava.model.builder import load_pretrained_model
|
| 10 |
+
from llava.mm_utils import get_model_name_from_path, process_images, tokenizer_image_token
|
| 11 |
+
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN
|
| 12 |
+
|
| 13 |
class EndpointHandler:
|
| 14 |
def __init__(self, path=""):
|
| 15 |
+
# path is the local path to your repository files
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Load the base model in 4-bit for efficiency
|
| 18 |
+
bnb_config = BitsAndBytesConfig(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
load_in_4bit=True,
|
| 20 |
+
bnb_4bit_quant_type="nf4",
|
| 21 |
+
bnb_4bit_compute_dtype=torch.float16,
|
| 22 |
+
bnb_4bit_use_double_quant=True,
|
| 23 |
)
|
| 24 |
+
|
| 25 |
+
# This function loads the base model and applies the LoRA adapter from your repo
|
| 26 |
+
model_name = get_model_name_from_path(path)
|
| 27 |
+
self.tokenizer, self.model, self.image_processor, self.context_len = load_pretrained_model(
|
| 28 |
+
model_path=path, # Loads LoRA from your repo
|
| 29 |
+
model_base="liuhaotian/llava-v1.5-7b", # Loads the original base model
|
| 30 |
+
model_name=model_name,
|
| 31 |
+
quantization_config=bnb_config
|
| 32 |
+
)
|
| 33 |
+
self.model.eval()
|
| 34 |
+
print("Model, tokenizer, and processor loaded.")
|
| 35 |
|
| 36 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 37 |
+
"""
|
| 38 |
+
Args:
|
| 39 |
+
data (:obj:`dict`):
|
| 40 |
+
A dictionary containing the prompt and image.
|
| 41 |
+
- "image": A base64 encoded string of the image.
|
| 42 |
+
- "prompt": The text prompt.
|
| 43 |
+
- "max_new_tokens" (optional): Max new tokens to generate. Default is 512.
|
| 44 |
+
Returns:
|
| 45 |
+
:obj:`dict`: A dictionary with the model's generated text.
|
| 46 |
+
"""
|
| 47 |
+
# Get inputs
|
| 48 |
+
base64_image = data.pop("image", None)
|
| 49 |
+
prompt = data.pop("prompt", None)
|
| 50 |
+
max_new_tokens = data.pop("max_new_tokens", 512)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
if not base64_image or not prompt:
|
| 53 |
+
return {"error": "Missing 'image' or 'prompt' in the request payload."}
|
| 54 |
|
| 55 |
+
# --- Image Processing ---
|
| 56 |
+
try:
|
| 57 |
+
image_bytes = base64.b64decode(base64_image)
|
| 58 |
+
image = Image.open(BytesIO(image_bytes)).convert("RGB")
|
| 59 |
+
except Exception as e:
|
| 60 |
+
return {"error": f"Failed to decode or open image: {e}"}
|
| 61 |
|
| 62 |
+
image_tensor = process_images([image], self.image_processor, self.model.config)
|
| 63 |
+
image_tensor = image_tensor.to(self.model.device, dtype=torch.float16)
|
|
|
|
| 64 |
|
| 65 |
+
# --- Prompt Formatting ---
|
| 66 |
+
conv_mode = "llava_v1" # Or the conversation mode you used during training
|
| 67 |
+
prompt = DEFAULT_IMAGE_TOKEN + '\n' + prompt
|
| 68 |
+
conv = conv_mode.conv.copy()
|
| 69 |
+
conv.append_message(conv.roles[0], prompt)
|
| 70 |
+
conv.append_message(conv.roles[1], None)
|
| 71 |
+
prompt_text = conv.get_prompt()
|
| 72 |
+
|
| 73 |
+
input_ids = tokenizer_image_token(prompt_text, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).cuda()
|
| 74 |
+
|
| 75 |
+
# --- Generation ---
|
| 76 |
+
with torch.inference_mode():
|
| 77 |
+
output_ids = self.model.generate(
|
| 78 |
+
input_ids,
|
| 79 |
+
images=image_tensor,
|
| 80 |
+
do_sample=True,
|
| 81 |
+
temperature=0.2,
|
| 82 |
+
top_p=None,
|
| 83 |
+
num_beams=1,
|
| 84 |
+
max_new_tokens=max_new_tokens,
|
| 85 |
+
use_cache=True,
|
| 86 |
+
)
|
| 87 |
|
| 88 |
+
# --- Decode and Return ---
|
| 89 |
+
decoded_text = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0].strip()
|
| 90 |
+
|
| 91 |
+
return {"generated_text": decoded_text}
|