codeShare commited on
Commit
113e061
1 Parent(s): 214dfd8

Upload joy_caption_jupyter (1).ipynb

Browse files
Files changed (1) hide show
  1. joy_caption_jupyter (1).ipynb +149 -0
joy_caption_jupyter (1).ipynb ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {
7
+ "id": "VjYy0F2gZIPR"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "!pip install gradio bitsandbytes transformers==4.43.3\n",
12
+ "\n",
13
+ "!wget https://huggingface.co/spaces/fancyfeast/joy-caption-pre-alpha/resolve/main/wpkklhc6/image_adapter.pt -O /content/image_adapter.pt\n",
14
+ "!wget https://huggingface.co/spaces/fancyfeast/joy-caption-pre-alpha/raw/main/wpkklhc6/config.yaml -O /content/config.yaml\n",
15
+ "\n",
16
+ "import gradio as gr\n",
17
+ "from huggingface_hub import InferenceClient\n",
18
+ "from torch import nn\n",
19
+ "from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM\n",
20
+ "from pathlib import Path\n",
21
+ "import torch\n",
22
+ "import torch.amp.autocast_mode\n",
23
+ "from PIL import Image\n",
24
+ "import os\n",
25
+ "\n",
26
+ "CLIP_PATH = \"google/siglip-so400m-patch14-384\"\n",
27
+ "VLM_PROMPT = \"A descriptive caption for this image:\\n\"\n",
28
+ "# MODEL_PATH = \"unsloth/Meta-Llama-3.1-8B\"\n",
29
+ "MODEL_PATH = \"unsloth/Meta-Llama-3.1-8B-bnb-4bit\"\n",
30
+ "CHECKPOINT_PATH = Path(\"wpkklhc6\")\n",
31
+ "\n",
32
+ "class ImageAdapter(nn.Module):\n",
33
+ "\tdef __init__(self, input_features: int, output_features: int):\n",
34
+ "\t\tsuper().__init__()\n",
35
+ "\t\tself.linear1 = nn.Linear(input_features, output_features)\n",
36
+ "\t\tself.activation = nn.GELU()\n",
37
+ "\t\tself.linear2 = nn.Linear(output_features, output_features)\n",
38
+ "\n",
39
+ "\tdef forward(self, vision_outputs: torch.Tensor):\n",
40
+ "\t\tx = self.linear1(vision_outputs)\n",
41
+ "\t\tx = self.activation(x)\n",
42
+ "\t\tx = self.linear2(x)\n",
43
+ "\t\treturn x\n",
44
+ "\n",
45
+ "# Load CLIP\n",
46
+ "print(\"Loading CLIP\")\n",
47
+ "clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)\n",
48
+ "clip_model = AutoModel.from_pretrained(CLIP_PATH)\n",
49
+ "clip_model = clip_model.vision_model\n",
50
+ "clip_model.eval()\n",
51
+ "clip_model.requires_grad_(False)\n",
52
+ "clip_model.to(\"cuda\")\n",
53
+ "\n",
54
+ "# Tokenizer\n",
55
+ "print(\"Loading tokenizer\")\n",
56
+ "tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, load_in_4bit=True, use_fast=False)\n",
57
+ "assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f\"Tokenizer is of type {type(tokenizer)}\"\n",
58
+ "\n",
59
+ "# LLM\n",
60
+ "print(\"Loading LLM\")\n",
61
+ "text_model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, load_in_4bit=True, device_map=\"auto\", torch_dtype=torch.float16)\n",
62
+ "text_model.eval()\n",
63
+ "\n",
64
+ "# Image Adapter\n",
65
+ "print(\"Loading image adapter\")\n",
66
+ "image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size)\n",
67
+ "image_adapter.load_state_dict(torch.load(\"/content/image_adapter.pt\", map_location=\"cpu\"))\n",
68
+ "image_adapter.eval()\n",
69
+ "image_adapter.to(\"cuda\")\n",
70
+ "\n",
71
+ "@torch.inference_mode()\n",
72
+ "def stream_chat(input_image: Image.Image):\n",
73
+ "\ttorch.cuda.empty_cache()\n",
74
+ "\n",
75
+ "\t# Preprocess image\n",
76
+ "\timage = clip_processor(images=input_image, return_tensors='pt').pixel_values\n",
77
+ "\timage = image.to('cuda')\n",
78
+ "\n",
79
+ "\t# Tokenize the prompt\n",
80
+ "\tprompt = tokenizer.encode(VLM_PROMPT, return_tensors='pt', padding=False, truncation=False, add_special_tokens=False)\n",
81
+ "\n",
82
+ "\t# Embed image\n",
83
+ "\twith torch.amp.autocast_mode.autocast('cuda', enabled=True):\n",
84
+ "\t\tvision_outputs = clip_model(pixel_values=image, output_hidden_states=True)\n",
85
+ "\t\timage_features = vision_outputs.hidden_states[-2]\n",
86
+ "\t\tembedded_images = image_adapter(image_features)\n",
87
+ "\t\tembedded_images = embedded_images.to('cuda')\n",
88
+ "\n",
89
+ "\t# Embed prompt\n",
90
+ "\tprompt_embeds = text_model.model.embed_tokens(prompt.to('cuda'))\n",
91
+ "\tassert 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)}\"\n",
92
+ "\tembedded_bos = text_model.model.embed_tokens(torch.tensor([[tokenizer.bos_token_id]], device=text_model.device, dtype=torch.int64))\n",
93
+ "\n",
94
+ "\t# Construct prompts\n",
95
+ "\tinputs_embeds = torch.cat([\n",
96
+ "\t\tembedded_bos.expand(embedded_images.shape[0], -1, -1),\n",
97
+ "\t\tembedded_images.to(dtype=embedded_bos.dtype),\n",
98
+ "\t\tprompt_embeds.expand(embedded_images.shape[0], -1, -1),\n",
99
+ "\t], dim=1)\n",
100
+ "\n",
101
+ "\tinput_ids = torch.cat([\n",
102
+ "\t\ttorch.tensor([[tokenizer.bos_token_id]], dtype=torch.long),\n",
103
+ "\t\ttorch.zeros((1, embedded_images.shape[1]), dtype=torch.long),\n",
104
+ "\t\tprompt,\n",
105
+ "\t], dim=1).to('cuda')\n",
106
+ "\tattention_mask = torch.ones_like(input_ids)\n",
107
+ "\n",
108
+ "\t#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)\n",
109
+ "\tgenerate_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)\n",
110
+ "\n",
111
+ "\t# Trim off the prompt\n",
112
+ "\tgenerate_ids = generate_ids[:, input_ids.shape[1]:]\n",
113
+ "\tif generate_ids[0][-1] == tokenizer.eos_token_id:\n",
114
+ "\t\tgenerate_ids = generate_ids[:, :-1]\n",
115
+ "\n",
116
+ "\tcaption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]\n",
117
+ "\n",
118
+ "\treturn caption.strip()\n",
119
+ "\n",
120
+ "\n",
121
+ "with gr.Blocks(css=\".gradio-container {max-width: 544px !important}\", analytics_enabled=False) as demo:\n",
122
+ "\twith gr.Row():\n",
123
+ "\t\twith gr.Column():\n",
124
+ "\t\t\tinput_image = gr.Image(type=\"pil\", label=\"Input Image\")\n",
125
+ "\t\t\trun_button = gr.Button(\"Caption\")\n",
126
+ "\t\t\toutput_caption = gr.Textbox(label=\"Caption\")\n",
127
+ "\trun_button.click(fn=stream_chat, inputs=[input_image], outputs=[output_caption])\n",
128
+ "\n",
129
+ "demo.queue().launch(share=True, inline=False, debug=True)"
130
+ ]
131
+ }
132
+ ],
133
+ "metadata": {
134
+ "accelerator": "GPU",
135
+ "colab": {
136
+ "gpuType": "T4",
137
+ "provenance": []
138
+ },
139
+ "kernelspec": {
140
+ "display_name": "Python 3",
141
+ "name": "python3"
142
+ },
143
+ "language_info": {
144
+ "name": "python"
145
+ }
146
+ },
147
+ "nbformat": 4,
148
+ "nbformat_minor": 0
149
+ }