import torch import torch.amp.autocast_mode import os import sys import logging import warnings import argparse from PIL import Image from pathlib import Path from tqdm import tqdm from torch import nn from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM from typing import List, Union import torchvision.transforms.functional as TVF from peft import PeftModel import gc import sys IS_COLAB = 'google.colab' in sys.modules # Constants IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.bmp', '.webp') HF_TOKEN = os.environ.get("HF_TOKEN", None) BASE_DIR = Path(__file__).resolve().parent # Define the base directory CHECKPOINT_PATH = BASE_DIR / Path("cgrkzexw-599808") CLIP_PATH = "google/siglip-so400m-patch14-384" DEFAULT_MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-bnb-4bit" #DEFAULT_MODEL_PATH = "unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit" # Default in Alpha One Two. #DEFAULT_MODEL_PATH = "Orenguteng/Llama-3.1-8B-Lexi-Uncensored-V2" # Works better but full weight. LORA_PATH = CHECKPOINT_PATH / "text_model" CAPTION_TYPE_MAP = { "Descriptive": [ "Write a descriptive caption for this image in a formal tone.", "Write a descriptive caption for this image in a formal tone within {word_count} words.", "Write a {length} descriptive caption for this image in a formal tone.", ], "Descriptive (Informal)": [ "Write a descriptive caption for this image in a casual tone.", "Write a descriptive caption for this image in a casual tone within {word_count} words.", "Write a {length} descriptive caption for this image in a casual tone.", ], "Training Prompt": [ "Write a stable diffusion prompt for this image.", "Write a stable diffusion prompt for this image within {word_count} words.", "Write a {length} stable diffusion prompt for this image.", ], "MidJourney": [ "Write a MidJourney prompt for this image.", "Write a MidJourney prompt for this image within {word_count} words.", "Write a {length} MidJourney prompt for this image.", ], "Booru tag list": [ "Write a list of Booru tags for this image.", "Write a list of Booru tags for this image within {word_count} words.", "Write a {length} list of Booru tags for this image.", ], "Booru-like tag list": [ "Write a list of Booru-like tags for this image.", "Write a list of Booru-like tags for this image within {word_count} words.", "Write a {length} list of Booru-like tags for this image.", ], "Art Critic": [ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.", "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.", "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.", ], "Product Listing": [ "Write a caption for this image as though it were a product listing.", "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.", "Write a {length} caption for this image as though it were a product listing.", ], "Social Media Post": [ "Write a caption for this image as if it were being used for a social media post.", "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.", "Write a {length} caption for this image as if it were being used for a social media post.", ], } class ImageAdapter(nn.Module): def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool): super().__init__() self.deep_extract = deep_extract if self.deep_extract: input_features = input_features * 5 self.linear1 = nn.Linear(input_features, output_features) self.activation = nn.GELU() self.linear2 = nn.Linear(output_features, output_features) self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features) self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features)) # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>) self.other_tokens = nn.Embedding(3, output_features) self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3 def forward(self, vision_outputs: torch.Tensor): if self.deep_extract: x = torch.concat(( vision_outputs[-2], vision_outputs[3], vision_outputs[7], vision_outputs[13], vision_outputs[20], ), dim=-1) assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}" else: x = vision_outputs[-2] x = self.ln1(x) if self.pos_emb is not None: assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}" x = x + self.pos_emb x = self.linear1(x) x = self.activation(x) x = self.linear2(x) # <|image_start|>, IMAGE, <|image_end|> other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1)) assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}" x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1) return x def get_eot_embedding(self): return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0) # Global Variables IS_NF4 = True IS_LORA = True MODEL_PATH = DEFAULT_MODEL_PATH device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Running on {device}") warnings.filterwarnings("ignore", category=UserWarning) logging.getLogger("transformers").setLevel(logging.ERROR) class ImageAdapter(nn.Module): def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool): super().__init__() self.deep_extract = deep_extract if self.deep_extract: input_features = input_features * 5 self.linear1 = nn.Linear(input_features, output_features) self.activation = nn.GELU() self.linear2 = nn.Linear(output_features, output_features) self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features) self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features)) # Mode token #self.mode_token = nn.Embedding(n_modes, output_features) #self.mode_token.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3 # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>) self.other_tokens = nn.Embedding(3, output_features) self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3 def forward(self, vision_outputs: torch.Tensor): if self.deep_extract: x = torch.concat(( vision_outputs[-2], vision_outputs[3], vision_outputs[7], vision_outputs[13], vision_outputs[20], ), dim=-1) assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}" else: x = vision_outputs[-2] x = self.ln1(x) if self.pos_emb is not None: assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}" x = x + self.pos_emb x = self.linear1(x) x = self.activation(x) x = self.linear2(x) # Mode token #mode_token = self.mode_token(mode) #assert mode_token.shape == (x.shape[0], mode_token.shape[1], x.shape[2]), f"Expected {(x.shape[0], 1, x.shape[2])}, got {mode_token.shape}" #x = torch.cat((x, mode_token), dim=1) # <|image_start|>, IMAGE, <|image_end|> other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1)) assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}" x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1) return x def get_eot_embedding(self): return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0) def load_models(): global MODEL_PATH, IS_NF4, IS_LORA try: if IS_NF4: from transformers import BitsAndBytesConfig nf4_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16) print("Loading in NF4") print("Loading CLIP 📎") clip_processor = AutoProcessor.from_pretrained(CLIP_PATH) clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model assert (CHECKPOINT_PATH / "clip_model.pt").exists() if (CHECKPOINT_PATH / "clip_model.pt").exists(): print("Loading VLM's custom vision model 📎") checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu', weights_only=False) checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()} clip_model.load_state_dict(checkpoint) del checkpoint clip_model.eval().requires_grad_(False).to(device) print("Loading tokenizer 🪙") tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True) assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}" print(f"Loading LLM: {MODEL_PATH} 🤖") text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, quantization_config=nf4_config, device_map=device, torch_dtype=torch.bfloat16).eval() if False and IS_LORA and LORA_PATH.exists(): # omitted print("Loading VLM's custom text model 🤖") text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, device_map=device, quantization_config=nf4_config) text_model = text_model.merge_and_unload(safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515 else: print("VLM's custom text model isn't loaded 🤖") print("Loading image adapter 🖼️") image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False).eval().to("cpu") image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=False)) image_adapter.eval().to(device) else: print("Loading in bfloat16") print("Loading CLIP 📎") clip_processor = AutoProcessor.from_pretrained(CLIP_PATH) clip_model = AutoModel.from_pretrained(CLIP_PATH).vision_model if (CHECKPOINT_PATH / "clip_model.pt").exists(): print("Loading VLM's custom vision model 📎") checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu', weights_only=False) checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()} clip_model.load_state_dict(checkpoint) del checkpoint clip_model.eval().requires_grad_(False).to(device) print("Loading tokenizer 🪙") tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True) assert isinstance(tokenizer, (PreTrainedTokenizer, PreTrainedTokenizerFast)), f"Tokenizer is of type {type(tokenizer)}" print(f"Loading LLM: {MODEL_PATH} 🤖") text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, device_map="auto", torch_dtype=torch.bfloat16).eval() # device_map="auto" may cause LoRA issue if IS_LORA and LORA_PATH.exists(): print("Loading VLM's custom text model 🤖") text_model = PeftModel.from_pretrained(model=text_model, model_id=LORA_PATH, device_map=device) text_model = text_model.merge_and_unload(safe_merge=True) # to avoid PEFT bug https://github.com/huggingface/transformers/issues/28515 else: print("VLM's custom text model isn't loaded 🤖") print("Loading image adapter 🖼️") image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False).eval().to("cpu") image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu", weights_only=False)) except Exception as e: print(f"Error loading models: {e}") sys.exit(1) finally: torch.cuda.empty_cache() gc.collect() return clip_processor, clip_model, tokenizer, text_model, image_adapter @torch.inference_mode() def stream_chat(input_images: List[Image.Image], caption_type: str, caption_length: Union[str, int], extra_options: list[str], name_input: str, custom_prompt: str, max_new_tokens: int, top_p: float, temperature: float, batch_size: int, pbar: tqdm, models: tuple) -> List[str]: global MODEL_PATH clip_processor, clip_model, tokenizer, text_model, image_adapter = models torch.cuda.empty_cache() all_captions = [] # 'any' means no length specified length = None if caption_length == "any" else caption_length if isinstance(length, str): try: length = int(length) except ValueError: pass # Build prompt if length is None: map_idx = 0 elif isinstance(length, int): map_idx = 1 elif isinstance(length, str): map_idx = 2 else: raise ValueError(f"Invalid caption length: {length}") prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx] # Add extra options if len(extra_options) > 0: prompt_str += " " + " ".join(extra_options) # Add name, length, word_count prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length) if custom_prompt.strip() != "": prompt_str = custom_prompt.strip() # For debugging print(f"Prompt: {prompt_str}") for i in range(0, len(input_images), batch_size): batch = input_images[i:i+batch_size] for input_image in input_images: try: # Preprocess image # NOTE: I found the default processor for so400M to have worse results than just using PIL directly #image = clip_processor(images=input_image, return_tensors='pt').pixel_values image = input_image.resize((384, 384), Image.LANCZOS) pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0 pixel_values = TVF.normalize(pixel_values, [0.5], [0.5]) pixel_values = pixel_values.to(device) except ValueError as e: print(f"Error processing image: {e}") print("Skipping this image and continuing...") continue # Embed image # This results in Batch x Image Tokens x Features with torch.amp.autocast_mode.autocast(device, enabled=True): vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True) image_features = vision_outputs.hidden_states embedded_images = image_adapter(image_features).to(device) # Build the conversation convo = [ { "role": "system", "content": "You are a helpful image captioner.", }, { "role": "user", "content": prompt_str, }, ] # Format the conversation convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True) assert isinstance(convo_string, str) # Tokenize the conversation # prompt_str is tokenized separately so we can do the calculations below convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False) prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False) assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor) convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier prompt_tokens = prompt_tokens.squeeze(0) # Calculate where to inject the image eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist() assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}" preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt # Embed the tokens convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to(device)) # Construct the input input_embeds = torch.cat([ convo_embeds[:, :preamble_len], # Part before the prompt embedded_images.to(dtype=convo_embeds.dtype), # Image convo_embeds[:, preamble_len:], # The prompt and anything after it ], dim=1).to(device) input_ids = torch.cat([ convo_tokens[:preamble_len].unsqueeze(0), torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), # Dummy tokens for the image (TODO: Should probably use a special token here so as not to confuse any generation algorithms that might be inspecting the input) convo_tokens[preamble_len:].unsqueeze(0), ], dim=1).to(device) attention_mask = torch.ones_like(input_ids) # Debugging #print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}") generate_ids = text_model.generate(input_ids=input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, do_sample=True, suppress_tokens=None, max_new_tokens=max_new_tokens, top_p=top_p, temperature=temperature) # Trim off the prompt generate_ids = generate_ids[:, input_ids.shape[1]:] if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"): generate_ids = generate_ids[:, :-1] caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0] all_captions.append(caption.strip()) if pbar: pbar.update(len(batch)) return all_captions def process_directory(input_dir: Path, output_dir: Path, caption_type: str, caption_length: Union[str, int], extra_options: list[str], name_input: str, custom_prompt: str, max_new_tokens: int, top_p: float, temperature: float, batch_size: int, models: tuple): output_dir.mkdir(parents=True, exist_ok=True) image_files = [f for f in input_dir.iterdir() if f.suffix.lower() in IMAGE_EXTENSIONS] images_to_process = [f for f in image_files if not (output_dir / f"{f.stem}.txt").exists()] if not images_to_process: print("No new images to process.") return with tqdm(total=len(images_to_process), desc="Processing images", unit="image") as pbar: for i in range(0, len(images_to_process), batch_size): batch_files = images_to_process[i:i+batch_size] batch_images = [Image.open(f).convert('RGB') for f in batch_files] captions = stream_chat(batch_images, caption_type, caption_length, extra_options, name_input, custom_prompt, max_new_tokens, top_p, temperature, batch_size, pbar, models) for file, caption in zip(batch_files, captions): with open(output_dir / f"{file.stem}.txt", 'w', encoding='utf-8') as f: f.write(caption) for img in batch_images: img.close() def parse_arguments(): parser = argparse.ArgumentParser(description="Process images and generate captions.") parser.add_argument("input", nargs='+', help="Input image file or directory (or multiple directories)") parser.add_argument("--output", help="Output directory (optional)") parser.add_argument("--bs", type=int, default=4, help="Batch size (default: 4)") parser.add_argument("--type", type=str, default="Descriptive", choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post"], help='Caption Type (default: "Descriptive")') parser.add_argument("--len", default="long", choices=["any", "very short", "short", "medium-length", "long", "very long"] + [str(i) for i in range(20, 261, 10)], help='Caption Length (default: "long")') parser.add_argument("--extra", default=[], type=list[str], help='Extra Options', choices=[ "If there is a person/character in the image you must refer to them as {name}.", "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).", "Include information about lighting.", "Include information about camera angle.", "Include information about whether there is a watermark or not.", "Include information about whether there are JPEG artifacts or not.", "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.", "Do NOT include anything sexual; keep it PG.", "Do NOT mention the image's resolution.", "You MUST include information about the subjective aesthetic quality of the image from low to very high.", "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.", "Do NOT mention any text that is in the image.", "Specify the depth of field and whether the background is in focus or blurred.", "If applicable, mention the likely use of artificial or natural lighting sources.", "Do NOT use any ambiguous language.", "Include whether the image is sfw, suggestive, or nsfw.", "ONLY describe the most important elements of the image." ]) parser.add_argument("--name", type=str, default="", help='Person/Character Name (if applicable)') parser.add_argument("--prompt", type=str, default="", help='Custom Prompt (optional, will override all other settings)') parser.add_argument("--model", type=str, default=DEFAULT_MODEL_PATH, help='Huggingface LLM repo (default: "unsloth/Meta-Llama-3.1-8B-bnb-4bit")') parser.add_argument("--bf16", action="store_true", default=False, help="Use bfloat16 (default: NF4)") parser.add_argument("--nolora", action="store_true", default=False, help="Disable VLM's custom text model (default: Enable)") parser.add_argument("--tokens", type=int, default=300, help="Max tokens (default: 300)") parser.add_argument("--topp", type=float, default=0.9, help="Top-P (default: 0.9)") parser.add_argument("--temp", type=float, default=0.6, help="Temperature (default: 0.6)") return parser.parse_args() def is_valid_repo(repo_id): from huggingface_hub import HfApi import re try: if not re.fullmatch(r'^[^/,\s\"\']+/[^/,\s\"\']+$', repo_id): return False api = HfApi() if api.repo_exists(repo_id=repo_id): return True else: return False except Exception as e: print(f"Failed to connect {repo_id}. {e}") return False def main(): global MODEL_PATH, IS_NF4, IS_LORA args = parse_arguments() input_paths = [Path(input_path) for input_path in args.input] batch_size = args.bs caption_type = args.type caption_length = args.len extra_options = args.extra name_input = args.name custom_prompt = args.prompt max_new_tokens = args.tokens top_p = args.topp temperature = args.temp IS_NF4 = False if args.bf16 else True IS_LORA = False if args.nolora else True if is_valid_repo(args.model): MODEL_PATH = args.model else: sys.exit(1) models = load_models() for input_path in input_paths: if input_path.is_file() and input_path.suffix.lower() in IMAGE_EXTENSIONS: output_path = input_path.with_suffix('.txt') print(f"Processing single image 🎞️: {input_path.name}") with tqdm(total=1, desc="Processing image", unit="image") as pbar: captions = stream_chat([Image.open(input_path).convert('RGB')], caption_type, caption_length, extra_options, name_input, custom_prompt, max_new_tokens, top_p, temperature, 1, pbar, models) with open(output_path, 'w', encoding='utf-8') as f: f.write(captions[0]) print(f"Output saved to {output_path}") elif input_path.is_dir(): output_path = Path(args.output) if args.output else input_path print(f"Processing directory 📁: {input_path}") print(f"Output directory 📦: {output_path}") print(f"Batch size 🗄️: {batch_size}") process_directory(input_path, output_path, caption_type, caption_length, extra_options, name_input, custom_prompt, max_new_tokens, top_p, temperature, batch_size, models) else: print(f"Invalid input: {input_path}") print("Skipping...") if not input_paths: print("Usage:") print("For single image: python app.py [image_file] [--bs batch_size]") print("For directory (same input/output): python app.py [directory] [--bs batch_size]") print("For directory (separate input/output): python app.py [directory] --output [output_directory] [--bs batch_size]") print("For multiple directories: python app.py [directory1] [directory2] ... [--output output_directory] [--bs batch_size]") sys.exit(1) if __name__ == "__main__": main()