Advertisement
Guest User

Untitled

a guest
Aug 12th, 2024
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.05 KB | None | 0 0
  1. from torch import nn
  2. from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
  3. from pathlib import Path
  4. import torch
  5. import torch.amp.autocast_mode
  6. from PIL import Image
  7. import os
  8.  
  9. CLIP_PATH = "google/siglip-so400m-patch14-384"
  10. VLM_PROMPT = "A descriptive caption for this image:\n"
  11. MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-bnb-4bit"
  12. CHECKPOINT_PATH = Path("wpkklhc6")
  13.  
  14. class ImageAdapter(nn.Module):
  15.     def __init__(self, input_features: int, output_features: int):
  16.         super().__init__()
  17.         self.linear1 = nn.Linear(input_features, output_features)
  18.         self.activation = nn.GELU()
  19.         self.linear2 = nn.Linear(output_features, output_features)
  20.    
  21.     def forward(self, vision_outputs: torch.Tensor):
  22.         x = self.linear1(vision_outputs)
  23.         x = self.activation(x)
  24.         x = self.linear2(x)
  25.         return x
  26.  
  27. # Load CLIP
  28. print("Loading CLIP")
  29. clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
  30. clip_model = AutoModel.from_pretrained(CLIP_PATH)
  31. clip_model = clip_model.vision_model
  32. clip_model.eval()
  33. clip_model.requires_grad_(False)
  34. clip_model.to("cuda")
  35.  
  36. # Tokenizer
  37. print("Loading tokenizer")
  38. tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=False)
  39. assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
  40.  
  41. # LLM
  42. print("Loading LLM")
  43. text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16)
  44. text_model.eval()
  45.  
  46. # Image Adapter
  47. print("Loading image adapter")
  48. image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)
  49. image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
  50. image_adapter.eval()
  51. image_adapter.to("cuda")
  52.  
  53. @torch.no_grad()
  54. def stream_chat(input_image: Image.Image):
  55.     torch.cuda.empty_cache()
  56.  
  57.     # Preprocess image
  58.     image = clip_processor(images=input_image, return_tensors='pt').pixel_values
  59.     image = image.to('cuda')
  60.  
  61.     # Tokenize the prompt
  62.     prompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)
  63.  
  64.     # Embed image
  65.     with torch.amp.autocast_mode.autocast('cuda', enabled=True):
  66.         vision_outputs = clip_model(pixel_values=image, output_hidden_states=True)
  67.         image_features = vision_outputs.hidden_states[-2]
  68.         embedded_images = image_adapter(image_features)
  69.         embedded_images = embedded_images.to('cuda')
  70.    
  71.     # Embed prompt
  72.     prompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))
  73.     assert prompt_embeds.shape == (1, prompt.shape[1], text_model.config.hidden_size), f"Prompt shape is {prompt_embeds.shape}, expected {(1, prompt.shape[1], text_model.config.hidden_size)}"
  74.     embedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))
  75.  
  76.     # Construct prompts
  77.     inputs_embeds = torch.cat([
  78.         embedded_bos.expand(embedded_images.shape[0], -1, -1),
  79.         embedded_images.to(dtype=embedded_bos.dtype),
  80.         prompt_embeds.expand(embedded_images.shape[0], -1, -1),
  81.     ], dim=1)
  82.  
  83.     input_ids = torch.cat([
  84.         torch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),
  85.         torch.zeros((1, embedded_images.shape[1]), dtype=torch.long),
  86.         prompt,
  87.     ], dim=1).to('cuda')
  88.     attention_mask = torch.ones_like(input_ids)
  89.  
  90.     #generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
  91.     generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, top_k=10, temperature=0.5, suppress_tokens=None)
  92.  
  93.     # Trim off the prompt
  94.     generate_ids = generate_ids[:, input_ids.shape[1]:]
  95.     if generate_ids[0][-1] == tokenizer.eos_token_id:
  96.         generate_ids = generate_ids[:, :-1]
  97.  
  98.     caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
  99.  
  100.     return caption.strip()
  101.  
  102.  
  103. print(stream_chat(Image.open("/path/to/boobas.png")))
  104.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement