Abdulmateen commited on
Commit
9e0766a
·
verified ·
1 Parent(s): 3453485

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +74 -49
handler.py CHANGED
@@ -1,66 +1,91 @@
 
1
  import torch
2
- from transformers import AutoProcessor, LlavaForConditionalGeneration
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
- # The 'path' argument will be the path to your LoRA repo on the Hub, e.g., "Abdulmateen/llava-finetuned"
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
- print("Loading processor...")
17
- # Pinning to a specific revision for stability
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
- torch_dtype=torch.float16,
26
- device_map="auto"
 
27
  )
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- print(f"Loading LoRA adapters from repository path: {path}...")
30
- # Load and merge your LoRA adapters onto the base model
31
- self.model = PeftModel.from_pretrained(self.model, path)
32
- print("✅ Model and adapters loaded successfully.")
33
-
34
- def __call__(self, data: dict) -> dict:
35
- # Get the prompt and image from the request payload
36
- prompt_text = data.pop("prompt", "Describe the image in detail.")
37
- image_url = data.pop("image_url", None)
38
- image_b64 = data.pop("image_b64", None)
39
- max_new_tokens = data.pop("max_new_tokens", 200)
40
-
41
- # Load image from either a URL or a base64 string
42
- if image_url:
43
- response = requests.get(image_url)
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
- # Format the prompt for LLaVA
52
- prompt = f"USER: <image>\n{prompt_text} ASSISTANT:"
53
 
54
- # Process inputs
55
- inputs = self.processor(text=prompt, images=image, return_tensors="pt").to("cuda")
 
 
 
 
56
 
57
- # Generate a response
58
- with torch.no_grad():
59
- output = self.model.generate(**inputs, max_new_tokens=max_new_tokens)
60
 
61
- # Decode and clean up the response
62
- full_response = self.processor.decode(output[0], skip_special_tokens=True)
63
- # Extract only the assistant's part of the response
64
- assistant_response = full_response.split("ASSISTANT:")[-1].strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- return {"generated_text": assistant_response}
 
 
 
 
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}